dimanche 1 février 2015

ID and EAN inheritance may violate Liskov Substitution Principle

I have a design question for my application.


I have a product and a category. Both must have an ID.


Category can have any positive integer as an ID. (-> Id-class)


Product must have an positive integer between 8 & 13 ciphers as an ID. (-> Ean-class)


Since that's the only thing these classes do (create an id) and a getter/setter with the correct check.


To reduce code (DRY) I let Ean inherit from Id. But won't that violate Liskov (LSP)?


My question:



  1. Is my LSP-reasoning correct? If yes:

  2. Should I solve it with creating an interface? (seems like duplicate code) Or is there another solution?


Thanks in advance!


Identifier.java



public class Identifier {

private Long id = 1000000000000L;

public Identifier(){

}

public Identifier(Long id){
setId(id);
}

public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

}


Ean.java



public class Ean extends Identifier {

private final static int MIN_AMOUNT_OF_CIPHERS = 8;

private final static int MAX_AMOUNT_OF_CIPHERS = 13;

private final static String ERROR_EAN_LENGTH = "err_ean_length";

public Ean() {
}

public Ean(Long ean) throws DomainException {
setEan(ean);
}

public Long getEan() {
return getId();
}

public void setEan(Long ean) throws DomainException {
if (String.valueOf(ean).length() < MIN_AMOUNT_OF_CIPHERS
|| String.valueOf(ean).length() > MAX_AMOUNT_OF_CIPHERS) {
throw new DomainException(ERROR_EAN_LENGTH);
}
setId(ean);
}

Aucun commentaire:

Enregistrer un commentaire