代码大全1
作为刚学Java半年的大二菜鸟,我总觉得代码能运行就是胜利。直到被《代码大全2》前七章“暴击”后,我才发现以前写的代码简直是灾难现场。
第一次作业要写“计算三角形面积”,我自信满满地在main方法里塞满所有逻辑:
public class Main {
public static void main(String[] args) {
int a = 3; // 边长1
int b = 4; // 边长2
int c = 5; // 边长3
int p = (a + b + c) / 2; // 半周长
double s = Math.sqrt(p * (p - a) * (p - b) * (p - c));
System.out.println("面积是" + s);
}
}
这代码像是把面条倒进碗里——全黏在一起了,
书里说“一个方法只做一件事”,我才明白该拆分成方法:
public class TriangleCalculator {
public static void main(String[] args) {
int sideA = 3;
int sideB = 4;
int sideC = 5;
double area = calculateArea(sideA, sideB, sideC);
System.out.println("面积:" + area);
}
private static double calculateArea(int a, int b, int c) {
int perimeter = a + b + c;
double semiPerimeter = perimeter / 2.0;
return Math.sqrt(semiPerimeter * (semiPerimeter - a) * (semiPerimeter - b) * (semiPerimeter - c));
}
}
虽然还是基础代码,但至少能看出“计算”和“输出”分开了!
我曾觉得变量名随便起没关系,结果一周后自己都看不懂代码:
// 计算两个数相加的平方
int x = 2;
int y = 3;
int z = x + y;
int ans = z * z; // ans是啥?平方和?结果?
书中说“变量名是迷你注释”,我试着用业务含义命名:
int firstNumber = 2;
int secondNumber = 3;
int sum = firstNumber + secondNumber;
int squaredSum = sum * sum;
虽然像小学生作文,但至少不会让人误以为ans是开根号的结果了!
有次我写了个“计算圆周长”的程序
double radius = 5.0;
double circumference = 2 * 3.1415926 * radius; // 3.1415926是什么?
两周后老师让改用更精确的Math.PI,我不得不满屏找3.1415926。书中教我“用常量代替数字”:
public class Circle {
private static final double PI = Math.PI; // 常量名全大写
public static void main(String[] args) {
double radius = 5.0;
double circumference = 2 * PI * radius;
System.out.println("周长:" + circumference);
}
}
现在改PI值只需要动一行代码,终于不用玩“找数字”游戏了!
第一次用文件读取时,我的代码“自信”到让人害怕:
public class FileReader {
public static void main(String[] args) {
File file = new File("data.txt");
Scanner scanner = new Scanner(file); // 文件不存在就直接崩溃
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
}
}
当程序在演示现场闪退时,我才明白书中说的“防御式编程”多重要。现在至少会加个try-catch:
public class SafeFileReader {
public static void main(String[] args) {
try {
File file = new File("data.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
} catch (FileNotFoundException e) {
System.out.println("文件找不到了,检查路径吧!");
}
}
}
看完《代码大全2》前七章,我像打开了新世界的大门。虽然现在还写不出优雅的代码,但至少不会再让变量名像密码、代码像一团乱麻了。原来编程不是“能跑就行”,而是要给未来的自己留条活路