Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Friday, August 08, 2008

Maven 2 Integration for Eclipse

I finally had some time to play with latest Eclipse version, named Ganymede, and the recent version of Maven2Integration, plugin for Maven Here are some impressions about it

Installation

Installation, by the way didn't go as smoothly as I expected. I pointed to the M2Integration update site, but Eclipse plugin dependency management is still messy. I got warnings I couldn't install M2Integration: part was related to integration with Subversion (which is an optional package, but I wanted it), So I had to install Subclipse plugin, pointing to the Subclipse update site, even if Ganymede isn't yet mentioned on the supported versions… the risk was worth taking :-)

I still had a couple of issues open: some packages related to zest couldn't be found (strangely this happened only on my Windows machine, on Mac OSX this didn't happen, but I guess it's unrelated to the OS). Those are part of a graphical library needed to draw fancy dependency graphs, so I had to to go to the GEF Update site to install them as well.

The last missing piece was support for AJDT. Well I won't probably need AJDT right now, but I preferred to have a complete installation, instead of remembering that I left some pieces behind. So included also the Ganymede compatible AJDT update site to my list. Then I was ready to install and run the m2Integration plugin.

Impressions

Looks like maven support within Eclipse got to an interesting stage. The plugin now assists throughout the whole POM management, and is pretty well organized. The plugin just interacts with Eclipse nicely, as the default build engine. There are still a couple of places where it might be more helpful: I typed a space in the artifact ID (my mistake, but the plugin should also help Maven newcomers…) and I had a nullPointerException. And while selecting the archetype, the choice was huge without contextual information. So it looked somewhat scary. Anyway the overall impression is pretty good: its definitely a useful tool if you're using maven within eclipse; and I really liked the dependency graph:

Here is a screenshot.




Wednesday, February 27, 2008

Java IDE Day

Just a quick info post to inform about the Java IDE Day, which will be free, in Genova - March 10th 2008 and Rome - March 12th 2008 jointly organized by Genova Java Users Group and Rome Java Users Group. For more information, please follow this link. I can't say if I'll join or not, yet, but the panel seems pretty interesting anyway.



Tags: , ,

Monday, January 21, 2008

Domain Driven Design in Java: Repositories and DAOs part 3

In the previous posts on the topic (part1 and part2) I've highlighted common characteristics and differences between the DAO and Repository patterns. In situations where the modeled domain is simple, a traditional DAO approach (backed up by frameworks) is probably good enough. If your domain is more complex, or if complexity is growing, differences between DAOs and Repositories become more important.

  • A larger domain calls for a higher level of abstraction: Repositories could help implementing new functionalities because they hide more of the underlying layers.
  • Complex systems cannot always be modeled with a one-database strategy: whether a Model-DAO-DB model makes sense for most of the normal application, this is a "reasonable assumption". There are anyway situation where a Repository should hide more complexity than a simple database call.
  • Simply stating that "access to the database should always happen through Aggregate Roots" could be not enough to preserve your architecture's integrity.

So, given that DAOs come almost for free in a Spring plus Hibernate environment, the question now is understand if we need something more than that. To put in another way, if DAOs drawbacks (tied to the database representation, more data-oriented than model-oriented, not enforcing access only via aggregates but a one-dao-per-entity approach) are something we can live with or a call for a targeted solution. To be honest, there's also one limitation with DAOs, which is related to the layer they belong to (the persistence layer or whatever you want to call it), while it is been said that Repositories belong to the domain layer. This is a controversial issue… I'll leave it for later.

Ok, the proposed approach with Repositories and DAOs is to have Repositories on top of the persistence layer, and have Repositories call specific DAOs. Something like

Which is quite similar to Debasish's proposal on this post. Repositories expose a more business-oriented interface, compared to DAOs and could enforce access only via Aggregate Roots. Repositories should belong to the domain layer, for a couple of reasons:

  • Data access isn't conceptually a dirty thing. A pure OOP approach made up by only traversing associations (and have am ORM framework doing the dirty job behind the scenes) could impact performance.
  • They should not be tied to any implementation issue. Repositories expose abstract store and retrieval operations but no implementation details.
  • They could contain business-oriented logic related to searches: getUnreconciledOperations(BankAccount ba) could be used instead of getOperationByAccountAndDateRange(BankAccount ba, Date from, Date to).

Personally, I like the proposed solution, which is also implemented via Spring dependency Injection. But I can't help feeling somewhat weak when it comes to explain the advantages. I mean "speaking the language of the domain" is a good thing to me. But is quite far to be a compelling principle when it comes to "sell" an architecture proposal to a team. They have established practices with DAOs, and we're suggesting to add another layer on top of it. If you are lucky enough to have a common understanding of DDD principles and values in your team, then you're probably in a sort of positive loop, and one DDD practice enforces another one and the whole result is a good thing. If this is not the case, this approach might look like it provides marginal value at the price of an increased complexity.

One more thing that could get in the way is code-generation. It is often possible to have some sort of code generation applied to DAOs. Such DAOs are good but flat, and in many cases they call for a business-oriented refinement, while hand-coded DAOs are generally somewhere in the middle. But if adding a Repository layer breaks the code-generation cycle, it could (one more time) be not worth the effort.



Friday, January 18, 2008

Domain Driven Design in Java: Repositories and DAOs part 2

In my previous post I've scratched the surface of the Repositores vs DAO debate, showing that there are points in common but also some differences. Now it's time to become a little less technology agnostic and try to solve the problem in a common java environment such as Spring plus Hibernate.

The original specification was totally technology agnostic – the only reference in the DDD book was to entity beans (which sound so naïve nowadays) – but there were some recommendations, quoting Eric Evans:

"Before implementing something like a repository, you need to think carefully about the infrastructure you are committed to, specially any architectural frameworks"

Ore the more concise:

"In general, don't fight your frameworks"

Which sounds as pragmatic as one would expect. Ok, we have frameworks. We have Hibernate that provides a convenient abstraction for database access, and we have Spring that suggest a mainstream way to deal with persistence through DAOs and the xxxDAOSupport classes. Do we still need repositories? In many cases the DAO approach could be quite sufficient, even if some attention must be put when dealing with Aggregate Roots.

Accessing persistence only through aggregates

One of the strongest recommendations of DDD is to partition the domain model, to highlight Aggregate Roots and related Entities and Value Objects. As a result you could conceptually draw regions on the class diagram, with some properties:

  • There's only one Aggregate Root per region
  • An Entity can belong to only one region
  • Value objects can be used in different regions

Mapping the concepts to Hibernate, a Value Object can be more or less implemented as a Hibernate Custom Type, while there's no difference in the implementation for simple Entities or Aggregate root. Put in another way, Hibernate's view of the domain model is flatter than the one you can achieve by applying domain driven principles to modeling. Does this matter? It depends a lot on the complexity of the domain. When dealing with relations such as the classic OrderLineItem, applying strictly the "access the data only through the Aggregate Root" rule help solving a lot of complex situations. They're simply less complex. As the system grows, you have a view (I liked the regions on the class diagram) that helps keeping coherence of the system. It's probably overkill for small systems, but DDD is for managing complexity, and it helps. Moreover, this type of approach gives also a consistent way to deal with Hibernate's features like lazy-loading: associations crossing regions boundaries were forced to be lazy-loaded, while inside the regions one could apply eager-loading if needed. So it makes sense to have a centralized access point related to Aggregate Roots instead of generic entities. Still you can enforce this rule by using only one DAO per Aggregate Root, or go for the more radical approach proposed by Debasish Ghosh in his blog, which is to have a Repository Layer on top of DAOs.

Continues on part 3.

Thursday, January 17, 2008

Domain Driven Design in Java: Repositories and DAOs

I past the last days digging the net from some information about the implementation of the Repository pattern, as described in Domain Driven Design, in a typical java environment backed by frameworks like Hibernate and Spring.

It turned out that the situation is more complicated than I expected, and that pieces of information are scattered all around, mostly in newsgroups and blogs, so it took me a while to grasp the whole picture. Here is my summary.

The REPOSITORY specification

The original definition of the repository pattern, comes from Martin Fowler's Patterns of Enterprise Application Architecture, but the pattern itself is credited to Edward Hieatt and Rob Mee. The whole idea is to abstract access to the underlying database and provide the illusion of an in-memory collection of domain objects. Hmmm… sounds a lot like DAO to me. And also a bit like Hibernate's lazy-loading. In fact the two concepts of Repository and DAO, are quite similar: they're doing basically the same thing.

Repositories and DAOs

So the first question is "Are Repository and DAOs the same thing with a different name?". I am tempted to write "Yes!", and this will anyway be a legitimate answer in many cases ( some evidences can be found on the Spring Forum and on Christian Bauer's blog), but some differences in the way the two patterns are used were emerging there and there, so I kept on investigating. Going back to the source didn't help, cause both the original definitions are rather vague, at least in 2008 terms, and open to a wide range of implementation styles. So, even if the original definitions were largely overlapping, common habits in using the two patterns consolidated , making Repositories and DAOs two solution styles for approaching the same problem, with some small differences.

  1. DAOs are strictly tied to the underlying representation on a DBMS. The original specification is more generic, allowing for file-based persistence and the like. But the vast majority of DAOs are pointing to a DBMS. Moreover, commonly used persistence frameworks, such as Hibernate help a lot in managing database portability, so this is a smaller issue nowadays, than it used to be. As a result the DAO concept eventually downsized, to a "database access point" while Repositories are still intended to be generic.
  2. Repositories provide a more abstract view over the underlying data model, providing an interface strictly coherent with the domain. DAOs might be implemented basically in many ways, but frameworks and code generation tools tend to put the focus on the data structure rather than on the domain model. This is sometimes a tiny issue, sometimes just a matter of style, but in large systems can degenerate in a severe maintenance problem.
  3. Repositories enforce access to the persistence layer on a one-repository-per-aggregate basis, while DAOs are normally developed one-per-entity or one-per-table. So, repositories are more tied to the DDD concept of Aggregate Root and have a different granularity than DAOs. This definitely makes the most significant difference.

Somehow, the differences above are just a matter of taste, except for point 3. So objections are valid and discussion may result endless. But for now I'll just say that the two patterns are doing basically the same thing, although with different styles. There are differences, especially if approaching the matter from a DDD angle. What's left to say is if those differences are enough to make a choice between one pattern and another, or eventually to choose both.

For a more complete perspective, please read also part 2 and part 3.

Monday, December 10, 2007

Back from the Rome Java Day 2007

… So I am back also from the Java Day, in Rome. It was my first time ever, there. And I was also a speaker (and obviously I was late with my slides…) so I feel like I missed quite a big part of it.

I followed Luca Garulli's presentation about the Roma Framework, which in some ways is a competitor of Grails (the subject of my speech) . Roma has some interesting features, like the built-in user profiling module, and a fancy Echo2 based web interface.

Even if I was dead hungry when I had my speech, I manage not to think about the food and to keep the speech reasonably enjoyable. Anyway, Grails is such an effective tool and full of good ideas that, even in a 10 minutes demo, the audience caught the tools potential, and getting to the end was a piece of cake.

This was one of the closing event, after that we went eating out with all the staff end the speakers in a typical restaurant nearby, and had some good time together. This made the perfect ending for a nice day: despite being a free event and basically based on volunteers the result was absolutely good (thanks to Mara and all the staff that made a hell of a job), with more than 1000 attendees this year.

By the way, presentations slides are already online, and mine can be downloaded here



Friday, November 09, 2007

Upcoming Events: Java Day 2007 in Rome

Java Day is approaching, the official site is up, and so is the program.
I'll be one of the speakers, talking about Grails

I've checked the official program of the day. And I'll be speaking around lunchtime. This is bad, because at that time I'll be incredibly hungry, and being hungry is the only thing that gets me angrier than bad code... At the last java conference in Milan I remember finishing late the morning session, and being the first afternoon session. So I had to skip lunch, really wanted my speech to and as soon as possible, just to have a pizza, a sandwich, or ... whatever. I'll be prepared this time.

Saturday, July 29, 2006

Java Conference presentation available

SUN has published the presentation we gave at the last Italian Java Conference. The downloadable material is here.

Tags: ,

Tuesday, July 04, 2006

Java Conference Afterthoughts


It took me quite a few time to recover from the Italian Java Conference. I was involved in a 3 hour seminar and a 45 minutes speech. Seminar’s title was “migrating applications from Delphi to Java”, while the short speech one was “Migrating development teams from Delphi to SUN Java Studio Creator”. The night before I met with Filippo Bosi and Giuseppe Madaffari, my co-speakers and with Mokabyte’s egghead Giovanni Puliti, to finalize the presentations. As expected, I went to sleep not before 3.00am. And woke up angry and disappointed 4 hours later.

Not so many people attended the seminar, probably because
  • you had to pay SUN 200€ for that

  • James Gosling was speaking in another conference hall
We had some troubles configuring my laptop with the projector, this made us lose some time which I tried to recover at the end… so we finished late. But then I was the first speaker of the afternoon, guess what? No lunch (I hate that). The smaller speech was unpredictably stuffed up with people, probably waiting for the following speech about XP and TDD, I suppose. I regretted shaping the slides in a too serious way for this one, while I had more funnier slides in our “private” performance. As a result the speech sounded a bit more boring than I wanted, but I really was too hungry and tired to add an extra verve to the speech.

After the speech (and the long awaited lunch) we hanged around the Mokabyte stand, where I bumped into Filippo Diotalevi, that was a speaker on the following day. He has been doing a lot of cool things since I knew him in BPM… chapeau!

Tags: ,

Saturday, June 24, 2006

Italian Java Conference

I'll be one of the speakers at the italian Java Conference in Milan next tuesday. Both the events (a seminar and a speech) focus on how to move developers from Delphi to Java, from an organizational and architectural point of view.

By the way, this is mainly an excuse to experiment Microformats in my blog.


June 27, 2006 - 10:00
-

13:00

-
Java Conference Seminar
- at

Milano


Migrare Applicazioni da Delphi a Java




By the way, the result of the experiment was that, after installing the Greasemonkey Firefox plugin I could see an "Add to calendar" icon on the page. Clicking on it resulted in a .ics file ready to be imported by MS Outlook. Still Outlook failed to import it...

Tuesday, May 02, 2006

Default Constructor: a possible solution


I finished my last post grunting like an angry old man. Time to stop whining and start proposing something. Ok, here’s what I do. As a rule in my projects, I mark parameterless constructors in domain classes as @deprecated. This way I can monitor bad coding habits without affecting frameworks that need to access the default constructor. This normally raises questions so I have a chance to explain to developers why I consider it an anti-pattern and to find a solution (normally a robust constructor or a factory).

Another possible solution is to make it a check in source code quality checkers such as checkstyle, this approach eases the burden of manually adding the deprecation comment in all the classes, but requires the team to be familiar with the tool, while deprecation should already be in every developer’s scope.

Tags: , ,

Tuesday, April 25, 2006

Why I hate the default constructor


Hmm, I think I should provide a more detailed (boring) explanation on the reasons why the default constructor is in the list of my most hated anti-patterns.

Back to basics
OO theory provided us with the gift of encapsulation: the ability to hide details of the internal structure of an object by providing access control to attribute and methods thus allowing to split the exposed behaviour of an object (its interface) from the internal structure (the implementation).

The rule of thumb says that you should define all of your attributes private, and then provide public methods for the interactions with other classes. It’s a common practice (a short way to say that I quite disagree with that, but this will drive me out of scope) to provide also public methods to access the properties of the object, in a JavaBeans like fashion.

JavaBeans specification
JavaBeans specification defined that a special category of java objects, the Beans, was identified by the following properties
  • presence of a public parameterless constructor

  • presence of public methods to access properties of the object, such as getters and setters in the form of getPropertyName() and setPropertyName(…)
Plenty of discussions arose on the subject “is JavaBeans specification breaking encapsulation?” arguing that making attributes public would have had the same effect.

Unfortunately, what most of the developers forgot was that java beans specification were meant to be used by tools like IDEs (one of the first implementation of the spec was used to add user defined graphics object in a graphical environment, so that you could create your components and add them to the JBuilder palette) or frameworks like Castor or Hibernate. Java Server Pages also use Java Beans as the underlying object for the pages. Java Beans specification allowed tools to dynamically access properties of given (and unknown) objects by relying on introspection, driven by the coding conventions mentioned above.

Having a commonly accepted syntax for accessor methods, was a good result indeed, but was largely abused. But this gave new popularity to the empty constructor anti-pattern.

Why is the empty constructor evil?
Ok, I need a basic example to start from. Suppose we have a simple class like this:
public class Person {

private String name;
private String surname;

public Person() {}

public String getName() { return this.name; }
public String getSurname() {return this.surname; }

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

By creating an empty object, and
then setting its property in a
Person p = new Person();
p.setName(“John”);
p.setSurname(“Smith);
fashion, we make a series of mistakes. At the end of the execution the result is just like
Person p = new Person(“John”,”Smith”);
assuming that we defined in Person.java a constructor like
Public Person (String name, String surname) {
this.name = name;
this.surname = surname;
}
But unfortunately the result it’s not the same during the execution. In other words object initialization is not atomic in the former case, while it is atomic in the latter. Moreover, the second constructor encapsulates creation logic, knowing that you need both name and surname to have a fully functional Person object. Using the default constructor, anybody trying to initialize the class should be aware of the internal details of the Person class to initialize the class.

Suppose then that you need instances of your class in different areas of your software. Every time, you should create your objects in the correct fashion. To do so, you normally would use the best replacement for OOP: cut & paste (which is a form of reuse after all…). Suppose then that you need to add an extra attribute to the Person class, namely birthDate, and that this attribute is required. Guess what? Changing the robust constructor to
public Person (String name, String surname, Date birthDate) {
this.name = name;
this.surname = surname;
this.birthDate = birthDate;
}
raises compilation problem on every invocation of the constructor. Is this a bad thing? Not at all! It allows you to correct every single invocation. It can be a simple job, or a tricky one (if the newly needed parameter is not so easy to get), but it ensures that the object is in the correct state. The other way round raises no compilation error, you know that you have to correct the code anyway, so you have the following options:
  • search every instance of new Person() throughout the code base and check that all the three setters are called (do you think that it’s fastest than fixing the compile errors?)

  • search some known instance of new Person(), add the new setter, and have a coffee

  • add the setter where we need it and let somebody else deal with the nullPointerException they are 99% likely to get.
Conclusion (where I explain my bitter mood)
What really puzzles me is that, every in the simplest situation, invoking the default constructor is almost always wrong! If your class has attributes, then you should favour a robust constructor instead, and makes you write less code. If it doesn’t have one, then maybe you don’t need a constructor at all but you could access static methods or use a factory to create your object. The only reason why we abuse so much this anti-pattern is just because we are damn lazy.

Tags: , ,

Monday, April 24, 2006

I hate the empty constructor


I was looking for inspiration for a short post about the abuse of the parameterless constructor. Then I found this and thought that there’s not so much else to say. If there is still somebody still convinced that

Person p = new Person();
p.setName(“John”);
p.setSurname(“Smith”);

is still as good as

Person p = new Person(“John”,”Smith”);

…please leave a comment.

Ok, then I thought this was a little bit too short, and wrote down some more explanation in the following post.

Tags: ,

Thursday, February 16, 2006

Type Checking and Code Smells


I’ve been caught for a while in the endless debate between strongly typed languages, such as Java, and loosely typed languages, such as Python. The main question could roughly be reduced to “is strong type checking worth the price?”, for python supporters the answer is clearly “No!”, cause the java syntax burden is not bringing so much of a value. I usually am a strong supporter of a strong type checking (even if I never used smalltalk, for me everything is an object) but in most java projects I’ve seen, strong type checking was never enforced, so developers were just dealing with a heavier syntax without enjoying its benefits.

Testing can introduce some safety degrees at deployment and release time, ensuring some more confidence on the produced code, but in this way you’re supposed to introduce a full-featured test suite, to really confident on software stability in the long term. But type checking was really meant with another goal: bullet proof (or fool proof) design. The best design example I remember, was the 3,5” floppy: even if it approximately looked like a square, it was not; and there was only one way it could be inserted in the slot (unless you were really creative, of course…). I used this metaphor a lot of times when teaching Java and OOP, but I am starting to wonder if it’s any more valid.

I usually get extremely suspicious (and worried, if it’s a project I am working on) when I see two things in code: empty constructors (and a lot of setters) and a huge list of String attributes. These two smells often came along, so the resulting aroma is a perfect blend. Ok, one thing changed from some years ago: a good IDE now shows more and more information about attributes and parameters, so – sometimes – the pessimistic control offered by strong type checking, can be surrogated by an optimistic naming convention (after all developers are supposed not to be that stupid). Still this is not an argument that can save empty constructors (and the resulting partially instantiated objects) from being intrinsically evil, and I can’t believe that none of those String attributes is a potential class.

But to really get some benefit from a more OO refactoring of the code you need behaviour, and if you’re pushed between a presentation framework, which doesn’t enforce OO data, such as Struts, and a lazy coded DAO layer, there’s not so much behaviour left to add to your classes, so – like an old man that feels out of fashion – I would look at all those String attributes in the code, and feel intimately disgusted, but then instead of invoking a refactoring session I’d rather have a glass of wine, thinking that the old times were better…

An article on the Python vs Java debate by Bruce Eckel
Martin Fowler's code smell "Data Clump"

and ConstructorInitialization


Tags: ,