【Effective Java】阅读
Java写了很多年,很惭愧,直到最近才读了这本经典之作《Effective Java》,按自己的理解总结下,有些可能还不够深刻
一、Creating and Destroying Objects
- Consider static factory methods instead of constructors (factory方法可以拥有名称,可以避免重复创建,比如单例模式)
- Consider a builder when faced with many constructor parameters(对于多个参数的比较适用,更加灵活,比如有两个相同类型参数的构造函数无法分辨的情况)
- Enforce the singleton property with a private constructor or an enum type(单例模式,1.5后用枚举实现更合适)
- Enforce noninstantiability with a private constructor (不允许实例化的对象写一个私有构造函数,以避免滥用,比如工具类)
- Avoid creating unnecessary objects (不要多余的创建类,比如在循环中去反复创建对象,特别需要避免的是基本类型和装箱类型的反复转换)
- Eliminate obsolete object references (比如对于pop操作,pop一个元素后要把数组的那一位无用的元素置为null)
- Avoid finalizers(除了一些关闭资源操作,不要再finally里包含不必要的处理)
二、Methods common to all objects
- Obey the general contract when overriding equals (equals方法覆盖时参数等必须对照上)
- Always override hashcode when override equals (equals覆盖时hashcode方法也要override,因为在集合类中的操作时为了快速会先比较hashcode)
- Always override toString (主要是为了使外界更容易了解实例信息)
- Override clone judiciously (clone方法要保证不改变原有实例)
- Consider implementing Comparable (对于需要排序的情况,实现Comparable接口是个好的选择)
三、Classes and interfaces
- Minimize the accessibility of classes and members (只给类和方法最小的访问权限是防止滥用的第一步)
- In public classes, user accessor methods, not public fields (这也是POJO的原因,因为可以在get,set方法里做额外的事情并且对于变化可控)
- Minimize mutability (尽可能限制可变,对于不需要变更要限制,加上final,private等限制)
- Favor composition over inheritance (组合优先于继承,其实继承是对封闭原则的一种破坏)
- Design and document for inheritance or else prohibit it (对于父类,需要写明注释)
- Prefer interfaces to abstract classes (接口优先于抽象类,因为继承只能是一个来源)
- Use interfaces only to define types (可用接口来声明类别)
- Preffer class hierachies to tagged classes (所谓的标签类是指一个类中拥有标签的属性,比如类可以被tag成圆形或者方形,这种情况用继承比较好)
- Use function objects to represent strategies (strategy pattern是策略模式,是允许在运行时选择算法的一种模式)
- Favor static member classes over nonstatic (对于不需要外界访问的内部类,用static是为了减少开销)
四、Generics
- Don't use raw types in new code (对于list,set等最好不要用raw类型,指明类型有助于提前让编译器发现错误)
- Eliminate unchecked warnings (也是为集合类而言)
- Prefer lists to arrays (推荐用list的原因也在于编译器可以发现错误,而数组不能检查元素类型)
- Favor generic types (E,V这种类型有助于代码复用)
- Use bounded wildcards to increase API flexibility (通配符?类型有助于API的灵活性)
- Consider typesafe heterogeneous containers
五、Enums and annotations
- Use enum instead of int constants (这个不用多说)
- Use instance fields instead of ordinals (对于枚举类,不要用ordinals来取其整数值)
- Use EnumSet instad of bit fields (用枚举集合来代替“位”属性,因为位移这种属性实在可读性差)
- Use EnumMap instead of ordinal indexing (用枚举的map代替ordinal方法来排序或者索引)
- Emulate extensible enums with interfaces (用接口实现枚举的可扩展性)
- Prefer annotations to naming patterns (注解的方法可以避免拼写等错误)
- Consistently use the Override annotation (如果是覆盖,用override注解能让编译器来检查错误)
- Use marker interfaces to define types (接口定义类型)
六、Methods
- Check parameters for validity (方法内检查参数的有效性是必要的)
- Make defensive copies then needed (所谓防卫性的copy,是为了防止外界构造实例后再次更改内部数据)
- Design method signatures carefully (方法的命名https://en.wikipedia.org/wiki/Naming_convention_(programming),参数个数不要过多)
- Use overloading judiciously (重载方法的选择是静态的,而重写方法的选择是动态的)
- Use varargs judiciously (可变参数的缺点运行时才会发现,可以用传递第一个必要的参数,剩下的用可变参数来解决)
- Return empty arrays or collections not nulls (减少空指针错误)
- Write doc comments for all exposed API elements (注释)
七、General programming
- Minimize the scope of local variables (封闭性原则)
- Prefer for-each loops to traditional for loops (减少中间参数使用)
- Know and use the libraries (尽量使用标准库的方法)
- Avoid float and double if exact answers are required (flocat,double是科学计算而生,如果需要精确值,使用int,long,BigDecimal代替)
- Prefer primitive types to boxed primitives (尽量使用基本类型)
- Avoid strings where other types are more approprivate (String虽然使用简单,但能用精确类型更好)
- Beware the performance of string concatenation (老生常谈问题,字符拼接用StringBuilder)
- Refer to obejects by their interfaces (用接口来做类型的引用会使代码更加灵活)
- Prefer interfaces to reflection (反射虽然好用但很多问题只有在运行时才能被发现)
- Use native methods judictiously (JVM为了支持多个语言允许native方法但一般不这样做,如果仅仅是为了提高性能)
- Optimize judiciously (改善性能的时候多考虑更改带来的后果)
- Adhere to generally accepted naming conventions (Java命名规范:http://docs.oracle.com/javase/specs/jls/se7/html/index.html)
八、Exceptions
- Use exception only for exceptional conditions (正常逻辑不应该用Exception)
- Use checked exceptions for recoverable conditons and runtime programming errors (需要继续操作的用checked exception)
- Avoid unnecessary use of check exceptions
- Favor the use of standard exceptions
- Throw exceptions appropriate to the abstraction
- Document all exceptions thrown by each method
- Include failure-capture information in detail message
- Strive for failure atomicity (异常的原子性)
- Don't ignore exceptions
九、Concurrency
- Synchronize access to shared mutable data
- Avoid excessive synchronization (同步不要泛滥)
- Prefer executors and tasks to threads
- Prefer concurrency utilities to wait and notify
- Document thread safety
- Use lazy initialization judiciously
- Don't depend on the thread scheduler
- Avoid thread groups
十、Serialization
- Implement serializable judiciously
- Consider using a custom serialized form
- Write readObject method defensively
- For instance control, prefer enum types to readResolve
- Consider serializations proxies instead of serialized instances
---栖息之鹰(一个外表懒洋洋的内心有激情的程序员)
此博客为笔者原著,转载时请注明出处,谢谢!