Non-Zero Constraints in POCO Objects

I am currently writing a financial application and we have a pretty standard customer table. It consists of many required fields and some additional ones like Cell / Fax, etc. I am using NHibernate as ORM and have all the mappings correct. It is already working.

I'm just wondering how can I "express" in code that a field is not null, without comments? I have hbm.xml files that document this, but it's awkward to look at them for things like this.

Another thing that comes to mind is that I don't want the repository to throw NHibernate Exceptions in my logic, so maybe I need to go through the validation route in the controller. However, how can I make the POCO code express that some fields might be empty?

Class Diagram

As you can see, I want Cellular and Fax to be optional, while Phone is required. They are all just composite mappings, so the mapping file just specifies that the individual elements of each must be non-null, but I hate doing Person.Cellular! = Null checking all the time to throw a NullReferenceException.

+1


source to share


2 answers


There are several ways to do this, depending on your POCO behavior and coding style. First, you can use nullable types to express that this field is null, and therefore it would be implicit that the others are not nullable. Alternatively, you can enter the phone value type as the Phone property type for POCO you illustrated, implying that since it is not a primitive type, it is "more important" - this will also allow you to encapsulate the phone number validation in a class on its own ...



In my mind, to be a true POCO object, I don't have to worry about the underlying zero-tolerance in the database table it is stored in ... in fact it must have validation and value types that express its behavior as a stand-alone object; thus, before it hits NHibernate, it is already in a valid state.

+1


source


Make the notnull properties readonly and write them through the 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;} 
}

      

+1


source







All Articles