I often use simple base classes for things like address and name for more complex
data structures, partly for readability and partly for easy formatting overrides.
So a User class might look something like:
class Subscriber
{
Base.Name Name;
Subscriber()
{
this.Name = new Name();
}
}
and the Name class would look as such:
class Name
{
string First = "";
string Last = "";
override string ToString()
{
return this.First + " " + this.Last;
}
}
Why not null or string.empty for the Name defaults? Quite simply those values don't
play well in the UI and introducing them there seems to cause more code and potential
gotchas than it solves. In the UI, this class structure is as simple as I think
it can be made:
User user = new User();
something = user.Name.First;
Does the
Law of Demeter
apply here? No - the Name object cannot be null and cannot return null parameter
values - those might be empty, but of course, we should probably checked if the
User object was actually loaded correctly to catch if the entire object is null.
User user = new User();
if(user.Load(SomeId))
{
something = user.Name.First;
somethingelse = user.Name.ToString();
}
else
{
//handle when User is still null
}
I'm always looking for readability and simplicity, I think this solves both well,
what do you think?