DEV Community

Discussion on: Avoid getters and setters whenever possible

Collapse
 
javasavvydev profile image
javasavvydev • Edited

Don't you use inheritance with java and OOP? Creating public variables instead of access methods can cause problems down the road, it also can lead to unexpected behavior. See the example below. While you probably wouldn't have a getter for a public variable, they are public for this demonstration of showing the difference. Remember, the highest cost of software is not the initial released product, but maintaining it!

public abstract class Animal {
public String name = "animal";
public String getName() { return this.name; }
}

public class Cat extends Animal {
public String name = "KIT-CAT";
}

public class PlayWithAnimal {
public static void main (String [] args) {
Animal animal1 = new Cat();
Cat cat = new Cat();
System.out.println(animal1.name);
System.out.println(animal1.getName());
System.out.println(cat.name);
System.out.println(cat.getName());

}
}

Output: animal, KIT-CAT, KIT-CAT, KIT-CAT
So now Inheritance is less useful. You can create an animal instance that contains a cat, but without a getter method you are now unable to access the cat's name...

It's also much easier to find "usages" of methods in most IDE's when using getters and setters. This can be very useful and powerful when refactoring code. (I have had to refactor code that didn't use getters and setters and it was more painful...

Some of the examples are just bad code practices, like the ability to add debts to the list, in this case it would be better to pass a copy as you said, that does not really have anything to do with getters and setters being bad, you would have the same problem with a public variable, but it COULD be protected through a getter method returning a copy.