Declaring Variables in a 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 simplicity and better readability, I want to turn the recipient 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 intended to return data only so as not to set / not declare / initialize things ... Is my simplified getter valid for best practices and coding rules?

+4
source share
4 answers

First of all, recommendations for properties usually determine that:

  • They must be cheap.

    Try to avoid costly computing or getting data from databases and such things.

  • They must be consistent.

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

  • - .

, "", getter

  • ( )

.

+6

. API. .

, .

. .

+1

A Getter . .

0
source

If I were you, I would go with a second solution. Since the scope of your variables does not indicate your getter method, they cannot be considered “real” declarations, but they are easier to read and debug. (The compiler optimizes your code for the best execution time and memory usage, so don't worry about the "extra" variables.) Also why do you use "var" when you know the exact type of the variable?

0
source

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


All Articles