Java Challenge #2: Is It Going to Compile?

Is it going to compile? If not, why? If you think it’s going to compile, what will happen? What will be the output?

Try to solve this challenge before seeing the answer below.

is_it_going_to_compile.jpg

Answer: It is going to compile! You see, the variable can be created with a class name, no problem. We can use the semicolon “;” several times too.

The char array declaration can be done as shown above. Later, maybe in a vector challenge, I can explain what happens when brackets “[]” are put before the variable.

doesthisCompile: Yes again. This command, called label, can be used for controlling external loopings with “continue” or “break” command, for example.

We can use System.out.println on the looping and we don’t have to use a condition in the second part of the “for”.

Java Challenge #2: Is It Going to Compile?

Java Challenge #1: String Pool

Every time we create a different String, an object is created in the pool. How many objects were created in this situation?

Try to solve this challenge before seeing the answer below.

String_pool.jpg

Answer: 3 Strings and 1 StringBuilder are created in the concatenation. For performance reasons, the JVM creates a pool of Strings. When a String with the same value is created, the JVM does not create another object in the pool.

Java Challenge #1: String Pool

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

8 Mistakes Java Developers Make that Negatively Affect their Skills

The problem: lack of knowledge causes bad quality code. You won’t be able to implement the best solution if you don’t know, for example, the language, framework, or any other technology with which you work.

You will probably reinvent the wheel many times if you don’t know at least the basics of the technology you are working with.

1 – Not studying at home

In the IT world we must be updated all the time, it’s crucial for our careers to study new technologies, use them and understand why they are important.

More important is to understand a new paradigm, because this is what takes time to learn. Instead of learning languages with the same paradigms, try to learn Clojure that uses Functional Programming in a very strong way. Don’t think it’s enough to just work with the technology, the concepts must be absorbed as well.

2 – Lack of discipline

Discipline? I don’t have discipline, that is a Japanese thing! Do you really think like this? If so, you are wrong, everyone can have discipline. It’s a matter of habit. Discipline is not easy, it takes effort to do what you must do!

Do not fall into the trap of your brain – just one more day, I will do it tomorrow. No!!!!!!! Do it now!!!! Do it as fast as you can!!!! Don’t get manipulated by yourself, focus on what is important to you and do it!!!!

You can try to use a calendar and schedule the times you are going to study.

In my case, I don’t like to use a calendar to study. I like to be flexible and study whenever I want, but I always complete a minimum number of study hours every week.

So, create a weekly goal and work toward it. Your goal could be to study 5, 15, 20, 30 hours each week – you know how much you can handle. The important thing is to follow your goal!

Apps like My Study Life and iStudiez can help you create a personalized study plan and track your progress.

3 – Using excuses

It’s another trap we must get rid of! Even without noticing, your brain will create a lot of excuses, it will say, “Oh, today I can’t study because I have to watch sports” or “Today I can’t because I am too tired” or “Today I have cook” or “Today I am going to the pub.”

I know all of the things I mentioned consume time, but it’s possible to manage your time and apply yourself to your goal. Even if it’s almost impossible for you, you can study at least 5 minutes every day.

4 – Think you already know everything

It’s common for developers to think they know everything because they are comfortable in the companies they work for. But the truth is, you never know what will happen tomorrow – you may lose your job suddenly, the company could go bankrupt or they may change their technology. If this happens, you could be in trouble.

Don’t wait until one of these situations happens to you. Be prepared! It takes time, dedication and studying to keep your skills up-to-date. You don’t want to be out of a job and hurrying to learn new skills. You may be a great developer, but no one knows everything.  Studying is a necessity!

5 – Not knowing your learning style

Learning style? What is this? Your learning style is the way you learn best. Finding out your learning style can help you learn things faster and more effectively.

What style learner are you?

A visual learner? (Seeing – Pictures, Diagrams, Graphics)

An auditory learner? (Hearing – Discussions, Dialogs, Music)

A kinesthetic learner? (Moving – Studying while exercising)

A tactile learner? (Touching – Practical activities, Podcasts)

Do you like reading books? Face-to-face courses? Listening to a podcast? Speaking to people? Once you have your answer, you can match your studies to your learning style. You can mix all of these styles, but you should focus on your dominant style to maximize your results.

6 – Not knowing the best sources of knowledge

Once you know your learning style, I will refer some sources here:

Online courses

Plural Sight

Code School

EDX

Coursera

Alura

Books

You should find the book of what you need. Don’t read everything. Read what can help you in your life.

Podcasts

Java Pub House

How to Program with Java

Enterprise Java Newscast

The Java Posse

Illegal Argument

7 – Not knowing how to manage your time

I don’t like to have fixed time for everything, you may like this. Find out how you work best. I like to define how many hours I am going to study during the week. If I can’t study on a particular day for some reason, I will compensate for these hours on another day. I like to be flexible.

But again, it’s up to you. Find what is most suitable for you and then  accomplish your goal!

8 – Not optimizing your time

We think we don’t have time for anything, but actually we do! If you commute to work by car, you can listen to a podcast. If you commute by bus, you can read a book. For example, if you spend 2 hours every day commuting, this means you have 10 hours per week and 40 hours per month to take advantage of! Don’t waste these valuable hours! Learn how to optimize your time and make every minute valuable! You will see the results!

8 Mistakes Java Developers Make that Negatively Affect their Skills