views:

59

answers:

2

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?

+1  A: 

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!)

Aviad Ben Dov
Yes, but it depends on the language.
jro
What depends on the language? In all OO languages this would be true. The only thing different will probably be the `final` field modifier, which might be called differently or not exist at all.
Aviad Ben Dov
I'm talking about Java, but I thought the concept was general enough to apply to other similar languages.
James McMahon
It is - my answer is the general concept.
Aviad Ben Dov
More specifically - I do the same when I write in C#, Objective-C, Java or C++.
Aviad Ben Dov
+1  A: 

It depends on you domain model and why you creating and abstract class. If you are defining your interface with it and want abstract class to keep some functionality it`s ok.

If you are just setting all the fields protected and then reusing them in your child classes. Well it depends, but I think a better way should be found. And it seems not very clear for your future reader to get data in the base class and all it's behavior in child classes. If you do not need base class ability to implement methods (and you do not need to store any functionality in your base class) maybe it`s a better choice to implement an interface with every of these child classes.

If you use some of base class inner fields it seems natural to me and it's ok. Just if you are using some of them in your child classes for similar things you can implement a template method and enjoy with overriding only the parts you really need to override.

Yaroslav Yakovlev