Preventing cohesive method arguments
Functions can take up a certain amount of arguments. For example:
method(arg, argx);
method(arg, argx, argy, argz, etc (...));
The above seems like a good solution. More parameters, the better right? I beg to differ. When arguments become (and behave) more cohesive - a better option is to create a single object as a method parameter.
However, this solution is not always the best option because the number of arguments influences parameter cohesiveness and method parameter usability.
For example, when a method (e.g., add(x, y)
) requires those limited amounts of arguments for method execution, implementing an object as a parameter does not make sense.
However, when this is not the case, and many parameters are required, an object parameter could be the solution.
obj = (new) {
arg,
argx,
argy,
argz
};
method(obj);
This ensures lower cohesion within method arguments. Also, the method arguments become easier to manage and refactor in the future. This strategy is useful for ever-changing public APIs. Furthermore, the concept of preventing cohesive method arguments can be further applied to CQRS (pattern) solutions. Improving APIs refactoring and improving backward-compatibility for your projects.