Search code examples
argumentsconventionscalling-convention

Argument Passing Convention - Declaring Arguments in Advance


Which of these is the correct way? Or is there a better 3rd option?

public Thing foo1(){
    String argument1 = "Argument #1";
    String argument2 = "Argument #2";
    Point argument3 = new Point(0,0);
    Thing something = new Thing(argument1, argument2, argument3);
    return something;
}

public Thing foo2(){
    Thing something = new Thing("Argument #1", "Argument #2", new Point(0,0));
    return something;
}

Note: I used Java in the example above, but I am not looking for a language specific answer.


Solution

  • Both are correct. It's a matter of taste.

    I tend to use the second solution whenever there aren't a lot of arguments, whose meanings are easily identifiable without good and meaningful variable names.

    I would even prefer a third way:

    return new Thing("Argument #1", "Argument #2", new Point(0,0));

    Besides, in certain languages, like Scala, you can provide the name of the parameter inside the call:

    new Thing(arg1 = "Argument #1", arg2 = "Argument #2", argPoint = new Point(0,0));
    

    Very nice way and furthermore, you might reorder the parameters without impacting the call.