Question

I am currently writing an financial application, and we have a pretty standard customer table. It consists of many mandatory fields, and some optional like Cell/Fax etc.. I'm using NHibernate as a ORM and have all the mappings right. It already works.

I just wonder, how do I "express" in code that a field is not-null without commenting? I have the hbm.xml files that document this, but it's kinda awkward to look at them for things like this.

The other thing that comes to mind is that I don't want the repository to throw NHibernate Exceptions at my Logic, so maybe I should go the validation route in the Controller. Still, how can I make the POCO code express that some fields can be null?

Class Diagram

As you can see, I want to have Cellular and Fax be optional while Phone mandatory. They are all just composite mappings, so the mapping file just specifies that the single elements of each have to be not-null, but I hate to do the Person.Cellular != null check all the time to avoid having a NullReferenceException.

Was it helpful?

Solution

There are a few ways of doing this depending on your POCO behaviour and coding style. Firstly, you could use nullable types to express that this field is nullable and it would therefore be implicit that the rest are not nullable. Alternatively you could introduce a Phone value type as the type for the Phone property of the POCO you illustrated, implying that because it is not a primitive type it is "more important" - this would also enable you to encapsulate phone number validation within the class itself.

In my mind, to be a true POCO object, it need not worry about the underlying nullability within the database table it is persited in... it should actually have validation and value types that express its behaviour as a stand alone entity; thus before it gets to NHibernate it is already in a valid state.

OTHER TIPS

Make notnull properties readonly and write to them via a public constructor. Make the default constructor protected or private.

public class DomainObject{
private string nnp;
protected DomainObject(){}
public DomainObject(string nnp){
this.nnp = nnp;
}
public string NotNullProp {get {return nnp;}}
public string NullableProp {get;set;} 
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top