Skip to content

Instantly share code, notes, and snippets.

@odrotbohm
Created September 12, 2012 11:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save odrotbohm/3706123 to your computer and use it in GitHub Desktop.
Save odrotbohm/3706123 to your computer and use it in GitHub Desktop.
Java properties: shadowing vs. exposing
class BaseClass {
private final Dependency dependency;
public MyBaseClass(Dependency dependency) {
Assert.notNull(dependency);
this.dependency = dependency;
}
protected void myBusinessMethod() { … }
}
class SubClass extends BaseClass {
private final Dependency dependency;
public SubClass(Dependency dependency) {
super(dependency);
this.dependency = dependency;
}
public void method() {
… = this.dependency; // using local dependencies
… = myBusinessMethod(); // using functionality of the superclass
}
}
// VS
class BaseClass {
private final Dependency dependency;
public MyBaseClass(Dependency dependency) {
Assert.notNull(dependency);
this.dependency = dependency;
}
protected Dependency getDependency() {
return dependency;
}
protected void myBusinessMethod() { … }
}
class SubClass extends BaseClass {
public SubClass(Dependency dependency) {
super(dependency);
}
public void method() {
… = getDependency(); // accessing internals of the superclass
… = myBusinessMethod(); // using functionality of the superclass
}
}
@wilkinsona
Copy link

Another advantage of exposing an accessor method, rather than relying on the subclass shadowing the dependency, is that it means that the superclass can wrap the dependency if it needs to. Doing so means that the subclass will then use the wrapped dependency, whereas in the shadowing approach it'll be using the unwrapped version. That might not be a requirement when you first write the superclass, but it helps to keep your options open.

With respect to where you draw the line; like Bruce, I'd only provide protected final getters for the pieces of the superclass that I consider to be part of its contract. I definitely wouldn't expose all of its fields via protected getters.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment