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.
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(); }
. , . , , , .
" ".
Null-Object .
, ,
GetFirstOrDefault().GetProduct()
: 1) Get, , 2) "" , Null Object. OrDefault null,
Get
OrDefault
null
GetFirst().GetProduct()
. , Null Object - / . ??//
Java .net , , , ( , , ). , (, String), , (, StringBuilder), , .
String
StringBuilder
struct Nullable<T>, , ( this) , . , (, default(string).Length ). , .net , , .
struct
Nullable<T>
this
default(string).Length
Source: https://habr.com/ru/post/1699605/More articles:VBA: basic syntax and sample tutorials - vbaVisual C ++ Wrap in C # - c ++Rails загружает файл без изображения в базу данных без использования серверных файлов temp? - rubyStored Procedures MSSQL2005 - sql-serverConverting a console application to a Windows application in Visual Studio 2008? - windowsHow to draw a concave corner rectangle in WPF? - wpfhttps://translate.googleusercontent.com/translate_c?depth=1&pto=aue&rurl=translate.google.com&sl=ru&sp=nmt4&tl=en&u=https://fooobar.com/questions/1699607/best-practices-for-allowing-users-to-choose-a-display-name-on-a-social-networking-website&usg=ALkJrhi-hi49YVBe9I1Vpx4aUYshX7HcQgMySQL operation with accounting application - mysqlCan I create a full-screen website without flash or Silverlight? - asp.netIs there a known pattern for event planning programmatically? - design-patternsAll Articles