Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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            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?

like image 651
Eric Avatar asked Jun 10 '11 16:06

Eric


2 Answers

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.

like image 60
Yet Another Geek Avatar answered Sep 17 '22 23:09

Yet Another Geek


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.

like image 35
InBetween Avatar answered Sep 20 '22 23:09

InBetween