For example, consider I have a class for other classes to extend:
public class LoginPage {
public String userId;
public String session;
public boolean checkSessionValid() {
}
}
and some subclasses:
public class HomePage extends LoginPage {
}
public class EditInfoPage extends LoginPage {
}
In fact, the subclass has not any methods to override, also I would not access the HomePage in generic way, i.e.: I would not do something like:
for (int i = 0; i < loginPages.length; i++) {
loginPages[i].doSomething();
}
I just want to reuse the login page. But according to https://stackoverflow.com/a/53354, I should prefer composition here because I don't need the interface LoginPage, so I don't use inheritance here:
public class HomePage {
public LoginPage loginPage;
}
public class EditInfoPage {
public LoginPage loginPage;
}
but the problem comes here, at the new version, the code:
public LoginPage loginPage;
duplicates when a new class is added. And if LoginPage needs setter and getter, more codes need to be copied:
public LoginPage loginPage;
private LoginPage getLoginPage() {
return this.loginPage;
}
private void setLoginPage(LoginPage loginPage) {
this.loginPage = loginPage;
}
So my question is, is "composition over inheritance" violating "dry principle"?
extends LoginPage
all over the place. CHECK MATE! – el.pescado Feb 12 '18 at 16:12LoginPage
a decorator. No more duplication, just a simplepage = new LoginPage(new EditInfoPage())
and you are done. Or you use the open-closed-principle to make the authentication module that can be added to any page dynamically. There a lots of ways to deal with code duplication, mainly involving finding a new abstraction.LoginPage
is likely a bad name, what you want to make sure is that the user is authenticated while browsing that page, while being redirected to theLoginPage
or shown a proper error message if he is not. – Polygnome Feb 13 '18 at 12:34