Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Functions without arguments - what is their role in software design? [closed]

In his book "Clean Code", Robert Martin states that the ideal number of function arguments is zero. Most people will agree that too many function arguments cause lots of issues. But as far as I can see, a function with zero arguments belongs to at least one of these categories:

  1. The function is trivial and always returns the same value.
  2. The function lacks referential transparency, its return value depends on external mutable state.
  3. The purpose of the function are its side effects.

Now functions of type (1) are not really useful while (2) and (3) should be avoided for well-known reasons.

I am aware that the book I mentioned is about OOP, so functions typically belong to an object and get an object reference passed as an implicit argument. But still, accessing object attributes either means (2) or (3).

So what am I missing?

If you answer this question, please don't just communicate your opinion but provide reasonable arguments or specific examples. Otherwise it will probably get closed.

like image 413
Frank Puffer Avatar asked Oct 19 '22 11:10

Frank Puffer


2 Answers

So what am I missing?

The key word in Martin's statement is "ideal". If you continue reading, he writes in depth about functions with one, two, and three arguments, but only mentions niladic functions in one context - testing. He claims that they are trivial to test, presumably because there is only one possible outcome, and it's either right or wrong.

So this is an ideal, and the principle to take from it is the fewer arguments, the better. In reality, obviously, this ideal is rarely achieved. The purpose of a function is usually to take input, whether directly, or indirectly through the object or system state (note that I would call those "arguments" as well to be consistent with Martin's analysis), and provide an output. When you have multiple arguments, the number of test cases increase exponentially, the maintenance is more difficult, etc.

So you are not "missing" anything, so long as you recognize that this is an ideal goal and not something that you should take as an absolute.

Some examples of "pure" niladic functions in C#:

DateTime.MinValue
String.Empty

Niladic functions in C# that return object or system state:

DateTime.Now()
object.GetHashCode()
String.Length
like image 125
D Stanley Avatar answered Oct 27 '22 10:10

D Stanley


The object's attributes will essentially serve as the arguments to the function. In this way, you can directly manipulate the object you are working with, rather than passing and returning values which you then attribute to the object after performing some behaviour contained in the function.

like image 42
jessi Avatar answered Oct 27 '22 10:10

jessi