I understand accessors have to do with OOP. For other languages such as C, imagine you have a function that given 2 numbers returns their sum. Should you name it getSum()
or sum()
?
3 Answers
If I have a function that computes a sum, I would simply call it sum
(a verb) whether I'm working in a procedural or an object-oriented language.
If I'm retrieving a property named sum
(a noun), I would follow the conventions for that specific language for doing so, for example, get_sum()
in C, getSum()
in Java or a Sum
property in C#.
Clarification: This does not mean that a property accessor cannot perform any computation. However, if the function is intended to perform a computation rather than expose a (computed) property value, it shouldn't be modeled like a property.
-
Sorry, could you explain what do you mean by retrieving a property? Mar 30, 2020 at 2:29
-
1@DuarteArribas: By property, I mean an attribute of an object, such as color or size. "Sum" is unlikely to be a property, unless you are modeling some kind of statistical object that has properties such as sum, average etc. Mar 30, 2020 at 2:50
-
2I would also add that I expect
getBlah
type functions to just return a piece of data that already exists, and should never fail nor be more than just a few cpu cycles in cost. Otherwise, if computation or other resources need to be used, it should have a different style name. Mar 30, 2020 at 3:31 -
1This advice breaks the Uniform Access Principle. A client must not know and must not be able to know whether a value was computed or retrieved. Mar 30, 2020 at 6:14
-
3@Kain0_0 unfortuantely lots of words in English are verbs and nouns e.g. sum– jk.Mar 30, 2020 at 6:52
Some functions are queries asking for results without asking for change.
But other "functions" are requests for change returning a result of success or failure, or sometimes (a reference to) the item created.
The former are just getters in some sense, while the latter are not despite returning a value.
a getter I'd expect to be a funtion () -> T i.e. takes no argument and returns something (Supplier<T>
in Java)
sum as a function does not have this signiture, it would have (int, int) -> int or similar. so no I would not call this getSum but sum.