Should a function that returns something be named as an accessor (getSomething)?
https://softwareengineering.stackexchange.com/questions/408129
-
09-03-2021 - |
题
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()
?
解决方案
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.
其他提示
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.