Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

To put it simply as an example,

public abstract class AbstractFellow {

    protected Thing buddy;
....

public class ConcreteFellow extends AbstractFellow {
     public void someMethod() {
          buddy.doSomething();
          //OR
          buddy = somethingElse;
          //OR
          somethingElse = buddy;
     }
}

Is this bad practice?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
726 views
Welcome To Ask or Share your Answers For Others

1 Answer

Opinions vary. My opinion is that even in abstract classes, using private members and protected accessors (i.e. protected getBuddy()) is a better practice.

It allows for the same things encapsulation always allowed: to contain the logic of obtaining the "buddy" object in the super-class, and allowing you to change that logic without breaking all inheriting classes.

The super-class might not expect buddy to be changed, either. For example, you might want to unregister listeners or do some other cleanup when that happens - having a setter method helps achieve that.

In addition, it obviously allows you to have Buddy as a read-only member (since you can provide only a getBuddy and no setBuddy), something that is not as easy to accomplish with a member (you can always set it to be final, but then you prevent the super-class from changing it, too!)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...