Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are better ways to create a method that takes many arguments? (10+?)

I was looking at some code of a fellow developer, and almost cried. In the method definition there are 12 arguments. From my experience..this isn't good. If it were me, I would have sent in an object of some sort.

Is there another / more preferred way to do this (in other words, what's the best way to fix this and explain why)?

public long Save (
    String today, 
    String name, 
    String desc, 
    int ID, 
    String otherNm, 
    DateTime dt, 
    int status, 
    String periodID, 
    String otherDt, 
    String submittedDt
)

ignore my poor variable names - they are examples

like image 754
Cody Avatar asked Mar 30 '12 14:03

Cody


3 Answers

It highly depends on the language.

In a language without compile-time typechecking (e.g. python, javascript, etc.) you should use keyword arguments (common in python: you can access them like a dictionary passed in as an argument) or objects/dictionaries you manually pass in as arguments (common in javascript).

However the "argument hell" you described is sometimes "the right way to do things" for certain languages with compile-time typechecking, because using objects will obfuscate the semantics from the typechecker. The solution then would be to use a better language with compile-time typechecking which allows pattern-matching of objects as arguments.

like image 183
ninjagecko Avatar answered Sep 30 '22 11:09

ninjagecko


Yes, use objects. Also, the function is probably doing too much if it needs all of this information, so use smaller functions.

like image 21
Marcin Avatar answered Sep 30 '22 10:09

Marcin


Use objects.

class User { ... }
User user = ...
Save(user);

It decision provides easy way for adding new parameters.

like image 35
Rover Avatar answered Sep 30 '22 09:09

Rover