记录Java编程的一些好习惯,不难,但重要!!!
如:
// Good naming
int age;
void printName() {}
class User {}
反例:
function isJieKuanText(uuid, asr_text, task_id) {}
你可以猜下是什么意思,留言告诉我,当然如果你遇到了比较有意思的命名,也欢迎分享出来,大家同乐!!!。
// 好的做法
int age = 5;
int multiplier = 2;
int result = age * multiplier;
final int MAX_SIZE = 10;
for (int i = 0; i < MAX_SIZE; i++) {
// do something
}
反例:
if(conn.identity == -1 && dtmfNumber == "0") {}
if(dtmfNumber == "1" || dtmfNumber == "2" || dtmfNumber == "3" || dtmfNumber == "4") {}
提高安全性,避免值被意外修改导致bug。
// 不好的做法
public void calculate() {
double taxRate = 0.25;
double result = amount * taxRate;
}
// 好的做法
public static final double TAX_RATE = 0.25;
public void calculate() {
double result = amount * TAX_RATE;
}
// 不好的做法
String name = "John";
String message = "Hello, " + name + "!";
// 好的做法
String name = "John";
StringBuilder sb = new StringBuilder();
sb.append("Hello, ");
sb.append(name);
sb.append("!");
String message = sb.toString();
StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(" ");
sb.append("World");
String message = sb.toString();
因为stringbuffer是线程安全,所以会有额外的加锁释放锁的性能开销,非必要就不要使用了。
public enum CarType {
SEDAN,
HATCHBACK,
SUV
}
try (FileInputStream fileInputStream = new FileInputStream(file)) {
// read from file
} catch (IOException e) {
// handle exception
}
import static java.lang.Math.PI;
import static java.lang.Math.pow;
double area = PI * pow(radius, 2);
public final class Person {
private final String name;
private final int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
// 没有接口
class Dog {
void bark() {
System.out.println("Woof");
}
}
class Cat {
void meow() {
System.out.println("Meow");
}
}
// 使用接口
interface Animal {
void makeSound();
}
class Dog implements Animal {
@Override
void makeSound() {
System.out.println("Woof");
}
}
class Cat implements Animal {
@Override
void makeSound() {
System.out.println("Meow");
}
}
可恢复,即可补偿。
public void readFromFile(String fileName) throws FileNotFoundException, IOException {
try (FileInputStream fileInputStream = new FileInputStream(fileName)) {
// read from file
}
}
不需要的操作不提供,也不允许通过其他手段获得。
public class BankAccount {
private double balance;
public double getBalance() {
return balance;
}
// 只允许存款,不允许取款
public void deposit(double amount) {
balance += amount;
}
}
// 硬编码值
if (statusCode == 200) {
// do something
}
// 常量值
private static final int HTTP_STATUS_OK = 200;
if (statusCode == HTTP_STATUS_OK) {
// do something
}
class Parent {
void print() {
System.out.println("Parent");
}
}
class Child extends Parent {
@Override
void print() {
System.out.println("Child");
}
}
// Class final 避免被继承
final class MyClass {}
// Method
class Parent {
// final 避免被重写
final void print() {}
}
class Child extends Parent {
// Compilation error: Cannot override the final method from Parent
}
你有什么好的编程习惯,也留言告诉我吧!!!