Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring variables in a getter

Tags:

c#

getter

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?

like image 597
Stacked Avatar asked Mar 12 '23 14:03

Stacked


1 Answers

First of all, the guidelines for properties usually dictate that:

  1. They should be cheap

    Try to avoid costly calculations or fetching data from databases and things like that.

  2. They should be consistent

    Reading the property twice should return the same value both times.

  3. 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

  • More readable
  • More maintainable
  • More reusable (or use more reusable code)

In terms of your actual example, I would definitely declare those variables.

like image 82
Lasse V. Karlsen Avatar answered Mar 21 '23 08:03

Lasse V. Karlsen