I've called this method multiple times in many places:
private String changeFirstCharCase(String word) {
return Character.toLowerCase(word.charAt(0)) + word.substring(1);
}
now I want to add toUpperCase
ability to this method without creating another method and I need the caller to determine which one to go with using a boolean as an arguement.
private static String changeFirstCharCase(String word, boolean toUpperCase) {
return toUpperCase
? Character.toUpperCase(word.charAt(0)) + word.substring(1)
: Character.toLowerCase(word.charAt(0)) + word.substring(1);
}
in this case I've to add a true/false parameter to every call I've made. but when I use varags, the calls that only need the toUpperCase
ability need to add their note, which could be anything.
private static String changeFirstCharCase(String word, String... toUpperCase) {
return toUpperCase.length > 0
? Character.toUpperCase(word.charAt(0)) + word.substring(1)
: Character.toLowerCase(word.charAt(0)) + word.substring(1);
}
in this way the old methods calls are untouched.
changeFirstCharCase(facadeType);
and the new ones can call:
changeFirstCharCase(facadeType, "toUpperCase")
is this aprouch standard in case of readability and maintenance?
This looks like poor API design to me. Requiring the users of your API to pass an additional String
argument (that could contain anything) in order to get the upper-case functionality is counter-intuitive.
If you don't want to touch the original methods, introduce new overloaded methods with the boolean
parameter:
private String changeFirstCharCase(String word) {
return changeFirstCharCase(word,false);
}
private String changeFirstCharCase(String word,boolean toUpperCase) {
return toUpperCase
? Character.toUpperCase(word.charAt(0)) + word.substring(1)
: Character.toLowerCase(word.charAt(0)) + word.substring(1);
}
or introduce a new method for the upper-case functionality, without the boolean
parameter:
private String changeFirstCharCase(String word) {
return Character.toLowerCase(word.charAt(0)) + word.substring(1);
}
private String changeFirstCharToUpperCase(String word) {
return Character.toUpperCase(word.charAt(0)) + word.substring(1);
}
Though in this case it would also make sense to rename the original method to changeFirstCharToLowerCase
.