Follow treslines by email clicking Here!

Saturday, March 17, 2012

Making beans/data reusable and simultaneously reducing class size to only one method

Hi there! Today i wanna share an idea with you (generic bean/Data)

If there is one thing a hate is to write beans, getter and setters again, again and again. I was searching for a solution on how to make beans reusable and classes more readable, smaller and cleaner. A typical or common situation is when you need domain objects. I've caught myself constantly writting the "same  boring code" again and again. So i decided to search for a solution, which could help me saving time. I had an idea, which i would like to share with you. I've called it: "GenericBean".

IMPORTANT: After listening to the feedbacks from other developers I decided to let this post alive just to show to you, why this approach is not recommend and shall not be used. Stay with POJO's. 

Let's say we have a database table called "address". This address table may contain following attributes:
  • ID
  • FIRST_NAME
  • SECOND_NAME
  • STREET
  • HOUSE_NUMBER
  • ZIP_CODE
  • LAND
Let's say now, we need a domain class called: SimpleDomainAddress. The normal way would be to do something like this:

public class SimpleDomainAddress {
 
 private double addressId;
 private String firstName;
 private String secondName;
 private String street;
 private int houseNumber;
 private String zipCode;
 private String land;


 public double getAddressId() {
  return this.addressId;
 }

 public void setAddressId( double addressId ) {
  this.addressId = addressId;
 }

 public String getFirstName() {
  return this.firstName;
 }

 public void setFirstName( String firstName ) {
  this.firstName = firstName;
 }

 public String getSecondName() {
  return this.secondName;
 }

 public void setSecondName( String secondName ) {
  this.secondName = secondName;
 }

 public String getStreet() {
  return this.street;
 }

 public void setStreet( String street ) {

  this.street = street;
 }

 public int getHouseNumber() {
  return this.houseNumber;
 }

 public void setHouseNumber( int houseNumber ) {
  this.houseNumber = houseNumber;
 }

 public String getZipCode() {
  return this.zipCode;
 }

 public void setZipCode( String zipCode ) {
  this.zipCode = zipCode;
 }

 public String getLand() {
  return this.land;
 }

 public void setLand( String land ) {
  this.land = land;
 }
}

So this is the way everybody would do i think. Now if you have another domain object you'll do that again and so on generating a lot of unnescessary code lines in my point of view.

Let us hold on to what we do here:
  • We always define new variables
  • We always define new methods
  • We should have added "theoretically" some comments to it. 
The following UML diagram visualizes GenericBean approach:
 

Null Object
First of all we define a NULL object that could be written like this:

public class Null {
 // NullObject
}

GenericBean
Then we write the generic bean. This bean could be bigger then the example here. This is only a show case to visualize the idea behind it. I will intentionally violate some code conventions by writting variables very short and beginning with an underscore following by a number. I'll explain later why I am doing this way.

public class GenericBean<A, B, C, D, E, F, G, H, I, J> {
 private A _0;
 private B _1;
 private C _2;
 private D _3;
 private E _4;
 private F _5;
 private G _6;
 private H _7;
 private I _8;
 private J _9;

 public A get_0() {
  return this._0;
 }
 
 public void set_0( A _0 ) {
  this._0 = _0;
 }

 public B get_1() {
  return this._1;
 }

 public void set_1( B _1 ) {
  this._1 = _1;
 }

 public C get_2() {
  return this._2;
 }

 public void set_2( C _2 ) {
  this._2 = _2;
 }

 public D get_3() {
  return this._3;
 }

 public void set_3( D _3 ) {
  this._3 = _3;
 }

 public E get_4() {
  return this._4;
 }

 public void set_4( E _4 ) {
  this._4 = _4;
 }

 public F get_5() {
  return this._5;
 }

 public void set_5( F _5 ) {
  this._5 = _5;
 }

 public G get_6() {
  return this._6;
 }

 public void set_6( G _6 ) {
  this._6 = _6;
 }

 public H get_7() {
  return this._7;
 }

 public void set_7( H _7 ) {
  this._7 = _7;
 }

 public I get_8() {
  return this._8;
 }

 public void set_8( I _8 ) {
  this._8 = _8;
 }

 public J get_9() {
  return this._9;
 }

 public void set_9( J _9 ) {
  this._9 = _9;
 }
}

Shriking to only one method
Ok, at this point we have no profit of it right? Let's write know the same class SimpleDomainAddress again, but now using the GenericBean and Null Object.

public class SimpleDomainAddress {
 
 private GenericBean<Double, String, String, String, Integer, String, String, Null, Null, Null> genericBean;

 public SimpleDomainAddress() {
/** 
Database table: Id, Firstname, Secondname, Street, HouseNumber, Zipcode, Land
(The last 3 entries doesn't exit in the database, so we set our generic bean to Null)
*/
  this.genericBean = new GenericBean<Double, String, String, String, Integer, String, String, Null, Null, Null>();
 }

 /**
  * This generic bean represents the database table. 
  * See bellow how to get and set the values from it.
  * <ul>
  * <li>get_0 <b>return</b> AddressId</li>
  * <li>get_1 <b>return</b> Firstname</li>
  * <li>get_2 <b>return</b> Secondname</li>
  * <li>get_3 <b>return</b> Street</li>
  * <li>get_4 <b>return</b> HouseNumber</li>
  * <li>get_5 <b>return</b> Zipcode</li>
  * <li>get_6 <b>return</b> Land</li>
  * <li>get_7 Null (not used)</li>
  * <li>get_8 Null (not used)</li>
  * <li>get_9 Null (not used)</li>
  * </ul>
  */
 public GenericBean<Double, String, String, String, Integer, String, String, Null, Null, Null> getGenericBean() {
  return this.genericBean;
 }
}

Good side effects:
  • With this approach, the class is shrinking to less than a few lines of code.
  • A good side effect is the comment that is gaining in importance and now is no longer redundant.
  • If we notice that the database needs to be expanded, we only need to replace a NULL entry with the new value and we're done. 
  • Easy to learn (this example says all), simple, reusable.
  • We always know which entry is the first and the last in the database (get_1 & get_6 in this example)
The reason why i wrote the variables like "_0", _1" and so on is that this way, when i type "get" or "set" in my IDE, i'll get the methods in the same order(sequence) as i defined the database fields in my constructor as you can see above. This make the usage in association with the comment more intuitive and powerful.

Advertising:
Optimized bets for playing EuroMillion's lottery on your Mobile Phone! 







Please rate this blog - Press +1


Monday, March 5, 2012

How to write a singleton? (pros and contras)

A singleton for each situation and the pros and contras of it?


Lazy synchronized initialization

public final class Session 
  {
      private static Session instance;
 
      /** singleton */
      private Session() {}
 
      /** if you do not need synchronisation do not mark it as synchronized */
      public synchronized static Session getInstance() 
      {
          return (instance == null) ? instance = new Session() : instance;
      }
      /** your methods goes here... */
   }


PRO: can be initialized lazy the first time it is used
CONTRA: Singletons shall be avoid because they are hard to test and debug. Futher they contribute to less cohesive designs.


No Lazy initialization needed

public class Session 
  {
    private final static Session INSTANCE = new Session();

    private Session() {}

    public static Session getInstance() 
    { 
      return Session.INSTANCE; 
    }

    protected Object clone() 
    {
      throw new CloneNotSupportedException();
    }

    /** your methods goes here... */
  }

PRO: Immediate allocation of the needed resource
CONTRA: Needs "more" resource as nescessary + CONTRA from first case


No Lazy initialization needed (the elegant, modern way)

public enum Session 
   {
       INSTANCE;
       private int session;

       public int getSession() {
           return ++session;
       }

       /** your methods goes here... */
   }


PRO: Very simple, modern way. Immediate allocation of the needed resource
CONTRA: Needs "more" resource as nescessary + CONTRA from first case



How can i motivate other developers ?

Well i do that by talking about, i wear my treslines.com t-shirt, i wear my bracelets with the CCD (Clean Code Developer Initials and colors) and i use my brand new treslines bag. It feels fantastic and even on the train people start talking to me asking about it. It is also a great idea to motivate agile teams and to share your expirience. You may want a great gift to show your appreciation to your team. Surprise them with a gadget from www.treslines.com. I love it.


How could we improve the quality of this article ?

If the content of this article does not help you, so please tell us how to improve the quality of it by giving your contructive feedbacks at the end of this blog. If it was useful to you giving and resuming to you the most important aspects of the subject treated, saving you a lot of time, then help us to maintain this blog with a little appreciation. With a small amount of your choice you help us to cover the prime costs like:
Hosting, autors’s research work, editorial work, blog quality, motivation to make things better than others resulting in a very useful information pool for you and a lot of other developers. Important : If you do not have the possibility to donate a little amount, than recommend this page to your friends. Thanks !






Source code convention tools

Literature, good books and references

Want to stay up to date ?