Assume I have the following class hierarchy:
A Person object contains a Customer object and the Customer object contains an Address object.
I do not care if the customer has an address or not, but if they do, I want to save it to the database. So in this case, is it perfectly fine to have something like:
try
{
Address addr = person.Customer.Address;
db.SaveAddress(addr);
}
catch
{
//I don't care, but if it is there, just save it.
}
In the above, I don’t care if Customer is null or Address is null. The other alternative I had was
if(person.Customer != null)
{
if(person.Customer.Address != null)
{
}
}
The above can long though if the hierarchy is long. Is there a more elegant way to check if a chain of objects is null without having to check each one.
You should always use exceptions for exceptional cases. You will suffer through performance penalties as there will be some context switching on the CPU.
You could combine the 2nd example to 1 line with most short circuiting languages.
Example:
Context Switching: http://en.wikipedia.org/wiki/Context_switch