0%

数据抽象 Data Abstraction

隐藏实现 并非 只是在变量之间放上一个函数层那么简单,隐藏实现 关乎 抽象

类不能简单地通过 Setter 和 Getter 把变量暴露出去,而应该暴露抽象接口,以便用户无需了解数据的的实现就能操作数据本体

如果把变量设为 private,然后通过 Setter 和 Getter 暴露,这跟设为 public 有什么区别

举两个例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Point {
public double x;
public double y;
}


public interface Point {
double getX();
double getY();
void setCartesian(double x, double y);
double getR();
double getTheta();
void setPolar(double r, double theta);
}
阅读全文 »

  • 代码格式关乎沟通,而沟通是专业开发者的头等大事

  • 每个空白行都是一条线索,表示出新的独立概念

  • 关系密切的概念应该互相靠近

  • 变量声明:应尽可能靠近其使用位置

  • 实体变量:应在类的顶部声明(Java)或 底部声明(C++, 剪刀原则),团队遵循相同规范即可

阅读全文 »

生活不止眼前的苟且,还有诗和远方

转眼,为期一周的旅游就结束了,此时那一幕幕还在眼前浮现,何不记录一番

与 2023 年(桐庐)不同,这次我和老婆一下去了两个海滨城市:烟台 和 威海

阅读全文 »

类型 Type

  • 创建型 Creational

含义 Intent

The intent of the abstract factory pattern is to provide an interface for creating families of related or dependent objects without specifying their concrete classes

阅读全文 »

注释不能美化糟糕的代码 Comments Do Not Make Up for Bad Code

  • 注释是用代码表达意图遭遇的失败

  • 写注释的常见动机之一是糟糕的代码的存在

用代码来阐释 Explain Yourself in Code

清晰的代码本身就能有效表达意图,应避免依赖注释

确实存在代码难以解释逻辑的情况。不幸的是,许多程序员因此认为代码几乎无法成为好的解释手段,这是错误的观点。如

1
2
// check to see if the employee is eligible for full benefits
if (employee.flags && HOURLY_FLAG) && (employee.age > 65))

可以重构为:

1
if (employee.IsEligibleForFullBenefits())

很多时候,简单到只需要创建一个描述了与注释所言同一事物的函数即可。

阅读全文 »

类型 Type

  • 创建型 Creational

含义 Intent

The intent of the factory method pattern is to define an interface for creating an object, but to let subclasses decide which class to instantiate. Factory method lets a class defer instantiation to subclasses.

阅读全文 »