If other types are more suitable, try to avoid using strings

original
2012/12/13 22:16
Reading 419

1. String is not suitable to replace other value types

When a piece of data enters a program from a file, network, or keyboard device, it usually exists in the form of a string. There is a natural tendency to let it continue to retain this form, but this idea is reasonable only when the data is actually text information in nature.

2. String is not suitable for replacing enumeration type

Enumeration types are more suitable than strings for representing constants of enumeration types

3. String is not suitable to replace aggregate type

If an entity has multiple components, it is usually inappropriate to use a string to represent the entity

 String userInfo="zhaohui#25"; Prefer to write a class to describe this dataset UserInfo userInfo2=new UserInfo("zhaohui", 25); class UserInfo{ private String userName; private int age; public UserInfo(String userName,int age){ this.userName=userName; this.age=age; } //Set, get methods }
4. The string is not suitable for replacing the capability table
 public class ThreadLocal{ private ThreadLocal(){} public static void set(String key,Object obj); public static void get(String key); } Problem: These strings represent a shared global namespace. For these methods to work, the string keys provided by the client must be unique. In fact, you can use an unforgeable key (sometimes called the ability key) to replace the string public class ThreadLocal{ private ThreadLocal(){} public static class Key{ Key(){} } public static Key getKey(){ return new Key(); } public static void set(Key key,Object value); public static Object get(Key key); }

Expand to read the full text
Loading
Click to lead the topic 📣 Post and join the discussion 🔥
Reward
zero comment
zero Collection
zero fabulous
 Back to top
Top