views:

84

answers:

2

What I mean is:

public class SomeBackingBean {

   protected String someString;

   public void setSomeString (String str) { 
      this.someString = str; 
   }

   public String getSomeString {
      return someString;
   }
}

It was just a general case for a general answer.

Now second example:

public abstract class AbstractBean<T extends EntityInterface> {

   protected T entity;

   public void setEntity (T t) {
      this.entity = t;
   }

   public void getEntity () {
      return entity;
   }

   protected ReturnType calculateSomethingCommon () {
      //use entity (knowing that it implements EntityInterface) 
      //to implement some common for all subclasses logic
   }
}

public class ConcreteBean extends AbstractBean<ConcreteEntity> {
   ...
   //and here we can write only specific for this bean methods
   ...
}

Is second example an example of bad practice too?

+3  A: 

In general, protected variables violate object oriented principles. You're giving other objects direct access to member variables. By doing so, you form tighter coupling and it makes it harder to change the variable, since other objects are directly using it. It also means you can't do things like validate when it's set, add logging around getters/setters, etc.

Jeff Storey
A: 

If, for example, you have a PropertyChangeListener registered to properties for a bean, any registered listeners might not be notified if a protected property is changed directly by a sub-class.

Luhar