lloistborn/fintech-api

Separating behavior of Domain object syntactically using Extension

Closed this issue · 0 comments

Problem

Say I have a domain object

public class Money {
  private int bigAmount;
  private int smallAmount;
  private Currency currency;

  public Currency GetCurrency() {
    return money.GetCurrency();
  }
}

The GetCurrency() is the behavior of this class.
While it is helpful to have it here,
There will be a point when this currency needs to be retrieved from other places, such as a database.

For that, we don't want to bloat the Money class with all of the database dependencies.

Proposed solution

We can use the manifold extension to separate the behavior from its class.
Here is how the Java code looks like:

@Extension
public class MoneyExtension {
  public static Currency GetCurrency(@This Money money) {
    return money.GetCurrency();
  }
}

// how to use it 
@Test
public void GetCurrencyBasedOnLocale_ShouldReturnSuccess() {
  Money money = new Money(10, 01, Currency.getInstance("USD"));
  
  String curr = money.GetCurrency().getCurrencyCode();
  Assert.assertTrue(curr == "USD");
}

Maven Manifold

<dependency>
  <groupId>systems.manifold</groupId>
  <artifactId>manifold-all</artifactId>
  <version>${manifold-version}</version> 
</dependency>