Rimozione di un campo
Anche senza Lazy<T> , puoi abbreviare il codice rimuovendo la variabile ridondante:
public string BrandAbbreviation { get; set; }
private CommonBrand _brand;
public CommonBrand Brand
{
get
{
if (!this._brand == null)
{
this._brand = new CommonBrand(this.BrandAbbreviation);
}
return this._brand;
}
}
Rimuovere _brandPopulated non ha solo il vantaggio di rimuovere alcune LOC, ma rende anche il codice più chiaro. Avendo un campo separato che contrassegna se è impostato _brand , potresti potenzialmente avere situazioni che non gestisci nel tuo codice (e che non sono ovvie da gestire a destra):
-
_brandPopulated è false , ma _brand è inizializzato su un valore. Dovremmo dimenticare il valore precedente? Dovremmo tenerlo?
-
_brandPopulated è true , ma _brand è null . Come lo gestisci? Controllate null dopo aver controllato _brandPopulated ? O forse non lo fai, e rischi di incontrare un brutto NullReferenceException ?
Introduzione (o non) Lazy<T>
In effetti puoi usare Lazy<T> , che rende possibile rendere il codice ancora più breve:
public string BrandAbbreviation { get; set; }
private readonly Lazy<CommonBrand> _brand;
public ClassName() // Replace by the name of the actual class.
{
this._brand = new Lazy<CommonBrand>(() => new CommonBrand(this.BrandAbbreviation));
}
public CommonBrand Brand
{
get
{
return this._brand.Value;
}
}