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

前端 未结 11 1186
刺人心
刺人心 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:39

    Depends, if your "properties" become mammoths and require a whole slew of business logic they shouldn't be properties, there should be a method. The example you posted looks ok to be a property. No standard way of doing it, go with your gut instinct; if it looks like it needs to do a lot you probably need a method.

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

    MSDN gives information about this here

    Class library designers often must decide between implementing a class member as a property or a method. In general, methods represent actions and properties represent data.

    Which one do you think it is? An action calculate/getLaborCost or data?

    WorkOrder workOrder = new WorkOrder();
    workOrder.LaborHours = 8;
    workOrder.LaborRate = 20;
    
    decimal cost = workOrder.LaborCost; // This is OK here
    

    but if you are going to do this for the same object also:

    worOrder.LaborHours = 18;
    decimal newCost = workOrder.LaborCost 
    

    Now this cannot be a property. It would be a lot better to be a method.

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

    Sometimes, you have to consider also what you're modeling... On some domains, the calculated values are often or expected to be an attribute of the model -- a Property. If this were the case, then write it as a Property even though the calculation is not at all trivial or a little bit expensive to compute. Just document it on your API or implement some caching mechanism to minimize recomputation for this property.

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

    It's largely just syntactic sugar anyway, so do want you is convention in your team, or what you prefer, as long as it is just returning information about the object and not changing it or interacting with other objects.

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

    I think they should all be properties. As long as it doesn't change the state of the object, I'm cool with it as a property.

    Additionally, if I'm using your class for data binding (WPF, etc.), then I can bind directly to your property without having to modify/extend the class.

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