views:

680

answers:

5

I'm wondering to using extension method to avoid checking for null in hierarchy. The example:

// GetItems(), GetFirstOrDefault(), GetProduct(), GetIDProduct() are extension methods like:
public static SomeType GetSomeProperty( this XYZ obj ) {
    if ( object.ReferenceEquals( obj, null ) ) { return default( SomeType ); }
    return obj.SomeProperty;
}

// the code with extension methods
Guid? idProduct = this.Invoice.GetItems().GetFirstOrDefault().GetProduct().GetIDProduct();
// instead of
Guid? idProduct = null;
Invoice invoice = this.Invoce;
if ( null != invoice ) {
    InvoiceItems items = invoice.Items;
    if ( null != items && items.Count > 0 ) {
        InvoiceItem item = items[0];
        if ( null != item ) {
            idProduct = item.IDProduct();
        }
    }
}

I know, there is available Null Object pattern, but the solution with this type of extension methods looks better.

Do you think, this solution is good or bad (because bad/good design, lucidity, whatever else)?

Please vote "Good" or "Bad" and why do you think so. Posts are flaged as community.

A: 

Please vote this for "good solution".

TcKs
+9  A: 

Please vote this for "bad solution".

TcKs
+1  A: 

I'd just do it sanely:

Guid? idProduct = null;
Invoice invoice = this.Invoce;

if (invoice != null && 
    invoice.Items != null &&
    invoice.Items.Count > 0 &&
    invoice.Items[0] != null) 
{
   idProduct = invoice.Items[0].IDProduct();
}
FlySwat
And do you know why is the solution with extension method bad? Or do you have "only" feeling? ( No offence, the feeling are sometimes better mentor than exact arguments ).It looks cool for me, but I'm not sure, there is some disadvantage.
TcKs
Its an abuse of extension methods and a codesmell in my opinion, especially with what you are trying to do only taking 4 lines (your example was needlessly complex)
FlySwat
This argument can be used also against the Null Object patter, right?Thanks for the opinion, this is exactly type of answer I'm looking for.
TcKs
Aside from anything else, it's pretty obvious that Jonathan's code won't go bang. You have to know that the others are extension methods which will work with null input otherwise. Also because there are only extension methods (not properties) you end up with non-idiomatic code.
Jon Skeet
A: 

This breaks the semantics of an instance method. Extension methods look like instance methods to the callers, and as such should behave like them. When you break semantics like this, the code will be harder to understand and maintain, its behavior will surprise most developers.

Jordão
+1  A: 

I vote this as "not-interested-in-that-solution".

I'm fine with a Null-Object-Pattern for my entity model classes.

herzmeister der welten