Confusion of method parameters

Often time methods take more than three parameters that are of the same type, for example.

void mymethod (String param1, String param2, String param3)

then it is very easy for the client to mix the order of the parameters, for example, invert param1 and param2:

mymethod (param2, param1, param3);

... which could be the reason for a lot of debugging time, which should be a trivial matter. Any tips on how to avoid such an error (other than unit tests)?

+3
source share
7 answers

You are looking for: Named parameter idioms in java

+7
source

Use javadoc, this is your friend.

IDE, , .
, Eclipse, javadoc @param, .

+4

volothamp, . , - Java, question.

, api, , , , . , . ..

, , , , . :

public printAddress(String name, String street, String city) {...}
print address(name, street, city);

, - :

public printAddress(Address address) {...}

Address address = new Address();
address.setName(name);
address.setStreet(street);
address.setCity(city);

printAddress(address);

, . , . , . :

public printAddress(Address address) {...}
printAddress(new Address().setName(name).setStreet(street).setCity(city))

, , .

+3

. , (, ints,...), . , , , , , - (.. , ).

, (- " 1 ,...)

+1

4 , API.

. String, String everthing.

, Name String, Person :

Person create( FirstName firstName, LastName lastName, Address address );   

String , , . , String, factory , . , - .

Java Puzzlers , .

-1

Java JavaBean, Java (POJO), . :

void mymethod (Parameters parametersObject)

and JavaBean parameters will have setParam1 (...), setParam2 (...), setParam3 (...), etc. and may even perform some basic internal validation, provide default values, etc.

If you do not want to go through the creation of the Parameters object, use Map, but then you will have to do additional checking inside your method for the absence of parameters. In addition, the keys to the card must be well known, that is, known both outside the method and inside the method.

-1
source

Source: https://habr.com/ru/post/1749373/


All Articles