Sunday, February 23, 2014

One scenario to use anonymous class

Anonymous class is helpful when you want temporarily change the class function or create a new implementation.

Here is one Scenario. Let’s say we can have an domain class user which properties are id, firstName, lastName, email, createDate… The users are loaded from a csv file.  The csv files may contains duplicated user information. When loading user from csv, it need determine if the user is duplicate. It only compares firstName, lastName and email. It does not care id and  createDate. So I want to implement the equals method which only compares firstName, lastName and email. But this equals method should only be used while loading users from csv. I don’t want to change the default equals behavior.

Here we can use anonymouse class when creating domain objects from csv files.  The pseudo code is like this.

//while loading user from csv
set.add(new User(firstName, lastName, email) {
public boolean equals(Object obj) {
return firstName.equals(obj.firstName) && lastName.equals(obj.lastName)
&& email.equals(

No comments:

Post a Comment