I’m setting all fields to nullable types where the back-end database fields they correspond to allow nulls. Good? Bad?
The long version:
It works just fine, I just feel like I might be abusing the fact that I can make stuff nullable.
Basically it’s an internal application for employee management that ties into our SQL database. I’m using a three layer structure, from presentation to back-end: Business Objects –> Business Logic –> Data Access.
For my Employee object, I have the following fields:
public class Employee : Person
{
private EmployeeTitle? _employeeTitle = null; //enum
private EmployeeType _employeeType; //enum
private DateTime _startDate;
private DateTime? _endDate = null;
private EmployeeInsuranceRecord _employeeInsuranceRecord = new EmployeeInsuranceRecord();
//...
}
public class EmployeeInsuranceRecord
{
private int? _employeeInsuranceRecordID = null;
private string _alienRegistrationNumber = null;
private string _healthInsuranceNumber = null;
private string _unemploymentInsuranceNumber = null;
private string _welfarePensionNumber = null;
private DateTime? _insuranceAcquiredDate = null;
//...
}
And in my database:
-
EmployeeTitleID allows nulls. An employee may start in a trial period for example, without a set job title.
-
EmployeeTypeID does NOT allow nulls. Even if an employee is a guest or on a trial period, this must be explicitly selected for record purposes.
-
StartDate does NOT allow nulls. If someone is going into the database, we need to know when they started.
-
EndDate however, does allow nulls. Anyone currently employed doesn’t have an EndDate yet.
-
I instantiate an EmployeeInsuranceRecord object on Employee instantiation, but each field within EmployeeInsuranceRecord is nullable because the EmployeeInsuranceRecords go into a separate table linked via an ID, therefore an Employee can exist without an EmployeeInsuranceRecord (common for people just starting, still in the initial paperwork process). By instantiating the EmployeeInsuranceRecord from the get-go, I can keep my presentation layer cleaner by not having the instantiate any classes there. This has no impact on performance, given the small scale we’re working with.
One annoyance of nulls is the coding overhead to keep checking for null before dereferencing / consumption of the value – you will probably need to use a bunch of static extension methods to make your life easier.
But much better to use null than to kluge a ‘magic value’ like DateTime.MinValue etc – this not only corrupts data but may pose problems when persisting to the database if you forget to map it back to null.
As you describe, some of the values become mandatory as they are ‘state’ dependent (e.g. EndDate is required when the employee resigns / retires / is fired). You need to split out your validation strategy based on this.