Creational Design Patterns: Singleton Pattern

The singleton design pattern is a software design pattern the restricts the the instantiation of a class to one object.
In comparison with other creational design patterns such as the abstract factory, factory and the builder pattern the singleton will create an object but will also be responsible so that only one instance of that object exists.

When creating a class as a singleton there are some certain problems that is has to tackle.

  • How can it be ensured that a class has only one instance.
  • How can the sole instance of a class be accessed easily
  • How can a class control its instantiation
  • How can the number of instances of a class be restricted

 

Suppose we have a class that sends messages.
The Messenger class.

package com.gkatzioura.design.creational.singleton;

public class Messenger {

    public void send(String message) {
        
    }
}

However we want the message procedure to be handled only by one instance of the Messenger class. Imagine the scenario where the Messenger class opens a tcp connection (for example xmpp) and has to keep the connection alive in order to send messages. It will be pretty inefficient to open a new xmpp connection each time we have to sent a message.

Therefore we will proceed and make the messenger class a singleton.

package com.gkatzioura.design.creational.singleton;

public class Messenger {

    private static Messenger messenger = new Messenger();

    private Messenger() {}

    public static Messenger getInstance() {
        return messenger;
    }

    public void send(String message) {

    }
}

As you can see we set the messenger constructor as private, and we initialized a messenger using a static variable.
Static variables are class level variables, memory allocation only happens once when the class is loaded in the memory. By this way we ensure that the messenger class will be instantiated only once.
The getInstance method will fetch the static messenger instance once called.

Obviously the previous approach has its pros and cons.
We don’t have to worry on thread safety and the instance will be created only when the Messenger class will be loaded. However it lacks in flexibility. Consider the scenario of passing configuration variables to the Messenger constructor. It is not possible using the previous approach.

A workaround is to instantiate the messenger class on the getInstance method.

package com.gkatzioura.design.creational.singleton.lait;

public class Messenger {

    private static Messenger messenger;

    private Messenger() {}

    public static Messenger getInstance() {

        if(messenger==null) {
            messenger = new Messenger();
        }

        return messenger;
    }
    
    public void send(String message) {

    }
}

The above approach might work in certain case but it misses on thread safety in cases where the class might get instantiated in a multithreaded environment.

The easiest approach to make our class thread safe is to synchronize the getInstance method.

package com.gkatzioura.design.creational.singleton.lait;

public class Messenger {

    private static Messenger messenger;

    private Messenger() {}

    public synchronized static Messenger getInstance() {

        if(messenger==null) {
            messenger = new Messenger();
        }

        return messenger;
    }

    public void send(String message) {

    }
}

That one will work. At least the creation of the messenger will be synchronized and no duplicates will be created.
The problem with this approach is that the synchronization is only needed once when the object is created. Using the above code will lead to unnecessary overhead.

The other approach is to use the Double-Checked Locking approach. Now Double-Checked locking needs extra care since it is easy to pick the broken implementation over the correct one.
The best approach is to implement lazy loading using the volatile keyword.

package com.gkatzioura.design.creational.singleton.dcl;

public class Messenger {

    private static final Object lock = new Object();
    private static volatile Messenger messenger;

    private Messenger() {}

    public static Messenger getInstance() {

        if(messenger==null) {
            synchronized (lock) {
                if(messenger==null) {
                    messenger = new Messenger();
                }
            }
        }

        return messenger;
    }

    public void send(String message) {

    }
}

By using the volatile keyword we prevent the write of a volatile to be reordered with respect to any previous read or write and a read of a volatile to be reordered with respect to any following read or write.
Also a mutex object is used to achieve synchronization.

To sum up we created an object and we also made sure that there will be only one instance of that object. Also we made sure that there won’t be any problem on instantiating the object in a multi-threaded environment.

You can find the sourcecode on github.

On the next blog post we will have a look at the prototype pattern.

Also I have compiled a cheat sheet containing a summary of the Creational Design Patterns.
Sign up in the link to receive it.

Creational Design Patterns: Builder Pattern

Previously we had a look at the factory and the abstract factory pattern. Those patterns serve their purpose and can be really useful however there are use cases where we have to create a very complex object and creating it requires different steps each one requiring different actions. In such cases the builder pattern can be really useful.
The builder design pattern is a creational design pattern and can be used in order to create complex objects step by step.

Supposing we have an object with many dependencies and in order to acquire each one these dependencies some certain actions have to be issued.
In such cases we can use the builder pattern in order to

  • Encapsulate creating and assembling the parts of a complex object in a separate Builder object.
  • Delegate the object creation to a Builder object instead of creating the objects directly.

Imagine the scenario of a backend system that has to compose and sent emails.
Creating an email might be a complex procedure. You have to specify the title, set the recipients, add a greeting add a closing statement. You might also want to use mustache instead. There is a wide range of options.

Having one class for all the actions needed to create an email might make our class bloated and loose its original purpose.

So we will start with the class responsible for sending the email.

package com.gkatzioura.design.creational.builder;

public class Email {

    private final String title;
    private final String recipients;
    private final String message;

    public Email(String title, String recipients, String message) {
        this.title = title;
        this.recipients = recipients;
        this.message = message;
    }

    public String getTitle() {
        return title;
    }

    public String getRecipients() {
        return recipients;
    }

    public String getMessage() {
        return message;
    }

    public void send() {

    }
}

As you can see the class contains only three string fields and there is no extra processing on them. So we shall create a builder class which will handle the message formatting, the recipient representation and the creation of the Email class.

package com.gkatzioura.design.creational.builder;

import java.util.HashSet;
import java.util.Set;

public class EmailBuilder {

    private Set recipients = new HashSet();
    private String title;
    private String greeting;
    private String mainText;
    private String closing;

    public EmailBuilder addRecipient(String recipient) {
        this.recipients.add(recipient);
        return this;
    }

    public EmailBuilder removeRecipient(String recipient) {
        this.recipients.remove(recipient);
        return this;
    }

    public EmailBuilder setTitle(String title) {
        this.title = title;
        return this;
    }

    public EmailBuilder setGreeting(String greeting) {
        this.greeting = greeting;
        return this;
    }

    public EmailBuilder setMainText(String mainText) {
        this.mainText = mainText;
        return this;
    }

    public EmailBuilder setClosing(String closing) {
        this.closing = closing;
        return this;
    }

    public Email create() {

        String message = greeting+"\n"+mainText+"\n"+closing;
        String recipientSection = commaSeparatedRecipients();

        return new Email(title,recipientSection,message);
    }

    private String commaSeparatedRecipients() {

        StringBuilder sb = new StringBuilder();
        for(String recipient:recipients) {
            sb.append(",").append(recipient);
        }

        return sb.toString().replaceFirst(",","");
    }

}

The next is step to make the email creation more strict so that creating an Email would only be possible through the EmailBuilder.

package com.gkatzioura.design.creational.builder;

import java.util.HashSet;
import java.util.Set;

public class Email {

    private final String title;
    private final String recipients;
    private final String message;

    private Email(String title, String recipients, String message) {
        this.title = title;
        this.recipients = recipients;
        this.message = message;
    }

    public String getTitle() {
        return title;
    }

    public String getRecipients() {
        return recipients;
    }

    public String getMessage() {
        return message;
    }

    public void send() {

    }

    public static class EmailBuilder {

        private Set recipients = new HashSet();
        private String title;
        private String greeting;
        private String mainText;
        private String closing;

        public EmailBuilder addRecipient(String recipient) {
            this.recipients.add(recipient);
            return this;
        }

        public EmailBuilder removeRecipient(String recipient) {
            this.recipients.remove(recipient);
            return this;
        }

        public EmailBuilder setTitle(String title) {
            this.title = title;
            return this;
        }

        public EmailBuilder setGreeting(String greeting) {
            this.greeting = greeting;
            return this;
        }

        public EmailBuilder setMainText(String mainText) {
            this.mainText = mainText;
            return this;
        }

        public EmailBuilder setClosing(String closing) {
            this.closing = closing;
            return this;
        }

        public Email build() {

            String message = greeting+"\n"+mainText+"\n"+closing;
            String recipientSection = commaSeparatedRecipients();

            return new Email(title,recipientSection,message);
        }

        private String commaSeparatedRecipients() {

            StringBuilder sb = new StringBuilder();
            for(String recipient:recipients) {
                sb.append(",").append(recipient);
            }

            return sb.toString().replaceFirst(",","");
        }

    }
}

The end result of using the builder pattern for creating an email will be like this.

Email email = new Email.EmailBuilder()
    .addRecipient("john@Doe.com")
    .setMainText("Check the builder pattern")
    .setGreeting("Hi John!")
    .setClosing("Regards")
    .setTitle("Builder pattern resources")
    .build();

To summarize by using the builder pattern we were able to create a complex object and its complex parts.

You can find the sourcecode on github.

On the next blog we will talk about the singleton pattern.

Also I have compiled a cheat sheet containing a summary of the Creational Design Patterns.
Sign up in the link to receive it.

Creational Design Patterns: Factory Pattern

Previously we had an introduction to the Creational Patterns and used the Abstract Factory Pattern in order to create a families of objects.

The next pattern is the Factory Pattern. Factory pattern is one of the most used patterns when it comes to Java.
So what is the Factory Pattern all about? The factory pattern deals with creating objects without specifying the exact class or the object that will be created.

Let’s get into action by using the factory pattern for a Voucher problem.
Supposing we have a loyalty feature in our application which, depending on the customer’s transactions, rewards the customer with some vouchers.
The voucher requires a voucher code and since it will be displayed on the application it requires a specially formatted html message.

The first step is to create the voucher interface.

package com.gkatzioura.design.creational.factory;

public interface Voucher {

    public String code();

    public String htmlMessage();
}

We will have two types of Vouchers for now however it will be easy to add more once the business people come with more ideas.

The first one is the food Voucher.

package com.gkatzioura.design.creational.factory;

import java.util.UUID;

public class FoodVoucher implements Voucher {

    private UUID code;
    private static final String htmlMessage= "<html><body>
<h1>Food Voucher</h1>

</body></html>";

    public FoodVoucher() {
        code = UUID.randomUUID();
    }

    public String code() {
        return code.toString();
    }

    public String htmlMessage() {
        return htmlMessage;
    }
}

And the second one it the clothes voucher.

package com.gkatzioura.design.creational.factory;

import java.util.UUID;

public class ClothesVoucher implements Voucher {

    private UUID code;
    private static final String htmlMessage = "<html><body>
<h1>Clothes Voucher</h1>

</body></html>";

    public ClothesVoucher() {
        code = UUID.randomUUID();
    }

    public String code() {
        return code.toString();
    }

    public String htmlMessage() {
        return htmlMessage;
    }
}

The vouchers will be created based on a transaction-points system.
The food voucher will be created in cases of less than 30 transaction points. For transaction-points higher than 30 the clothes voucher shall be created.
So the next step is to create the mechanism that will create the vouchers based on the transaction points.
The best candidate for this is the Factory Pattern.

package com.gkatzioura.design.creational.factory;

public class VoucherFactory {

    public Voucher create(Integer discountPoints) {

        if(discountPoints<=0) {
            throw new IllegalArgumentException("Invalid number of discount points!");
        }

        if(discountPoints<30) {
            return new FoodVoucher();
        } else {
            return new ClothesVoucher();
        }
    }

}

To sum up by choosing the factory pattern

  • We create the vouchers needed without exposing to the client any creation logic.
  • The client does not have to specify the exact class of the object that will be created.

You can find the source code on github.

On the next blog post we will have a look at the builder pattern.

Also I have compiled a cheat sheet containing a summary of the Creational Design Patterns.
Sign up in the link to receive it.

Creational Design Patterns: Abstract Factory Pattern

The Abstract Factory Pattern is a creational pattern and is one of the most popular patterns along with the builder and the factory pattern. Creational patterns are used in order to create objects instead of creating objects directly using a constructor.

The Abstract Factory Pattern provides a way to encapsulate a group of individual factories that have a common theme without specifying their concrete classes.

The intent in employing the pattern is to insulate the creation of objects from their usage and to create families of related objects without having to depend on their concrete classes.

By using that pattern the client doesn’t have to be aware of the objects and their implementation details. It is a responsibility of the Abstract Factory’s Implementation to implement the objects and handle all the details in order to do that successfully.

So let’s get into action and start solving problems.
Supposing we are responsible for the canning process of various products.
Regarding the canning procedure there are two objects that have to be created. The can’s main body and the can’s top.
Also considering the fact that we might have various forms of canning we might as well have various factories which can handle the canning process. For example we might have a factory for beer canning or a factory for food canning.

Regarding the description above it seems that abstract factory is the way to go. We do have a family of objects and we do want to hide the construction of these objects.

We will start by adding two interfaces regarding the functionality of a can’s top and a can’s body.

package com.gkatzioura.design.creational.abstractfactory;

public interface CanTop {

    void open();

}
package com.gkatzioura.design.creational.abstractfactory;

public interface CanBody {

    void fill();

}

Then we shall create an abstract factory which will provide the methods to implement in order to create those objects.

package com.gkatzioura.design.creational.abstractfactory;

public abstract class CanningFactory {

    public abstract CanTop createTop();

    public abstract CanBody createBody();

}

As mentioned we have cases of beer canning. Thus we will have implementations of the CanTop and the CanBody class.

package com.gkatzioura.design.creational.abstractfactory.beer;

import com.gkatzioura.design.creational.abstractfactory.CanTop;

public class BeerCanTop implements CanTop {

    public void open() {

    }
}
package com.gkatzioura.design.creational.abstractfactory.beer;

import com.gkatzioura.design.creational.abstractfactory.CanBody;

public class BeerCanBody implements CanBody {

    public void fill() {

    }
}

Then we shall implement a Beer Canning Factory.

package com.gkatzioura.design.creational.abstractfactory.beer;

import com.gkatzioura.design.creational.abstractfactory.CanBody;
import com.gkatzioura.design.creational.abstractfactory.CanTop;
import com.gkatzioura.design.creational.abstractfactory.CanningFactory;

public class BeerCanningFactory extends CanningFactory {

    public CanTop createTop() {
        return new BeerCanTop();
    }

    public CanBody createBody() {
        return new BeerCanBody();
    }

}

The other case is food canning. We will provide implementations of the CanTop and CanBody class for this case too.

package com.gkatzioura.design.creational.abstractfactory.food;

import com.gkatzioura.design.creational.abstractfactory.CanBody;

public class FoodCanBody implements CanBody {

    public void fill() {

    }
}
package com.gkatzioura.design.creational.abstractfactory.food;

import com.gkatzioura.design.creational.abstractfactory.CanTop;

public class FoodCanTop implements CanTop {

    public void open() {

    }
}

As a last step we will provide the abstract factory implementation for cases of food canning.

package com.gkatzioura.design.creational.abstractfactory.food;

import com.gkatzioura.design.creational.abstractfactory.CanBody;
import com.gkatzioura.design.creational.abstractfactory.CanTop;
import com.gkatzioura.design.creational.abstractfactory.CanningFactory;

public class FoodCanningFactory extends CanningFactory {

    public CanTop createTop() {
        return new FoodCanTop();
    }

    public CanBody createBody() {
        return new FoodCanBody();
    }

}

What we just did is using the abstract factory pattern in order to create a family of objects regarding the canning process. We insulated the creation process from the usage of the CanTop and CanBody. Also we are able to create a family of objects without depending on their concrete classes.

You can find the sourcecode on github.

On the next blog post we will have a look at the Factory Pattern.

Also I have compiled a cheat sheet containing a summary of the Creational Design Patterns.
Sign up in the link to receive it.

Solid Principles: Dependency inversion principle

Up until now we had a look on the single responsibility, open/closed, liskov substitution and interface segregation principles.
Dependency Inversion is one of the last principle we are gone look at.
The principle states that

A. High-level modules should not depend on low-level modules. Both should depend on abstractions.
B. Abstractions should not depend on details. Details should depend on abstractions.

Let’s get started with some code that violates that principle.
As a software team and we need to implement a project. For now the software team consists of:

A BackEnd Developer

package com.gkatzioura.solid.di;

public class BackEndDeveloper {

    public void writeJava() {
    }
}

And a FrontEnd developer

package com.gkatzioura.solid.di;

public class FrontEndDeveloper {

    public void writeJavascript() {
    }

}

And our project uses both throughout the development process.

package com.gkatzioura.solid.di;

public class Project {

    private BackEndDeveloper backEndDeveloper = new BackEndDeveloper();
    private FrontEndDeveloper frontEndDeveloper = new FrontEndDeveloper();

    public void implement() {

        backEndDeveloper.writeJava();
        frontEndDeveloper.writeJavascript();
    }

}

So as we can see the Project class is a high level module and it depends on low level modules such as BackEndDeveloper and FrontEndDeveloper. We are actually violating the first part of the dependency inversion principle.

Also by the inspecting the implement function of the Project.class we realise that the methods writeJava and writeJavascript are methods bound to the corresponding classes. Regarding the project scope those are details since in both cases they are forms of development. Thus the second part of the dependency inversion principle is violated.

In order to tackle this problem we shall implement and interface called the Developer interface.

package com.gkatzioura.solid.di;

public interface Developer {

    void develop();
}

Therefore we introduce an abstraction.

The BackEndDeveloper shall be refactored to

package com.gkatzioura.solid.di;

public class BackEndDeveloper implements Developer {

    @Override 
    public void develop() {
        writeJava();
    }
    
    private void writeJava() {
    }
    
}

And the FrontEndDeveloper shall be refactored to

package com.gkatzioura.solid.di;

public class FrontEndDeveloper implements Developer {

    @Override 
    public void develop() {
        writeJavascript();
    }
    
    public void writeJavascript() {
    }
    
}

The next step in order to tackle the violation of the first part would be to refactor the Project class so that it will not depend on the FrontEndDeveloper and the BackendDeveloper class.

package com.gkatzioura.solid.di;

import java.util.List;

public class Project {

    private List<Developer> developers;
    
    public Project(List<Developer> developers) {
    
        this.developers = developers;
    }

    public void implement() {

        developers.forEach(d->d.develop());
    }

}

The outcome is that the Project class does not depend on lower level modules but abstractions. Also low-level modules and their details depend on abstractions.

You can find the source code on github.

Also I have compiled a cheat sheet containing a summary of the solid principles.
Sign up in the link to receive it.

Solid Principles: Interface segregation principle

Previously we examined the liskov substitution principle. Next principle is the interface-segregation. The interface-segregation principle (ISP) states that no client should be forced to depend on methods it does not use.

Imagine an interface with many methods in our codebase and many of our classes implement this interface although only some of its methods are implemented.

In our case the Athlete interface is an interface with some actions of an athlete.

package com.gkatzioura.solid.segragation;

public interface Athlete {

    void compete();

    void swim();

    void highJump();

    void longJump();

}

We have added the method compete but also there some extra methods like swim highJump and longJump.
Suppose that JohnDoe is a swimming athlete. By implementing the Athlete interface we have to implement methods like highJump and longJump which JohnDoe will never use.

package com.gkatzioura.solid.segragation;

public class JohnDoe implements Athlete {

    @Override
    public void compete() {
        System.out.println("John Doe started competing");
    }

    @Override
    public void swim() {
        System.out.println("John Doe started swimming");
    }

    @Override
    public void highJump() {
    }

    @Override
    public void longJump() {
    }
}

The same problem will occur for another athlete who might be a field Athlete competing on high jump and long jump.
We will follow the interface segregation principle and we will refactor the original interface

package com.gkatzioura.solid.segragation;

public interface Athlete {

void compete();
}

Then we will create two other interfaces one for Jumping athletes and one for Swimming athletes.

package com.gkatzioura.solid.segragation;

public interface SwimmingAthlete extends Athlete {

    void swim();

}
package com.gkatzioura.solid.segragation;

public interface JumpingAthlete extends Athlete {

    void highJump();

    void longJump();

}

And therefore John Doe will not have to implement actions that he is not capable of performing.

package com.gkatzioura.solid.segragation;

public class JohnDoe implements SwimmingAthlete {

    @Override
    public void compete() {
        System.out.println("John Doe started competing");
    }

    @Override
    public void swim() {
        System.out.println("John Doe started swimming");
    }

}

You can find the source code on github. The last principle is the dependency inversion principle.

Also I have compiled a cheat sheet containing a summary of the solid principles.
Sign up in the link to receive it.

Solid Principles: Liskov substitution principle

Previously we took a dive into solid principles including the single responsibility and the open/closed principle.
The Liskov substitution principle (LSP) is a particular definition of a subtyping relation, called (strong) behavioral subtyping,

Supposing object S is a subtype of object T, then objects of type T may be replaced with objects of type S without altering any of the desirable properties of T.

Suppose we have the Employee class.

package com.gkatzioura.solid.liskov;

public class Employee {

    public void work() {

        System.out.println("Employee is working");
    }

}

Also we have another class which inherits the Employee class.

package com.gkatzioura.solid.liskov;

public class EmployeeOnVacation extends Employee {

    @Override
    public void work() {
        throw new IllegalArgumentException("Employees on vacation should not work");
    }
}

Supposing that we have a project.

package com.gkatzioura.solid.liskov;

import java.util.List;

public class Project {

    public void start(List<Employee> employees) {

        for(Employee employee:employees) {
            employee.work();
        }
    }
}

And we assign our employees to start working on it


        List<Employee> employees = new ArrayList<>();
        employees.add(new EmployeeOnVacation());
        employees.add(new Employee());

        Project project = new Project();
        project.start(employees);

The outcome would be an exception due to the employee who is on vacation and thus the project will not be completed.

The employee on vacation is an employee however he will not work. Even if the method didn’t throw an exception the method work would do nothing and this would affect delivering our project since our actucal team’s velocity is not the one we originally thought it was.

In order to avoid violating the principle we shall use a different approach and change the class hierarcy.

We will change the original employee class.

package com.gkatzioura.solid.liskov;

public class Employee {

    public String getTitle() {
        return "The employee's title";
    }

} 

And we will make make two different employee interfaces.
The WorkingEmployee interface.

 
package com.gkatzioura.solid.liskov;

public interface WorkingEmployee {

    public void work();
}

And the non working employee interface.

package com.gkatzioura.solid.liskov;

public interface NonWorkingEmployee {

    void relax();
}

Then the project will use only employees who are implementations of the WorkingEmployee interface and extend the employee class.

package com.gkatzioura.solid.liskov;

public class WorkingEmployeeImpl extends Employee implements WorkingEmployee {

    @Override
    public void work() {

    }
}
package com.gkatzioura.solid.liskov;

import java.util.List;

public class Project {

    public void start(List<WorkingEmployee> workingEmployees) {

        for(WorkingEmployee workingEmployee:workingEmployees) {
            workingEmployee.work();
        }
    }
}
List<WorkingEmployee> employees = new ArrayList<>();
employees.add(new WorkingEmployeeImpl());
Project project = new Project();
project.start(employees);

You can find the source code on github. Next principle is the interface segregation principle.

Also I have compiled a cheat sheet containing a summary of the solid principles.
Sign up in the link to receive it.

Solid Principles: Open/closed principle

Previously we talked about the single responsibility principle. The open/closed principle is the second principle in the row regarding the solid principles acronym.

“Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification”

By employing that principle the goal is to extend a module’s behaviour without modifying its source code.

Imagine a scenario of applying a discount to one of our products. A discount service will apply the discount specified and give back the discounted price.

Currently our system has only one kind of discount which applies to all adults.

package com.gkatzioura.solid.ocp;

import java.math.BigDecimal;
import java.math.RoundingMode;

public class Discount {

    public BigDecimal apply(BigDecimal price) {

        BigDecimal percent = new BigDecimal("0.10");
        BigDecimal discount = price.multiply(percent);
        return price.subtract(discount.setScale(2, RoundingMode.HALF_UP));
    }
}

And the discount service shall apply this discount to the price given.

package com.gkatzioura.solid.ocp;

import java.math.BigDecimal;

public class DiscountService {

    public BigDecimal applyDiscounts(BigDecimal price,Discount discount) {

        return discount.apply(price);
    }
}

However our company wants to offer a discount to seniors, thus we have the senior Discount.

package com.gkatzioura.solid.ocp;

import java.math.BigDecimal;
import java.math.RoundingMode;

public class SeniorDiscount {

    public BigDecimal apply(BigDecimal price) {

        BigDecimal percent = new BigDecimal("0.20");
        BigDecimal discount = price.multiply(percent);
        return price.subtract(discount.setScale(2, RoundingMode.HALF_UP));
    }
}

This makes things a little more complicated for the discount service since the service has to apply both the discount for adult and both the discount for seniors.

package com.gkatzioura.solid.ocp;

import java.math.BigDecimal;

public class DiscountService {

    public BigDecimal applyDiscounts(BigDecimal price,Discount discount) {

        BigDecimal discountPrice = price.add(BigDecimal.ZERO);
        discountPrice = discount.apply(discountPrice);
        return discountPrice;
    }

    public BigDecimal applySeniorDiscount(BigDecimal price,SeniorDiscount discount) {

        return discount.apply(price);
    }

}

By doing so we modified the discount service sourcecode to extend its behaviour. Also for every different discount that the sales department might come up with, the discount service will get extra methods.

In order to follow the open/closed principle we will create a discount interface.

package com.gkatzioura.solid.ocp;

import java.math.BigDecimal;

public interface Discount {

    BigDecimal apply(BigDecimal price);
}

The default discount will be renamed to the AdultDiscount and implement the discount interface.

package com.gkatzioura.solid.ocp;

import java.math.BigDecimal;
import java.math.RoundingMode;

public class AdultDiscount implements Discount {

    @Override
    public BigDecimal apply(BigDecimal price) {

        BigDecimal percent = new BigDecimal("0.10");
        BigDecimal discount = price.multiply(percent);
        return price.subtract(discount.setScale(2, RoundingMode.HALF_UP));
    }
}

The SeniorDiscount will also implement the Discount interface.

package com.gkatzioura.solid.ocp;

import java.math.BigDecimal;
import java.math.RoundingMode;

public class SeniorDiscount implements Discount {

    @Override
    public BigDecimal apply(BigDecimal price) {

        BigDecimal percent = new BigDecimal("0.20");
        BigDecimal discount = price.multiply(percent);
        return price.subtract(discount.setScale(2, RoundingMode.HALF_UP));
    }
}

Last but not least our DiscountService will be refactored in order to apply discounts based on the Discount interface.

package com.gkatzioura.solid.ocp;

import java.math.BigDecimal;

public class DiscountService {

    public BigDecimal applyDiscounts(BigDecimal price,Discount[] discounts) {

        BigDecimal discountPrice = price.add(BigDecimal.ZERO);

        for(Discount discount:discounts) {

            discountPrice = discount.apply(discountPrice);
        }

        return discountPrice;
    }
}

By this way the discount service will be able to apply different discounts without altering its source code.

The same principle can be applied to the Discount.
Supposing we want to have a basic discount to be applied extra when a discount is applied.

package com.gkatzioura.solid.ocp;

import java.math.BigDecimal;
import java.math.RoundingMode;

public class BasicDiscount implements Discount {

    @Override
    public BigDecimal apply(BigDecimal price) {

        BigDecimal percent = new BigDecimal("0.01");
        BigDecimal discount = price.multiply(percent);
        return price.subtract(discount.setScale(2, RoundingMode.HALF_UP));
    }
}

By extending the BasicDiscount class we are able to have more discounts with the behaviour of the BasicDiscount and also extend this behaviour without modifying the BasicDiscount sourcecode.

You can find the source code on github. The next principle is the liskov substitution principle.

Also I have compiled a cheat sheet containing a summary of the solid principles.
Sign up in the link to receive it.

Solid Principles: Single responsibility principle

The single responsibility principle is the first principle from the solid acronym.

“A class should have only one reason to change.”

Every module or class should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by the class.

For example imagine the scenario of a navigation software.
We have a position which based on the direction given (north, south, west, east) the position should change.

The Position class contains values regarding the x and y axis position.

package com.gkatzioura.solid.single;

public class Position {

    private Integer xAxis;
    private Integer yAxis;

    public Position(Integer xAxis, Integer yAxis) {
        this.xAxis = xAxis;
        this.yAxis = yAxis;
    }

    public Integer getxAxis() {
        return xAxis;
    }

    public void setxAxis(Integer xAxis) {
        this.xAxis = xAxis;
    }

    public Integer getyAxis() {
        return yAxis;
    }

    public void setyAxis(Integer yAxis) {
        this.yAxis = yAxis;
    }
}

The direction is an enum representing the direction towards North, East, South and West.

package com.gkatzioura.solid.single;

public enum Direction {
    N,W,S,E
}

And at last there is a Navigator class which is responsible for navigating according to the direction and position change.


public class Navigator {

    public Position navigate(Position position, Direction direction) {
        ....
    }

}

In order to navigate properly the navigator should resolve the next position based on the direction. Also the navigator should fix the position in cases of values below 0.


public class Navigator {

    public Position navigate(Position position, Direction direction) {

        Position nextPosition = resolve(position,direction);
        Position fixedPosition =fix(nextPosition);
        return fixedPosition;
    }

    public Position resolve(Position position,Direction direction) {

        switch (direction) {
            case N:
                return new Position(position.getxAxis(),position.getyAxis()+1);
            case S:
                return new Position(position.getxAxis(),position.getyAxis()-1);
            case W:
                return new Position(position.getxAxis()-1,position.getyAxis());
            case E:
                return new Position(position.getxAxis()+1,position.getyAxis());
            default:
                throw new IllegalArgumentException();
        }
    }

    public Position fix(Position position) {

        return new Position(
                position.getxAxis()<0?0:position.getxAxis(),
                position.getyAxis()<0?0:position.getyAxis()
        );
    }

}

The problem with this approach is that in case the position validity criteria changes we have to change the Navigator class. The same applies in case of the position movement mechanisms changes. The navigator instead of just navigating is responsible for both resolving the next position and for fixing the new position.

An approach that does not break the single responsibility principle is to create a class that will resolve the next position and a class responsible for fixing the new position.

The NextPositionResolver class will resolve the next position based on the direction given.

package com.gkatzioura.solid.single;

public class NextPositionResolver {

    public Position resolve(Position position,Direction direction) {

        switch (direction) {
            case N:
                return new Position(position.getxAxis(),position.getyAxis()+1);
            case S:
                return new Position(position.getxAxis(),position.getyAxis()-1);
            case W:
                return new Position(position.getxAxis()-1,position.getyAxis());
            case E:
                return new Position(position.getxAxis()+1,position.getyAxis());
            default:
                throw new IllegalArgumentException();
        }
    }

}

The PositionRepairer class will fix the position in case of invalid x or y values.

package com.gkatzioura.solid.single;

public class PositionRepairer {

    public Position fix(Position position) {

        return new Position(
                position.getxAxis()<0?0:position.getxAxis(),
                position.getyAxis()<0?0:position.getyAxis()
        );
    }

}

The Navigator class will have as dependencies the NextPositionResolver and PositionRepairer classes in order to perform the navigation properly.

package com.gkatzioura.solid.single;

public class Navigator {

    private NextPositionResolver nextPositionResolver;
    private PositionRepairer positionRepairer;

    public Navigator(NextPositionResolver nextStepResolver,PositionRepairer positionRepairer) {
        this.nextPositionResolver = nextStepResolver;
        this.positionRepairer = positionRepairer;
    }

    public Position navigate(Position position, Direction direction) {

        Position nextPosition =  nextPositionResolver.resolve(position,direction);
        Position fixedPosition = positionRepairer.fix(nextPosition);
        return fixedPosition;
    }

}

You can find the source code on github. Next principle is the open/closed principle.

Also I have compiled a cheat sheet containing a summary of the solid principles.
Sign up in the link to receive it.

My language will overtake yours

From time to time I stumble upon articles comparing one programming language to another or articles which claim that ‘one language will rule them all’.
Most of these comparisons depend largely on metrics based on searches and hits according to popularity (for example tiobe).

The question is not if the data is accurate but if comparisons like these are any more relevant to the current landscape of software development.

Back in the past we used to have languages developed in order to replace other languages and make developers more comfortable. Some languages became obsolete, and some were overtaken by others.
However as the industry continued to evolve, languages started to be associated with some certain fields of our industry. For example when it comes to machine learning and deep learning, python is the first language that comes to mind. As the fields of the industry involved the languages associated with, evolved too, leading to the development of tools and frameworks. As a result we now have programming languages with a huge ecosystem. The tools and the frameworks were not build in a day, it took years, a lot of effort, skills and experience on the pretty specific problems they had to tackle. As the years pass these tools mature and evolve.

Even though there are many good options out there, the major factors on adoption are not based on the language by itself but more on the tools that come with it.
Let’s take for example Java and the Java EE ecosystem. Although there is a great amount of articles discussing the death of Java, Java continuous to be the first choice, especially when it comes to enterprise development. There are certainly languages with better syntax and more convenient tools, but Java comes along with a huge ecosystem.
I believe that the language comparison should shift from language comparison to an ecosystem comparison based on the field.

Another fact that has to be considered is also the boost that happens to several industries. Certain industries require pretty specific solutions and tools, thus leading to a boost in the adoption to those tools and frameworks. It is not that a language just got more popular among developers, instead the industry just got bigger.

Finally we should take into consideration universities. Computer science universities play a leading role in the creation of the language popularity landscape.
For example many of the c language hits are due to university assignments. Furthermore r&d finds its way to the industry, implemented with different tools for environments much different than the original one.

All in all I believe that language comparison is no longer relevant. The industry has evolved a lot and the applications that we develop are largely different than the ones we used to develop in the past. In the past we used to develop console applications and it made sense to compare syntax and extra features. Nowadays we develop large scale applications in clustered environments employing various architectures and we need more than just a language to tackle these problems.