The term ‘arity’ evokes images of complex differential diagrams that requires a graduate degree to understand, but the concept itself is rather simple. Arity is a value that represents the number of arguments a function takes. Does your method accept a single argument? Then it’s arity is one. Does it accept two arguments? Then it’s arity is two. Simple.
So it’s simple: a method’s arity is identical to its number of parameters? Not so fast! Arity refers specifically to arguments. Arguments are the values you pass into a method or function. A parameter typically expects you to pass a value to it when you call a method, but it’s possible that the value has been defaulted.
Bob Martin’s Clean Code Tip of the Week #10 was “Avoid Too Many Arguments.” That seems fair enough, but why is it that you hear things like “functions rarely have an arity greater than one.” There are two primary issues at play here.
1. Function inputs can be represented as composite types so that every argument is reduced to one.
2. Functions can be curried so that functions have one argument and returns another function (which has one argument and continues until the full chain is unraveled).
When closures occur, number one is sure to follow to capture the variables used within the lambda expression. The important thing to note is that although the compiler is taking care of the closure, human readers of the code are still experiencing many arguments. Uncle Bob’s tip should still be followed.
Number two is a powerful language feature, but it suffers from the same issue as above.
Lower arity also occurs when side effects from other external sources (such as system variables) are resulting in affected out with fewer arguments. This is undesirable, but sometimes necessary.
As always, keep your code readable and maintainable. Strive for lower arity, but don’t let it break you. Besides, I’d rather you call it “binary” than “arity 2.”