commons-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Jörg Schaible <joerg.schai...@gmx.de>
Subject Re: [lang] LANG-510
Date Fri, 05 Mar 2010 11:12:20 GMT
Henri Yandell wrote at Freitag, 5. März 2010 10:32:

> Thinking further on moving StringUtils to CharSequence, I'd like to
> take the String left(String, int) method as an example. It depends on
> substring(int, int), so is entirely possibly to move over to
> subSequence(int, int).
> 
> Hypothetical new method:
> 
>     CharSequence left(CharSequence, int)
> 
> The downside here is that users currently storing this in a String are
> going to have to cast. Generics to the rescue.
> 
>     <T extends CharSequence> T left(T, int)
> 
> This hits two problems:
> 
> 1) EMPTY is returned when the int is less than 0; EMPTY is a String and
> not T. 
> 2) subSequence returns CharSequence and not T.

Because you do not necessarily get the same type. The API gives room for 
optimized types.

> I could add a wrapper method to make Strings nicer:
> 
>     public static String left(String str, int len) {
>         if (str == null) {
>             return null;
>         }
>         return left( (CharSequence) str, len).toString();
>     }
> 
> But that doesn't help the StringBuffer/StrBuilder/StringBuilder user;
> they still get a sucky API.
> 
> Am I missing anything obvious here, or should I give up the ghost on
> trying to take these methods to CharSequence APIs?

Since the most important implementations (String/StringBuilder/StringBuffer) 
all return effectively a String, you may actually return one also:

     public static String left(CharSequence str, int len) {
         if (str == null) {
             return null;
         }
         return str.subSequence(0, len).toString();
     }

Opinions?

- Jörg


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@commons.apache.org
For additional commands, e-mail: dev-help@commons.apache.org


Mime
View raw message