Needless to say, I completely agree with all the above points, so what was the solution? well the solution was to come up with a common constants class in which you dump all your constants and add comments to group each in a certain way. Needless to say there will be some groupings which are outrageously funny. Like in one of the projects we had to check and constantize all integers, doubles, numbers. (refer to : Magic Numbers), due to lack of time (now thats new ain’t it?
), people were adding things like public static final int INTEGER_1 = 1 !!.
And top that with all things mixed up, one can be assured that the class turns out to be a mess. To top all of this java introduced a feature called static imports. Probably because many lame programmers were complaining that it is “too” much of an effort to precede the CONSTANT_NAME with its class, so it my class that has all the constants is called something like CONSTANTS, i would have to do something like CONSTANTS.CONSTANT_EMPLOYEE_ID or something in those lines to refer to any constant; So basically to solve this, java provides for static imports, all you have to do is import static XXX.XXX.XXX.CONSTANTS.* and viola! you don’t have to do that DOT thing anymore. This is Evil! How am I supposed to know that this constant belongs to this class only and not anywhere else?! needless to say my code gets more obfuscated and hard to read and maintain with static imports.
So where is the solution? Solution my friends lies in creating a common interface, generically tying it up to something and then creating separate place holders for each TYPE of constants. So if you want to group all IDs for example, use IDPlaceHolder which would implement this interface. Lets get started on how to do this. First we will create an interface called IConstantPlaceHolder like this :
// Java docs removed for clarity.
public interface IConstantPlaceHolder<T extends Serializable> extends Serializable {
// gets the value for the constant
public abstract T getValue();
// sets the value for the constant.
public abstract void setValue(final T value);
}
As you can see IConstant place holder is generically tied to a type "T" (let me know if you think of a better name than just a T
). It has two methods setValue and get value. It is a Common interface for constants that serves as a place holder for all constants grouped in a meaningful way. For example, all ID constants could be placed in one spot. A typical implementation would be something like:
public enum IDPlaceHolder implements IConstantPlaceHolder<Long> {
DEFAULT_ID(1008L);
private Long id;
// default constructor sets the value.
private IDPlaceHolder(final Long id){
setValue(id);
}
// get the value
public final Long getValue(final Long id){
return this.id;
}
// set the value
public final setValue(final Long id){
this.id = id;
}
}
Now all i have to do in client code is IDPlaceHolder.DEFAULT_ID.getValue() and i will have 1008L at my behest. It is expected and recommended that an IConstantPlaceHolder be implemented with the help of an enum, by using an enum one can take advantage of inherent type-safe features in java language. Similar to above we can/may have something like a place holder for all properties or association paths in Hibernate. For our purposes, lets take a simple example of simple string properties like first name, last name etc for an employee.
:
public enum GenericStringPropertyPlaceHolder implements IConstantPlaceHolder<String> {
// employee's first name.
EMPLOYEE_FIRST_NAME("Mahadev"),
// employee's last name.
EMPLOYEE_LAST_NAME("Shiva"),
// employee's address.
EMPLOYEE_ADDRESS("Brahmlok"),
// employee department
EMPLOYEE_DEPT("NA");
// the property value we want to set.
private String propertyValue;
// get the value
public final String getValue() {
return propertyValue;
}
//set the value
public void setValue(String value) {
this.propertyValue = value;
}
// constructor that sets the property value.
private GenericStringPropertyPlaceHolder(String propertyValue) {
setValue(propertyValue);
}
}
As you can make out, in my client code, I would do something like GenericStringPropertyPlaceHolder.EMPLOYEE_LAST_NAME.getValue() and i will get Shiva as the result. So basically to sum up what we have done in above to implementations is:
Advantages
Obviously, lot of you might be thinking at this point what is need for all this? well my justification is that when a project grows larger and larger, we will eventually end up with a file that looks bulky, bloated and all over the place and then at that point we would ask where is the separation of concerns that i love so much here ?. Trust me, even in a small project this can serve a lot of purposes by putting a constant to the place it belongs.
An improvement to the above place holder thing can be adding a MODEL in generic parameters and further restricting constants only specific to a model. I have not come with a final draft for the same, when i do, i’ll try to post it as a follow up. Btw, thanks for your encouraging emails and support, appreciate it and Stay tuned!
Regards
Vyas, Anirudh
Why Generic DAO is not perfect?
For starters a simple justification would be separation of operational concerns; we want our “operational” aspects for that Model / Persistent class be separated. So for example in a DAO if i am doing a SAVE operation, i should only be concerned with doing a SAVE in DAO and nothing else, If i have a DAO method which deletes a model, then DAO should only be able to handle DELETE and nothing else.
Using a Generic DAO can reduce clutter, but to truly separate out operational aspects would make the code even cleaner (off course it adds a “tad” extra burden of writing more classes/interfaces but it also would make the code more robust IMHO), the code needs to be functionally separate as well or operationally separate to make it a better suited candidate for writing robust test cases.
Let’s Get Started!
Continuing with my philosophy of “lets get down and dirty” in code, lets get on with seeing somethings in action. I will start out by creating bunch of interfaces on which I would then elaborate to give an idea as to what I meant when i said “separation of Operational Concerns”. Lets pull out a common Generic DAO interface.
public interface IGenericOperationDAO<OPERATION extends IOperation<TYPE>,
TYPE extends Serializable,
MODEL extends AbstractModel<>,
ID extends Serializable>{
/**
* Performs operation on a model.
*
* @param operationType
* operation to perform
* @param model
* model to be operated upon.
* @see IOperation
*/
public abstract void performOperation(final OPERATION operationType,
final MODEL model);
}
Lets examine this interface a little to get a glimpse of what i am talking about. IGenericOperationDAO is tied to a MODEL (an AbstractModel is just an abstract class that extends Serializable and serves as a common model for our Models that match the tables in Database). Our GenericOperationDAO interface has one method, that is well apparently very "Generic", it just says performOperation takes in an IOperation type and a model. an IOperation type interface is basically something like this:
/**
* Gets the operation type.
*
* @return the operationType
*/
public abstract TYPE getOperationType();
An operation type can be DELETE, CREATE, READ, UPDATE or anything of that sort. An implementation for this operation is as follows. (For simplicity’s sake, lets assume that we need to do only a deletion (C-U-D operations will be the same).:
public class DeleteOperation implements IOperation<String> {
/**
* {@inheritDoc}
*/
public final String getOperationType() {
return "Delete";
}
}
As you can make out that operation type simply returns a delete “string” (this can be useful in comparing operation types within a DAO), a string is not very robust approach IMHO, if someone has better ideas, feel free to share
!
Now since perform operation is perhaps too generic, lets extend this interface to incorporate our deletions. Here is an example of a generic Delete interface:
public interface IGenericDeleteOperationDAO extends IGenericOperationDAO<DeleteOperation, String, AbstractModel<Long>, Long> {
/**
* Deletes a model.
*
* @param model
* model type to be deleted.
*/
public abstract void processDelete(final AbstractModel<Long> model);
}
Notice that our generic delete DAO is generically typed to DeleteOperation type.
As we can make out from the above, the generic delete dao inherits performOperation from its generic counter part and extends it by adding processDelete which basically takes in the model and deletes it. All implementing classes (Concrete that is) are expected to implement this method. But as we can make out that we probably don’t want to do certain kinds of things that are in here by implementing this interface directly. Implementing this interface has to be discouraged here since it does NOT directly enforce me going and implementing performOperation unfortunately. To avoid that from happening, lets create another abstraction (i.e. an Abstract Class which implements certain parts of this functionality), see below:
// java docs left out for clarity
public abstract class AbstractGenericDeleteOperationDAO implements IGenericDeleteOperationDAO {
/**
* Default constructor. Calls perform
* operation which in turn calls process
* delete to delete the model given.
*/
public AbstractGenericDeleteOperationDAO(final DeleteOperation operationType, final AbstractModel<Long< model) {
performOperation(operationType, model);
}
// javadocs left out
public abstract void processDelete(final AbstractModel<Long< model);
//javadocs left out
public void performOperation(DeleteOperation operationType, AbstractModel<Long< model) {
if (!operationType.getOperationType().equalsIgnoreCase("delete")) {
throw new UnsupportedOperationException("No other operation except DELETE supported");
} else {
processDelete(model);
}
}
}
Quickly the above code will do this:
So basically a simple implementation of a DAO from a client perspective would look like this:
/**
* Employee delete dao. Concerns itself with just the delete operations for an Employee Model.
*
* @author Anirudh Vyas
*/
public class EmployeeDeleteOperationDAO extends AbstractGenericDeleteOperationDAO {
/**
* Full constructor.
*
* @param operationType
* delete operation type.
* @param model
* model type to be operated upon.
*/
public EmployeeDeleteOperationDAO(DeleteOperation operationType, AbstractModel<Long> model) {
super(operationType, model);
}
/**
* {@inheritDoc}
*/
@Override
public final void processDelete(final AbstractModel<Long> model) {
// perform Hibernate Deletes here...
}
}
Now at real client side for this DAO would be a simple matter of doing something like new EmployeeDeleteOperationDAO(DELETE, employeeModel); and viola! we are done! … similar pattern can be followed for Creation, Reads, Updates. For combination of CRUD operation, a perform operation should be enough. Later we will see how we can improve upon the operation type to make it a little more dynamic than just comparing it with a string or returning a simple string “delete” or a “create” in operation type, so stay tuned and thanks for reading!
Addendum : understandably there can be improvements done in this; refinements etc. If you have any feel free to comment out here, instead of mailing them. That would keep it consistently here. I will try my best to post whenever i get any emails about the refinement.
Regards
Vyas, Anirudh
Keeping in my traditional approach, lets define what a code review is, (taken from Wikipedia off course):
Code review is systematic examination (often as peer review) of computer source code intended to find and fix mistakes overlooked in the initial development phase, improving both the overall quality of software and the developers’ skills.
Types of Code reviews :
This was more or less formalized by Michael Fagan. The essence of Fagan inspections lies in comparing output of minuscule operation to the so called “exit-criteria” already defined or comparing with output requirements as defined earlier in requirement gathering process. This kind of review makes a lot of sense in keeping the code on track for the end result software product. More often than not, in their ever increasing quest for developing “cool” software developers tend to overlook requirements specifications. The idea is to verify (at each step in an iteration) functional aspects of what is being developed, assigned to individual developers. For example if Sam is working on “search” aspect of the system (I am using Non Programming language on purpose), Is he following what is “required” ?, Is the requirement being “met” by what he has written? … by asking those kinds of questions and validating the code; the end product becomes bug resistant (It obviously can never be Bug free
). The important piece of the puzzle is to do this in smaller iterations and not at the end of development iteration, where developer has worked on a size able block of code already. If the code written is working and is meeting the functional requirements, it seems that fagan inspections would pass through. In “real” world this is off course only one side of the story. More often than not the requirements are not the ONLY factor in doing inspections; sometimes inspections can yield a “possible” crack through in the code which off course leads to more rework. A typical Inspection process involves Planning —> Overview —> Preparation —> Inspection —> Rework —> Follow up.
Developers meet one on one, and sit down side by side, to inspect each line of code, and review happens by asking questions; like “Why is this being done in this way and not “that” way? … Often these kinds of reviews evoke emotional responses from both the developers involved. ( for more read this great article : Code Reviews without much pain!). In most cases developers involved are emotionally involved with the code that they write, hence it becomes very important to criticize their code very carefully and not to go overboard about the cynicism. As you would read in the link, More often a senior developer will be reviewing a junior developer’s code, if that is the case, it is of paramount importance that senior developer shoulder’s the responsibility of reviewing code in a “constructive” manner drawing a line between what is “required”, what is “right” way, what is officially “correct” way of doing things. In many cases, (as I have seen in the past and seeing now) developers will often be asked to rework their stuff for the sake of being “consistent”. Understandably that makes the code more readable and maintainable, but more often developers will be reluctant to refactor their code to more OO unless it is absolutely necessary, therefore when i say “Careful” i really mean careful in the sense that review should not hinder the overall project time lines. It is very easy to sit there and be an architect stating what could have been done in a better way, than actually refactoring it (by refactoring I meant making it Object oriented yet not breaking functional aspects of the system). Utmost care has to be taken to pass on judgments on what others are writing or doing. In XP world, code reviews form an essential aspect for each iterations to allow a healthy product to move forward. Under pressure deadlines, it is very important to have a few quick sessions (without laying out all the things that “You” want as opposed to what “ALL” people would agree upon) in which decisions are taken about what is acceptable and what is not. It is VERY VERY important that decision is made by keeping at least 80% of the team happy. This I am speaking from experience; Before my current project, the place where i worked at, code reviews were done at a very late stage, there was an excel sheet that was sent out to the entire team to make changes at Class level. (stating Line Number, methods where the problem is). This is obviously not a good approach, since it can be very annoying for developers who will have to refactor their code at such a late stage in the game, when “functional” aspects are already covered.
Needless to say, code reviews form an important aspect in software development. In doing code reviews aside from emotional aspects, utmost care has to be taken to avoid being “obsessive” about style of the code. You can enforce a formatting standard by using common XML or something similar ( depends on platform, I am speaking from Eclipse /IDEA/ Rational Application Developer perspective off course), but that should be the end of it. I have seen this happen in many code reviews where some people prefer somethings written in some ways , for example I usually prefer my If-ELSE constructs leave a line in between (I took this approach from someone just a year back, because that made my own code readable); Now this still adheres to the coding standards / format of the common formatting XML, but reviewers who have their own style of writing the code will often want to enforce that style in the code that they are reviewing. This is obviously a nuisance in the code review process. As i said earlier, utmost care has to be taken to draw a line as where you would want to stop and look at what would be advantages of doing things in such a way. In my experience, If a developer writes code in a certain way, but is a stickler for certain types of constructs (still adhering to a common formatting standard), he/she should be allowed to be at that. Enforcing things that “YOU” as a developer want can prove to be decisively spoiling relationships in team dynamics. (I have had this kind of experience in almost every project now, where a senior developer wants code to look in a certain way and then he goes over board in enforcing it.).
Code inspection and reviews can be enforced with some of Version Control systems. Especially with products like “All Fusion Harvest Change Manager” (now it is renamed to something else), where packages are assigned to be promoted to other stages in a project (for example DEVELOPMENT —> QA / TEST stage) only when they have passed code reviews assigned by developers. Again, developers developing the code might want to check in their code and test it out on the live server without wasting their time waiting on code reviews (if the reviewer is not available), in such cases , they would still be able to do so with systems like Harvest. In my experience and opinion version control system should be used for checking in “functional” code until you reach a logical point where things are working. A non working code or breaking code checked in can be hazardous to the team. In projects where maven is used, Test First (TDD) approach can be very annoying. especially when developers write test cases which off course are broken because the functional pieces for which tests were written are not in working condition. So a simple mvn clean install (used for building projects, more on Maven later). would not work for the entire team, because test cases are executed and they would be fail, off course one can skip the tests altogether but still. In this respect, a checked in functional piece, however small it might be, can be guaranteed to work since it passes the test. In such cases a code review for such piece of code becomes irrelevant, unless off course as i said in my previous passages people want to play one-on-one tag matches with each other.
Teams working on projects with stringent deadlines often tend to overlook importance of code reviews. Code reviews can go a long way in eliminating certain kinds of errors / bugs and make code look more consistent and maintainable, provided off course a well thought off plan is executed. Cynics have often pointed out to me that in XP world, code reviews are not needed at all, since doing pair programming can eliminate the need for that. True only for 1% times in my opinion. I am not a pair programming basher, but i do feel sometimes that senior developers will often do almost most of the coding or thinking part, which means that junior developers will not think or grow while writing their code. Constructive pair programming means listening to others and pointing juniors out in right direction … This off course is too generic or subjective and almost always doesn’t work. In my experience, pair programming will only help those developers who are “just starting out”, for people who have been working for sometime, if and when paired with people who have been in the business for years can be disastrous. Disastrous in the sense that it can often create friction between two passionate programmers who know their stuff and turn pair programming into knowledge matches; this is obviously not good for the team and for the future efforts.
All in all code reviews form crux of every organization, they help in fixing issues that might arise in maintenance phase which off course are costlier and time consuming to fix than in development phase itself. Beyond not meeting functional requirements, code reviews can help in finding out potential performance bottle necks as well.
]]>I have to go on a detour for bit (from elegant visitor to strategy pattern to DI … ) to something that most of the Java people are familiar with; Data Transfer Object, or most commonly known as a DTO. The reasons for this detour are related to something i have been playing with for a while (i’ll ellaborate in later posts). First of all keeping with my tradition of referring definitions, here’s what wikipedia has to say about a DTO :
Data Transfer Objects (DTO), formerly known as Value Objects or VO, are a design pattern used to transfer data between software application subsystems. DTOs are often used in conjunction with Data Access Objects to retrieve data from a database.
The difference between Data Transfer Objects and Business Objects or Data Access Objects is that DTOs do not have any behavior except for storage and retrieval of its own data (accessors and mutators).
Not much insight but still, it explains it in a nutshell. A data transfer object was born to reduce the number of calls through wire in an atypical multi tiered architecture. Usually at the server end there would be an assembler which takes care population of data etc. If anyone of you have ever worked with pre EJB 3.0 days, you would know why they used DTOs. Basically the idea was that an Entity bean would typically expose a method that would copy its entire state into an object that could be serialized. Now this object could be used
by any client in whatever manner needed. Typically code would be something like :
public class CustomerEntityBean implements javax.ejb.EntityBean{
public CustomerDTO getCustomerDTO( ){
// prepare a customer DTO with First Name.
return new CustomerDTO(this.getFirstName());
}
}
Nothing special going on in there, except that customer DTO constructor is called with getFirstName( ) method of the bean being called to allow for populating the customer DTO. In EJB 3 you are saved from doing all this (or so they say
) because your entities are detachable (in the sense that they are not ALWAYS managed by the container), so essentially they behave like DTOs when in “detached state. There are DTOs and then there are something called Value objects. Often both are used interchangeably. Although this is not true. For two DTOs the equality is based on object identity, whereas two value objects are equal in terms of their state. By this i mean for example two customers are equal if : their customer id AND OR customer Name is equal. For two value objects to be equal you can have all properties or subset of properties that uniquely identify each of them dictate the equality. (overriding equals)
A good example of Value object would be Date, for example something like 11/11/2011 is value object, as you can make out it is:
A value object should always override equals method. ( refer to : Value Object for more details ) . A DTO on the other hand is just used as a mutable object. Their equality is based on object identity rather than state identity as stated earlier. (CustomerVO vs CustomerDTO, VO = Value Object). Although this example is admittedly lousy because ideally i would want to keep my value objects very simple, like a Date for example (as opposed to a Customer).
Apart from all of this lets keep things even more clear, throughout the course of this blog I would be using the term Model for representation of “actual” data to be retrieved or persisted. In Hibernate terms the Model is a “Model” of what lies in database or what will lie in database (Talk about puns
).
Abuses
Throughout its long history DTO has been utilized for all kinds of purposes. In EJB days usually the mantra was to use them for making expensive three tiered calls easier, but times have changed since pre-historic EJB 1.x days. While it does make a lot of sense today why DTOs were needed originally, in today’s world people are simply abusing the term and pattern in their projects mostly. (I am speaking from experience off course, I don’t claim that everyone is doing this, before someone jumps a gun on me
). Some of the common blunders / mistakes / abusive usage is :
Lets tackle each one of those abuses one by one, as first one says, there is quite often the case for passing DTOs around simply because parameters are too much in one method call. While this might be a more object oriented approach, but it doesn’t justify the usage of a DTO for this. If there are two many parameters sitting independently, may be it is required that they all be composed into One Model class and then passed around. If the method that is being called exists in a separate tier (lets assume that tiers are not even in different VMs for now) only THEN should a DTO be considered for usage.
The second one is pretty self explanatory; Value objects being immutable are often used interchangeably with DTOs, while this is not a pain for much of the time, but still as a purist you’d want to see Value objects being used for what they are.
Finally, In couple of cases I have seen people do this : They compose DTOs with a DTO to transfer some data and retrieve it as a matter of convenience, Although it is not harmful in any sense, One should refrain from composing DTOs within a DTO (as opposed to a Model within a DTO) a DTO can have n number of models, it can have n number of lists, but if we are adding DTOs within a DTO, it tells me that we want to use Outer DTO as a shuttle to transfer Inner DTO because of some stringent need. I don’t think that plays out really well with a good design.
It is sometimes hard to point out why DTO can be such an anti pattern sometimes (I know a lot of folks believe that it is, but unfortunately i am not one of them.) I have been working on a project that uses a very interesting commons framework, that glorifies the DTO pattern to its most simple, most elegant and pure roots (Which is why I am proud to be part of this project
). I’ll elaborate on this later. Its a matter of personal taste as to how we write our code, however thinking what is intended use for what you are doing can go a long way in simplifying things for us.
Regards
Vyas, Anirudh
As may be evident from above, this is not completely flexible approach. Especially because i am doing (as a client) something like context.setStrategy(new DivisionStrategy) or something in those lines. So client “knows” about the the strategy really; and our code is tied up in that sense …
So first lets setup Dependency Injection container. a method setUp( ) demonstrates that below.
public static void setUp(Class<? extends IStrategy> ... strategies){
for(Class<? extends IStrategy> strategy : strategies){
System.out.println("( Strategy Interface ) ---> ( " + strategy.getSimpleName() + " )");
// prepare the type Map ...
typeMap = new StrategyTypeMap();
// prepare the value list
List
valueList.add(DivisionStrategy.class);
valueList.add(MultiplicationStrategy.class);
valueList.add(SumStrategy.class);
// configuration complete.
typeMap.configureTypeMap(strategy, valueList);
}
}
Lets break the code down in steps and look at it closely. In setting our CustomDIContainer, we use a typeMap (we’ll talk about that in a bit), we simply loop through classes passed to the method, add the classes to list and finally insert the entry in the Map. This map is a specialized Type map which takes in a Key (which in our case is IStrategy Interface) and a valueList in form of Classes that implement the Key Interface. So we have strategies that are being added here.
public static IStrategy getImplementation(Class<? extends IStrategy> key, String typeToGet){
// notice how i pass things around here ... be careful ... read this before you proceed!
return instantiateImplementation(getAppropriateImplementation(key, typeToGet));
}
private static Class<? extends IStrategy> getAppropriateImplementation(Class<? extends IStrategy> key, String typeToGet){
List>Class<? extends IStrategy>> searchList = getCollection(key);
if(typeToGet.trim().equalsIgnoreCase("DIVISION")){
Class<? extends IStrategy> returnType = null;
for(Class<? extends IStrategy> classType : searchList){
if(classType.isAssignableFrom(DivisionStrategy.class)){
returnType = classType;
}
}
// return
return returnType;
}else if(typeToGet.trim().equalsIgnoreCase("SUM")){
Class<? extends IStrategy> returnType = null;
for(Class<? extends IStrategy> classType : searchList){
if(classType.isAssignableFrom(SumStrategy.class)){
returnType = classType;
}
}
// return
return returnType;
}else if(typeToGet.trim().equalsIgnoreCase("MULTIPLICATION")){
Class<? extends IStrategy> returnType = null;
for(Class<? extends IStrategy> classType : searchList){
if(classType.isAssignableFrom(MultiplicationStrategy.class)){
returnType = classType;
}
}
// return
return returnType;
}else{
// return finally
return DivisionStrategy.class;
}
private static IStrategy instantiateImplementation(Class<? extends IStrategy> key){
IStrategy returnStrategy = null;
try {
returnStrategy = key.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
// return
return returnStrategy;
}
^^ Wow this is a huge block of code to digest; but lets break it into pieces and make it a little easy. Basically we are trying to get Implementation for the IStrategy interface we pass in (It could have been other interface as well, but lets not worry about it at the moment). Now :
Next, we populate our good old Context;
public static Context populateContext(String typeToGet){
Context context = Context.getInstance();
context.setStrategy(getImplementation(IStrategy.class, typeToGet));
// return
return context;
}
Finally here is our much improved TestWithDI (compare this with Strategy Pattern Part - I example and you will know what i meant when i said, cleaner approach).
public static void main(String[] args) {
// SETUP THE DI CONTAINER
CustomDIContainer.setUp(IStrategy.class);
// define context using SUM
Context context = CustomDIContainer.populateContext("SUM"); // <-- Notice how we do a SUM! no more new SumStrategy in setter of context ...
Integer result = (Integer)context.getStrategy().operation(400, 200);
System.out.println("( Result of the SUM with DI was ) ---> ( ” + result + ” )”);
// define context using Multiplication
// Notice how we do a MULTIPLICATION! No more new Multiplication in setter of context …
Context multiplicationContext = CustomDIContainer.populateContext(”MULTIPLICATION”);
Integer multiplicationResult = (Integer)multiplicationContext.getStrategy().operation(400, 200);
//log
System.out.println(”( Result of the MULTIPLICATION with DI was ) —> ( ” + multiplicationResult + ” )”);
// define context using Dviision
// Notice how we do a DIVISION! no more new SumStrategy in the setter of context …
Context divisionContext = CustomDIContainer.populateContext(”DIVISION”);
Integer divisionResult = (Integer)divisionContext.getStrategy().operation(400, 200);
//log
System.out.println(”( Result of the DIVISION with DI was ) —> ( ” + divisionResult + ” )”);
}
Finally note that in setUp( ) method we Will have to add our Interfaces and implementations for our Oh so Hot DI container
. We can move this configuration to XML too, although XML approach can be unreliable because if i or any other developer removes any thing (any interface or alike implementations) your code will fail. (We’ll explore the DI concept in later posts). Also this Dependency injection is not a full dependency injection demonstration, as you might notice that i am using populateContext explicitly, normally i should be able to do something like context.load() which will load and wire all dependencies for me, which if i add Context as a bean in our setUp of DI container, i could wire the context attribute for implementing strategy very easily, (As a rough idea to you guys (I will explore this concept later on), you add context to a list of dependencies managed by the container, when container loads the Class, it finds that it has an outside dependency, so it will run a check on its list, if it has the class type which is required to populate this setter field, it will do so. I wanted to make concept more clear so i didnt add those things up here.
Next we will take a look at Improvising our visitor pattern in removing “accept” method and making it more flexible through Generics. ( For continuation purpose; here’s the link:
Visitor Pattern - Part I. Speaking of generics, we can use Generics to improve the above code too … but thats for another time of the day.
Stay Tuned ! and thanks for your visits.
Regards
Vyas, Anirudh
Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.The strategy pattern is useful for situations where it is necessary to dynamically swap the algorithms used in an application. The strategy pattern is intended to provide a means to define a family of algorithms, encapsulate each one as an object, and make them interchangeable. The strategy pattern lets the algorithms vary independently from clients that use them.
As i always do, i believe in writing code rather than writing passages of theory. First I will show Simple implementation of strategy and compare it with What it my code would look like without strategy pattern, then i will tell you guys how to tweak my Strategy pattern to allow removal of some of the “hard wired” initializations. So lets get on with it, we’ve got a lot of ground to cover.
public interface IStrategy extends Serializable{
public Object operation(Object firstOperand, Object secondOperand);
}
Once again to keep things simple, i have stripped all java documentation etc. (And not to mention that it somehow breaks the flow on Word press). So as you can make out, we have a strategy interface; It has one method namely operation which takes two operands. The “Whats” and “Hows” of operation are left to implementors. This strategy helps in isolating the algorithm itself and allows it be to implemented in different ways. If you ask me, by now you might already know what strategy pattern is, but devil is in the details as they say.
public class MultiplicationStrategy implements IStrategy {
private static final long serialVersionUID = 1L;
private static final int VALUE_ZERO = 0;
/**
* {@inheritDoc}
*
*/
public Object operation(Object firstOperand,
Object secondOperand) {
Integer opOne = VALUE_ZERO;
Integer opTwo = VALUE_ZERO;
if (firstOperand instanceof Integer
&& secondOperand instanceof Integer) {
opOne = castOperand(firstOperand);
opTwo = castOperand(secondOperand);
}
// return the sum of two integer
return multiplyOperands(opOne, opTwo);
}
// casts the operand without checking anything
//... this assumes that a check was made already
private final Integer castOperand(final Object firstOperand) {
Integer opOne;
opOne = ((Integer) firstOperand);
// return here
return opOne;
}
// multiplies two operands.
private final int multiplyOperands(final Integer opOne,
final Integer opTwo) {
return opOne * opTwo;
}
}
^^ The above is an implementation of IStrategy, likewise (without showing any further strategies) assume that we have SumStrategy, DivisionStrategy. (Division will off course have that divide by 0 logic etc. but thats not our concern).
Next we have something called a Context now context class holds a reference to a IStrategy type with a setter and a getter for the same. This context will later be used to tie a strategy to applied in a particular scenario. ( For example if client wants to multiply two numbers, a multiplication strategy will be set on this class and so on ).
public class Context {
private IStrategy strategy;
private static int counter = 0;
// private constructor.
private Context(){
}
/**
* returns the context instance
* initialized with Strategy type.
*
* @param strategy
* strategy instance to be set for this context.
*
* @return context
* singleton context instance
*/
public static Context getInstance(){
// return instance
return new Context();
}
/**
* gives the strategy for this context.
*
* @return strategy
* the strategy to get
*/
public IStrategy getStrategy() {
if(counter == 0){
throw new IllegalStateException(" initialization of context not complete...");
}
// return
return strategy;
}
/**
* sets the strategy for this context.
*
* @param strategy
* strategy to be set.
*/
public void setStrategy(IStrategy strategy) {
this.strategy = strategy;
counter++;
}
Now for the real deal, lets see how client invokes the same and how everything falls in place.
public class Test {
/**
*
*
* @param args
* arguments to be passed.
*
*/
public static void main(String[] args) {
// $Id - Step 1 : get the Context instance and pass in Strategy type.
Context context = Context.getInstance();
// $Id - State ( Context ) : division strategy being set
context.setStrategy(new DivisionStrategy());
// perform the operation :
//Notice that i am not calling any specific operations ( like sum( ) or division( ) etc.)
Integer result = (Integer)context.getStrategy().operation(400, 200);
// print
System.out.println("( Result of Division strategy was ) --> ( " + result + " ) ");
// $Id - Step 2 : get the Context
// instance and pass in Strategy type.
Context sumContext = Context.getInstance();
// $Id - State ( Context ) : Sum strategy being set
sumContext.setStrategy(new SumStrategy());
// perform the operation
// Notice that i am not calling any specific
// operations ( like sum( ) or division( ) etc.)
Integer sumResult = (Integer)sumContext.getStrategy().operation(400, 200);
// print
System.out.println("( Result of Sum strategy was ) --> ( " + sumResult + " ) ");
// $Id - Step 3 : get the Context instance and pass in Strategy type.
Context multiplyContext = Context.getInstance();
// $Id - State (Context) : Multiplication
multiplyContext.setStrategy(new MultiplicationStrategy());
// perform the operation
// Notice that i am not calling
// any specific operations ( like sum( ) or division( ) etc.)
Integer multiplyResult = (Integer)multiplyContext.getStrategy().operation(400, 200);
// print
System.out.println("( Result of Multiplication strategy was ) --> ( " + multiplyResult + " ) ");
}
Here’s what we are doing above in a nutshell :
Whats the difference you may ask? well for one, As a client i only used operation( ) and nothing like Multiplication or division etc. (Off course i can think of dozens of other better examples than above, but simplicity is the key to understanding the concept).
Now It is really easy to see what my code would be like without using a strategy, in a nutshell it would be something like :
class Test{
....
main(String[] args){
client.performOperation("OPERATION_TYPE");
}
...
performOperation(String operationType){
if(operationType.trim().equalsIgnoreCase("blah_blah){
// do blah blah operation
}else if(operationType.trim().equalsIgnoreCase("blah){
// do blah blah blah operation
}
... // and so on
}
}
One can obviously see separation of concerns here and cleanliness in the code. But thats not all … Somehow i don’t find my strategy pattern satisfying. To me, we are using (in setting Strategies in context as you may recall, refer above if you don’t), but before using them we do an explicit set. But thats not what i want. I want something to wire this dependency on fly based on some criteria given by the client. (.A.K.A Dependency Injection ). I”ll show how to do that and modify the above to test to make it much better … so stay tuned!
Regards
Vyas, Anirudh
Visitor pattern arose from the need to handle different ‘kinds’ of data in a collection differently by some class; for example a list could have Strings, other Lists etc. In such a scenario; you’d end up writing instanceof checks (ugly); This example of handling different kinds of data in a collection might not be the best; but just bear with me for the moment. (I mention this different type thing because i will give a ‘generified Visitor pattern example in next post).
I believe in posting code and getting down to it; its like the source talks to me, saying all kinds of things that went in developer’s head while he was writing it. I had to strip Comments and javadocs out of this, because for some strange reason it seemed to break the post; I’ll post the files / project instead if someone asks for it.
Lets get on with it!
public void accept(IVisitor visitor);
}
The above is an interface for abstracting all visitable objects. A visitable object could be anything visitor ‘visits’; Typically vistable object (like a Destination for example) ‘accepts’ a visitor and calls visitor.visit(this) in accept method to delegate the responsibility of handling the logic for this visitation. (excuse the pun, i am a poor writer i guess).
public void visit(IVisitable visitable);
}
^^ A visitor interface that All visitors must implement. A visitor visits a ‘Visitable’ object (which in turn ‘accepts’ its visit) and calls this method to let the visitor handle business logic.
To understand and make it all concrete; lets consider a classic Transaction example; where we need to handle two types of transactions; viz. Deposit Transaction; Withdrawal Transactions. I could accomplish this without visitor off course (It turns and looks ugly and Not very OO apparently but it can work, as i will show below). In our example assume that Transaction is a IVisitable type given below.
private Integer type;
public void accept(IVisitor visitor) {
visitor.visit(this);
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
@Override
public String toString() {
return “” + getType();
}
}
Next we implement two kinds of visitors (each for handling the type of transactions viz Deposit, Withdrawal).
public void visit(IVisitable visitable) {
System.out.println(” Performing a deposit on ” + visitable.toString());
}
}
Sounds naive, but hey! thats what my example tries to accomplish; elucidate concepts and not bloat the code.
public void visit(IVisitable visitable) {
System.out.println(” Performing withdrawal on ” + visitable.toString());
}
}
Next we create a visitor Factory which will be responsible for creating visitors; You will typically get hold of visitors using this. (I have not concentrated on making visitors singleton and other blah blah, i’ll leave that to you Java gurus out there).
private static final Integer DEPOSIT = 100;
private static final Integer WITHDRAW = 200;
private static VisitorFactory visitorFactory;
private VisitorFactory(){
// Nothing here
}
public static VisitorFactory getInstance(){
if(visitorFactory == null){
visitorFactory = new VisitorFactory();
}
return visitorFactory;
}
public IVisitor getVisitor(IVisitable visitable){
IVisitor returnVisitor = null;
if(((Transaction)visitable).getType().compareTo(DEPOSIT) == 0){
returnVisitor = new DepositVisitor();
}else if(((Transaction)visitable).getType().compareTo(WITHDRAW) == 0){
returnVisitor = new WithdrawVisitor();
}else{
// default visitor
returnVisitor = new DepositVisitor();
}
// return
return returnVisitor;
}
}
Next; I illustrate the crux of the idea. I will first show how clean and flexible the code is, by showing A test case with VisitorPattern.
private static final Integer DEPOSIT = 100;
private static final Integer WITHDRAWAL = 200;
public static void main(String[] args) {
Transaction tx = new Transaction();
tx.setType(DEPOSIT); // SETTING TYPE AS DEPOSIT … NOTICE HOW CLEAN THIS CODE LOOKS
processTransaction(tx);
Transaction tx0 = new Transaction();
tx0.setType(WITHDRAWAL); // SETTING TYPE AS WITHDRAW … NOTICE HOW CLEAN THIS CODE LOOKS
processTransaction(tx0);
}
private static void processTransaction(Transaction tx) {
processTransaction(tx, VisitorFactory.getInstance().getVisitor(tx));
}
private static void processTransaction(Transaction tx, IVisitor visitor) {
tx.accept(visitor);
}
}
Notice that if i want to add another type of transaction visitor; i can do so easily (hook it up in factory) and delegate back to the same method. My ‘above code’ remains the same.
Now the Ugly code without the above pattern … =)
private static final Integer DEPOSIT = 100;
private static final Integer WITHDRAWAL = 200;
public static void main(String[] args) {
Transaction tx = new Transaction();
processTransaction(tx);
}
public static void processTransaction(Transaction tx) {
if(tx.getType() == DEPOSIT){
System.out.println(” Do the deposit …”);
}else if(tx.getType() == WITHDRAWAL){
System.out.println(” Do the Withdrawal …”);
}
}
}
As you can make out it looks ugly; if i wanted to add another type of transaction; i’d have to add another if. While this is not such a strong example; it does show the concept of it. I can never imagine Wikipedia’s examples (they give a Car, Engine example) while it is a great example in every way; but i find it hard to directly apply the concept in daily work without the examples related to work i do. (thats the reason i hate Head First Design patterns book so much).
State Maintenance
I should point out however that wikipedia stresses an important point pretty well. In ‘visiting’ an IVisitable type; a visitor can maintain state of its previously visited IVisitable(s) and form a tree or graph of Nodes of sort. This can particularly useful if you want to form a tree structure and then modify the structure at a later stage to do some business process transformations.
More To follow : ‘Generics’ Version of the above.
Regards
Vyas, Anirudh
Core topics in Software development boils down to two things:
1.) How do you write bug free / less bug prone code; meaning if you are writing a simple method for example doing something trivial as taking two arguments (i am saying arguments and NOT parameters) and dividing both; returns remainder of the division, you would want two things to happen in this case :
• Both arguments are non null OR at the very least the denominator is NEVER null.
• Even though arguments are not null, sometimes my arguments be of incompatible types …
• How do you provide enough information about program behavior being predictible by using either tools or doing a “dry run” of the code (i.e. running code mentally).
Out of all of the above reasons; the general consensus is that “there is never enough information” for the compiler to “infer” things on its own by parsing the code and analyzing it. Therefore whereas additional information can be added on the behalf of the compiler, (like synthetic stuff in Java may be or something else) or annotations by users that go along with the code to provide some help as an add on info to compiler.
Basic idea of an Annotations (for Non knowers):
For those of you who are not familiar with annotations; i suggest you go through :
Annotations
For those of you coming from C#, you guys are already familiar with annotations I am guessing (I am looking for how it is in C# though, I am not familiar with it completely).
In short for helping Java Compiler, you provide additional information for it to infer some things on its own using them. For example; you could write something like:
@Test
Public void testSomething( )
And the frameworks (frameworks like TestNG, JUNIT use the above), would simply use the above annotation to invoke this method as a test. (Yeah … for those of us who have done a bit of coding in past with JUNIT may agree that It was such a pain to stub out test cases by doing something like: public void _testSomething( ) to allow the framework to ignore it; but anyways)
But the most common usage that comes to mind (it happens often) to some us is; wont it be great if we could have something like @NonNull or something of that sorts that provides compiler with enough information to infer and allow / disallow addition of certain values to a reference type or anything for that matter?
JSR 305 addresses above issues and allows (as part of language) to add annotations in more places … ( like List<@NotNull String> for example). If there’s something that all of us as programmers want it is that method parameters being annotated with NotNull so that at some point some tool gives some warning that the value “might” be null as soon as it is de-referenced somewhere.
3 Cases proposed:
Other suggestions include @NonNegative, @Signed, @NonSigned etc… work is still in progress.
Another interesting aspect that was discussed was to add something like:
when you pass parameters in a different order, you get weird behavior at Runtime! Rather than compiler complaining about it, this is because all above “parameters” are integer types … (small ints!); so it doesn’t matter.
The fix of this was pretty cool; you basically add @ResultSetType annotation (you must create such an annotation yourself and add this annotation to the method parameter that you want to typify ( for example in above I would write @ResultSetType annotation followed by resultSetType name) and the next time a programmer calls things in wrong order, well guess what compiler would complain! (assuming that you add the @ResultSetType to small int static constants of ResultSetTypes you declared, which should have been an Enum in the first place.
For full details, refer to above video link.
Regards
Vyas, Anirudh
I have accumulated fair amount of experience working with following frameworks ( UI / Web ):
Out of all the above, I think Apache Wicket Framework stands out as the PROUD WINNER HANDS DOWN ( YeaH yEAH all you Tapestry people out there, try APACHE WICKET! ). Apache Wicket reminds me of Swing Model of programming; the best part is that while programming in Web Paradigm; i dont feel that i am in Web kind of programming mode. For example if i am coding things in struts or any other so called MVC framework, i would be doing JSP and writing configuration files and god knows what not.
Bottom line : WHY? WHY? WHY? WHY? what is the need for all of this ?
Flaws in frameworks which call themselves “MVC”
The truth is that i knew about this flaw for a long time ( Recently someone reminded me of this flaw over again, hence the rush to type in ) Basically, ( for those of you who are not familiar with MVC, refer to : MVC ) in almost all frameworks you’d find JSP which is a view, a controller servlet which handles and delegates to other classes some responsibility and controls the flow of application, the model which could be a Plain Old Java Object (POJO). Now the problem with JSP is that it simply (in almost all cases) is never a pure view, why? well because it has something called EL (expression language) which can provide for conditional constructs ( like for example
Here comes Apache Wicket!
To understand how Apache wicket solves above annoying issues, i think it’d be appropriate to go through with a simple application flow:
I have to try Flex and OpenLaslo yet, but Wicket is HOT!
Note : I haven’t been through the typical sequence of what happens when a request comes in, how Wicket handles it; I’ll cover those things in later posts …
For now try this site : Wicket Stuff
Regards
Vyas, Anirudh
The goal of Autofetch is reduce the modularity penalty and programmer burden of specifying associations which should be loaded with an object query. These specifications are sometimes are called fetch profiles, prefetch directives, or joins. These specifications are an important performance optimization because they reduce the number of round-trips to a persistence store whether that be a relational database, object database, or flat file. Autofetch is a library which integrates with object persistence tools and automatically handles prefetching data. Using dynamic program profiling, Autofetch determines the right prefetch directives for each query a program executes.
For example, Autofetch integrates with Hibernate to eliminate the need for the programmer to specify fetch directives in queries and laziness in entity mappings. Autofetch currently only integrates with Hibernate. However, we are interested in integrating with other object persistence technologies including object databases and other object relation mappers.
Autofetch was developed at the University of Texas at Austin by Ali Ibrahim for research by Ali Ibrahim and William Cook. An initial implementation was used for a paper submission to the ECOOP conference in 2006. Subsequently it was rearchitected and improved for open source release. Autofetch is licensed under the LGPL license.
For more check out :