Sunday, 12 June 2011

Builder style setters or Chained invocation in Java

Setters idiom in Java is an evil and I hate it. And I don't hate it because you have to invoke setXXX methods multiple times when you have to set many fields. The most annoying thing for me is that you can only set one field in a line. This is because setter method return this stupid void. Here is the example:

public class Car {  
private int maxSpeed;
// remainder omitted

public void setMaxSpeed(int maxSpeed) {
this.maxSpeed = maxSpeed;
}
// remainder omitted
}

So my code using the Car class will look like this:

Car car = new Car();  
car.setMaxSpeed(210);
car.setSpeedUnit("km/h");
car.setLength(5);
// remainder omitted


I have an idea how the life of the developers can be made easier using builder-style setters "pattern". Here is the new BETTER Car class:


public class Car {  
private int maxSpeed;
private String speedUnit;
// remainder omitted

public Car setMaxSpeed(int maxSpeed) {
this.maxSpeed = maxSpeed;
return this;
}

public Car setSpeedUnit(String speedUnit) {
this.speedUnit = speedUnit;
return this;
}
// remainder omitted
}


I can now instantiate and initialize my Car object in one line (maybe wrapped but still one line of code):

Car car = new Car()  
.setMaxSpeed(210)
.setSpeedUnit("km/h")
.setLength(5)
...


What do you think? Isn't it much easier now? Of course if you extend Car class it becomes more tricky as you have to repeat all the setter methods like this:

public class Truck extends Car {  
private int capacity;
private String capacityUnit;
// remainder omitted

@Override
public Truck setMaxSpeed(int maxSpeed) {
super.setMaxSpeed(maxSpeed);
return this;
}

@Override
public Truck setSpeedUnit(String speedUnit) {
super.setSpeedUnit(speedUnit);
return this;
}
// remainder omitted
}


Looking at the better use case


The example is not very good above, so please bear with this. Actually when there is class hierarchy having full inheritance among them, example – There is a class called Person as the Base class. Now suppose GrandParent extends Person, Parent extends GrandParent, Child extends Parent. Now the common properties of these can be set by some interface say ISetter (stupid name, please ignore).


Now all the common settings can be set by implementing ISetter interface and that will be kind of one-liner, increasing the code readability.

Saturday, 11 June 2011

Various relations in software design - Association, Aggregation, Composition, Abstraction, Generalization, Realization, Dependency

We will just discuss about some of the terms used in software engineering, regarding relationship among the objects, and how they are represented in class diagram.

Association

Association is a relationship between two objects. In other words, association defines the multiplicity between objects. You may be aware of one-to-one, one-to-many, many-to-one, many-to-many all these words define an association between objects. Aggregation is a special form of association. Composition is a special form of aggregation.

Example: A Student and a Faculty are having an association. The relationship between a car and a driver is representative of this relationship. The car will have a driver who will be associated with the car for a period of time.

Aggregation

Aggregation is a special case of association. A directional association between objects. When an object ‘has-a’ another object, then you have got an aggregation between them. Direction between them specified which object contains the other object. Aggregation is also called a “Has-a” relationship.

 
A FileReader object that has been created using a File object represents a mutual dependency where the two objects combine to create a useful mechanism for reading characters from a file. The UML symbols for expressing this relationship as shown in following figure which involve a line connecting the two classes with a diamond at the object that represents the greater whole.


Composition

Composition is a special case of aggregation. In a more specific manner, a restricted aggregation is called composition. When an object contains the other object, if the contained object cannot exist without the existence of container object, then it is called composition.

Example: A class contains students. A student cannot exist without a class. There exists composition between class and students. Other example of this is a customer object and its related address object; the address object cannot exist without a customer object. This relationship is shown with a darkened diamond at the object, which represents the greater whole, as shown in the following figure:

Difference between aggregation and composition

Composition is more restrictive. When there is a composition between two objects, the composed object cannot exist without the other object. This restriction is not there in aggregation. Though one object can contain the other object, there is no condition that the composed object must exist. The existence of the composed object is entirely optional. In both aggregation and composition, direction is must. The direction specifies, which object contains the other object.
Example: A Library contains students and books. Relationship between library and student is aggregation. Relationship between library and book is composition. A student can exist without a library and therefore it is aggregation. A book cannot exist without a library and therefore its a composition. For easy understanding I am picking this example. Don’t go deeper into example and justify relationships!

Abstraction

Abstraction is specifying the framework and hiding the implementation level information. Concreteness will be built on top of the abstraction. It gives you a blueprint to follow to while implementing the details. Abstraction reduces the complexity by hiding low level details.
Example: A wire frame model of a car.

Generalization

Generalization uses a “is-a” relationship from a specialization to the generalization class. Common structure and behaviour are used from the specializtion to the generalized class. At a very broader level you can understand this as inheritance. Why I take the term inheritance is, you can relate this term very well. Generalization is also called a “Is-a” relationship.

Example: Consider there exists a class named Person. A student is a person. A faculty is a person. Therefore here the relationship between student and person, similarly faculty and person is generalization.

Realization

Realization is a relationship between the blueprint class and the object containing its respective implementation level details. This object is said to realize the blueprint class. In other words, you can understand this as the relationship between the interface and the implementing class.

Example: A particular model of a car ‘GTB Fiorano’ that implements the blueprint of a car realizes the abstraction.

Dependency

Change in structure or behaviour of a class affects the other related class, then there is a dependency between those two classes. It need not be the same vice-versa. When one class contains the other class it this happens.

Example: Relationship between shape and circle is dependency. The same relationship would exist for a stock transfer object that needed to use a stock item object to get the information on the stock item being transferred. The stock transfer object would have a dependency relationship with the stock item object; the stock transfer object would read the transfer information and could then discard the stock item object and continue processing.

Thursday, 9 June 2011

Don't use Evil Boolean Constructors

This is something straight out of the Effective Java book, which every, really, every Java developer should read. But I still find a lot of calls to Boolean constructors, to this very day, 6 years after the book was out. (Has doing code review turned me into a grumpy nagging old man or what?)
The twin constructors of java.lang.Boolean, namely, Boolean(String) and Boolean(boolean) should never be called from within your application. The only legit user of these two constructors is the Boolean class itself. The reason is simple: you only need two Boolean instances, really. One to represent true, one to represent false. That’s it. And these two objects already exist as class variables of Boolean, namely, Boolean.TRUE, and Boolean.FALSE. You only need these two.
You don’t need the constructors for converting from the primitive boolean and String either. There are two static methods available just for this purpose. Boolean.valueOf(String) and Boolean.valueOf(boolean). Instead of saying:
Boolean isMad = new Boolean(true);
Boolean isNotCrazy = new Boolean("TRUE");

say -
Boolean isMad = Boolean.valueOf(true);
Boolean isNotCrazy = Boolean.valueOf("TRUE");

Because valueOf() returns either Boolean.TRUE or Boolean.FALSE, instead of creating another unnecessary Boolean instance. For the case when you already know whether to pass true or false, instead of saying:
book.setRegurgitable(new Boolean(false));

simply say
book.setRegurgitable(Boolean.FALSE);

So, be very suspicious of the existence of “new Boolean” in your codebase. If your code is based on JDK 1.4 or above, really, there shouldn’t be any “new Boolean” anymore, anywhere. In fact, if there’s a legit case when one just have to use the Boolean constructors in their code, please let me know, I’ll be grateful.

MVC/Designer Example

Saturday, 28 May 2011

Difference between Factory Pattern or Abstract Factory Pattern and Builder Pattern

Abstract factory may also be used to construct a complex object, then what is the difference with builder pattern? In builder pattern emphasis is on ‘step by step’. Builder pattern will have many number of small steps. Those every steps will have small units of logic enclosed in it. There will also be a sequence involved. It will start from step 1 and will go on upto step n and the final step is returning the object. In these steps, every step will add some value in construction of the object. That is you can imagine that the object grows stage by stage. Builder will return the object in last step. But in abstract factory how complex the built object might be, it will not have step by step object construction.

Both are creational pattern but differ:
Factory Pattern Builder Pattern
The factor pattern defers the choice of what concrete type of object to
make until run time.
E.g. going to a restaurant to order the special of  the day.  The waiter is the interface to the factory that takes the
abstractor generic message "Get me the special of the day!" and returns
the concrete product (i.e "Chilli Paneer" or some other dish.)
The builder pattern encapsulates the logic of how to put together a
complex object so that the client just requests a configuration and the
builder directs the logic of building it.   E.g The main contractor
(builder) in building a house knows, given a floor plan, knows how to
execute the sequence of operations (i,e. by delegating to subcontractors)
needed to build the complex object.  If that logic was not encapsulated in
a builder, then the buyers would have to organize the subcontracting
themselves 
The factory is concerned with what is made. The builder with how it is
made. So it focuses on the steps of constructing the complex object.
In case of Factory or Abstract Factory, the product gets returned immediately Builder returns the product as
the final step.

Thursday, 26 May 2011

Tuesday, 24 May 2011

Solution to Square rectangle problem

We have already gone through this problem here.
So inheritance is not always useful, but composition may be the key sometimes.

public class Square  
{
private Rectangle r;
public void SetWidth (double x) { r.SetWidth (x); r.SetHeight (x); }
public void SetHeight (double x) { r.SetWidth (x); r.SetHeight (x); }
public void GetWidth () { return r.GetWidth; }
public void GetHeight() { return r. GetHeight; }
public void GetArea () { return r. GetArea; }
}

So it solves our problem.