zoukankan      html  css  js  c++  java
  • Effective Java 50 Avoid strings where other types are more appropriate

    Principle

    • Strings are poor substitutes for other value types. Such as int, float or BigInteger.
    • Strings are poor substitutes for enum types. As discussed in Item 30.
    • Strings are poor substitutes for aggregate types. A better approach is simply to write a class to represent the aggregate, often a private static member class (Item 22).

      // Inappropriate use of string as aggregate type

      String compoundKey = className + "#" + i.next();

         

    • Strings are poor substitutes for capabilities(unforgeable key).

      Client-provided string keys are used to identify each thread-local variable:

         

      // 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 root cause: the string keys represent a shared global namespace for thread-local variables.

         

      public class ThreadLocal {

      private ThreadLocal() { } // Noninstantiable

      public static class Key { // (Capability)

      Key() { }

      }

      // Generates a unique, unforgeable key

      public static Key getKey() {

      return new Key();

      }

      public static void set(Key key, Object value);

      public static Object get(Key key);

      }

         

      It is a simple, faster and more elegant matter to make this API typesafe by generifying the ThreadLocal class (Item 26):

      public final class ThreadLocal<T> {

      public ThreadLocal() { }

      public void set(T value);

      public T get();

      }

         

      Summary

      Avoid the natural tendency to represent objects as strings when better data types exist or can be written. Used inappropriately, strings are more cumbersome, less flexible, slower, and more error-prone than other types. Types for which strings are commonly misused include primitive types, enums, and aggregate types.

         

  • 相关阅读:
    Python爬取网页信息
    C++面向程序设计(第二版)课后习题答案解析
    蓝桥杯——算法分析
    python爬虫——数据爬取和具体解析
    python爬虫——爬取网页数据和解析数据
    Python文件的读写操作
    C++第三章课后作业答案及解析---指针的使用
    C语言蓝桥杯比赛原题和解析
    Web开发技术---简单的登录验证
    C++面向对象程序设计第三章习题答案解析
  • 原文地址:https://www.cnblogs.com/haokaibo/p/avoid-strings-where-other-types-are-more-appropriate.html
Copyright © 2011-2022 走看看