質問

I have a problem with the LSP in my program. I have a Base Class that is abstract and two different types of products , one is Food , the other is an Electronic device. I need to make a method that returns the expirationDate/Warranty for those products. The problem is that one is of type Date, and the other (warranty) is of type Int... Do you have any idea how to make a method that satisfies both of those data types? without using switch/if statements since that will violate the OCP.

private static void printExpirationDateStatistics(List<Product> foodProducts) {
for (Product product : foodProducts) {
  System.out.println(product.getExpirationDate());
}

}

Is there any way that is can modify this function to handle both food and electronics so I don't have to make another method for each new product is add ?

Those are the methods from the base class

    public Date getExpirationDate() {
    return expirationDate;
  }

  public void setExpirationDate(Date expirationDate) {
    this.expirationDate = expirationDate;
  }

  public int getWarranty() {
    return warranty;
  }

  public void setWarranty(int warranty) {
    this.warranty = warranty;
  }

I tried making one getValidity method but the problem is that for food it should return Date, and for electronics should return Int. Any ideas ?

役に立ちましたか?

解決

The problem you face here is that you want to abstract over two informationen a kind of common "expiration" information. The problem is that this abstraction is unknown to the code, it's currently only in present in your head :)

It's currently implemented in 2 flavours: Integers and Dates (though I have no idea what this Integer is about? Is it a year count? ... the number of lottory winner since 1990? I don't know).

I would propose adding a new Interface for this abstraction, e.g.

public interface Expiration<T> {
    T getExpiration();
}

In this case your two base classes can implement Expiration<Date> and Expiration<Integer> and you could base your validation logic on that. For example like:

 public boolean isValid(Expiration<Date> potentialyExpired) {
     final Date expirationDate = potentialyExpired.getExpiration();
     final Date now = new Date();
     return expirationDate.before(now);
 }

That can only be done when you can access the classes in question though. Is this abstraction enough or are you in need in even more?

You could want to abstract over the different type of Expiration in such a way that you don't need to have both of them around and unify them at some point. But to decide that kind of thing one would need to know more about the meaning of the other type (the Integer one).

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top