Thursday, December 27, 2007

This Blog Will Continue on TechPer.net

I have decided to stop blogging on this Blogger hosted service. My blog will continue on my own domain, www.techper.net. If you have subscribed to my feed through my TechPer FeedBurner URL, there will be no changes for you. In a short while, I will simply switch the feedburner datasource to that of the new domain, and you will get to read posts of the new blog.

I have decided not to try and copy or move any content from this blog onto the new domain. It stays here, where it is already indexed, bookmarked and discussed. Also, I will keep comments open and participate in any interesting discussions on old posts here.

The new site: www.techper.net

Thursday, November 29, 2007

10 Tips on JPA Domain Modelling

This post is a collection of tips on what I think is good advice, when domain modelling in Java with JPA as ORM mapping technology. Do you agree? Do you have extra advice? Please let me know!

Here they come, in no particular order.

1. Put Annotation on Methods, not Attributes
If using annotations on attributes, JPA engine will set directly in the attributes using reflection, hereby by-passing any code in setters and getters. This makes it hard to do extra work in setters and getters, if the need arises.

In addition, if you add a getter for some calculated value which has no corresponding attribute, you can mark it @Transient on the method. Had you been putting it on the attributes, you would have no attribute to put the annotation on.

Whatever you do: Try not to mix, using with annotations both on fields and methods. Some JPA providers cannot handle this!

2. Implement Serializable
The specification says you have to, but some JPA providers does not enforce this. Hibernate as JPA provider does not enforce this, but it can fail somewhere deep in its stomach with ClassCastException, if Serializable has not been implemented.

3. Use The Fine Grained Domain Modelling and Mapping Possibilities in JPA
If coming from EJBs (before EJB3), you are not used to be able to do fine grained modelling. EJB2.x was very entity centric. In JPA, you have @Embeddable and @Embedded. Doing more fine grained domain modelling can help make your domain model more expressive.

An @Embeddable is a value object, and as such, it shall be immutable. You do this by only putting getters and no (public) setters on its class. The identity of a value object is based on its state rather than its object id. This means, that the @Embeddable will have no @Id annotation.

As an example, given the domain class Person:
@Entity
public class Person implements Serializable {
...
private String address;

@Basic
public String getAddress() { return address; }
public void setAddress(String address) { this.address = address; }
}
We could express Address better, by giving it a class of its own. Not because it should be mapped to some other table, but because it makes sense in this particular model. Like this:
@Embeddable
public class Address implements Serializable {
...
private String houseNumber;
private String street;

@Transient
public String getHouseNumber() { return houseNumber; }

@Transient
public String getStreet() { return street; }

@Basic
public String getAddress() { return street + " " + houseNumber; }

// setter needed by JPA, but protected as value object is immutable to domain
protected void setAddress(String address) {
// do all the parsing and rule enforcement here
}
}

@Entity
public class Person implements Serializable {
...
private Address address;

@Embedded
public Address getAddress() { return address; }
public void setAddress(Address address) { this.address = address; }
}
The better expressiveness comes from: a) Putting a named class on a concept in the model and, b) having a place (the value object class) where to put domain logic and enforce domain rules.

4. Implement Equality using Real Domain Attribute Values
Classes marked @Entity will always have an id attribute. Often, this is a long sequence. It can be tempting to use this value when implementing equals and hashCode (which is also a requirement), but I recommend against it. I can find two good reasons: One based on modelling rules and one based on technical terms.
  • Modelling rule: A class modelled as an entity should be uniquely distinguishable from other instances, solely based on a combination of some of its domain attributes. A long sequence, used solely to obtain relational identification, does not constitute a domain attribute. If you are unable to find a unique combination, it might very well be a sign of a problem with the model.
  • Technical term: If equality is based on a database generated and assigned value, you will not be able to use equals and hashCode before an instance has been persisted. That includes putting the instance into container classes, as they rely on equals and hashCode.
5. Protect the Default Constructor
The JPA specification mandates a default constructor on mapped classes, but a default constructor seldom makes sense in modelling terms. With it, you would be able to construct an entity instance with no state. A constructor should always leave the instance created in a sane state. The requirement for the default constructor is only to make dynamic instantiation of instances of the class possible by the JPA provider.

Luckily, you can, and are allowed to, mark the default constructor as protected. Hibernate will even accept it as private, but that is not by the spec.

6. Protect Setter Method on Id Attribute
Basically the same story as above. In this case, it is just because it makes no sense for the application to assign an id.

NOTE: This is only for when the id attribute is marked as assignable by the provider.

7. Avoid Primitives when Mapping Id Attribute
Simply use Long and not long. This makes it possible to detect a not yet set value by testing for null. If using Java5 or above, auto-boxing should take away the pain.

8. Use the Basic Annotation to Override Defaults
By all means, use @Basic to override the default true value of optional to false, for those fields that are not actually optional (I often find that to be most of my attributes).

9. Go Ahead and Use the Column Annotation
Even if you are not interested in generating a schema or DDL from it, you should not hold back on using the @Column annotation. It tells the reader of the code about important information related to the attribute. This is stuff like nullability, length, scale and precision.

10. Do Not Use java.sql.Date/java.sql.Timestamp in Domain Model
Instead, use java.util.Date or java.util.Calendar. Using the types from the java.sql package is a leakage of concerns into the domain model, that we do not want, nor need.

Just remember to put @Temporal on date and calendar attributes.


Wednesday, November 28, 2007

Now You Can "Click" on a Newspaper Article

When google introduced printed ads in newspapers as part of the AdWords product some time ago, my first response was something in the lines of "what the f...". How can that be a good idea. I didn't give it much thought, and have also been unable to see the big idea there.

Well, until today, when I noticed googles Print Ads 2D Barcodes technology. The idea is to put a small 2D barcode next to the printed ad, in which a URL to a website is encoded. You can then take a snapshot of the barcode with your mobile phone, have software on the phone automatically decode the 2D barcode into the URL, and lastly open a web browser, again on the phone, taking you to the URL.

That is kind of cool, I think :-)

Of course, google has software to decode 2D barcodes, which runs on J2ME and of course Android.

But there are others too. Take a look at Nokia mobile codes, where you can create 2D codes and get scanner software for your phone. To the right is a 2D barcode of the URL to this blog. Sadly, I did not find any barcode scanner software ready for download to my Sony Ericsson W810i. Guess I will have to build zxing and run is on J2ME then.

Thursday, November 22, 2007

Why Override Annotation is Cool

Since Java5 which brought us annotations, Java has had the @Override annotation. But I don't see it used very often, so here I will try and explain why I find it valuable.

When you write a POJO like this:
public class Person {
private String name;

...

public String tostring() {
return "Person[" + name + "]";
}
}
Where the intention of the tostring() method was to override the Object#toString() method, you might be surprised when your method is not called. In this example, it was due to a simple case error ("tostring()" and not "toString()"), but in other scenarios, the error can be hidden somewhere else in a more complex method signature.

Had you been putting a @Override annotation on top of the method signature, you would have gotten a compiler error (or quite possibly already in the IDE). So the @Override annotation says that the annotated method must fulfill the contract of a method up in the class hierarchy. That is the valuable part of the override annotation :-)

Eclipse and IDEA
Last time I tried Eclipse, it played nice and automatically put the annotation on methods, when I used Eclipse keyboard shortcuts to introduce an override. This was on by default. It is not in IDEA :-( But is is very simple to add. Notice the little checkmark "Insert @Override" in the dialog that Ctrl-O opens? Check it, and it will be checked by default from here on.

C# Has It Built-In
The C# language of .Net has a override keyword as a part of language itself. In the C# language you are forced to use the keyword, which is okay by me, as I like it. What I really do not like then, is the virtual keyword of C#. I much better like that all methods are virtual in Java. But that is another story...

Speedlinking About Flex Libraries and Tools

Here is some collected information about the flex/as3 libraries I have seen out there:

Component Libraries
These are either AS3 utility libraries or flex UI component libraries.
  • as3corelib: Contains a bunch of useful stuff like MD5 and SHA hashing, VCard parsing, jpeg and png encoding, JSON support and utilities for working with arrays, dates, numbers, strings and xml. Seems to be Adobe contributed code.
  • flexlib: A lot of nice UI components and stuff, like the TreeGrid. Also with some Adobe contributions.
  • alivepdf: A way to produce pdf output via as3 code. Not sure where I would use that. Maybe if someone needed to off-load the server from the task. Maybe it is most useful in AIR applications and not so much in the more constrained flex sandbox.
  • actionscript3libraries: A nice list of others over at http://riaforge.org/.
  • tweener: Doing animations using code to move things instead of being forced into the flash timeline model.
  • flexvizgraphlib: A really interesting library with which you can do data visualization in flex

Frameworks
These are not simply libraries of functionality, but whole frameworks that tries to help you structure your complete flex application into something manageable. Mostly helpful when your flex application gets really large, I think. These are about application architecture.
  • Cairngorm: A MVC based framework. Done by Adobe themselves.
  • PureMVC: Another MVC based framework
  • Model-Glue: Well, yet another MVC based framework :-)
  • ARP: A pattern based framework.
  • Flest: Hmm, a MVC looking framework which claims not to be an MVC implementation
  • Foundry: Interesting in that in includes a Java/server-side part, which claims to aid in FDS server development. Not important for dudes like me, which try to avoid FDS, though.
Testing
Some libraries that aid in automatic testing of your flex applications.
  • flexunit: JUnit based API. Not dependent on payware.
  • funfx: Write your tests in the nice ruby language. Uses the automation package of FDS to remote control the application when doing automatic testing, which leads to the need of a license on FDS (payware).
Tools
Do you know of other tools, libs or the like, please let me know. I would like to know!