Using protected with composed class in an implented interface?

I

iksrazal

I was having a friendly discussion with another developer, who did
something like:

public interface MyInterface
{
public List getMyList(int myInt);
}

public class MyInterfaceImpl implements MyInterface
{
// composition
protected MyProtectedClass myObject;

public List getMyList(int myInt)
{
myObject.findList(myInt);
}
}

The developers point was that since this class will be used by several
different clients, it is possible that in the future someone may
decide to use 'extends' on MyInterfaceImpl, and so any internal class
using composition should be protected.

Agree or disagree? Care to explain why?
iksrazal
 
O

Oscar kind

iksrazal said:
The developers point was that since this class will be used by several
different clients, it is possible that in the future someone may
decide to use 'extends' on MyInterfaceImpl, and so any internal class
using composition should be protected.

He's right in that the internal state should be "protected" (this is not
the keyword). If a subclass can tweak your internal state, you don't know
what to expect. This is not wrong per se, but attracts bugs. I tread it as
wrong for that very reason.

I would therefore say that the object needs to be private; not protected.
If it's nice/good/... for a subclass to access it, create a protected
accessor (getFoo() method).
 
M

Marcin Grunwald

Oscar said:
I would therefore say that the object needs to be private; not protected.
If it's nice/good/... for a subclass to access it, create a protected
accessor (getFoo() method).

I agree that it should be private. If you aren't sure that it should be
protected than better do it private - prophesying isn't good idea. Later
you can easily change private to protected, opposite direction is always
more complicated.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,566
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top