DESIGN PATTERNS SAGA #3: REAL PROJECT SITUATIONS WITH SINGLETON

The problem: Imagine if we always had to create new instances for expensive objects, like DatabaseConnectors or Loggers, and use them in many places in the system. Imagine all the wasted memory. You could easily have a memory leak and your system could not work at all. How can we solve this problem? Is there a way to deal with it? Yes! The Singleton Pattern solves this problem, and the good thing is, it is very simple to implement it!

The diagram:

Logger

Get the source code:

https://github.com/rafadelnero/nobugsproject.git >> design-patterns-saga

Yes, only one class – it’s the simplest Pattern in my opinion, but it solves serious problems that can completely compromise your system. I will use a Logger class as an example because every system needs a log, right?

Let’s see in a practical way how to use it!

1 – The Singleton class: The first thing we do is to declare the Logger class as static because we want it to be used in the entire application. Then we must create a private constructor to avoid direct instantiations. We also create the getInstance() method where we finally create the instance of Logger. It’s important to make clear that we are using lazy loading. We first ask if the object was created. If not, we create the instance. Another important thing to mention is that we are synchronizing the creation of the object. This means that we are avoiding concurrency problems. Once we create the instance, we won’t have to create it anymore.

 public class Logger {

	private static Logger logger = null;

	private Logger() {
		super();
	}

	public static Logger getInstance() {
		if (logger == null) {
			synchronized (Logger.class) {
				if (logger == null) {
					logger = new Logger();
				}
			}
		}

		return logger;
	}

}

2 – The Unitary Test:

Summary of actions:
1 – We created the Singleton class
2 – We declared the static Logger class
3 – We created the getInstance() method using lazy loading

You can try out this test:

public class SingletonTest {

	@Test
	public void verifyIfTheInstancesAreTheSame() {
		Logger firstLog = Logger.getInstance();
		Logger secondLog = Logger.getInstance();
		Logger thirdLog = Logger.getInstance();

		Assert.assertEquals(firstLog, secondLog);
		Assert.assertEquals(secondLog, thirdLog);
	}

}

To practice this Pattern you can create, for example, DatabaseConnector class and make it the Singleton. Then create your Unitary Test to check if the instance is the same. Try to use TDD (Test Driven Development). Start the development from the test.

DESIGN PATTERNS SAGA #3: REAL PROJECT SITUATIONS WITH SINGLETON

DESIGN PATTERNS SAGA #2: REAL PROJECT SITUATIONS WITH BUILDER

The Problem: Not using the right pattern for the right situation and creating difficult to find bugs.

In day-to-day work I continually see complex objects being constructed without any patterns at all. What happens? Well, we see giant Services with 10, 20, 30 or more lines with setters from the objects being populated. Do you think we can continue coding like this? Of course not!

This structure looks like procedural programming. We must learn the best programming techniques so that we can deliver quality software and avoid bugs. If we use the Builder pattern effectively, we can make awesome, flexible and powerful code.

Builder

The diagram:

Builder.PNG

Get the source code:

https://github.com/rafadelnero/nobugsproject.git >> design-patterns-saga

1 – Calculation Class: This a simple class with values of a calculation. It has attributes, getters and setters and some important details in this class:

  • The setters are private to avoid direct access
  • The getter of the list is unmodifiable to avoid new elements adding
  • The constructor is private for avoiding instantiation

We are using a really important concept here, ENCAPSULATION! But, how can I change those fields if they are private? You will see in the next topic.

 public class Calculation {

	private long idCalculation;

	private long idPeriodicity;

	private List<Price> prices;

	private Date dtCalculation;

	private Calculation() {
		prices = new ArrayList<>();
	}

	// Builder class omitted, it will be explained in the next topic

	private final void setIdCalculation(long idCalculation) {
		this.idCalculation = idCalculation;
	}

	private final void setIdPeriodicity(long idPeriodicity) {
		this.idPeriodicity = idPeriodicity;
	}

	private final void setDtCalculation(Date dtCalculation) {
		this.dtCalculation = dtCalculation;
	}

	public final long getIdCalculation() {
		return idCalculation;
	}

	public final long getIdPeriodicity() {
		return idPeriodicity;
	}

	public final Date getDtCalculation() {
		return dtCalculation;
	}

	public final Collection<Price> getPrices() {
		return Collections.unmodifiableCollection(prices);
	}

}

2 – Static Inner Builder Class: Here is where the magic happens! We are going to build the Calculation object and with the Builder we can have access to modify the fields.

In the constructor:

  • public Builder(long idCalculation, long idPeriodicity): we are initiating the Builder class with the required fields, that is why they are being passed in the constructor.
  • In the method Builder withDate(Date dtCalculation): we are putting information in dtCalculation. Most importantly we are returning “this”, the Builder. It makes  invoking another method directly possible.
  • The method public Builder withPrice(long idCurrency, BigDecimal priceValue) builds the Price object. See that this method delegates the responsibility for the Builder of the Price class.
public static class Builder {

		private Calculation calculation = new Calculation();

		public Builder(long idCalculation, long idPeriodicity) {
			calculation.setIdCalculation(idCalculation);
			calculation.setIdPeriodicity(idPeriodicity);
		}

		public Builder withDate(Date dtCalculation) {
			calculation.setDtCalculation(dtCalculation);

			return this;
		}

		public Builder withPrice(long idCurrency, BigDecimal priceValue) {
			Price price = new Price.Builder(new Random().nextLong()).withPrice(idCurrency, priceValue).build();
			calculation.prices.add(price);

			return this;
		}

		public Calculation build() {
			return calculation;
		}

	}

3 – Price Class: This is pretty much the same as the Calculation class – no new concept here!

public class Price {

	private long idPrice;

	private long idCurrency;

	private BigDecimal priceValue;

	private Price() {
		super();
	}

	public static class Builder {

		private Price price = new Price();

		public Builder(long idPrice) {
			price.setIdPrice(idPrice);
		}

		public Builder withPrice(long idCurrency, BigDecimal value) {
			price.setIdCurrency(idCurrency);
			price.setPriceValue(value);

			return this;
		}

		public Price build() {
			return this.price;
		}

	}

	// Getters and Setters omitted 

}

4 – Unitary Test: The final process. Let’s finally build our objects!

Summary of actions:

1 – We encapsulate the attributes of the POJO
2 – We make the constructor of the POJO private
3 – We create a static Builder class inside the POJO class
4 – We declare the POJO class inside the Builder
5 – We create methods in the Builder that return the Builder
6 – Finally, we build the object

You can execute your tests with these Unitary Tests:

public class BuilderTest {

	private static final long ID_CALCULATION = 1L;

	private static final long ID_PERIODICITY = 1L;

	private static final long ID_CURRENCY = 1L;

	private static final Date DT_CALCULATION = new Date();

	private static final BigDecimal PRICE_VALUE_1 = BigDecimal.ONE;
	private static final BigDecimal PRICE_VALUE_2 = BigDecimal.TEN;

	@Test
	public void validateCalculationInformationTest() {
		Calculation calculation = new Calculation.Builder(ID_CALCULATION, ID_PERIODICITY).withDate(DT_CALCULATION)
				.withPrice(ID_CURRENCY, PRICE_VALUE_1).withPrice(ID_CURRENCY, PRICE_VALUE_2).build();

		Assert.assertEquals(ID_CALCULATION, calculation.getIdCalculation());
		Assert.assertEquals(ID_PERIODICITY, calculation.getIdPeriodicity());
		Assert.assertEquals(DT_CALCULATION, calculation.getDtCalculation());

		Iterator<Price> iterator = calculation.getPrices().iterator();
		Price firstPrice = iterator.next();
		Price secondPrice = iterator.next();

		Assert.assertEquals(ID_CURRENCY, firstPrice.getIdCurrency());
		Assert.assertEquals(PRICE_VALUE_1, firstPrice.getPriceValue());

		Assert.assertEquals(ID_CURRENCY, secondPrice.getIdCurrency());
		Assert.assertEquals(PRICE_VALUE_2, secondPrice.getPriceValue());
	}

	@Test(expected = UnsupportedOperationException.class)
	public void validatePricesIsImmutableTest() {
		Calculation calculation = new Calculation.Builder(ID_CALCULATION, ID_PERIODICITY).build();

		calculation.getPrices().add(new Price.Builder(new Random().nextLong()).withPrice(ID_CURRENCY, PRICE_VALUE_1).build());
	}

}

To practice this Pattern, create another POJO and check if the fields correspond to each other in your Unitary Test.

Keep up the great work. Stay tuned for more articles next week!

DESIGN PATTERNS SAGA #2: REAL PROJECT SITUATIONS WITH BUILDER

Design Patterns Saga #1: Real Project Situations with Factory Method and Strategy

The problem: If we don’t know what Design Patterns we have available to solve day-to-day situations, it’s going to be very difficult to implement the best solutions.

Our code can have very high coupling and no cohesion which causes no flexibility and no scalability. Then, you-know-who is going to appear. If you thought bugs, yes! You are right! The bugs will have a party in the code, making our lives very stressful.

Very experienced programmers of GOF (Gang of Four) Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides created Design Patterns, solutions for common and day-to-day coding situations. Many of the problems GOF faced were solved after creating the Patterns, that’s why it’s so important to know them.

Instead of going through the same problems they did for many years, we can learn those Patterns and make our code clean, flexible and powerful.

I had the following situation in my job. I had to receive a command from a Web Service and call the specific Service for each command.

What solution would be appropriate for this situation?

Factory Method + Strategy

The diagram:

class_diagram.PNG

Get the source code:

https://github.com/rafadelnero/nobugsproject.git >> design-patterns-saga

1 – Invoker class: the executeAction() method will receive the command and depending on the command received, it will invoke the correspondent Service.

public class BillingInvoker {

	public void executeAction(String command) {
		int idContract = 1;

		new BillingServiceFactory(command).getService().execute(idContract);
	}

}

2 – This is where we use the pattern Factory Method. Pretty simple, isn’t it? We receive the command in the constructor and decide what Service we are going to invoke.

I created an Enum to make the selection clearer and easier to read. I just make a parse to an Enum. Then I choose the Service to be invoked in the command ‘switch case’.

Another important thing to be aware of is that the method getService() is returning an interface. I am using polymorphism in this method. It returns any BillingService, any class that implements it.

public class BillingServiceFactory {

	private String command;

	public BillingServiceFactory(String command) {
		this.command = command;
	}

	public BillingService getService() {
		BillingEnum billingEnum = BillingEnum.parse(command);

		switch (billingEnum) {

		case PRE_CALCULATION:
			return new BillingPreCalculation();

		case CALCULATION:
			return new BillingCalculation();

		default:
			throw new IllegalArgumentException("The service does not exist.");
		}
	}

}

3 – Let’s check out the BillingService interface. Actually, it’s very simple, but necessary to make the Strategy pattern work. With this interface, we can use the very powerful technique, polymorphism. We can invoke the execute(long idContract) method from any class that implements BillingService.

public interface BillingService {

	public void execute(long idContract);

}

4 – Now that we know about the BillingService interface, we can come back to the Invoker class and check it out better. No secret, we just:

  1. Instantiated the class BillingServiceFactory
  2. Passed the command in the constructor
  3. Invoked the getService() method where we get one implementation of the interface BillingService

Here is the magic! We are going to invoke the execute(long idContract) method from the interface, and guess what, we are controlling what implementation we are invoking by the command!

We are isolating the responsibilities and making the code powerful! An important detail is that we must create a generic method name in BillingService, because we don’t know what we are going to invoke. When we return the implementation of the interface we can only use the interface method. You could use a specific method from the implementation if you use class cast only.

public class BillingInvoker {

	public void executeAction(String command) {
		int idContract = 1;

		new BillingServiceFactory(command).getService().execute(idContract);
	}

}

5 – The invocation! Let’s suppose we receive a command to invoke BillingCalculation. What are we going to do? We are going to invoke the BillingCalculation method!

public class BillingCalculation implements BillingService {

	public void execute(long idContract) {
		calculateContract(idContract);
	}

	public void calculateContract(long idContract) {
		System.out.println("BillingCalculation was invoked");
	}

}

6 – The output! It will be printed: BillingCalculation was invoked

We made it!

Summary of our actions:

  1. The Invoker class instantiates the Factory class
  2. The Factory class decides what Service is going to be invoked
  3. The Invoker gets the Service
  4. The Invoker invokes the method of the Service implementation
  5. The output of the Service implementation is printed

You can test the pattern with these Unitary Tests:

public class StrategyFactoryMethodTest {

	private static final long idContract = 1;

	@Test
	public void invokePreCalculationTest() {
		BillingService billingService = new BillingServiceFactory(BillingEnum.PRE_CALCULATION.getCode()).getService();

		billingService.execute(idContract);
		Assert.assertTrue(billingService instanceof BillingPreCalculation);
	}

	@Test
	public void invokeCalculationTest() {
		BillingService billingService = new BillingServiceFactory(BillingEnum.CALCULATION.getCode()).getService();

		billingService.execute(idContract);
		Assert.assertTrue(billingService instanceof BillingCalculation);
	}

	@Test(expected = IllegalArgumentException.class)
	public void notExistentCommandTest() {
		new BillingServiceFactory("777").getService();
	}

}

To practice using this Pattern you can implement a new unitary test to a new Service and make it work!

Design Patterns Saga #1: Real Project Situations with Factory Method and Strategy