1

I'm a little bit confused about how to properly use getter and setter in some case. Let's imagine for example a class named Car.

This Car has a maintenanceBook, and this one some information about the Car:

class Car() {
    MaintenanceBook maintenanceBook;
}

class MaintenanceBook() {
    String date;
    String lastCall;
}

What is the best practice to access to the different parameters of the maintenanceBook:

  • set all parameters to public and use car.maintenanceBook.date or...
  • implement getter and use car.getMaintenanceBook().getDate(); ?
Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
  • This should help - [Java Getter and Setter Tutorial - from Basics to Best Practices](http://www.codejava.net/coding/java-getter-and-setter-tutorial-from-basics-to-best-practices) –  Aug 09 '18 at 12:11

2 Answers2

3

You should prefer:

  • Getters and setters over the public parameters - these allow additional functionality as validation is.
  • Final parameters set with a constructor with getters only, if possible - a step towards the immutability.

Also, I prefer printers over getters in general. Moreover, it's not a good idea to generate getters/setters right upon creating a class but only and only if you need them (Hibernate mapping is an exception, for example).

Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
1

This has nothing to do with java it self. It's about the encapsulation concept which is fundamental in all object orientated languages. (https://en.wikipedia.org/wiki/Encapsulation_(computer_programming))

So according to this fundamental concept car.getMaintenanceBook().getDate() is the the right solution.

Dimitrios Begnis
  • 823
  • 6
  • 16