According to Why is Clean Code suggesting avoiding protected variables?, I should avoid protected variables because of the reason : "closely related concepts should not be separated into different files", that means, for example, if all Animal must have an _id field:
public class Animal{
protected String _id;
public String getId(){
return _id;
}
}
public class Cat extends Animal{
}
public class Dog extends Animal{
}
To avoid protected fields, I should use "private" to limit the access of _id:
public class Animal{
private String _id;
public String getId(){
return _id;
}
}
public class Cat extends Animal{
//use this.getId() to access _id
}
public class Dog extends Animal{
//use this.getId() to access _id
}
However, it seems that it is still not fulfill "closely related concepts should not be separated into different files" because the _id field is a "closely related thing", which is not put in Cat and Dog, so I think it should be:
public interface Animal{
public String getId();
}
public class Cat implements Animal{
private String _id;
public String getId(){
return _id;
}
}
public class Dog implements Animal{
private String _id;
public String getId(){
return _id;
}
}
which delete the instance variables in base class and copy and paste
private String _id;
public String getId(){
return _id;
}
to all child classes.
I think as all instance variables in base class (include the private one) are "closely related to the child class", which should not separate them from child class, and hence we should avoid all base class instance variables and then copy and paste all base class instance variables to the child class. Is it true? If not, what do I misunderstand about this suggestion?
id
is not the best example. Flag instance variables are often better candidates to be protected within a hierarchy like this. Sure, we could implement one or two methods to toggle the flag but, Is it worth it? And, before any of you rush to say "of course because encapsulation bla bla bla" think first if you are one of those lombok lovers who hate writing setter and getters-