When to use properties instead of functions

后端 未结 6 1338
感情败类
感情败类 2020-11-29 01:43

This is probably a matter of personal preference, but when do you use properties instead of functions in your code

For instance to get an error log I could say

6条回答
  •  一生所求
    2020-11-29 01:56

    I use properties when its clear the semantic is "Get somevalue from the object". However using a method is a good way to communicate "this may take a bit more than a trivial effort to return".

    For example a collection could have a Count property. Its reasonable to assume a collection object knows how many items are currently held without it actually having to loop through them and count them.

    On the hand this hypothetical collection could have GetSum() method which returns the total of the set of items held. The collection just a easily have a Sum property instead but by using a method it communicates the idea that the collection will have to do some real work to get an answer.

提交回复
热议问题