简体   繁体   中英

Seeking a OOP design review for generic typed class

I am implementing a operation helper class like:

class ComparisonHelper {
  
  public static Comparison<Long> lt(String key, long value) {
    return new Comparison<>(ComparisonOperator.LT, key, value);
  }
  
  public static Comparison<Integer> lt(String key, int value) {
    return new Comparison<>(ComparisonOperator.LT, key, value);
  }

  public static Comparison<Float> lt(String key, float value) {
    return new Comparison<>(ComparisonOperator.LT, key, value);
  }

  public static Comparison<Double> lt(String key, double value) {
    return new Comparison<>(ComparisonOperator.LT, key, value);
  }

// 4 more methods for each of ComparisonOperator.[LTE, GT, GTE]
// total 16 methods in the class
// LT - less than, GT - greater than, GTE - greater than equals, LTE - greater than equals
}

I am ending up with a lot of duplicate methods that only differ in small details. I want to offer a user of this class to be able to create comparisons like ComparisonHelper.lt("key", 20) or ComparisonHelper.gte("key", 30.0) . In future, I can support comparisons for say Date or any other generic type. How can I improve my design?

If you want to redesign you class to be OOP , think of it as an object with methods. Avoid using 'er' suffix in class name, it should be a noun not a verb under cover. As an object that has methods it should respond to a qeuestion: isBiggerThan , isSmallerThan , isLonger and of course we want to compare an object to another object, so method parameter of the method should be an object of the same type as the main one.

This class seems that needs to be extracted into an interface named Comparable for example. The object Apple , that will implement the interface will have method isGreaterThan(Comparable comparable) that can return a Boolean with the answer, or object that hold comparison result named ComparisonResult , or simply Result . We can have also an abstract Apple if its needed, named Fruit .

In this example lt(String key, long value) its procedural thinking, this is why you have troubles to transform it in OOP, because it makes no sense as an object abstraction from real world. We don't have strings and longs in real world.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM