在面向对象编程中,构造函数是用于初始化对象状态的特殊方法。将null作为参数传递给构造函数可能会导致各种问题,因为这通常表示缺少有效值或未初始化的状态。
public interface Logger {
void log(String message);
}
public class ConsoleLogger implements Logger {
public void log(String message) {
System.out.println(message);
}
}
public class NullLogger implements Logger {
public void log(String message) {
// 什么都不做
}
}
// 使用示例
public class Service {
private final Logger logger;
public Service(Logger logger) {
this.logger = logger != null ? logger : new NullLogger();
}
}
public class User {
private final String name;
public User(String name) {
if (name == null) {
throw new IllegalArgumentException("Name cannot be null");
}
this.name = name;
}
}
public class Product {
private final String id;
private final String name;
private Product(String id, String name) {
this.id = id;
this.name = name;
}
public static Product create(String id, String name) {
if (id == null || name == null) {
throw new IllegalArgumentException("Parameters cannot be null");
}
return new Product(id, name);
}
}
import java.util.Optional;
public class Order {
private final String id;
private final String customerName;
public Order(String id, Optional<String> customerName) {
this.id = Objects.requireNonNull(id, "ID cannot be null");
this.customerName = customerName.orElse("Anonymous");
}
}
| 方法 | 优点 | 缺点 | |------|------|------| | 空对象模式 | 消除null检查,提供默认行为 | 需要创建额外的类 | | 参数验证 | 立即发现问题,快速失败 | 需要编写验证代码 | | 工厂方法 | 更灵活的参数处理 | 增加复杂性 | | Optional | 明确表示可选参数 | Java 8+才支持,可能过度使用 |
通过采用这些实践,可以显著提高代码的健壮性和可维护性,减少由null引用引起的错误。
没有搜到相关的文章