Clean Code Study Notes 2
2013-12-30 21:29
288 查看
尽量少用 switch ,除非你觉得它是如此的恰如其分。
注释
用代码本身,而不是注释,去表达意图。
糟糕的代码不需要注释,要也没用。
别让读注释的时间比读代码还长。
每当你想在语句右侧加注释之前,先考虑下,是不是该减短这个函数了。
面向过程 还是 面向对象
这里,类更应该被看作为结构体,一种数据结构。
并没有把相关的函数封装到类里去,而是统一交给 area 函数处理。
instanceof 就像是 switch 的升级版,同级分布处理各个数据结构。
在面向过程下,添加一个类是很麻烦的,必须去修改 area 函数。
但添加一个函数是很干净的,比如求周长的函数。
相比之下,目前,我更偏爱面型对象的形式。
一,PI 的归属不会再尴尬,Circle 所有。
二,NoSuch 异常,可以不需要了。
这种形式下,添加一个类是很干净的。
但添加一个函数,却需要在修改所有的类。
如何选择,就看你需要哪种形式的解耦了。
注释
用代码本身,而不是注释,去表达意图。
糟糕的代码不需要注释,要也没用。
别让读注释的时间比读代码还长。
每当你想在语句右侧加注释之前,先考虑下,是不是该减短这个函数了。
面向过程 还是 面向对象
public class Square { public Point topLeft; public double side; } public class Circle { public Point center; public double radius; } public class Shape { public final double PI = 3.14; public double area(Object shape) throws NosSuchShapeException { if (shape instanceof Square) { Square s = (Square)shape; return s.side * s.side; } else if (shape instanceof Circle) { Circle c = (Circle)shape; return PI * c.radius * c.radius; } throw new NosSuchShapeException; } }
这里,类更应该被看作为结构体,一种数据结构。
并没有把相关的函数封装到类里去,而是统一交给 area 函数处理。
instanceof 就像是 switch 的升级版,同级分布处理各个数据结构。
在面向过程下,添加一个类是很麻烦的,必须去修改 area 函数。
但添加一个函数是很干净的,比如求周长的函数。
public class Square implements Shape { private Point topLeft; private double side; public double area() { return side*side; } } public class Circle implements Shape { private Point center; private double radius; public final double PI = 3.14; public double area() { return PI * radius * radius; } }
相比之下,目前,我更偏爱面型对象的形式。
一,PI 的归属不会再尴尬,Circle 所有。
二,NoSuch 异常,可以不需要了。
这种形式下,添加一个类是很干净的。
但添加一个函数,却需要在修改所有的类。
如何选择,就看你需要哪种形式的解耦了。
相关文章推荐
- Clean Code Study Notes 1
- Clean Code Notes
- clean-code-php
- 《Writing clean code》读书笔记
- ORACLE STUDY NOTES 01
- keep code tight&clean
- Google Code Jam Notes - Cross The Maze - Java
- 单元测试JUnit 4(二)——keeps the bar green to keeps the code clean
- Study notes for Feature Engineering
- 文献综述——In-Situ Visualization in Fluid Mechanics using Catalyst: A Case Study for Code Saturne
- DOM study notes
- Git study notes
- LINQ study notes
- Study notes for B-tree and R-tree
- Preliminary MySQL Study Notes
- Study notes of achieving a senior software engineer
- The pseudocode programming process--Code complete reading notes(9)
- Statements -- Code complete reading notes
- source code study
- Testing View Controllers Lighter View Controllers Clean table view code