在 Java 中,降低代码复杂度通常涉及以下几个方面:
简化逻辑:
遵循单一职责原则(SRP):
使用设计模式:
减少重复代码:
利用 Java 标准库:
Stream
API、Optional
类、Collections
工具类等。编写可测试的代码:
代码重构工具:
以下是一个简单的示例,展示如何通过提取方法和使用策略模式来降低代码复杂度:
public class Calculator {
public int add(int a, int b) {
if (a < 0 || b < 0) {
throw new IllegalArgumentException("Negative numbers are not allowed");
}
return a + b;
}
public int subtract(int a, int b) {
if (a < 0 || b < 0) {
throw new IllegalArgumentException("Negative numbers are not allowed");
}
return a - b;
}
public int multiply(int a, int b) {
if (a < 0 || b < 0) {
throw new IllegalArgumentException("Negative numbers are not allowed");
}
return a * b;
}
public int divide(int a, int b) {
if (a < 0 || b < 0) {
throw new IllegalArgumentException("Negative numbers are not allowed");
}
if (b == 0) {
throw new IllegalArgumentException("Division by zero is not allowed");
}
return a / b;
}
}
public interface Operation {
int apply(int a, int b);
}
public class Addition implements Operation {
@Override
public int apply(int a, int b) {
return a + b;
}
}
public class Subtraction implements Operation {
@Override
public int apply(int a, int b) {
return a - b;
}
}
public class Multiplication implements Operation {
@Override
public int apply(int a, int b) {
return a * b;
}
}
public class Division implements Operation {
@Override
public int apply(int a, int b) {
if (b == 0) {
throw new IllegalArgumentException("Division by zero is not allowed");
}
return a / b;
}
}
public class Calculator {
private Operation operation;
public Calculator(Operation operation) {
this.operation = operation;
}
public int performOperation(int a, int b) {
return operation.apply(a, b);
}
}
public class Main {
public static void main(String[] args) {
Calculator addition = new Calculator(new Addition());
System.out.println("Addition: " + addition.performOperation(10, 5));
Calculator subtraction = new Calculator(new Subtraction());
System.out.println("Subtraction: " + subtraction.performOperation(10, 5));
Calculator multiplication = new Calculator(new Multiplication());
System.out.println("Multiplication: " + multiplication.performOperation(10, 5));
Calculator division = new Calculator(new Division());
System.out.println("Division: " + division.performOperation(10, 5));
}
}
通过这种方式,我们将复杂的操作逻辑分解成多个简单的类,并使用策略模式来选择不同的操作,从而降低了代码的复杂度。