DESIGN PATTERNS SAGA #7: REAL PROJECT SITUATIONS WITH COMMAND

Creating multiple methods inside only one class can bring many problems like inflexibility and difficulty maintaining code. I am sure all of us have already seen a class full of methods and different responsibilities, right? Classes like these are very difficult to understand, take a lot of time to find out what is happening in all methods and are difficult to test. Fortunately, there is a way to solve this problem – we can use the Command Pattern! The Command Pattern encapsulates its behavior in a separate class that is executed by the Invoker class.

command_diagram.PNG

Get the Design_Patterns_Saga_GitHub_Source_Code

A very common example of the Command Pattern is the Thread class that receives the Runnable interface with the command inside the run method.

public class ThreadCommandExample {

	public static void main(String[] args) {
		TaskCommand command = new TaskCommand(10, 12); 

		Thread invoker = new Thread(command);
		invoker.start();
	}

	static class TaskCommand implements Runnable {

		int num1;
		int num2;

		TaskCommand(int num1, int num2) {
			this.num1 = num1;
			this.num2 = num2;
		}

		@Override
		public void run() { //execute method
			System.out.println(num1 * num2); //receiver
		}
	}
}

1 – Command interface: This is the base of the Pattern, without this generic interface nothing happens. No secrets here, just an interface that has the execute method, nothing more.

public interface Command {

	public void execute();

}

2 – Discount class: this class contains the information to be processed. It’s a simple POJO.

public class Discount {

	private boolean eligible;
	private boolean discountApplied;

	public Discount(boolean eligible) {
		this.eligible = eligible;
	}

	public void applyDiscount() {
		discountApplied = true;
		System.out.println("Discount applied!");
	}

	// Getters and setters omitted

}

3 – Commands: These actions must be executed inside the Invoker. The ApplyDiscountCommand has the business requirements in order to apply the discount. The ApplyAllDiscountsCommand is responsible for encapsulating the ApplyDiscountCommand in order to apply all the discounts once. So, this Command receives a Discount list and invokes the applyDiscount method.

public class ApplyDiscountCommand implements Command {

	private Discount discount;

	public ApplyDiscountCommand(Discount discount) {
		this.discount = discount;
	}

	@Override
	public void execute() {
		if (discount.isEligible()) {
			discount.applyDiscount();
		}
	}

}

public class ApplyAllDiscountsCommand implements Command {

	private List<Discount> discounts;

	public ApplyAllDiscountsCommand(List<Discount> discounts) {
		this.discounts = discounts;
	}

	@Override
	public void execute() {
		discounts.forEach(e -> new ApplyDiscountCommand(e).execute());
	}

}

4 – CommandInvoker: As the name says, it’s going to invoke the Command. We are receiving the Command in the Constructor to be executed in the execute method.

public class CommandInvoker {

	private Command command;

	public CommandInvoker(Command command) {
		this.command = command;
	}

	public void execute() {
		this.command.execute();
	}

}

5 – Unit Tests: All is set to execute Unit Tests. To execute the Command, create the Discount list. Then use the CommandInvoker passing the Command in the Constructor. In the end, execute the Command!

Now, ensure the discounts were applied correctly!

public class CommandTest {

	@Test
	public void applyCommandTest() {
		List<Discount> discounts = mockDiscounts();

		ApplyAllDiscountsCommand command =
                   new ApplyAllDiscountsCommand(discounts);

		CommandInvoker invoker = new CommandInvoker(command);
		invoker.execute();

		Assert.assertTrue(discounts.get(0).isDiscountApplied());
		Assert.assertFalse(discounts.get(1).isDiscountApplied());
		Assert.assertTrue(discounts.get(2).isDiscountApplied());
		Assert.assertFalse(discounts.get(3).isDiscountApplied());
	}

	private List<Discount> mockDiscounts() {
		return Arrays.asList(new Discount(true),
                     new Discount(false), new Discount(true),
                     new Discount(false));
	}

}

Summary of actions:

1 – Created the Command interface.
2 – Created the request object (POJO).
3 – Created the Commands implementing the Command interface.
4 – Implemented the execute method in each Command.
5 – Created the CommandInvoker class to execute the commands.
6 – Invoked the Command through the InvokerCommand class.

To practice the Command Pattern you can create another Discount Command, for example, GoalDiscountCommand that is responsible for applying a Discount depending on the price the client paid for the product and create another test method to make sure it works! Try to use TDD (Test Driven Development). Start the development from the test. Remember, the only way to master the Design Patterns is by practicing them! So, I strongly recommend you clone the project and implement your new Discount Command!

DESIGN PATTERNS SAGA #7: REAL PROJECT SITUATIONS WITH COMMAND

DESIGN PATTERNS SAGA #6: REAL PROJECT SITUATIONS WITH CHAIN OF RESPONSIBILITY

The problem: For complex business logic with lots of conditions, we could certainly use one giant class with lots of ifs. But by doing this,  the class would be highly coupled and with no cohesion. Consider using the Chain of Responsibility Pattern when you have business logic to implement that is dependent on several conditions.

Pros: Using this Pattern you can encapsulate your logic and you can easily create new features using different conditions.

Cons: If the chain gets too large, we can have performance problems. Be careful when using this Pattern.

The diagram:

chain_of_responsibility_diagram.png

The source code:
https://github.com/rafadelnero/design-patterns-saga.git

1 – The Handler class:  This class controls all the flows of the Chain of Responsibility Pattern.

public void setSucessor(Handler successor) – It sets the next chain to handle the next condition. We must create a chain based on all the classes that extend Handler.

public abstract Response handleRequest(Request request) – All the chain classes must implement this method. All the business logic will be executed inside this method.

 public abstract class Handler {
	protected Handler successor;

	public void setSucessor(Handler successor) {
		this.successor = successor;
	}

	public abstract Response handleRequest(Request request);

}

2 – The DiscountHandler class: In this class, we will configure the Chain of the classes that can handle the logic.  Basically, we will instantiate all the classes and set them in the setSuccessor(Handler handler) method. Remember that this Chain must be executed in the correct order as the following:

public class DiscountHandler {

	public Response applyDiscount(Request request) {
		Handler noDiscount = new NoDiscount();
		Handler basic = new BasicDiscount();
		Handler moderate = new ModerateDiscount();
		Handler vip = new VipDiscount();

		noDiscount.setSucessor(basic);
		basic.setSucessor(moderate);
		moderate.setSucessor(vip);

		return noDiscount.handleRequest(request);
	}

}

3 – The Chain: Now we have the classes that will create the chain. We must instantiate them from the root. In the case of this chain, they must be executed in the correct order.

All the classes must extend Handler to be part of the Chain.

When extending the Handler class we must implement the handleRequest abstract method. For example, if the request corresponds to the BasicDiscount condition, the logic from this class will be executed or else the next object in the Chain will handle this logic and so forth.

The classes from the chain are:

public class NoDiscount extends Handler {
	
	@Override
	public Response handleRequest(Request request) {
		if (request.getCustomerSalesAmount()
                  .compareTo(BasicDiscount.minimalValue) < 0) {
			return new Response(DiscountType.NO_DISCOUNT);
		} else {
			return successor.handleRequest(request);
		}
	}

}

public class BasicDiscount extends Handler {

	public static BigDecimal minimalValue = new BigDecimal("10000");

	@Override
	public Response handleRequest(Request request) {
		if (request.getCustomerSalesAmount()
                  .compareTo(ModerateDiscount.minimalValue) < 0) {
			System.out.println("Execute some business logic here");

			return new Response(DiscountType.BASIC);
		} else {
			return successor.handleRequest(request);
		}
	}

}

public class ModerateDiscount extends Handler {
	
	public static BigDecimal minimalValue = new BigDecimal("50000");

	@Override
	public Response handleRequest(Request request) {
		if (request.getCustomerSalesAmount()
                  .compareTo(VipDiscount.minimalValue) < 0) {
			return new Response(DiscountType.MODERATE);
		} else {
			return successor.handleRequest(request);
		}
	}

}

public class VipDiscount extends Handler {

	public static BigDecimal minimalValue = new BigDecimal("100000");

	@Override
	public Response handleRequest(Request request) {
		if (request.getCustomerSalesAmount()
                   .compareTo(minimalValue) >= 0) {
			System.out.println("Execute some business logic here");
			
			return new Response(DiscountType.VIP);
		}
		
		throw new IllegalArgumentException("Invalid argument.");
	}

}

4 – The Unitary Tests: Finally we will see the Pattern working! We are going to test if the request value corresponds to the correct condition. The test will be done for all the Chain classes.

 public class ChainOfResponsibilityTest {

	@Test
	public void verifyIfBasicDiscountWasAppliedTest() {
		Response response = new DiscountHandler()
                 .applyDiscount(new Request(new BigDecimal("20000")));

		Assert.assertEquals(response
                 .getDiscountType(), DiscountType.BASIC);
	}

	@Test
	public void verifyIfModerateDiscountWasAppliedTest() {
		Response response = new DiscountHandler()
                 .applyDiscount(new Request(new BigDecimal("50000")));

		Assert.assertEquals(response
                 .getDiscountType(), DiscountType.MODERATE);
	}

	@Test
	public void verifyIfVipDiscountWasAppliedTest() {
		Response response = new DiscountHandler()
                 .applyDiscount(new Request(new BigDecimal("100000")));

		Assert.assertEquals(response
                 .getDiscountType(), DiscountType.VIP);
	}

	@Test
	public void verifyIfNoDiscountWasAppliedTest() {
		Response response = new DiscountHandler()
                  .applyDiscount(new Request(new BigDecimal("5000")));

		Assert.assertEquals(response
                .getDiscountType(), DiscountType.NO_DISCOUNT);
	}

}

Summary of actions:

1 – Created the Handler class.
2 –  Extended the Handler class by the Chain classes.
3 – Implemented the handleRequest(Request request) method in the Chain classes.
4 – Created the Chain using the setSuccessor(Handler handler) method.
5 – Invoked the handleRequest method from the Chain root.

To practice the Chain of Responsibility Pattern you can create another DiscountType, for example, the SpecialDiscount and create another test method to make sure it works! Try to use TDD (Test Driven Development). Start the development from the test. Remember to use the IDE’s shortcuts for faster coding!

DESIGN PATTERNS SAGA #6: REAL PROJECT SITUATIONS WITH CHAIN OF RESPONSIBILITY

DESIGN PATTERNS SAGA #5: REAL PROJECT SITUATIONS WITH ABSTRACT FACTORY

The problem: Sometimes we need to create complex objects based on abstractions and types. What can we do to deal with this problem? Create lots of “ifs”? No, we can use the Abstract Factory Pattern! Basically, with this Pattern we can create an abstraction of the abstraction. Although this Pattern is not commonly used on enterprise projects, it’s very important to know. One of the cons of this Pattern is that it is complex.

The diagram:

abstract_factory_diagram.PNG

The source code:
https://github.com/rafadelnero/design-patterns-saga.git

1 – The VirtualCoinFactory: Everything begins here in the VirtualCoinFactory class.

The getVirtualCoinFactory(double moneyToInvest) method controls what factory will be returned based on the amount of moneyToInvest. If it is 2000 or more, it will return either the BitcoinFactory or EtheriumFactory. You can see that it is a Factory of another Factory. This is the top class of the Factories.

The abstract getVirtualCoin(VirtualCoinType virtualCoinType) method must be implemented by the other Factory subclass, then we can get a specific class from any type of VirtualCoin.

 public abstract class VirtualCoinFactory {

	public static double BIT_COIN_VALUE = 2000;

	public static VirtualCoinFactory
             getVirtualCoinFactory(double moneyToInvest) {

		if(moneyToInvest >= BIT_COIN_VALUE) {
			return new BitcoinFactory();
		}
		else {
			return new EtheriumFactory();
		}
	}

	public abstract VirtualCoin getVirtualCoin
                        (VirtualCoinType virtualCoinType);

	public abstract Validator getValidator
                   (VirtualCoinType virtualCoinType);
}

2 – The BitcoinFactory: This is the class that extends the top class VirtualCoinFactory.

As a consequence, the getVirtualCoin(VirtualCoinType virtualCoinType) method has to be implemented returning the Bitcoin based on the type, Integer or Fractioned.

To do this process we have to use the polymorphism concept and return a generic type. We have to create this class:

public class VirtualCoin {

	protected double volume;

	protected int buyOrderAmount;
	protected int sellOrderAmount;

	// Getters and setters omitted
}

In the Bitcoin classes, we have to extend VirtualCoin.

public class IntegerBitcoin extends VirtualCoin {

}

public class FractionedBitcoin extends VirtualCoin {

}

The getValidator(VirtualCoinType virtualCoinType) method is used to validate something in the Bitcoin. You can add any method you find suitable for your business requirements here. We also use polymorphism here.

public class BitcoinFactory extends VirtualCoinFactory {

	@Override
	public VirtualCoin getVirtualCoin(VirtualCoinType virtualCoinType) {
		switch(virtualCoinType) {

		case FRACTIONED:
			return new FractionedBitcoin();

		case INTEGER:
			return new IntegerBitcoin();
		default:
			throw new
                         IllegalArgumentException("Card type not found.");
		}
	}

	public Validator getValidator(VirtualCoinType virtualCoinType) {
		switch(virtualCoinType) {

		case FRACTIONED:
			return new FractionedBitcoinValidator();

		case INTEGER:
			return new IntegerBitcoinValidator();
		default:
			throw new
                         IllegalArgumentException("Card type not found.");
		}
	}

}

3 – The EtheriumFactory: There is no new concept here, just the flow of Etherium.

public class EtheriumFactory extends VirtualCoinFactory {

	@Override
	public VirtualCoin getVirtualCoin(VirtualCoinType virtualCoinType) {
		switch (virtualCoinType) {
		case FRACTIONED:
			return new FractionedEtherium();
		case INTEGER:
			return new IntegerEtherium();
		}

		throw new IllegalArgumentException
                 (virtualCoinType + " not found");
	}

	@Override
	public Validator getValidator(VirtualCoinType virtualCoinType) {
		return new EtheriumValidator();
	}

}

4 – Unitary Tests: Now we are going to see if the classes created from the Abstract Factory will be correct.

On the checkBitcoinCreationTest() method we get the instance of the VirtualCoin based on the value 2000, returning the BitcoinFactory. Having the BitcoinFactory we can get the IntegerBitcoin or the FractionedBitcoin based on the type we pass.

Then we check if the returned classes are correct. We use the Reflection methods getClass().getSimpleName() to check if the instances are correct. We do the same process with Etherium.

public class AbstractFactoryTest {

	public static final double BITCOIN_VALUE = 2000;
	public static final double ETHERIUM_VALUE = 1000;

	@Test
	public void checkBitcoinCreationTest() {
		VirtualCoinFactory abstractFactory = VirtualCoinFactory.
                       getVirtualCoinFactory(BITCOIN_VALUE);

		VirtualCoin integerBitcoin = abstractFactory.
                   getVirtualCoin(VirtualCoinType.INTEGER);
		VirtualCoin fractionedBitcoin = abstractFactory.
                  getVirtualCoin(VirtualCoinType.FRACTIONED);

		Assert.assertEquals("IntegerBitcoin", integerBitcoin.
                  getClass().getSimpleName());
		Assert.assertEquals("FractionedBitcoin", fractionedBitcoin.
                  getClass().getSimpleName());
	}

	@Test
	public void checkEtheriumCreationTest() {
		VirtualCoinFactory abstractFactory = VirtualCoinFactory.
                 getVirtualCoinFactory(ETHERIUM_VALUE);

		VirtualCoin integerEtherium = abstractFactory.
                 getVirtualCoin(VirtualCoinType.INTEGER);
		VirtualCoin fractionedEtherium = abstractFactory.
                 getVirtualCoin(VirtualCoinType.FRACTIONED);

		Assert.assertEquals("IntegerEtherium", integerEtherium.
                 getClass().getSimpleName());
		Assert.assertEquals("FractionedEtherium", fractionedEtherium.
                 getClass().getSimpleName());
	}

}

Summary of actions:

1 – Created the top Abstract Factory class.
2 – Created the generic method that returns the sub Factory.
3 – Created a generic method on the sub Factory class that returns the final class.

To practice the Abstract Factory Pattern you can create another sub Factory, it can be another VirtualCoin, and make it return the correct object! Try to use TDD (Test Driven Development). Start the development from the test.

DESIGN PATTERNS SAGA #5: REAL PROJECT SITUATIONS WITH ABSTRACT FACTORY

Design Patterns SAGA #4: Real Project Situations With Prototype

The Problem: We could solve the Prototype problem in an easy way, but we would have to write several setters and create a converter that passes all the information from getter to setter. For example:

newContract.setId(contract.getId());
newContract.setName(contract.getName());

We can’t assign the object reference because both variables will be pointing to the same object. If I change one of the references both references will be identical.

contract = newContract;
contract.setName("It's the same object reference!");

Both references will be the same value. The reference variable newContract.getName() will return “It’s the same object reference!”.

What would be a real world situation in which the Prototype Pattern could be used? We can use it for logging, for example. In order to keep the old state and get the new state of the object, we must use the Prototype Pattern. We can’t copy the reference and use the same object. Another situation would be when we must copy information from an entity and save the same information using JPA.

So, how do you prefer doing the object copy? By manual setters? By using Reflection methods? Or using the clone method from Java API? I will show you the possible ways to solve this problem. I prefer the clone() method!

The diagram:

prototype_diagram.PNG

Get the source code:
https://github.com/rafadelnero/design-patterns-saga.git

1 – The Contract POJO: The first thing we have to realize is that this class is implementing Cloneable. The second thing is that we are overriding the clone() method. We are also changing clone() visibility to “public“.

On the clone() method, we reference the super class cloning the object like this:

clonedContract = (Contract) super.clone();

Unfortunately, the interface Cloneable was implemented in Java 1.0 where generics didn’t exist yet. As a consequence, we need to use class casting.

Shallow Copy vs. Deep Copy: On the below example, we are using Deep Copy. This means we are making a copy with all the related objects inside the Contract class. See that we are doing it manually:

clonedContract.contractComplement = (ContractComplement) contractComplement.clone();

We are copying also the ContractComplement class. An example of Shallow Copy is pretty simple. We just have to copy the Contract class.

public class Contract implements Cloneable {

	private long id;

	private String name;

	private ContractComplement contractComplement;

	private BigDecimal price;

	public Contract(long id, String name,
			ContractComplement contractComplement, BigDecimal price) {
		this.id = id;
		this.name = name;
		this.contractComplement = contractComplement;
		this.price = price;
	}

	public Contract() {
		super();
	}

	@Override
	protected Object clone() {
		Contract clonedContract;
		try {
			clonedContract = (Contract) super.clone();
			clonedContract.contractComplement = (ContractComplement) contractComplement.clone();
			return clonedContract;
		} catch (CloneNotSupportedException e) {
			throw new RuntimeException(e);
		}
	}

	// Getters and Setters omitted

}

2 – The ContractComplement class: There is no new concept here. We just implemented the Cloneable interface and overrode the clone() method using the super.clone() method to clone this object.

public class ContractComplement implements Cloneable {

	private String complementName;

	private Integer specificProductPrice;

	public ContractComplement() {
		super();
	}

	public ContractComplement(String complementName, Integer specificProductPrice) {
		this.complementName = complementName;
		this.specificProductPrice = specificProductPrice;
	}

	@Override
	protected Object clone() throws CloneNotSupportedException {
		return super.clone();
	}

	// Getters and Setters omitted

}

3 – The Unitary Test: Now we are going to check if the objects are really different and if the values are equal.

checkIfTheObjectWasClonedTest() method: Here we are testing the Prototype Pattern with the clone() method from the Java API. We are checking if the object was successfully cloned.

checkIfTheObjectWasCopiedByBeanUtilsTest: This is an alternative way to solve this problem. We can use the utility class BeanUtils from the Spring dependency. We have to add it to the pom.xml:
        org.springframework
        spring-beans
        4.3.9.RELEASE

There are some cons about using this class:

1 – We must create getters and setters. We can’t encapsulate them.
2 – The copy is done by Reflection. It’s very slow.
3 – We must copy the objects manually.

public class PrototypeTest {

	// Constants omitted.

	@Test
	public void checkIfTheObjectWasClonedTest() {
		Contract contract = mockContract();

		Contract contractPrototype = (Contract) contract.clone();

		checkIfTheObjectsAreCloned(contract, contractPrototype);
	}

	@Test
	public void checkIfTheObjectWasCopiedByBeanUtilsTest() throws IllegalAccessException, InvocationTargetException {
		Contract contract = mockContract();

		Contract contractToBeCopied = new Contract();
		ContractComplement complementContractToBeCopied = new ContractComplement();

		BeanUtils.copyProperties(contract, contractToBeCopied);
		BeanUtils.copyProperties(contract.getContractComplement(), complementContractToBeCopied);

		contractToBeCopied.setContractComplement(complementContractToBeCopied);

		checkIfTheObjectsAreCloned(contract, contractToBeCopied);
	}

	private Contract mockContract() {
		ContractComplement complement = new ContractComplement(COMPLEMENT_NAME, QTD_CUSTOMERS);

		Contract contract = new Contract(ID_CONTRACT, CONTRACT_NAME, complement, CONTRACT_VALUE);
		return contract;
	}

	private void checkIfTheObjectsAreCloned(Contract contract, Contract contractToBeCopied) {
		Assert.assertTrue(contract.getId() == contractToBeCopied.getId());
		Assert.assertTrue(contract.getName().equals(contractToBeCopied.getName()));
		Assert.assertTrue(contract.getPrice().equals(contractToBeCopied.getPrice()));

		ContractComplement complement = contract.getContractComplement();
		ContractComplement copiedComplement = contractToBeCopied.getContractComplement();

		Assert.assertTrue(complement.getComplementName().equals(copiedComplement.getComplementName()));
		Assert.assertTrue(complement.getSpecificProductPrice().equals(copiedComplement.getSpecificProductPrice()));

		Assert.assertFalse(contract.equals(contractToBeCopied));
		Assert.assertFalse(contract.getContractComplement().equals(contractToBeCopied.getContractComplement()));
	}

}

Summary of actions:

1 – Implemented the Cloneable interface.
2 – Overrode the clone() method.
3 – Changed the visibility of the clone() method to public.
4 – Invoked the super.clone() method.
5 – Made a copy of ContractComplement in the clone() method explicitly.

To practice the Prototype Pattern you can create another POJO, implement the Cloneable interface and make the Deep Copy! Try to use TDD (Test Driven Development). Start the development from the test.

Design Patterns SAGA #4: Real Project Situations With Prototype

Java Challenge #9: Tokenizer

It is so important to know that Tokenizer exists and to know what tools you have available to make your code powerful!

Try to solve this challenge before seeing the answer below.

tokenizer.jpg

Answer: This is an easy one. We created the object Scanner passing the String to be tokenized, separated by a pattern. At first, you’ve got to know what the symbols on the tokens mean.

This symbol is called Regex. Many languages use the same concept:
http://www.vogella.com/tutorials/JavaRegularExpressions/article.html

In simple words, this symbol “[^\\w*]” means “not a word” so it will tokenize by the comma “,“.

The result is:
ThisIsIt
theFinalString
NoBugsProject

Java Challenge #9: Tokenizer

Java Challenge #8: Enums Implementing Interfaces

Enums, do you really master them? Can you tell me if it’s going to compile? If not, explain why. If so, write the result.

Try to solve this challenge before seeing the answer below.

enumchallenge.jpg

Answer: The first thing to observe is the implementation of the interface Invoker on the Enum. It’s not very common to do this, but it’s possible. When we access the Enum reference of the reference it does not make a difference. The invokeShenLong() method will be invoked in the same way bringing all the Enums declared on DragonBalls. When we enter in the loop, we are not using brackets ({}) on the “if” command. This means that only one line will be executed.

Conclusion: Until the Enums are equaled, the looping will continue. In the end, the iterated Enums will be FIFTH and equal to one another.

The output will be:
Same dragon ball
FIFTH

Java Challenge #8: Enums Implementing Interfaces

JAVA CHALLENGE #7: Interfaces and Abstract classes

Who is stronger? Master Yoda or Darth Vader? What will the output be? Solve this challenge and find out!

Before seeing the answer below, try it out!

starwarschallenge.jpg

Answer: At first we create an anonymous inner class of Darth Vader, that means any class that implements DarthVader interface. We have only one getNumber() method.

With MasterYoda, things are different. We created an abstract class with the getNumber() method and another one in the inner class of MasterYoda. This is the same as DarthVader, it is an anonymous inner class. This challenge is pretty tricky because you can see that there is a method overloading both methods. Which one will be invoked? See that we are passing a new Integer(FORCE) for the getNumber() method. For this reason, the method from the abstract class will be invoked and MasterYoda will have the force of 20.

The answer is:
30
The stronger Jedi is: Master Yoda

May the force be with you!

JAVA CHALLENGE #7: Interfaces and Abstract classes