Design Patterns : Event Bus

Today we are continuing our series studying design patterns, last couple of blog-posts contained already mentioned GoF design patterns, today we are tackling one that is kind of new (and by that i mean not mentioned in the GoF book) and that is the Event Bus
note : all the code samples and implementation details can be found in the repo .

Motivation

Imagine having a large scale application containing a lot of components interacting with each other, and you want a way to make your components communicate, while maintaining loose coupling and separation of concerns principles, the Event Bus pattern can be a good solution for your problem .
The idea of an Event bus is actually quite similar to the Bus studied in Networking (Bus Topology). you have some kind of pipeline and computers connected to it and whenever one of them sends a message it’s dispatched to all of the others, and then they decide if they want to consume the given message, or just discard it.
networking-bus
At a component level it’s quite similar, the computers are your application components and the message is the event or the data you want to communicate, the pipeline is your EventBus object .

Implementation

There is no “correct” way to implement an Event Bus, i’m going to give a peak at two approaches here, finding other approaches is left as an exercise to the reader .

FIRST PATTERN

This one is kind of classic as it relays on defining your EventBus interface (to force a given contract) and implementing it the way your want, and define a Subscribable (another contract) to handle Event (and yet another contract) consumption .


package io.github.chermehdi.bus;
/**
* interface describing a generic event, and it's associated meta data, it's this what's going to
* get sent in the bus to be dispatched to intrested Subscribers
*
* @author chermehdi
*/
public interface Event<T> {
/**
* @returns the stored data associated with the event
*/
T getData();
}

view raw

Event.java

hosted with ❤ by GitHub


package io.github.chermehdi.bus;
import java.util.Set;
/**
* Description of a generic subscriber
*
* @author chermehdi
*/
public interface Subscribable {
/**
* Consume the events dispatched by the bus, events passed as parameter are can only be of type
* declared by the supports() Set
*/
void handle(Event<?> event);
/**
* describes the set of classes the subscribable object intends to handle
*/
Set<Class<?>> supports();
}


package io.github.chermehdi.bus;
import java.util.List;
/**
* Description of the contract of a generic EventBus implementation, the library contains two main
* version, Sync and Async event bus implementations, if you want to provide your own implementation
* and stay compliant with the components of the library just implement this contract
*
* @author chermehdi
*/
public interface EventBus {
/**
* registers a new subscribable to this EventBus instance
*/
void register(Subscribable subscribable);
/**
* send the given event in this EventBus implementation to be consumed by interested subscribers
*/
void dispatch(Event<?> event);
/**
* get the list of all the subscribers associated with this EventBus instance
*/
List<Subscribable> getSubscribers();
}

view raw

EventBus.java

hosted with ❤ by GitHub

The Subscribable declares a method to handle a given type of objects, and also what type of objects it supports by defining the supports method .

The Event Bus implementation holds a List of all the Subscribables and notify all of them each time a new event comes to the EventBus dispatch method .

Opting for this solution gives you compile time checking of the passed Subscribables, and also it’s more OO way of doing it, no reflection magic needed, and as you can see it can be easy to implement
The downside is that contract forcing thing, you always need a new class to handle a type of event, which might not be a problem at first, but as your project grows you’re going to find it a little bit repetitive to create a class just to handle simple logic, such as logging, or statistics .

SECOND PATTERN

This pattern is inspired from Guava’s implementation, the Event Bus implementation looks much simpler and easier to use. for every event consumer you can just annotate a given method with @Subscribe and pass it an object of the type you want to consume (a single object/parameter) and you can register it as a message consumer by just calling

eventBus.register(objectContainingTheMethod);
to Produce a new Event all you have to do is call eventBus.post(SomeObject) and all the interested consumers will be notified .
what happens if no consumer is found for a given object, well .. nothing really in guava’s implementation they call them DeadEvent’s in my implementation the call to post is just ignored .


package io.github.chermehdi.guavabus;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
/**
* Simple implementation demonstrating how a guava EventBus works generally, without all the noise
* of special cases handling, and special guava collections
*
* @author chermehdi
*/
public class EventBus {
private Map<Class<?>, List<Invocation>> invocations;
private String name;
public EventBus(String name) {
this.name = name;
invocations = new ConcurrentHashMap<>();
}
public void post(Object object) {
Class<?> clazz = object.getClass();
if (invocations.containsKey(clazz)) {
invocations.get(clazz).forEach(invocation -> invocation.invoke(object));
}
}
public void register(Object object) {
Class<?> currentClass = object.getClass();
// we try to navigate the object tree back to object ot see if
// there is any annotated @Subscribe classes
while (currentClass != null) {
List<Method> subscribeMethods = findSubscriptionMethods(currentClass);
for (Method method : subscribeMethods) {
// we know for sure that it has only one parameter
Class<?> type = method.getParameterTypes()[0];
if (invocations.containsKey(type)) {
invocations.get(type).add(new Invocation(method, object));
} else {
List<Invocation> temp = new Vector<>();
temp.add(new Invocation(method, object));
invocations.put(type, temp);
}
}
currentClass = currentClass.getSuperclass();
}
}
private List<Method> findSubscriptionMethods(Class<?> type) {
List<Method> subscribeMethods = Arrays.stream(type.getDeclaredMethods())
.filter(method -> method.isAnnotationPresent(Subscribe.class))
.collect(Collectors.toList());
checkSubscriberMethods(subscribeMethods);
return subscribeMethods;
}
private void checkSubscriberMethods(List<Method> subscribeMethods) {
boolean hasMoreThanOneParameter = subscribeMethods.stream()
.anyMatch(method -> method.getParameterCount() != 1);
if (hasMoreThanOneParameter) {
throw new IllegalArgumentException(
"Method annotated with @Susbscribe has more than one parameter");
}
}
public Map<Class<?>, List<Invocation>> getInvocations() {
return invocations;
}
public String getName() {
return name;
}
}

view raw

EventBus.java

hosted with ❤ by GitHub

You can see that opting for this solution requires less work from your part, nothing prevents you from naming your handler methods intention-revealing names rather than a general handle . and you can define all your consumers on the same class you just need to pass an different event type for each method .

Conclusion

Implementing an Event Bus pattern can be beneficial for your code base as it help loose coupling your classes and promotes a publish-subscribe pattern , it also help components interact without being aware of each other . which implementation to follow is a matter of taste and requirements .

Serializing Java Objects to XML

HI !

in my last post i talked about java -Costume- Serialization, so for today i will continue on that topic but this time i will write objects to a more human readable format “XML”.

today’s post is more of an introduction to a class (two classes actually ) XMLEncoder and XMLDecoder .

XMLEncoder is an complementary alternative to the ObjectOutputStream Class . instead of series of bytes you get a textual format .

XMLEncoder Write Objects with the Java Beans Convention in mind, it’s not necessary to implement the Serializable interface, but your Object must have these two properties :

1- public empty constructor

2- getters and setters for every protected/private property

as per how the XMLEncoder works , it uses reflexion to know the state of each field and convert them to XML format, let’s look at an example to make it clearer :

let’s Say we have a Settings Class that contains information about a certain user :


// simple class written as a Java bean
public class Settings {
private String settings1;
private Integer settings2;
public Settings(){}
public Settings(String settings1, Integer settings2) {
this.settings1 = settings1;
this.settings2 = settings2;
}
public String getSettings1() {
return settings1;
}
public void setSettings1(String settings1) {
this.settings1 = settings1;
}
public Integer getSettings2() {
return settings2;
}
public void setSettings2(Integer settings2) {
this.settings2 = settings2;
}
@Override
public String toString() {
return "Settings{" +
"settings1='" + settings1 + '\'' +
", settings2=" + settings2 +
'}';
}
}

view raw

Settings.java

hosted with ❤ by GitHub

now we Create A Serializer class that will handle the serialization and deserialization process :


import java.beans.ExceptionListener;
import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.FileInputStream;
import java.io.FileOutputStream;
/**
* @author Mehdi Maick
* Created by mac on 17/11/2016.
*/
public class Serializer {
// Serialize the given Object
public static void serializeToXml(Settings settings) throws Exception {
FileOutputStream f = new FileOutputStream("settings.xml");
XMLEncoder encoder = new XMLEncoder(f);
encoder.setExceptionListener(new ExceptionListener() {
public void exceptionThrown(Exception e) {
System.out.println("an Exception Occured " + e.getMessage());
}
});
encoder.writeObject(settings);
encoder.close();
f.close();
}
// Deserialize an Object
public static Settings desrializeFromXml() throws Exception {
FileInputStream fis = new FileInputStream("settings.xml");
XMLDecoder decoder = new XMLDecoder(fis);
Settings decodedSettings = (Settings) decoder.readObject();
decoder.close();
fis.close();
return decodedSettings;
}
//main to test
public static void main(String[] args) throws Exception {
Settings s = new Settings("user settings", 98);
serializeToXml(s);
Settings same = desrializeFromXml();
System.out.println(same);
}
}

view raw

Serializer.java

hosted with ❤ by GitHub

this will create a settings.xml file this is the content :


<?xml version="1.0" encoding="UTF-8"?>
<java version="1.8.0_60" class="java.beans.XMLDecoder">
<object class="lib.Settings">
<void property="settings1">
<string>user settings</string>
</void>
<void property="settings2">
<int>98</int>
</void>
</object>
</java>

view raw

settings.xml

hosted with ❤ by GitHub

magic isn’t it .

Well there you have it Writing Objects to Xml for more advanced Usage please check out this tutorial .  Happy Coding 😀 …

 

Costume Serialisation with Java Externalizable .

HI !

today were going to tackle an interesting subject , costume serialisation with java.

before talking about costume serialization we need to know what serialization actually means :

To put in  simple words : it’s a mechanism provided by Java to represent an object as a sequence of bytes,  including all the information about the object type, and attributes…

the goal of Serialization is to write objects to convert objects to binary streams , that are easy to transmit via files, network …

to benefit from this mechanism in Java , it’s simple : implement the java.io.Serializable 

interface and your good to go.

now to getting back to the topic at hand , because it’s easy to make an object serializable in java, it comes with it’s downsides , there are two actually :

The performance downside :

the serialization proccess stores a lot of additional meta-data needed to identify the object 😦

The ” I’m forced to serialize this way and i don’t want to ” downside : 

their is no control on how the java serialization will work, (of course you can say that this field will get serialized and this field not ) but there is no control about how to do read and write your data as bytes …

here when the Externalizable java Interface comes to the picture it provides two main methods readExternal(ObjectInput in), and writeExternal(ObjectOutput out).

this interface extends the Serializable interface and by overriding these methods you can have more control on the serialization process i quote from the @javadoc :

 Only the identity of the class of an Externalizable instance is written in the serialization stream and it is the responsibility of the class to save and restore the contents of its instances.

So let’s take a look on how to do this.

Basically i’m going to explain the role of the two mentionned methods, and how they work with a small example . so let’s begin 😀

writeExternal(ObjectOutput out);

Is used to provide the logic for serialization , writing the fields of class into bytes. You are free to store only those fields which you want back after reading the serialized object back

readExternal(ObjectInput in);

does the exact opposite , but a rule of thumb . do the reading and the writing in same order

Order Matters .

now an example :p


import java.util.*;
import java.io.*;
/**
*
* @author Mehdi Maick
*
*/
public class CostumeObject implements Externalizable {
private String fieldtoWrite;
private Integer thisAlso;
private String thisIdontWantToWrite;
public CostumeObject(String filedtoWrite, Integer thisAlso, String thisIdontWantToWrite) {
this.fieldtoWrite = filedtoWrite;
this.thisAlso = thisAlso;
this.thisIdontWantToWrite = thisIdontWantToWrite;
}
// Notice that i read with the same order i Write
// there is a lot of methods in ObjectOuput and ObjectInput classes i'll let
// you check them out
@Override
public void writeExternal(ObjectOutput out) throws IOException {
out.writeInt(thisAlso);
out.writeUTF(fieldtoWrite);
}
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
thisAlso = in.readInt();
fieldtoWrite = in.readUTF();
}
}

that’s it for today , Happy Coding … 😀

Design Patterns : Builder

Hi !

This one is one of my favorite design patterns, it makes object creation so simple yet so elegante ,and easy to read and understand .u can consider it as an alternative way to create

Complex Objects.

before we talk about anything else , i wanted to mention that the implementation i will be given here is slightly different from the one you will find on the Web , cause i find this one easier to implement and to understand , if you didn’t like this implementation, all you have to do is google builder design pattern . okay let’s begin .

let’s start by a formal definition :

Builder Pattern aims to “Separate the construction of a complex object from its representation so that the same construction process can create different representations.”

The Builder Design pattern gives Total control over the steps of construction process.it also allow’s us to vary the product internal representation by giving us a lot of methods to change the state of the object .

suppose we have a project , with some kind of User class (basicaly any kind of project 😀 )

once your user is created, you don’t want to modify it again , you wanna make it as an Immutable Object . let’s give our User class 4 attributes name, address,  phone and age .

in normal practice . you would pass the given arguments to the constuctor somthing a bit like this :

  public User(String name, String address, String phone, int age){
     this.name = name;
     this.address = address;
     this.phone = phone;
     this.age = age;
  }

looks good, but wait what if only the name and phone are mandatory , this means we need more constructors

  public User(String name,String phone, int age){}
  public User(String name,String phone, String address){} ...
 

 

okay if you still think this is fine , let’s add another attribute maybe date of birth,

now we need even more constructors , you see where i’m going …

So the only options we have is to keep adding constructors , or loose the Immutablilty of the Object , and provide setters to change the given attributes 😦 .

Here where the Builder  Pattern comes to rescue , it will keep the immutablity of the Object and help construct it efficiently let’s look at a basic implementation which will make things clear (er) :


/**
* We are constructing a User class like the one mentioned in the blog-post only
* the name and phone number are obligatory
*
* @author Mehdi Maick
*/
public class User {
private final String name; // required
private final String phone; // required
private final int age; // optional
private final String address; // optional
private User(UserBuilder builder) {
this.name = builder.name;
this.age = builder.age;
this.phone = builder.phone;
this.address = builder.address;
}
// no setters first rules of making an object Immutable
public String getFirstName() {
return name;
}
public int getAge() {
return age;
}
public String getPhone() {
return phone;
}
public String getAddress() {
return address;
}
@Override
public String toString() {
return "User: " + name + ", " + age + ", " + phone + ", " + address;
}
public static class UserBuilder {
// same fields as the User Class
private final String name;
private int age;
private String phone;
private String address;
public UserBuilder(String name, String phone) {
this.name = name;
this.phone = phone;
}
public UserBuilder age(int age) {
this.age = age;
return this;
}
public UserBuilder phone(String phone) {
this.phone = phone;
return this;
}
public UserBuilder address(String address) {
this.address = address;
return this;
}
// Return the finally constructed User object
public User build() {
User user = new User(this);
validate(user);
return user;
}
private void validate(User user) {
// this is to do some kind of validation about the constructed
// object
// throw exception or errors if it dosen't match some set criteria
}
}
public static void main(String[] args) {
User myUser = new User.UserBuilder("mehdi", "000000")
.age(30)
.phone("1234567") // i modified the phone number
.address("221B baker street")
.build();
System.out.println(myUser);
}
}

view raw

User.java

hosted with ❤ by GitHub

There you have it a quick implementation of the Builder design pattern , i hope you learned something . Happy Coding …

Design Patterns : Factory

Well as it’s name suggests , the factory design pattern is a fancy and efficient method for creating objects, some use case of it is if your application is going to change the process of object creation , or you want to hide the process of object creation “the new keyword basically ” .

this particular pattern introduces the concept of “loose coupling” between classes , this is done by programming using abstract entities, hiding the concrete implementation to make the application more flexible and less fragile .

no more talk , let’s get to the implementation .

first let’s describe a problem :

we are designing a video game , and at some point we need to create a lot of different types of enemies for our hero so to facilitate the process of enemies creation , we create an abstract Enemy class and then specefic enemy classes , then we create a “Factory” class to generate the objects , something kind of like this :

First of all we create an enum, to keep track of enemy types


public enum EnemyType {
BIGENEMY,
SMALLENEMY,
SMARTENEMY
}

view raw

EnemyType.java

hosted with ❤ by GitHub

then we create the Abstract Enemy class


public abstract class Enemy {
private EnemyType enemyType;
public Enemy(EnemyType enemyType) {
this.enemyType = enemyType;
}
// this is for subclasses to implement
protected abstract void construct();
public EnemyType getType() {
return enemyType;
}
public void setType(EnemyType enemyType) {
this.enemyType = enemyType;
}
}

view raw

Enemy.java

hosted with ❤ by GitHub

and then we start implementing the subclasses of our Enemy class :


public class SmartEnemy extends Enemy {
public SmartEnemy() {
super(EnemyType.SMARTENEMY);
construct();
}
// you can do all kinds of stuff here i'm
// just keeping it simple and only printing a message to the console
@Override
protected void construct() {
System.out.println("creating the smart enemy object ");
}
}

view raw

SmartEnemy.java

hosted with ❤ by GitHub


public class SmallEnemy extends Enemy {
public SmallEnemy() {
super(EnemyType.SMALLENEMY);
construct();
}
@Override
protected void construct() {
System.out.println("creating the smaall enemy object ");
}
}

view raw

SmallEnemy.java

hosted with ❤ by GitHub

the BigEnemy class is just the same as the others .

now to create the Factory objects, in our case the object creation will depend on it’s Type

if a SmallEnemy type passed to the factory it will create a new SmallEnemy Object .

Something that looks a bit like this


public class EnemyFactory {
public static Enemy create(EnemyType enemyType) {
Enemy enemy = null;
switch (enemyType) {
case SMALLENEMY:
enemy = new SmallEnemy();
break;
case SMARTENEMY:
enemy = new SmartEnemy();
break;
default:
// throw some kind of exception
throw new RuntimeException("the given enemy type does not existe ");
}
return enemy;
}
}

testing it is quite simple . you can add other kind of enemy types easily now  .

here are some other benefits of the factory design pattern (which i didn’t know , i googled it while writing this blog-post :p ) :

  • Allows you to hide implementation of an application  (the core interfaces that make up your application)
  • Allows you to easily test the seam of an application (that is to mock/stub) certain parts of your application so you can build and test the other parts

there you have it folks . the factory design pattern . Happy Coding …

 

 

 

Making A class Immutable In Java

Once i mention Immutable and Java, the first thing that commes to mind is String class.

and you’d be absoloutley right. an Immutable Object is a special Object that is state is unchangeable once it’s created . so in the String example :


String a = "MyString";
String b = "MyOtherString";
a = a + b; // a new String has been created here
String s = a.substring(1); // the "a" string is not modified a new String Object is created every single time
// we do this kind of operations

view raw

Immu.java

hosted with ❤ by GitHub

this is Good … but one may ask, why would i want to make an object immutable ?

Their is many benefits to making an Immutable Object i’m going to mention a few of them:

  1. They are automatically thread-safe and have no synchronization issue
  2. Allow hashCode to use lazy initialization, and to cache its return value (i will talk about lazy initialisation later )
  3. Do not need an implementation of clone

and many more … now the question is How to make One 😉

first of all their is guide lines when it comes to creating Immutable Objects :

1 – D’ont Provide setter methods :

this one is obvious from the definition of an Immutable Object , setters are meant to change the state of an Object . this kind of behaviour is not acceptable in Our Object.

2- Make all the fields private and final  :

The private part is again to not make them accessible or modifiable from outside the class,

and the “final”  part is to not accidentally change the value of a field once it’s set.

3- Don’t Allow Subclass to Override Super Class’s Methods  :

this can be done by making the class itself final .

To Construct this kind of Objects i’m going to give a Code Sample describing these guidelines . it may help you when trying to create your own Immutable Objects.


public final class MyImmutableObject {
/**
* Both String and Integer Classes Are Immutable
*/
private final String ObjectName;
private final Integer ObjectId;
/**
* private Constructors so No Unplanned Constructions of an Object Occurs
*
* @param ObjectName
* @param ObjectId
*/
private MyImmutableObject(String ObjectName, Integer ObjectId) {
this.ObjectName = ObjectName;
this.ObjectId = ObjectId;
}
/**
* to Create New Instances of the Immutable Object You Must pass by this
* method kind of a factory design pattern
*
* @param ObjectName
* @param ObjectId
* @return
*/
public static MyImmutableObject getNewInstance(String ObjectName, Integer ObjectId) {
return new MyImmutableObject(ObjectName, ObjectId);
}
// getter methods after all we have read access to an Immutable Object
public Integer getObjectId() {
return ObjectId;
}
public String getObjectName() {
return ObjectName;
}
/**
* for Debugging
*/
public String toString() {
return ObjectId + " " + ObjectName;
}
public static void main(String[] args) {
MyImmutableObject obj = MyImmutableObject.getNewInstance("MyObject", 1);
System.out.println(obj);
modify(obj.getObjectId(), obj.getObjectName());
System.out.println(obj);
}
public static void modify(Integer ObjectId, String ObjectName) {
ObjectId = 2;
ObjectName = "MyObjectModified";
}
}

the Output of the Operation Is :

1 MyObject
1 MyObject

 

So that’s it i hope this was helpful . Happy Coding …

Abstraction in Java

Okay ! today we talk about Abstraction, a lot of you know what “abstract” keyword means,

and how to use it to achieve polymorphisme, but what Abstraction really means ?

In simple words: “Abstraction captures only those details about an object that are relevant to the current perspective.” it’s a bit of a  fancy definition , but essentially Abstraction defines object’s that acts as “abstract actors” ,they can communicate , perform work , and report their change of state.

it can also work as kind of a layer(s) to hide how low level  work is done, and make the programmer focus on doing bigger stuff, and not concerne himself  with all the jargon

from low level communication and network buffering, to splitting a string or sorting an array .

It’s good to know that their is two types of abstraction

Control Abstraction :

All software written is just a bunch of statements and declarations that are repeated (one way or another) or similar in structure.

Control abstraction is the process of identifying all such statements and expose them as a unit of work. We normally use this feature when we create a function to perform any work.

Data Abstraction :

Is the way to create complex data types and exposing only meaningful operations to interact with data type, where as hiding all the implementation details  from outside world.

Benefit of this approach involves capability of improving the implementation over time e.g : solving performance issues, easy debugging ,easy backward compatibility …

The idea is that such changes are not supposed to have any impact on client code, since they involve no difference in the abstract behaviour.

Well that’s it for Abstraction , Happy Coding …

First blog post

This is my first blog so go easy on me :p

I’m a student who happens to love the java programming language and decided to start a blog dedicating it to share my experience trying to learn more about this amazing language

so i hope you don’t find me boring and that you’ll find what you’re looking for here 😀

Happy Coding …

Java Champions

So the idea behind this blog-post is that not a lot of people know about java champions,

what it means , or how to become one . So in order to remove any ambiguity, i’ll try to explain all those things mentioned above. let’s get started :

First, what’s a Java Champion : 

"Java Champions are an exclusive group of passionate Java technology and community leaders who are community-nominated and selected under a project sponsored by Oracle. Java Champions get the opportunity to provide feedback, ideas, and direction that will help Oracle grow the Java Platform"

So they are people selected by the community to help decide how the future of the language will be , they come from different places around the glob, different jobs (some not even in the Industry ) . so how do they get chosen ?

A good Java Champion Candidate is a better be an Engineer or a Project Manager or an Architect with Seniority and lots of Experience, besides   the candidates must have influence in the developer’s community, and have to be involved in many open source Projects . after all the community is what makes a real “Champion” .

it’s also good to know that the nomination process is done by peer Review , or recommendation, just by providing your name, and profile to the oracle committee

(of course you should meet those conditions mentioned above) plus Reasons for nomination , in other words why you should be nominated what have you done to the community and what projects have you worked on .

So that’s all the importent things you should know about the subject, for more information  Try this Link to find out more. Happy Coding …