Extension Method instead of Null Object Template

I am interested in using the extension method to avoid checking for a null value in the hierarchy. 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 that there is a Null Object pattern, but a solution with such extension methods looks better.

Do you think this decision is good or bad (because the design is bad / good, clarity, something else)?

Please vote "Good" or "Bad" and why you think so. Messages are shared as a community.

+3
source share
5 answers

I would just do it great:

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();
}
+2
source

. , . , , , .

+1

" ".

Null-Object .

+1

, ,

GetFirstOrDefault().GetProduct()

: 1) Get, , 2) "" , Null Object. OrDefault null,

GetFirst().GetProduct()

. , Null Object - / . ??//

0

Java .net , , , ( , , ). , (, String), , (, StringBuilder), , .

struct Nullable<T>, , ( this) , . , (, default(string).Length ). , .net , , .

0

Source: https://habr.com/ru/post/1699605/


All Articles