Behavioural Design Patterns: Iterator

The iterator pattern is one of the most used patterns from the behavioural ones. Most of the times you use it without even noticing it. Supposing you have a container with elements and you want to traverse them. Iterating the elements might differ based on the container, retrieval method etc. By using the iterator pattern we can decouple the algorithms used by the containers, and the retrieval methods and abstract the iteration of the elements contained.

For example when it comes to retrieving paged data from a rest endpoint the iterator can help you to abstract it. Therefore you won’t expose the user with any information on how you retrieve the next batch of data.

I will make a new iterator interface similar the one provided by the java language.

package com.gkatzioura.design.behavioural.iterator;

public interface Iterator<T> {

    boolean hasNext();
    
    T next();
    
}

We will use the github jobs api since it is open to issue rest queries and search for jobs.
The first page is page zero.

https://jobs.github.com/positions.json?page=0.

We shall create a simple object which would contain the id, title and company information.

package com.gkatzioura.design.behavioural.iterator;

import java.util.UUID;

public class GitHubJob {

    private final UUID id;
    private final String company;
    private final String title;

    public GitHubJob(UUID id, String company, String title) {
        this.id = id;
        this.company = company;
        this.title = title;
    }

    public UUID getId() {
        return id;
    }

    public String getCompany() {
        return company;
    }

    public String getTitle() {
        return title;
    }
}

Our first step would be to create a repository witch shall fetch the data of the page specified.

package com.gkatzioura.design.behavioural.iterator;

import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.apache.commons.io.IOUtils;
import org.json.JSONArray;
import org.json.JSONObject;

public class GitHubJobsRepository {

    public static final String GITHUB_JOB_API = "https://jobs.github.com/positions.json?page=";

    public List<GitHubJob> fetch(int page) throws Exception {

        List<GitHubJob> gitHubJobs = new ArrayList<>();

        URL url = new URL(GITHUB_JOB_API+page);
        HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
        String response = IOUtils.toString(httpConnection.getInputStream(), Charset.defaultCharset());
        JSONArray jsonArray = new JSONArray(response);

        for(int i=0;i<jsonArray.length();i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            GitHubJob gitHubJob = new GitHubJob(
                    UUID.fromString(jsonObject.getString("id")),
                    jsonObject.getString("company"),
                    jsonObject.getString("title"));
            gitHubJobs.add(gitHubJob);
        }

        return gitHubJobs;
    }

}

What’s great with this api is that if you ask for a page that does not exists you get an empty json object, thus asking for a non existing page won’t give us an exception like 404, therefore no need for error handling for this case.

Now the interesting part is the iterator.

package com.gkatzioura.design.behavioural.iterator;

import java.util.ArrayList;
import java.util.List;

public class GitHubIterator implements Iterator<GitHubJob> {

    private List<GitHubJob> currentJobsPage = new ArrayList<>();
    private int page = 0;

    private final GitHubJobsRepository gitHubJobsRepository;

    public GitHubIterator(GitHubJobsRepository gitHubJobsRepository) {
        this.gitHubJobsRepository = gitHubJobsRepository;
    }

    @Override
    public boolean hasNext() {
        fetchPageIfNeeded();
        return currentJobsPage.size()>0;
    }

    @Override
    public GitHubJob next() {
        fetchPageIfNeeded();

        if(currentJobsPage.size()==0) {
            return null;
        }

        return currentJobsPage.remove(0);
    }

    private void fetchPageIfNeeded() {
        if(page == -1) {
            return;
        }

        if(currentJobsPage==null||currentJobsPage.size()==0) {
            try {
                currentJobsPage = gitHubJobsRepository.fetch(page);
                if(currentJobsPage.size()==0) {
                    page = -1;
                } else {
                    page++;
                }
            } catch (Exception e) {
                throw new RuntimeException();
            }
        }
    }
}

The iterator shall contain a page request from github. For each element requested one item shall be removed from the page. Once the page gets empty a new page shall be requested.

Whether the user asks for another element or if another element exists the code shall check if the current page is empty and if yes it will request for the next page. If we got an empty page this mean that there should not be any extra request to the iterator.

The next step would be to add a method to the repository which shall give back the github iterator.

public class GitHubJobsRepository {

...

    public Iterator<GitHubJob> iterator() {
        return new GitHubIterator(this);
    }

...
}

So let us sum up and iterate over all the entries.

package com.gkatzioura.design.behavioural.iterator;

public class IteratorExample {

    public static void main(String[] args) throws Exception {
        GitHubJobsRepository gitHubJobsRepository = new GitHubJobsRepository();

        Iterator<GitHubJob> gitHubJobIterator = gitHubJobsRepository.iterator();

        while (gitHubJobIterator.hasNext()) {
            GitHubJob gitHubJob = gitHubJobIterator.next();
            System.out.println(String.format(" id: %s title: %s company: %s",gitHubJob.getId(),gitHubJob.getTitle(),gitHubJob.getCompany()));
        }
    }

}

You can find the source code on github.

It is also worth referencing patterns we saw previously such as the interpreter, chain of responsibility and the command pattern.

Behavioural Design Patterns: Interpreter

Previously we had a look at the chain of responsibility and the command pattern. They do tackle different problems however they both delegate an action to another component, the command patterns always delegates the action, the chain of responsibility if the action cannot be handled it will be forward it to its successor.

We are going to switch context and check the interpreter pattern.
The interpreter pattern specifies how to evaluate custom languages.
The examples are limitless, for example the spel language for spring or even a sql like language.

We will keep things simple and create an interpreter for a simple query language only with select and where statements. This is not impossible in the real world, just thing about dynamodb and how simple its expressions are, the examples are countless.

So let’s start with our clause interface.

package com.gkatzioura.design.behavioural.interpreter;

public interface Clause{

}

I will implement the WhereClause

package com.gkatzioura.design.behavioural.interpreter;


public class WhereClause implements Clause {

    /**
     * Add values related to the where clause functions and expressions
     */

    public WhereClause() {
    }

    /**
     * Add functions for expressions for equals not equals etc.
     */

}

And the SelectClause

package com.gkatzioura.design.behavioural.interpreter;

import java.util.Optional;

public class SelectClause implements Clause {

    private Optional<WhereClause> optWhereClause = Optional.empty();

    public <T> T load(Class<T> valueType) {

        /**
         * Apply filter according to the where clause
         */
        if(optWhereClause.isPresent()) {

        }

        /**
         * Load data
         */

        /**
         * Serialize/Deserialize data based on the type
         * For example if you use jackson it will be:  new ObjectMapper().readValue("text",valueType);
         */


        return null;
    }

    public void setWhereClause(WhereClause whereClause) {
        this.optWhereClause = Optional.of(whereClause);
    }
}

The load function shall load our data based on the expression given.

Both clauses are linked together however the select clause can produce results even when ‘where’ statements have not been given whatsoever. In any case when it comes to loading the data the select clause will check and apply any filter statements that the where clause might have (if exists) and then return the data.
Let’s move to the interpreter specific parts

We will create the expression interface.

package com.gkatzioura.design.behavioural.interpreter;

public interface Expression {

    Clause interpret(String context);

}

The interpretation of the text given will give us back a clause.

We shall create the WhereExpression.

package com.gkatzioura.design.behavioural.interpreter;

public class WhereExpression implements Expression {

    @Override
    public WhereClause interpret(String context) {
        WhereClause whereClause = new WhereClause();
        /**
         * Parse the string and find any where statements ie. A=1 AND B!=2 and apply them.
         */

        return whereClause;
    }

}

And the Select Expression.

package com.gkatzioura.design.behavioural.interpreter;

public class SelectExpression implements Expression {

    @Override
    public SelectClause interpret(String context) {
        SelectClause selectClause = new SelectClause();

        /**
         * Parse text and check for expressions like `SELECT * FROM ` or `SELECT A,B,C FROM` .
         */

        return selectClause;
    }

}

The last step would be the query expression.

package com.gkatzioura.design.behavioural.interpreter;

public class QueryExpression implements Expression {

    @Override
    public SelectClause interpret(String context) {

        SelectClause selectClause = new SelectExpression().interpret(context);

        if(context.contains("WHERE")) {

            WhereClause whereClause = new WhereExpression().interpret(context);
            selectClause.setWhereClause(whereClause);
        }

        return selectClause;
    }

}

So let’s put them all together. We shall interpret a query which fetches a list of integers.

package com.gkatzioura.design.behavioural.interpreter;

public class Interpreter {

    public static void main(String[] args) {
        String selectionString = "SELECT b FROM foo WHERE a=1";
        Integer[] values = new QueryExpression()
                .interpret(selectionString)
                .load(Integer[].class);
    }

}

You can find the sourcecode on github.

Behavioural Design Patterns: Command

Previously we used the Chain of Responsibility pattern in order to handle a complex problem with road incidents in a region, solving the problem in the first place or forwarding it to another incident handler.

The command pattern is quite different to the cor pattern since it helps us in order to delegate an action/request to another object capable of executing it. Thus there is no direct execution whatsoever.

For the command pattern we need an object to encapsulate all the information needed to perform an action or trigger an event sometime later.

One of the scenarios where it might seem very familiar is when it comes to queues and consuming those messages. Pretty much the same way elastic beanstalk workers consume messages from queues.

Each message in a queue contains a command and the code that handles that message has to execute it.
Let’s do this with an example from the betting industry.
We are going to have some bets being backed and sent over to our booking system.

So let’s create the bet class.

package com.gkatzioura.design.behavioural.command;

public class Bet {

    private final String match;
    private final Integer amount;

    public Bet(final String match, final Integer amount) {
        this.match = match;
        this.amount = amount;
    }

    public String getMatch() {
        return match;
    }

    public Integer getAmount() {
        return amount;
    }
}

Now let’s add a class which shall contain our bet actions. This is going to be our bet book.

package com.gkatzioura.design.behavioural.command;

public class BetBook {

    public void addBacking(String match, Integer amount) {
        /**
         * Add the backing to the book
         */
    }

}

Now it is time for us to specify the bet command. The bet command is going to be applied to our Bet book.

package com.gkatzioura.design.behavioural.command;

public interface BetCommand {

    void applyTo(BetBook betBook);

}

This brings us to the Backing command.

package com.gkatzioura.design.behavioural.command;

public class BackingCommand implements BetCommand {

    private final Bet bet;

    public BackingCommand(final Bet bet) {
        this.bet = bet;
    }

    @Override
    public void applyTo(BetBook betBook) {
        betBook.addBacking(bet.getMatch(),bet.getAmount());
    }

}

So let’s put them all together.

package com.gkatzioura.design.behavioural.command;

import java.util.ArrayList;
import java.util.List;

public class Command {

    public static void main(String[] args) {
        List<BetCommand> betCommands = new ArrayList<>();
        betCommands.add(new BackingCommand(new Bet("match1",10)));
        betCommands.add(new BackingCommand(new Bet("match2",11)));

        BetBook betBook = new BetBook();
        betCommands.forEach(bc->bc.applyTo(betBook));
    }

}

So imagine that we just gathered our bet commands and we got them dispatched to a microservice responsible to apply each command to our bet book.

You can find the source code on github.

Behavioural Design Patterns: Chain of Responsibility

We had a look on creational design patterns and structural design patterns. On this blog we will focus on behavioural design patterns.

From wikipedia

Behavioural design patterns are design patterns that identify common communication patterns between objects and realise these patterns. By doing so, these patterns increase flexibility in carrying out this communication.

Creational design patterns realise the creation of objects.
Structural design patterns provide ways to realise relationships with objects.
Behavioural design patterns realise the communication between objects.

The chain of responsibility pattern has to do with command objects being handled and passed to other objects by logic-containing processing objects.

There are many examples that come to mind. One of them is road infrastructure issues which need to be handled by towns, municipalities or states.

The towns should be responsible for its road issues, the municipality should handle the infrastructure that has to do with towns, hamlets and villages and the state all the rest such as urban roads, bridges etc.

There are various road incidents pothole, accidents, the collapse of a bridge you name it.
This brings us to the road incident model.

package com.gkatzioura.design.behavioural.cor;

public class RoadIncident {

    private final double latitude;
    private final double longtitude;
    private final String report;

    public RoadIncident(double latitude, double longtitude, String report) {
        this.latitude = latitude;
        this.longtitude = longtitude;
        this.report = report;
    }

    public double getLatitude() {
        return latitude;
    }

    public double getLongtitude() {
        return longtitude;
    }

    public String getReport() {
        return report;
    }
}

The latitude and longitude are the coordinates. Based on the coordinates each geographical region should proceed or pass the incident to the next region.

The next step is implementing the incident handler interface.

package com.gkatzioura.design.behavioural.cor;

public interface RoadIncidentHandler {

    void handle(RoadIncident roadIncident);

    boolean withinBounds(double lat, double lng);

}

Each geographical region should be identify if the incident is within its bound and should be handled by it. If not the incident should be forwarded to its successor.

We should start with the state road incident handler.

package com.gkatzioura.design.behavioural.cor;

public class StateRoadRoadIncidentHandler implements RoadIncidentHandler {

    @Override
    public void handle(RoadIncident roadIncident) {
        if(!withinBounds(roadIncident.getLatitude(),roadIncident.getLatitude())) {
            throw new IllegalArgumentException("Incident cannot be handled by state. No successor available");
        }

        /**
         * Handle the incident
         */
    }

    @Override
    public boolean withinBounds(double lat, double lng) {

        /**
         * Reverse geolocation, look up by name, radius based distance etc.
         */

        return true;
    }
}

So the state has no successor. It is the highest level, thus if the incident is out of it’s bounds then it will throw an illegal argument exception.

Then we go to the municipality handler. The municipality handler does have a successor. It can be the state or something else we might come up in the future.

package com.gkatzioura.design.behavioural.cor;

public class MunicipalityRoadRoadIncidentHandler implements RoadIncidentHandler {

    private final RoadIncidentHandler successor;

    public MunicipalityRoadRoadIncidentHandler(final RoadIncidentHandler successor) {
        this.successor = successor;
    }

    @Override
    public void handle(RoadIncident roadIncident) {
        if(!withinBounds(roadIncident.getLatitude(),roadIncident.getLongtitude())) {
            successor.handle(roadIncident);
        } else {
            /**
             * Handle the incident
             */
        }
    }

    @Override
    public boolean withinBounds(double lat, double lng) {
        /**
         * Reverse geolocation, look up by name, radius based distance etc.
         */
        return false;
    }
}

If the municipality incident handler is not able to handle the incident then it will forward it to its successor.

The last one is going to be the town road incident handler.

package com.gkatzioura.design.behavioural.cor;

public class TownRoadRoadIncidentHandler implements RoadIncidentHandler {

    private final RoadIncidentHandler successor;

    public TownRoadRoadIncidentHandler(final RoadIncidentHandler successor) {
        this.successor = successor;
    }

    @Override
    public void handle(RoadIncident roadIncident) {
        if(!withinBounds(roadIncident.getLatitude(),roadIncident.getLongtitude())) {
            successor.handle(roadIncident);
        } else {
            /**
             * Handle the incident
             */
        }
    }

    @Override
    public boolean withinBounds(double lat, double lng) {
        /**
         * Reverse geolocation, look up by name, radius based distance etc.
         */
        return false;
    }
}

The same rule that applies to the municipality applies to the town handler. If the incident is not within its bounds it will forward it to its successor.

Let’s put them all together.

package com.gkatzioura.design.behavioural.cor;

public class ChainOfResponsibility {

    public static void main(String[] args) {
        StateRoadRoadIncidentHandler state = new StateRoadRoadIncidentHandler();
        MunicipalityRoadRoadIncidentHandler municipality = new MunicipalityRoadRoadIncidentHandler(state);
        TownRoadRoadIncidentHandler firstTown = new TownRoadRoadIncidentHandler(municipality);
        TownRoadRoadIncidentHandler secondTown = new TownRoadRoadIncidentHandler(state);

        RoadIncident roadIncident = new RoadIncident(0d,0d,"Something happened");
        firstTown.handle(roadIncident);
        secondTown.handle(roadIncident);
    }

}

So the municipality’s successor is the state. Also the state is the successor for the second town.
The first town has the municipality as the successor.

Regarding the first town if the incident can be handled only by the state then it will be forwarded from the first town to the municipality and then from the municipality to the state.
Regarding the second town if the incident cannot be handled it will be forwarded to the state.

You can find the sourcecode on github.