I need to use instances which represent mathematical functions along with their parameters end enable their evaluation. I can take 2 approaches:
1: have a single class representing all the math functions:
class TrigonometricFunction extends Function {
private double param;
private String name;
public TrigonometricFunction(double param, String name) {
this.param = param;
this.name = name;
}
public double evaluate() {
double radParam = toRadians(param);
if ("sin".equals(name)) {
return Math.sin(radParam);
}
if ("cos".equals(name)) {
return Math.sin(radParam);
}
// about 10 more functions would go here...
}
}
Advantages of this approach:
- have to create and test just a single class
- no code duplicity (conversion of param to radians)
Disadvantages:
- inefficient evaluation (have to do a lot of String comparisons in evaluate() depending on the function name), but would this even be an issue?
- looks ugly and just doesn't feel right
2: have a separate class for each math function:
class SinFunction extends Function {
private double param;
public SinFunction(double param) {
this.param = param;
}
public double evaluate() {
double radParam = toRadians(param);
return Math.sin(radParam);
}
}
class CosFunction extends Function {
private double param;
public CosFunction(double param) {
this.param = param;
}
public double evaluate() {
double radParam = toRadians(param);
return Math.cos(radParam);
}
}
Advantages:
- small classes, single responsibility, just seems better
- more effective evaluation as in the first solution (no String comparisons) (?)
Disadvantages:
- have to implement and test a lot of small classes which look basically the same
- duplicate code (calling conversion to radians in each class)
- more expensive to create instances (have to do the String comparison here).
Which approach is better and why? Or do you have a better solution?