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

11 Mistakes Java Developers make when Using Exceptions

The problem: If you use Exceptions in the wrong way, bugs will be very difficult to find. If you always use generic Exceptions, how can other developers know what error has occurred? You have to understand why we use Exceptions and how to use them effectively!

See the 11 mistakes Java Developers make when using Exceptions.

First, let’s see the hierarchy of the Exception classes.

Checked Exceptions / Unchecked Exceptions

1 – Using only the Exception class

It’s a common mistake that developers specifically catch the Exception class for any error. It’s much more difficult to identify the error if you see only an Exception being caught. The solution to this problem is to create specific Exceptions – but watch out, not too specific!

2 – Creating lots of specific Exceptions

Don’t create Exceptions for everything. Your application will be full of classes, useless repetition and you will create unnecessary work. Instead, create Exceptions for really important business requirements. For example, if you are developing a bank system one possible Exception would be when trying to withdraw money and the balance is zero: BalanceNotAvailableException. Another Exception would be transferring money to another person and the account does not exist, you can create: BankAccountNotFoundException and show an understandable Exception message to the user.

RuntimeException could be used when the bank’s server is out of service. Here you can use, for example: ServerNotAvailableException. The system must crash for this kind of error. There is no recovery.

3 – Creating a log for every catch

Logging every Exception catch will pollute your code. To prevent this, just log once and throw your Exception in the last catch. You won’t lose your Stacktrace if you wrap the Exception. If you are working with web applications, you should create a catch on your controller layer and log the error.

4 – Not knowing the difference between Checked and Unchecked Exceptions

When should Checked Exceptions be used? Use Checked when there is a recoverable error or an important business requirement.

The most common Checked Exception is the Exception class. Two related classes from Exception are FileNotFoundException and SQLException.You are obligated to handle or declare these exceptions. You must throw or catch the Exception or else it won’t compile.

When should Unchecked Exceptions be used? Use Unchecked when there is no recovery. For example, when the memory of the server is overused.

RuntimeException is used for errors when your application can not recover. For example, NullPointerException and ArrayOutOfBoundsException. You can avoid a RuntimeException with an ‘if’ command. You should not handle or catch it.

There is also the class Error. It is an Unchecked Exception too. Never try to catch or handle this kind of Exception. They are errors from the JVM and are the most serious kind of Exception in Java. You must analyze the cause of Exceptions like this and change your code.

5 –  Silencing Exceptions

Never catch the Exception and do nothing, for example:

try {
    System.out.println("Never do that!");
} catch (AnyException exception) {
    // Do nothing
}

The catch will be useless. It’s impossible to know what happened and the Exception will be silenced. The developer will be obliged to debug the code and see what happened. If we create a good log, the time-consuming analysis won’t be necessary.

6 – Not following the principle “throw early, catch late”

If you have to handle Exception, for example, in your Service, you should do two things:

  1. Wrap your Exception
  2. Throw the Exception to the last catch and handle it.

7 – Not using clear messages on the Exceptions

Always use clear messages on your Exceptions. Doing this will help a lot when finding errors. Even better, create a Properties File with all Exception messages. You can use the file on your View layer and show users messages about the business requirements.

8- Not cleaning up after handling the Exception

After using resources like files and database connection, clean them and close them so that you won’t harm the system’s performance. You can use the finally block to do it.

9 – Not documenting Exceptions with javadoc

To avoid headaches, always Document why the Exception is being thrown in your method. Document your Exception and explain why you created it.

10 – Never lose the Stacktrace

When wrapping an Exception in another one, don’t just throw the other Exception, keep the Stacktrace.

Bad code:

try {
    // Do the logic
} catch (BankAccountNotFoundException exception) {
    throw new BusinessException();
}

Good code:

try {
    // Do the logic
} catch (BankAccountNotFoundException exception) {
    throw new BusinessException(exception);
}

11 – Not organizing the hierarchy of specific Exceptions

If you don’t organize the hierarchy of your Exceptions, the relationship will be difficult between the parts of the system. You will have lots of problems.

You should use an hierarchy similar to this one:

                                                                                     Exception

BusinessException

AccountingException

HumanResourcesException
BillingCodeNotFoundException

  EmployeeNotFoundException

11 Mistakes Java Developers make when Using Exceptions

5 Great Programming Techniques Every Developer Should Know

1 – Encapsulate ifs inside their methods, not outside them:

Bad example:


If (value > 500) {

     applyDiscountForGreaterThan500();

} else if (value > 1000) {

     applyDiscountForGreaterThan1000();

}

Good example:

// encapsulated ifs in the methods 

applyDiscountIfValueIsGreaterThan500(); 

applyDiscountIfValueIsGreaterThan1000();

2 – Stop a moment to think about the name of the package/class/method/variable

YES, names are EXTREMELY important.

With a self-describing name, it is very easy to find out what your code is doing.

For this reason, do not use the first name that pops into your head. Think about the best possible name that describes exactly for what your package, class, method, variable is responsible.

Avoid ambiguous names! If a bug occurs in this functionality, it will be very difficult to find it.

Examples of ambiguous names:

 Double clientValue; // Value of the client, value of what?

 void hide() // What does that hide?

 class Historic {} // Historic of what? Historic for everything? 
  //Where is the cohesion? 

Specific names help A LOT!

3 – Get to know the shortcuts of your IDE

I am going to use Eclipse’s example. It’s very important to use the shortcuts so you can code two or three times faster.

Control + 3 = “Eclipse’s Google” – write “new class” for example.

Control + shift + F = format your code.

Control + 1 = do various actions. For example, invoke a method that does not exist yet and use the shortcut.

Alt + up = moves a line of code to the above line.

Control + shift + R = search any archive you want on your project.

Control + H = search any word you want on your project.

Alt + Shift + R = rename any package, class, method, variable and update all the references.

Configure Eclipse’s formatter. Change it from 80 characters per line to 120. Configure save actions too so you can have actions when you save your code on Eclipse. For example, we can use the command “organize imports” after each save.

There are many other shortcuts, but remember, you need to use them until they get automatic for you. If you forgot to use the shortcut, undo what you did without using the shortcut and then, do the same thing using the shortcut, so you’ll never forget it. For example, if you are going to delete a code line and you forget to use the shortcut, just undo it and use the shortcut control + D.

More sources:

Eclipse Shortcuts

Netbeans Shortcuts

IntelliJ Shortcuts

4 – Encapsulate methods for what you need

Have you noticed a lot of code in your application that does the same thing?

Why not encapsulate a method for this?

For example:

Calendar c = Calendar.getInstance();

c.setTime(new Date());

c.add(Calendar.DATE, +1);

Date userDate = c.getTime();

It would be a lot easier and much clearer to encapsulate all this code in a separated class and method:

Date nextDay = DateUtils.getNextDay();

Consider if need to keep state of your object, if so, instantiate it!

Remember, the most important thing here, is to encapsulate your solution!

5 – Create the culture of Code Review in your company

Even if the company you work for doesn’t use a Code Review tool, ask your friend to take a look at your code.

Each developer has his own experiences. We can learn a lot by sharing them.

Many things that you may not have noticed in a simple Code Review could be uncovered in a peer Code Review. You will see your mistakes and learn from them!

Follow me on Twitter to learn more great programming techniques. I will be sending a new one each week!

For learning new techniques every week, subscribe here on NoBugsProject email list!

Remember, practicing these techniques will make you an even greater developer.

5 Great Programming Techniques Every Developer Should Know