Java – this method standard uses varags Length instead of Boolean?

I call this method many times in many places:

private String changeFirstCharCase(String word) {
    return Character.toLowerCase(word.charAt(0)) + word.substring(1);
}

Now I want to add the touppercase function to this method without creating another method. I need the caller to use Boolean values as parameters to determine which method to use

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 want to add a true / false parameter for each call But when I use varags, calls that only need touppercase capability need to add their comments, which can 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, old method calls are not affected

changeFirstCharCase(facadeType);

New can call:

changeFirstCharCase(facadeType,"toUpperCase")

Is this an aprouch standard in the case of readability and maintenance?

Solution

To me, this seems like a bad API design It is counterintuitive to ask API users to pass additional string parameters (which may contain anything) for capitalization

If you don't want to touch the original method, use the Boolean parameter to introduce a new overloaded method:

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 uppercase function without Boolean parameters:

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);
}

In this case, though, it makes sense to rename the original method changefirstchartlowercase

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>