There is a StoreService
in the project, which provides some methods to read from and write to a remote data store. e.g.
public class StoreService {
public StoreService(String url, String username, String password) {}
public void save(String category, String key, String value) {}
public String read(String category, String key) {}
}
Then I see there is another UserStoreService
which is in a sub-module of the project, which extends StoreService
:
public class UserStoreService extends StoreService {
public UserStoreService(String url, String username, String password) {
super(url, username, password);
}
public void saveUserName(String userId, String userName) {
super.save("user", userId, userName);
}
public void getUserName(String userId, String userName) {
return super.read("user", userId);
}
}
You can see it just add some methods. Is it good to use extends
here?
I can make it without extends
:
public class UserStoreService {
private StoreService storeService;
public UserStoreService(String url, String username, String password) {
this.storeService = new StoreService(url, username, password);
}
public void saveUserName(String userId, String userName) {
storeService.save("user", userId, userName);
}
public void getUserName(String userId, String userName) {
return storeService.read("user", userId);
}
}
But I'm not sure which solution is better, and when should I use extends
and when not.
This really depends on your requirements-- there is no intrinsic 'better or worse' in these scenarios.
Off the top of my head, here are some considerations:
Advantages of inheritance (first scenario):
Advantages of delegation (second scenario):
For delegation in this scenario, you can also consider having a common super-interface, which will often give you the best of both worlds.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments