Kevin's Blog

IT, Scala, Java, Web, Ubuntu

Tag: Eclipse (page 2 of 3)

Method Chaining, to use, or not to use

It was a Gavin King’s book from which I first heard about method chaining since it is not that popular style in Java.

Bauer and King in their book entitled ‘Java Persistence with Hibernate’ (2007), point out that method chaining is convenient in some cases and is more popular in Smalltalk than in Java for Smalltalk, unlike Java, does not have void type. Thus when a method is invoked, it normally returns the object itself in which the method is placed.

Although it is used to improve readability and to reduce the amount of source code, I didn’t really like this style as it can be less readable and might make code difficult to debug. How can the technique to improve readability make the code less readable? By less readable, I mean the code may possibly be unpredictable or make the programmer confused in some cases.

Let’s look at some example.

This is a simple JavaBean named Item

package com.lckymn.kevin.test.methodchaining;

/**
 * @author Lee, SeongHyun (Kevin)
 */
public class Item
{
	private int id;
	private String name;

	public Item(int id, String name)
	{
		this.id = id;
		this.name = name;
	}

	public int getId()
	{
		return id;
	}

	public void setId(int id)
	{
		this.id = id;
	}

	public String getName()
	{
		return name;
	}

	public void setName(String name)
	{
		this.name = name;
	}

	@Override
	public String toString()
	{
		return "ID: " + id + "\n" + "Name: " + name + "\n";
	}
}

This is a Storage class designed to use method chaining.

package com.lckymn.kevin.test.methodchaining;

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

/**
 * @author Lee, SeongHyun (Kevin)
 */
public class Storage
{
	private List<Item> items;

	public Storage()
	{
		this.items = new ArrayList<Item>();
	}

	public Storage put(String name)
	{
		items.clear();
		return and(name);
	}

	public Storage and(String name)
	{
		items.add(new Item(name.hashCode(), name));
		return this;
	}

	public Item get(int index)
	{
		return items.get(index);
	}

	public List<Item> getAll()
	{
		return items;
	}
}

Now, let’s use it.

package com.lckymn.kevin.test.methodchaining;

/**
 * @author Lee, SeongHyun (Kevin)
 */
public final class MethodChainingTest
{
	public static void main(String[] args)
	{
		String name = new Storage().put("A").and("B").and(null).and("D").get(0).getName();
		System.out.println("Name: " + name + "\n");

		System.exit(0);
	}

}

What is this? It looks like instantiating a Storage object yet the end it assigns String value to String variable named name?

It seems confusing. First, instantiate Storage. Then call several methods in it. Finally call the method which returns a String value. However, the Storage class doesn’t even have any method returning the String value. It is the method in the Item class.

OK, move to the other problem that is difficulty in debuging.
The example code above does not have any compile time error yet when it runs the result is

Exception in thread "main" java.lang.NullPointerException
	at com.lckymn.kevin.test.methodchaining.Storage.and(Storage.java:26)
	at com.lckymn.kevin.test.methodchaining.MethodChainingTest.main(MethodChainingTest.java:10)

The tenth line in the MethodChainingTest.main method is this.

		String name = new Storage().put("A").and("B").and(null).and("D").get(0).getName();

The twenty-sixth line in the Storage.and method is this.

		items.add(new Item(name.hashCode(), name));

So this line of the code causes NullPointerException but and() method is called three times in the tenth line of the MethodChainingTest class. Which one of these causes the error? In the example, it is very obvious that the and() method call with null parameter is the one. However, in real-life programme, it is usually much more difficult to find.

So, as already mentioned, I did not like using method chaining. Then again there came a time when it was very convenient and useful to use method chaining. I found it very useful when I was making a XML generator programme for an Ajax application. I made it using Java API for XML Processing (JAXP). It required to generate simple XML based on a given object so it might be too much to use XML data binding frameworks and tools such as Java Architecture for XML Binding (JAXB) and XStream. Although both JAXB and XStream are simple and easy to use and can be used to serialise objects, I wanted to have more control than what the framework provides. JAXP with Simple API for XML (SAX) parsing interface was just suitable for what I needed, yet it is not very pleasant to use the SAX interface. It uses ContentHandler interface when making XML contents and the following code is what it looks like when using it.

contentHandler.startDocument();

AttributesImpl atts = new AttributesImpl();
atts.addAttribute(null, null, "type", null, "User");
contentHandler.startElement(null, null, "users", atts);

atts.clear();
atts.addAttribute(null, null, "id", null, "kevin");
atts.addAttribute(null, null, "surname", null, "Lee");
atts.addAttribute(null, null, "givenName", null, "Kevin");
contentHandler.startElement(null, null, "user", atts);
contentHandler.characters("Test value".toCharArray(), 0, "Test value".length());
contentHandler.endElement(null, null, "user");

atts.clear();
atts.addAttribute(null, null, "id", null, "john");
atts.addAttribute(null, null, "surname", null, "Doe");
atts.addAttribute(null, null, "givenName", null, "John");
contentHandler.startElement(null, null, "user", atts);
contentHandler.characters("Blah Blah".toCharArray(), 0, "Blah Blah".length());
contentHandler.endElement(null, null, "user");

atts.clear();
atts.addAttribute(null, null, "id", null, "tom");
atts.addAttribute(null, null, "surname", null, "Smith");
atts.addAttribute(null, null, "givenName", null, "Tom");
contentHandler.startElement(null, null, "user", atts);
contentHandler.characters("12345".toCharArray(), 0, "12345".length());
contentHandler.endElement(null, null, "user");

contentHandler.endElement(null, null, "users");

contentHandler.endDocument();

As all I want was simple XML for an Ajax application, I had to type ‘null‘ many times as parameter values for namespace URI and local name which were definitely unnecessary for my programme. Since the data transfered through network need to be small, XML sent to the front-end Ajax application had better not have the data such as namespace and schema location information and so on.

However, what I all had was, as shown above, the ugly code which repeatedly calls same methods with many ‘null’ parameters. So I tried to find a better way and eventually came up with that it might be a good idea to use method chaining. Even so, there were still the two problems I mentioned.

The method chaining code example that I showed earlier is, in fact, a misuse of method chaining. That can be much better if it is used properly. After all, it is not the technique that makes the code less maintainable but how it is used that makes the code less maintainable.

Think about this. If a knife is used by a murderer, the result of using it would be a dead body while if it is used by a chef, the result would be a delicious meal unless the chef is the murderer. :) (I think I used this sentence when I had my presentation in the third year in my undergraduate days. The subject was about IT and ethics, and I was emphasising that technologies have nothing to do with ethics yet how we use these is important when it comes to ethics).

So, how can those two problems be solved? First of all, please don’t get me wrong. I am not saying that the way I am going to tell here is the best, but it is just what I do. That’s it.

I chose to implement fluent interface yet with my own taste.

Cho, YoungHo (2008) in his article, ‘Applicaiton of Domain-Driven Design 2.Aggregate and Repository #3‘, also says that although FLUENT INTERFACE might violate the principle of COMMAND-QUERY SEPARATION which enforces to separate the method to change the state of an object from the method to query the state, FLUENT INTERFACE using method chaining can enable the interface design to be more readable and easier to use.

If you can understand Korean and are interested in Domain-Driven Design (DDD), his articles about DDD are really worth reading.
http://aeternum.egloos.com/category/Domain-Driven%20Design
It is well written with appropriate example code and supporting theories and principles.

So my tastes are
1. The prefix ‘Fluent’ shall be used to tell it is a fluent interface.
e.g.)
public interface FluentContentHandler
public interface FluentStorage

2. void return type shall be used to stop method chaining if the method should not be used with other methods in the fluent interface or if it has some side-effect when using with other methods so that the programmer should be noticed it by void return type.
e.g.)
void endDoc()
void finish()

3. Otherwise, all the methods shall return the type of interface itself, and the name of the normal methods which return the type of the interface itself shall begin with verb.
e.g.)
FluentContentHandler openElem(String qName)
FluentContentHandler setText(String qName)
FluentSaxAttributes create(String qName, String value)

OR
The name of the method which must be used before the other methods shall begin with a verb.
e.g.)
FluentSaxAttributes create(String qName, String value)
The name of the method which must be used after the method the name of which begins with a verb shall be an appropriate preposition or conjunction.
e.g.)
FluentSaxAttributes with(String qName, String value)
FluentSaxAttributes and(String qName, String value)

4. If other types than the interface itself need to be returned, distinguishable method names shall be used. The name of the methods which return other type than the type of the interface itself shall begin with a preposition followed by a noun.
e.g.)
List toList()
Map toMap()
Collection toCollection()

I believe, these can help me to get over the first matter, and the code would be more readable as expected.

So let’s have a look at the new fluent interfaces for my XML generator programme.

package com.lckymn.kevin.test.xml;

import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;

/**
 * @author Lee, SeongHyun (Kevin)
 */
public interface FluentSaxContentHandler
{
	void startDoc() throws SAXException;

	void endDoc() throws SAXException;

	FluentSaxContentHandler openElem(String qName) throws SAXException;

	FluentSaxContentHandler openElem(String qName, FluentSaxAttributes attributes) throws SAXException;

	FluentSaxContentHandler setText(String text) throws SAXException;

	void closeElem(String qName) throws SAXException;
}

The programmer using this interface had better be aware of that startDoc() and endDoc() methods are to start and to end the XML document so use it once and therefore these return void type to warn. Similarly, closeElem() method the type of which is void closes the element with the name given as the parameter so the programmer had better stop method chaining here and open a new element with another method chaining.

package com.lckymn.kevin.test.xml;

import org.xml.sax.helpers.AttributesImpl;

/**
 * @author Lee, SeongHyun (Kevin)
 */
public interface FluentSaxAttributes
{
	FluentSaxAttributes create(String qName, String value);

	FluentSaxAttributes add(String qName, String value);

	AttributesImpl toAttributesImpl();
}

Since the ContentHandler requires AttributesImpl as attributes toAttributesImpl() method needs to return AttributesImpl and therefore its name consists of the preposition ‘to’ and the noun ‘AttributesImpl’.

Now let’s use these.

	contentHandler.startDoc();
		
	contentHandler.openElem("users", atts.create("type", "User"));
		
	contentHandler.openElem("user", atts.create("id", "kevin").add("surname", "Lee").add("givenName", "Kevin")).setText("Test value").closeElem("user");
	contentHandler.openElem("user", atts.create("id", "john").add("surname", "Doe").add("givenName", "John")).setText("Blah Blah").closeElem("user");
	contentHandler.openElem("user", atts.create("id", "tom").add("surname", "Smith").add("givenName", "Tom")).setText("12345").closeElem("user");
		
	contentHandler.closeElem("users");
	
	contentHandler.endDoc();

It looks much simpler and readable than the previous code below.

	contentHandler.startDocument();

	AttributesImpl atts = new AttributesImpl();
	atts.addAttribute(null, null, "type", null, "User");
	contentHandler.startElement(null, null, "users", atts);

	atts.clear();
	atts.addAttribute(null, null, "id", null, "kevin");
	atts.addAttribute(null, null, "surname", null, "Lee");
	atts.addAttribute(null, null, "givenName", null, "Kevin");
	contentHandler.startElement(null, null, "user", atts);
	contentHandler.characters("Test value".toCharArray(), 0, "Test value".length());
	contentHandler.endElement(null, null, "user");

	atts.clear();
	atts.addAttribute(null, null, "id", null, "john");
	atts.addAttribute(null, null, "surname", null, "Doe");
	atts.addAttribute(null, null, "givenName", null, "John");
	contentHandler.startElement(null, null, "user", atts);
	contentHandler.characters("Blah Blah".toCharArray(), 0, "Blah Blah".length());
	contentHandler.endElement(null, null, "user");

	atts.clear();
	atts.addAttribute(null, null, "id", null, "tom");
	atts.addAttribute(null, null, "surname", null, "Smith");
	atts.addAttribute(null, null, "givenName", null, "Tom");
	contentHandler.startElement(null, null, "user", atts);
	contentHandler.characters("12345".toCharArray(), 0, "12345".length());
	contentHandler.endElement(null, null, "user");

	contentHandler.endElement(null, null, "users");

	contentHandler.endDocument();

Yet there is one more problem still left that is difficulty in debugging.

King and Bauer (2007) suggests that “itโ€™s better to write each method invocation on a different line”.

So rewrite the code

	contentHandler.startDoc();

	contentHandler.openElem("users", atts.create("type", "User"));

	contentHandler.openElem("user", atts.create("id", "kevin")
			.add("surname", "Lee")
			.add("givenName", "Kevin"))
			.setText("Test value")
			.closeElem("user");
	contentHandler.openElem("user", atts.create("id", "john")
			.add("surname", "Doe")
			.add("givenName", "John"))
			.setText("Blah Blah")
			.closeElem("user");
	contentHandler.openElem("user", atts.create("id", "tom")
			.add("surname", "Smith")
			.add("givenName", "Tom"))
			.setText("12345")
			.closeElem("user");

	contentHandler.closeElem("users");

	contentHandler.endDoc();

Now not only does it solve the problem in debugging but it is also even more readable. My problem solved! ๐Ÿ˜€
Well, unfortunately there is one more problem. :(

I am using Eclipse and it has a nice automatic formatting feature. So whenever I press SHIFT+CTRL+F, it automatically formats the code opened in the editor based on the format configuration. This means if I use that function, I lose the coding style of writing each method invocation on a different line as Eclipse formatter puts all the method on a different line together on one line. So do I have to reformat by myself after every automatic formatting? It’s really annoying. :(

Fortunately, a few changes in formatter configuration can solve this problem.

Click the ‘Window’ menu -> ‘Preferences’

When the ‘Preferences’ menu pops up
-Expand the ‘Java’ -> Expand the ‘Code Style’ -> Select the ‘Fomatter’

-Click the ‘Edit’ button on the top right-hand side.
Expand the 'Java' -> Expand the 'Code Style' -> Select the 'Fomatter' -> Click the 'Edit' button on the top right-hand side

-The profile window appears -> Select the ‘Line Wrapping’ -> Expand the ‘Function Calls’ -> Select the ‘Qualified invocations’ -> Select the ‘Wrap all elements, except first element if not necessary’ as the ‘Line wrapping policy’ -> Select the ‘Default indentation’ as the ‘Indentation policy’ -> Check the ‘Force split’ -> Click the ‘OK’ button.
Profile window appears -> Select the 'Line Wrapping' -> Expand the 'Function Calls' -> Select the 'Qualified invocations' -> Select the 'Wrap all elements, except first element if not necessary' as the 'Line wrapping policy' -> Select the 'Default indentation' as the 'Indentation policy' -> Check the 'Force split' -> Click the 'OK' button

-Click the ‘OK’ button to apply the changes.

Now, the Eclipse Java formatter formats the code, using method chaining, as what I want.

Finally, how can I improve my first example of method chaining?
The Item class does not need to be changed.

Write the fluent interface, FluentStorage.

package com.lckymn.kevin.test.fluentinterface;

import java.util.List;

/**
 * @author Lee, SeongHyun (Kevin)
 */
public interface FluentStorage
{
	FluentStorage add(String name);
	
	List<Item> toList();
}

Write the class implements it.

package com.lckymn.kevin.test.fluentinterface;

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

/**
 * @author Lee, SeongHyun (Kevin)
 */
public class FluentListStorage implements FluentStorage
{
	private List<Item> items;

	public FluentListStorage()
	{
		items = new ArrayList<Item>();
	}

	@Override
	public FluentStorage add(String name)
	{
		items.add(new Item(name.hashCode(), name));
		return this;
	}

	@Override
	public List<Item> toList()
	{
		return items;
	}

}

Now use the fluent interface.

package com.lckymn.kevin.test.fluentinterface;

import java.util.List;

/**
 * @author Lee, SeongHyun (Kevin)
 */
public final class MethodChainingTest
{
	public static void main(String[] args)
	{
		FluentStorage fluentStorage = new FluentListStorage().add("A")
				.add("B")
				.add(null)
				.add("D");

		List<Item> items = fluentStorage.toList();
		for (Item item : items)
		{
			System.out.println(item);
		}
		int howMany = items.size();
		System.out.println("There " + (1 < howMany ? "are " + howMany + " items" : "is " + howMany + " item") + " in the storage.");
		System.exit(0);
	}

}

When it runs, it displays the following error messages yet now I know that the fourteenth line causes the error.

Exception in thread "main" java.lang.NullPointerException
	at com.lckymn.kevin.test.fluentinterface.FluentListStorage.add(FluentListStorage.java:21)
	at com.lckymn.kevin.test.fluentinterface.MethodChainingTest.main(MethodChainingTest.java:14)

The fourteenth line is this.

				.add(null)

So change it to

				.add("C")

I could finally have the correct result.

ID: 65
Name: A

ID: 66
Name: B

ID: 67
Name: C

ID: 68
Name: D

There are 4 items in the storage.

So method chaining, to use, or not to use? It’s all up to you. ๐Ÿ˜€

References
Bauer, C. and King, G. 2007, Java Persistence with Hibernate, Manning Publications Co., New York.

Cho, Y. 2008, Applicaiton of Domain-Driven Design 2. Aggregate and Repository #3, viewed 29 June 2009, <http://aeternum.egloos.com/1173825>.

ROO So Cool!!! -04-

Continued from
http://blog.lckymn.com/2009/05/17/roo-so-cool-03/

There are two other aspects which are Choice_Roo_Plural and Choice_Roo_ToString.

"Choice" in Plural Form, "Choices"

"Choice" in Plural Form, "Choices"


Choice_Roo_Plural declares that the Choice has a method named getPluralName() which returns a String type value, “Choices” which is the plural form of “Choice”. I don’t really get why it is necessary though. I first thought it might be the name of the table with which the Choice_Roo_Entity matches, yet the table name is choice.

Bind entity com.springsource.vote.domain.Choice on table choice

It is probably for the future use as a name of domain object in plural form may be frequently required when displaying the list of it.

Now, let’s look at the last aspect.

toString() method for Choice

toString() method for Choice


The last one is Choice_Roo_ToString which declare that Choice has toString() method.

privileged aspect Choice_Roo_ToString {
    
    public java.lang.String Choice.toString() {    
        StringBuilder sb = new StringBuilder();        
        sb.append("id: ").append(getId()).append(", ");        
        sb.append("version: ").append(getVersion()).append(", ");        
        sb.append("namingChoice: ").append(getNamingChoice()).append(", ");        
        sb.append("description: ").append(getDescription()).append(", ");        
        return sb.toString();        
    }    
    
}

It returns String containing the information about Choice which includes all the values of the variables from the aspects as well. This String is used to display the information about Choice object in the view, WEB-INF/jsp/vote/create.jsp.

All these mixins can be good Separation of Concerns (SoC). Each aspect has what should be a concern in a particular mixin only. For example, id and version of Choice are not really a concern of Choice itself as it does not have any meaning for Choice, yet it is very important for OR mapping. Thus it is separated from Choice and only occurs in Choice_Roo_Entity which plays the role of a persistent object.

It is not a completely new ways to write mixin using inter-type declarations in AspectJ (http://today.java.net/pub/a/today/2005/12/15/writing-mixins-with-aop.html). Nevertheless, Spring ROO is still so cool as I have never seen any automatically generated code by Java frameworks uses mixins written using inter-type declarations as a nice way of SoC. I may need to call ROO RSoC (Real Separation of Concerns). :)

OK, I am now running out of time so had better finish this post quickly.

I would just finally like to point out some minor issues I found.

1. An error in dojo JS toolkit.

dojo JS Toolkit Error

dojo JS Toolkit Error

2. An error in roo.css file.

CSS Error

CSS Error

#wrap {
	margin:0 auto;
  	position:relative;
  	float:center;  	
  	top: 0px;
  	left:0px;
  	width:800px;
  	text-align:left;  	

}

center is not a float value.

3. Using a String’s equals() method to test for an empty String. This might be OK for a small application like the ROO example but it can bring about some performance issue for a big application with numerous simultaneous user requests.

Performance Issue - Test for Empty String

Performance Issue - Test for Empty String


So the following code from ChoiceEditor_Roo_Editor

if (text == null || "".equals(text))

had better be

if (text == null || 0 == text.length())

I wrote more details about it here with performance tests.
http://blog.lckymn.com/2009/05/17/test-for-empty-string/

Finally, it’s my wish. I found that aspect code is not really supported by the Eclipse functions for Java such as Call Hierarchy and Open Declaration. It would be much better if aspects are fully supported by the Eclipse functions for Java. However, it may have something to do with AJDT not Spring ROO integration.

Phew, I have eventually written this. ๐Ÿ˜€ Even though I tried ROO approximately two weeks ago, I did not have time to write about it.

ROO So Cool!!! -03-

Continued from
http://blog.lckymn.com/2009/05/17/roo-so-cool-02/

Now, let’s look at more interesting one that is the ROO generated source code!

As you can see, there are many AspectJ aspects in the com.springsource.vote.domain package. So I’ll firstly try to look at the Choice class which is not an aspect.

Domain object - Choice

Domain object - Choice


Wow! Is that it? Without the annotations, it consists of only two lines of code in the class. Just two variable declarations.

So where are the others?

Check out the Choice_Roo_Entity aspect.

Persistent Object (Aspect)

Persistent Object (Aspect)


It appears to be a persistent object class with a persistence manager which means it includes data access logic. This sounds like normal Active Record yet if you closer look at the code, it uses AspectJ’s inter-type declaration to add more attributes and behaviours to the domain object Choice.

    @javax.persistence.Id    
    @javax.persistence.GeneratedValue(strategy = javax.persistence.GenerationType.AUTO)    
    @javax.persistence.Column(name = "id")    
    private java.lang.Long Choice.id;

This code above is declaring long type id variable to the type Choice to use as an identifier for OR mapping. Because it is declared as a private variable, it is impossible to access it inside the code of Choice but possible only inside this Choice_Roo_Entity aspect.

What about the Choice_Roo_JavaBean.

JavaBean (Aspect)

JavaBean (Aspect)


It has all the getters and setters for the Choice class and again inter-type declaration is used for adding these accessor methods. So an instance of Choice type cannot only behave as a persistent object but also as a JavaBean object. If you look into the jsp file, you can see it is used just like the methods belong to Choice class.
In order to access the variables inside Choice object, the Choice_Roo_JavaBean is defined as privileged aspect.

privileged aspect Choice_Roo_JavaBean {
    
    public java.lang.String Choice.getNamingChoice() {    
        return this.namingChoice;        
    }    
    
    public void Choice.setNamingChoice(java.lang.String namingChoice) {    
        this.namingChoice = namingChoice;        
    }    
    
    public java.lang.String Choice.getDescription() {    
        return this.description;        
    }    
    
    public void Choice.setDescription(java.lang.String description) {    
        this.description = description;        
    }    
    
}

So as shown above, Choice_Roo_JavaBean is a privileged aspect and therefore it can access namingChoice and description variables which are declared in Choice.

So what is it? It is a mixin. Mixin is a class which provides a functionality to a subclass yet mixin itself is not supposed to stand alone. So a class can collect its functionality by inheriting from one or more mixins through multiple inheritance. However, as we all know, Java does not support multiple inheritance. So to use mixins in Java world, inter-type declarations in AspectJ can be used.

privileged aspect Choice_Roo_Entity {
    
	(...)
    
    @javax.persistence.Id    
    @javax.persistence.GeneratedValue(strategy = javax.persistence.GenerationType.AUTO)    
    @javax.persistence.Column(name = "id")    
    private java.lang.Long Choice.id;    
    
    (...)
    
    public java.lang.Long Choice.getId() {    
        return this.id;        
    }    
}

As seen in the aspect code above, a long type variable is added to the type Choice and a getId() method which returns a long type value that is the value in the variable, id, just added by the aspect. So an instance of Choice type can have getId() method even though it does not exist in the Choice class. Therefore, as mentioned, Choice type can have characteristics of both persistent object and JavaBean.

AspectJ is also used to declare Choice type as a configurable type.

Make Choice @Configurable

Make Choice @Configurable


This code reveals that Choice type has @org.springframework.beans.factory.annotation.Configurable annotation.

privileged aspect Choice_Roo_Configurable {
    
    declare @type: Choice: @org.springframework.beans.factory.annotation.Configurable;    
    
}

Next:
http://blog.lckymn.com/2009/05/17/roo-so-cool-04/

Older posts Newer posts

© 2018 Kevin's Blog

Theme by Anders NorenUp ↑

%d bloggers like this: