I have a complex getter as follows
public bool IsOk
{
get
{
return (IsFirstCondition && (IsSecondCondition.Items.First.Item == MyItems.PublicItems.BestItem
|| IsThirdCondition.Collection.EditedItem.IsTheMostUsedItem);
}
}
For the sake of simplicity and better readability, I want to turn my getter into something like:
public bool IsOk
{
get
{
var isBestItemm = IsSecondCondition.Items.First.Item == MyItems.PublicItems.BestItem;
var isMostUsedItem = IsThirdCondition.Collection.EditedItem.IsTheMostUsedItem;
return (IsFirstCondition && (isBestItemm || isMostUsedItem);
}
}
As far as I know, a getter is meant to return data only not to set/declare/initialize things... Is my simplified getter valid regarding best practices and coding guidelines?
First of all, the guidelines for properties usually dictate that:
They should be cheap
Try to avoid costly calculations or fetching data from databases and things like that.
They should be consistent
Reading the property twice should return the same value both times.
They should not introduce side-effects
Reading the property changes the underlying object somehow.
If you can avoid that, use any normal "tricks" to refactor the property getter to be
In terms of your actual example, I would definitely declare those variables.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With