Issue
description:
- I need write a new DTO(data transfer object) class
AppleRequestuse some ofPriceRequestDTO class member. - The database table field be like:
ID, supplier_id, supplier_name, size, color, price, etc
- I got a class
PriceRequestwhich I can't change it, but my co-workers may change its member into@NotBlankin the future. So if I useinheritto achieve it, it may not work in the future. - The
AppleRequestclass andPriceRequestclass don't have the "is-a" relationship, it means not allAppleRequestisPriceRequest. In other words,they don‘t have any obvious father-son relationship, just share some of member. - They are both DTO to a same database table.
code:
- PriceRequest:
@Data
public class PriceRequest {
private int id;
@NotBlank
private String supplierId;
//maybe @NotBlank in the future
private String supplierName;
}
- AppleRequest:
@Data
public class AppleRequest extends PriceRequest {
private String color;
private String size;
}
- main
public class Sandbox {
public static void main(String[] args)
{
AppleRequest apple = new AppleRequest();
apple.setId(1);
apple.setColor("red");
apple.setSupplierName("");
System.out.println("id:"+apple.getId()+" SupplierName:"+apple.getSupplierName()+" Color:"+apple.getColor());
}
}
what I have tried:
- just copy-paste all member I need in
PriceRequestintoAppleRequest. But it seems a little stupid.
@Data
public class AppleRequest {
private int id;
private String supplierName;
private String color;
private String size;
}
question:
- Should I use
compositioninstead ofinherit, or any better way to deal with this situation? - How to avoid the change of
PriceRequestmakeAppleRequestnot working.
Solution
If both classes are logically distinct, then bite the bullet and write two distinct classes. That way, they will remain logically distinct and changes in one class won't affect the other class. Copy-pasted code is only bad if it is logically equivalent. (Temporary) structural equivalence doesn't justify making the two classes dependent on one another.
If one class depends on the other (and it doesn't matter if the dependency is caused by inheritance or composition), then changes in one will always change the other. But if the changes shouldn't affect the other class, then you must touch both classes now.
You might want to read up on cohesion: Change together, what belongs together (and your two classes don't belong together).
Answered By - knittl
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.