Aug 22

I write web applications in Java, and have been doing so for some time now. I like to think that I’ve become pretty good at it, and I can usually get something working quickly and efficiently. This means that my choice of frameworks and tools is somewhat specialised, and others would make a different choice, perhaps Grails or Ruby on Rails. This article is not about which framework is superior to another, but rather what I’m currently using and why it’s good for me right now.

Next year, it should be different otherwise I’m not really progressing.

IDE

Intellij IDEA. I used to be an Eclipse evangelist, but then my friend Gareth introduced me to
Intellij and I never looked back. Well, maybe once or twice when I had to reorient myself within the new IDE, but once I got the hang of it then that was it. Everything just works really well, and the refactoring is amazing. Especially in XML and JavaScript. Oh, you thought refactoring was just for Java? I invite you to download the freebie version of Intellij and try out the goodness for yourself. If you’re a contractor like me you’ll find that the productivity increase pays for the IDE within a day or two.

Build systems

I’ve written about this before, but there is only one build system for me at the moment: Maven. I think it reduces the problem of creating portable builds (and environments) to a pretty simple format. It’s a pretty straightforward way of allowing a disparate team of developers to work on different aspects of a large project. In my opinion, a build system should be able to get a new developer productive within 30 minutes. That includes time reading the wiki to locate the appropriate project and check it out of version control. It also includes the time taken for the developer to figure out (using only the documentation) how to build and deploy it locally with a sample set of data and a demonstration page so they can see how the application is supposed to work. If your set up does not allow a developer to do this, then – seriously – look at your systems.

In Maven, the way I’ve got my stuff set up, you get a fully operational environment as described above by doing the following:

1) Check out your project from version control
2) Type mvn clean jetty:run at the command line in the project checkout directory
3) Navigate to localhost:8080/SomeApp in the browser (the wiki will tell you where to go)

That’s it, and it’s the same procedure for all applications at all tiers of the stack. The act of
issuing that command will automatically ensure that the correct supporting versions of any other JARs and WARs are downloaded, included and executed within the same Jetty instance. This gives a complete set of interactivity so that a developer knows they have a representative slice of the overall system. Not bad for a single memorable command, eh?

Web services with RESTEasy and JAXB

I used to use SpringMVC for my web front end. It remains an excellent implementation of the standard Model/View/Controller design pattern that made front end design much simpler than the frameworks that had gone before – I’m looking at Struts here. Now, I’m hooked on an even simpler framework that trivialises the whole creation of web services to a mere typing exercise: RESTEasy. Wow. What a revelation! I’m sure that in Spring 3+ they’ve done something similar (and I will take a look, I promise) but right now RESTEasy is my best friend. Here’s an example of creating a simple web service to respond to a GET request:

@Path("/hello")
public class Hello {
 @GET
 @Path("/{name}")
 public String example(@PathParam("name") String name) {
 return String.format("Hello, %s",name);
 }
}
HTTP GET /ExampleApp/hello/bob
Hello, bob

It’s difficult to imagine a simpler way of coding that service up. Nothing is wasted, the web.xml is trivial and the same for pretty much all the web services on the back end. And it integrates with Spring too. And JAXB. And JSON. And Maven. In fact, it’s damn near perfection.

And what’s so good about JAXB I hear you ask? Well, let me tell you. Take a POJO, apply some simple annotations and hand it over to RESTEasy. All that hard effort of turning it into XML or JSON or whatever for transmission to the outside world is all taken away. Consider a simple class that provides a list of Users formatted as a paged result set:

@XmlRootElement(name="Result")
public class Result {
 @XmlElementWrapper(name="Users")
 @XmlElement(name="User")
 private List<User> users=new ArrayList<User>();
 @XmlAttribute(name="firstResult")
 private int firstResult;
 @XmlAttribute(name="batchSize")
 public int getBatchSize() {
 return users.size();
 }
 public void setFirstResult(int firstResult) {
 this.firstResult=firstResult;
 }
}

Assume that User has been created and marked up in a similar fashion. Put this into a RESTEasy web service, like so

@Path("/search")
public class SearchService {
 UserDao userDao = new UserDao();
 @GET
 @Path("/{query}")
 public Result example(@PathParam("query") String query) {
 return userDao.search(query);
 }
}

You’ll see the following

HTTP GET /ExampleApp/search/bob
<Result firstResult="1" batchSize="1">
 <Users>
 <User>
 <Name>Bob</Name>
 </User>
 </Users>
</Result>

Neat and very obvious how it all works so maintenance issues drop off.

Database access with JPA Now I jumped on the Hibernate wagon with everyone else. It solved a huge problem in the ORM world in a neat and elegant manner. It also educated mere mortals into the proper way to think about the way our applications dealt with database issues. I’m thinking of sessions, lazy loading, avoiding the dredge anti-pattern, entity to table mappings and on and on.

In fact Hibernate was so good that it sparked a complete revisit of the awful EJB approaches so that EJB3 is actually palatable – if you’re starved of any alternative that is. I’m still not convinced that EJB is compatible with an Agile approach to development. I’ve not yet seen an EJB work efficiently in a Jetty environment that neatly supports JUnit integration testing against an in-memory HSQL database. Spring on the other hand manages that feat with ease, particularly in JUnit4.

One good thing about EJB3 is the creation of the JPA and JTA specifications, which formalised what had been going on in Hibernate for ages before. All those lovely annotations were ratified and the persistence layer took a major leap forward. As a developer this puts me in a good position where I can be ambivalent about the implementation technology behind the annotations. Want me to code up your DAOs using JPA and JPQL, that’s fine. Want the same done with Hibernate and HSQL, just gimme a mo to tweak some queries and you’re good to go.

Automated functional testing

I’ve discussed this elsewhere too, but I thought I’d include a mention here for completeness. No development stack is complete without catering for automated testing. Everyone reading this naturally has a unit test for everything – don’t you? You don’t?! You’d better get started then, ‘cos everyone else has. However, once you’ve got your unit tests working nicely with both dependency injection and mocking approaches. Which reminds me, I’d recommend JMockit over JMock these days due to it’s better handling of static methods which are sometimes forced on us by legacy code. Then it’s time to consider the functional testing. For some reason everyone seems to adopt the line of “Oooh, I’d love to do that but I just don’t have the time.”, which in my opinion doesn’t add up. Every developer should strive to make their days easier, and having the safety net of a  comprehensive set of functional tests is essential. Take a look at my detailed article on the most excellent SeleniumRC for more information.

Performance

With the above technologies, I can usually get a full-blown, integration tested RESTful web service off the ground and operational against a database within 2 hours. Most of that time is spent typing and configuring for the particular problem I’m facing. I know other frameworks exist that could speed that up (Appfuse and Spring Roo, er, spring to mind – sorry). And, yes,
I do have templates to solve standard problems. However, within the constraints imposed by my clients who want to use, or be guided into using, a particular technology, this is a pretty good delivery time.

  • Share/Bookmark
Jan 29

Anybody here ever seen a zombie flick? Well then, we all know what a zombie is, but what is a zombie meme? Read on for more.

What is a meme?

For that we need to refer to Richard Dawkins and his book The Selfish Gene. He makes the parallel between a human gene and a unit of culture, which he termed a meme. I’m using culture here in it’s social sense to mean a collection of ideas that shapes our actions that is common to our society. There are a lot of interesting parallels that cross over between the genome based view of biological systems, and the memetic view of cultural systems.

For example, our genes use us to replicate. Therefore genes compete with other genes (in other humans) to ensure their continued replication. One strategy is to introduce characteristics in their host that promote the end result of successful replication. This is the basis of evolution and the continued survival of the most fit organism for their environment.

Memes compete with each other by taking up space in our culture, which essentially means our awareness. They can be as simple as knowing that an iPod can be used to play music, or as complex as a natural language. To be successful a meme must replicate, and there are many strategies to help it do so. The “put wheels on a sledge to make a wagon” meme was successful in creating the automobile industry because it was immediately obvious to anyone looking at a wagon how to build it. The manifestation of the meme (the wagon) was replicated, and so the meme was able to leverage this to create many more copies of itself than the original item. More people know about wagons than own one.

So a zombie meme is…?

One that no longer serves a useful purpose and is simply getting replicated for the sake of it. People simply adopt the zombie meme as “best practice” without question and mindlessly repeat the instructions regardless of how damaging those instructions are.

Examples of this include wasteful business practices:

“Can you print that email for my records?”
“We only take orders by fax, then we type them into our computer system. Hope you’ve got good handwriting.”
“Please read the 50 page guide before filling out this form.”

or software development methodologies:

“Code around it quick, we’ll get the users to test it.”
“We design, code, test and ship. In that order. Once.”
“We don’t use XP, we use Scrum.”

Hang on – did you just have a go at Scrum?

Indirectly, yes. Scrum is the prevailing Agile implementation and there are a lot of excellent reasons to use it. However, simply using a particular methodology without fully understanding what type of development environment it is targeted at is essentially allowing a zombie meme to infiltrate and replicate.

But everyone does Scrum so it must be the best, I hear you mutter. Not necessarily. Consider the article Flaccid Scrum by Martin Fowler where excited project managers pick up on the Scrum process. All is well for a while then the project slams into a brick wall due to overwhelming technical difficulties caused by a legacy code base. This isn’t Scrum’s fault, you need to have good technical practices in place before Scrum will show it’s many advantages. A better choice in this scenario would be XP with all it’s technical recommendations.

Another scenario is that the nature of the work doesn’t lend itself to a constantly changing work load, such as maintenance programming or rapid response to a fickle client. Some changes take a day, others a week or so. Scrum relies on a clear stretch of time to accomplish the work, whereas Kanban provides a much more flexible approach.

And what if the project involves a dual-shore development team, operating in different time zones? It may be better to adopt the Stride approach (PDF), which is based on Scrum but tailored for separated teams.

As I mentioned earlier, memes replicate, but they also mutate leading to a conflation of ideas that can in turn lead to a better fit. Such is the case with a group of people who are now trying to blend Scrum with Kanban to find an even more efficient and flexible development process.

There are interesting times ahead, and not a zombie in sight.

  • Share/Bookmark
Tagged with:
Jan 27

As a full time developer I spend a lot of time writing code. And I almost never get it right first time. I did once, a long time ago, and since then I’ve not had such luck so I’ve had to rely on a myriad of safety nets, such as unit tests and a keep it simple approach to design. Even then my code tends to grow somewhat organically leading to various code smells that a healthy wave of refactoring wafts away.

I thought I’d take this opportunity to share the ones I use the most often – in fact I couldn’t really live without them these days.

1) Rename and Change Method Signature

My personal favourites. Rename does just what it says on the tin. Initiate the refactoring, tell the IDE to apply it in all the right places and it just does it. When applied to fields in Java beans, the IDE will ask if sir would like those getters/setters renamed as well, and throughout the application, including JSPs. Yes, please, do that for me and save me a whole bunch of time.

Change Method Signature is even better because it includes Rename as a happy side effect. Want to change the order of those parameters and their types but don’t want to screw up all the myriad of calls into those methods? Why, yes, yes I do, Mr IDE. Just click in this box until you’re happy with the new order and let me do all the hard work. Don’t mind if I do (cracks open beer).

2) Extract Method

Especially useful when exploring a new code base. If you want to simplify a method that has clearly gotten out of hand, just select the area you feel should be a method in it’s own right and hit that refactor button. Suddenly all that complex code is whisked away and in it’s place is a simple method call. And if your IDE is really spiffy then you’ll find that all the other copy/pasted versions of that code have also been refactored into the method call. Marvellous.

3) Pull Up and Push Down

Have you suddenly discovered that a method or field is going to be duplicated in a bunch of subclasses? Use Pull Up to move the duplicated method or field into a super class. Done correctly, the IDE will automatically apply the refactoring to all subclasses with the duplication and substitute the super class reference in it’s place.

Push Down, as it’s name suggests, does the opposite. Your wonderful base class is now preventing subclasses from specialising as they should so you push the field or method down so that the subclasses can implement the method or not as they see fit.

4) Extract Base Class

Want to do a Pull Up but don’t have a super class in place? No problem, just use this and select the methods/fields that you want pulled up. Want that base class abstract? Not a problem, just tick the box, sir.

5) Introduce Parameter Object

If there’s one thing I really hate it’s a method with a long parameter list. And by long I mean 5 parameters maximum. Especially if they’re all named string1, string2, stringX and so on because a) it’s mental, 2) it’s confusing and iii) nobody will ever get the parameters in the correct order.

The solution to this debacle is, of course, to introduce a parameter object. A simple Value Object (read Java Bean) that abstracts all the parameters away behind a single reference. Want to add a new parameter but don’t want to have to go and change all the method signatures on your publicly available API? Just make sure they take a parameter object and the API will continue to work as you change the properties on the parameter object. If you were feeling really ambitious you could put validation code into the parameter object to provide a defensive layer, but that’s just silly, isn’t it? Isn’t it?

6) Introduce Constant

We’ve all done it: hard coded a string or number somewhere. Then used it again. And again. Then realised that, really, it should be defined properly somewhere up in the root of the class or ideally injected. And that is exactly what the Introduce Constant refactoring does. With a swift click of the mouse all the duplications are pulled up into a single, well named constant field destined to remain the single point of reference for that datum for all time. Very DRY.

7) Introduce Field

Method signatures getting a bit repetitive with that same reference getting passed around all over the place? It’s about time that parameter was converted into a fully fledged field.

The only problem with refactoring is that after you’ve done it a few times you kind of get addicted to it. Before long you’ll be spotting duplications and excessive parameter lists all over the place and applying refactorings to tidy them all up and what are you left with? Just well designed, clean code that is much easier to maintain.

  • Share/Bookmark
Tagged with:
Jan 27

Nope. Well that was easy. Except you probably do.

According to the Don’t Repeat Yourself (DRY) principle, all code and reference material should have a single point of reference that is both unambiguous and easy to find.

Most major development efforts will be spread over several large projects. As a natural result of this there is going to be some duplication between, at least, the fundamental utility and data access classes. One approach in combating this duplication is to create a project that could absorb a lot of the commonality found in several diverse applications into a single module for inclusion in each.

As most developers know, the Apache Foundation have provided a vast array of common extensions to the Java language – some of which have been included in later versions of the language itself because they were so useful. However, as a taster, there are file utilities, specialised collections, string manipulation methods, date handlers, logging frameworks all of which provide a standardised approach to solving commonly found problems. Rather than roll your own library, why not take the best of breed from Apache and ask new developers coming to the company if they have familiarity with these libraries? The learning curve drops away the more you depend on freely available standard software.

Even after refactoring the existing code to use the various Apache Commons libraries, the size of the common project will increase. It is important to keep it focused so that it does not swell to be an all-encompassing uber-module that all projects must depend on. As the packages contained within the distributable JAR get too numerous, split them out into sub-modules that are highly targeted. A JAR for utilities, another for DAO interfaces, another for web utilities. Different projects can then use these highly specific, and loosely coupled, collections of foundation classes to meet their exact needs without needing a load of extraneous dependencies to also be included.

If you are using a build process like Maven then the issue of dependency management becomes trivial. Developers can make updates to the common modules and release new versions of the JAR into the company repository (managed by Artifactory for example). Other developers are unaffected until they decide to update their project file to include this higher release version. This allows them to continue without the new features saving the upgrade to a later time that suits them.

As these modules begin to grow in size it becomes difficult to keep track of all that useful code that your developers have spent a lot of time creating. It is at  this point you should consider introducing the role of a Code Librarian. This role, ancillary to normal development duties, is responsible for the maintenance of code that is deemed to be useful in more than one project. They can also assist with refactoring the original design of the code so that it fits with a wider audience. Typically the code librarian would sit in on code reviews, or be called over if doubt has arisen. They can then point out where the developer has written code themselves that should have been brought in from a common library, or to find ways of incorporating new code into the library.

The creation of a well-maintained centrally-managed code repository drastically reduces the amount of time and effort it takes to get a new project off the ground and out into production. It also greatly reduces the amount of developer time spent debugging. If the supporting documentation, such as a Wiki, contains good examples and references to other similar classes with slightly different applications then developers will quickly find themselves avoiding the re-invention of the wheel. For an example of this, take a look at the YUI framework documentation.

  • Share/Bookmark
Tagged with:

You should follow me on TwitterYou should follow me on Twiiter here.

preload preload preload