Skip to content

Instantly share code, notes, and snippets.

@gaplo917
Last active December 7, 2016 15:50
Show Gist options
  • Save gaplo917/c19bd07e0444f4bd364f0fbd1d0fbf8c to your computer and use it in GitHub Desktop.
Save gaplo917/c19bd07e0444f4bd364f0fbd1d0fbf8c to your computer and use it in GitHub Desktop.
Java without Named and Default arguments makes code verbose and increase the chance of human error
// Java
// Ugly work around to save time (compared to method overload)
void doSomething(
@NotNull String fname,
@NotNull String lname,
@Nullable String addr,
@Nullable Gender gender
) {
requireNonNull(fname);
requireNonNull(lname);
if(addr == null) addr = "N/A";
if(gender == null) gender = Gender.Unknown;
// do sth
}
String lastName = "lastName";
String firstName = "firstName";
String gender = Gender.Male;
String address = "address";
// As we know the implementation will provide default value for null
// so we type null in the parameter...
// code-smell? WTF by new comer?
// Question: What is the null suppose to be?
doSomething(firstName,lastName,null,null);
doSomething(firstName,lastName,address,null);
doSomething(firstName,lastName,null,gender);
doSomething(firstName,lastName,address,gender);
// without named paramenter...
// Can you notify the bug when you type out this?
// it is safe to compile but logically error
// bug: lastName and firstName are swapped
doSomething(lastName,firstName,address, gender);
// To avoid null and expose a better API
// without default and namged argument, method overloading is the only way
void doSomething(String fname, String lname) {
doSomething(fname,lname,"N/A", Gender.Unknown);
}
void doSomething(String fname, String lname, String addr) {
doSomething(fname,lname,addr, Gender.Unknown);
}
void doSomething(String fname, String lname, Gender gender) {
doSomething(fname,lname,"N/A", gender);
}
void doSomething(String fname, String lname, String addr, Gender gender) {
// do sth
}
// Question:
// if you asked to add one more arugment let say "Phone"
// how many overloading is needed?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment