开发者

Should I use a property or a method for a calculated value? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Properties vs Methods

I have some vector geometry classes, and there is lots of functionality I don't know whether to implement as (readonly) properties or methods. Examples include:

Vector.Length                   or              Vector.Length()
Vector.Perpendicular        开发者_Python百科    or              Vector.Perpendicular()
Matrix.Determinant              or              Matrix.Determinant()
Matrix.Inverse                  or              Matrix.Inverse()

Should I implement these as methods, or as properties? None of them mutate the object they apply to, so in that respect, they seem suited as properties. On the other hand, they involve calculations (albeit small ones - this is 2D geometry), which is apparently bad for properties.

Is there any rule as to which I should use in this scenario?


Properties are meant for enabling the Uniform Access Principle, and thus properties is the best choice here eventhough you got some calculations. This is because they are things that describe an object more than doing things to an object and do not require parameters for any external calculation.

With right to mutation, getters should not mutate and setters may mutate according to the Command Query Separation Principle.


I would implement Vector.Length and Matrix.Determinant as properties, as they entail very lightweight calculations (2D).

However, Matrix.Inverse and Vector.Perpendicular don't fit, IMHO, as properties because they aren't describing the object. They are returning a new object that happens to comply with some mathematical condition. I'd implement these as Vector.GetPerpendicular() and Matrix.GetInverse()

But of course, this is just personal taste. I'd do it that way but its perfectly fine to implement them all as properties.


Usually people assume that properties are not too expensive to invoke and that they will complete in near constant time. It sounds like you would be fine with a property.


People generally expect methods to take some time to execute (and potentially throw) while this is less true for properties.

For instance you are more likely to have a property as a condition in a for loop than you are to see a method there. Methods are somewhat expected to have side-effects while properties are expected to not mutate the object.

As a rule of thumb, if you are comfortable with your properties being executed hundreds of times then they are ok.

If you go with methods, it might help it you call them GetXxx().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜