The Flyweight Structural Pattern in Java

Intent: Considered as a structural pattern, the flyweight pattern helps in sharing the objects efficiently. Motivation: In situations where you need to create several objects and many of the them may represent the same value. In these instances, it is possible to share the values as long as the objects are immutable. Implementation: A good…

Building objects with the Builder Pattern

Another pattern used to create objects is the builder pattern. Intent: If you needed to create an object that requires many values to be set at the time the object is instantiated. Motivation: With the data objects in an application growing, the constructors also grow to contain many attributes. For example, in the Book class…

How to Create Immutable Objects in Java

Immutable objects pattern is one of the creational patterns. If you have to create read-only objects that can be shared and used by multiple classes then making the objects immutable will be a good pattern choice. Motivation: If you want to create objects that can be shared across multiple classes, but for some security reasons…

The JUnit Test Life Cycle

Running a test suite in JUnit follows a defined set of steps. These steps can help you modularize the tests and reuse as much code as possible. The annotations were introduced in JUnit 4 (before JUnit 4 you would need your class to extend TestSuite) . If you have some computations, such as preparing the…

Virtual Methods in Java

Virtual methods in Java are all non-static methods. Virtual method invocation means that Java will look at the subclass when trying to find the right method to call. Let’s examine an example of using virtual method invocation: Consider a method that takes an input an Animal reference and performs some operations based on the type…

Factorial Function with Java

Let’s say you needed a utility function to calculate the factorial of a number. Below is an example preceded with its test function (in a TDD approach). The unit test would look like this: And the function like this: