Item 50: Avoid strings where other types are more appropriate

1.  Strings are poor substitutes for other value types. If there’s an appropriate value type, whether primitive or object reference, you should use it; if there isn’t, you should write one.

 

2.  Strings are poor substitutes for enum types.

 

3.  Strings are poor substitutes for aggregate types. If an entity has multiple components, it is usually a bad idea to represent it as a single string. You can’t provide equals, toString, or compareTo methods but are forced to accept the behavior that String provides. A better approach is simply to write a class to represent the aggregate, often a private static member class.

 

4.  Strings are poor substitutes for capabilities. If the ThreadLocal API was designed as below :

// Broken - inappropriate use of string as capability!
public class ThreadLocal {
    private ThreadLocal() { } // Noninstantiable
    // Sets the current thread's value for the named variable.
    public static void set(String key, Object value);
    // Returns the current thread's value for the named variable.
    public static Object get(String key);
}

The problem with this approach is that the string keys represent a shared global namespace for thread-local variables. In order for the approach to work, the client-provided string keys have to be unique. Also, the security is poor. A malicious client could intentionally use the same string key as another client to gain illicit access to the other client’s data. This API can be fixed by replacing the string with an unforgeable key (sometimes called a capability), or even using ThreadLocal instance itself as a key with typesafe:

public final class ThreadLocal<T> {
    public ThreadLocal() { }
    public void set(T value);
    public T get();
}

 

你可能感兴趣的:(enum,String,threadLocal)