C# read-only calculated properties, should they be methods?

前端 未结 11 1189
刺人心
刺人心 2021-01-31 13:55

I have several entities that have calculated fields on them such as TotalCost. Right now I have them all as properties but I\'m wondering if they should actually be methods. Is

相关标签:
11条回答
  • 2021-01-31 14:25

    If they are a) lightweight and b) have no side effects, I would make them Properties.

    Lightweight is a bit fuzzy of course, but the rule of thumb is: If I ever have to worry calling a Property (be it in a loop or anywhere else), it should possibly be a method.

    0 讨论(0)
  • 2021-01-31 14:29

    If a property is particularly expensive to calculate, I might change it to a GetWhatever() method. This serves as a hint to whoever uses my class that this value requires some significant work to arrive at, and the caller should cache the value rather than calling the method multiple times.

    Trivial calculations are perfectly appropriate inside of properties.

    0 讨论(0)
  • 2021-01-31 14:29

    In my opinion, it's a preference; it's what you want to do. I do propreties in most cases, unless there is logic involved. Additionally, if you need to pass in parameters to change the functionality then obviously a method would apply...

    0 讨论(0)
  • 2021-01-31 14:30

    I think methods should perform actions on the object, typically change the state of the object. Properties should reflect the current state of the object even if the property is calculated. So you should keep your properties IMO.

    0 讨论(0)
  • 2021-01-31 14:33

    It's OK to use calculated properties rather than methods, as long as the calculation doesn't take a noticeable time

    See Property usage guidelines

    0 讨论(0)
  • 2021-01-31 14:39

    I would leave them as properties. But there's not "standard" reason to do things one way or another. If you're by yourself, do whatever you like best. If you're on a team, then follow conventions the rest of your team are following.

    0 讨论(0)
提交回复
热议问题