I have been taught to always use getters and setters. However, I don't know the pros and cons of these methods, as by implementing them we are exposing the data and also hiding it.
I am a little confused about this. Can anybody give some proper advice on why we use a getter/setter and what the advantages are?
Getters and setters are used to protect your data, particularly when creating classes. For each instance variable, a getter method returns its value while a setter method sets or updates its value.
Getters and setters are methods used to declare or obtain the values of variables, usually private ones. They are important because it allows for a central location that is able to handle data prior to declaring it or returning it to the developer.
1) getter and setter method gives you centralized control on how a the particular field is initialized and provided to the client which makes the validation and debugging much easier. you can simply put breakpoints or print statement to see which thread are accessing and what values are going out.
The reason for declaring the getters and setters private is to make the corresponding part of the object's abstract state (i.e. the values) private. That's largely independent of the decision to use getters and setters or not to hide the implementation types, prevent direct access, etc.
The basic "private field with public getter and setter that do nothing but return or set the field" pattern is indeed completely pointless when it comes to encapsulation, except that it gives you a chance to change it later without changing the API.
So don't use that pattern unthinkingly. Carefully consider what operations you actually need.
The real point of getters and setters is that you should only use them where they are appropriate, and that they can do more than just get and set fields.
IllegalArgumentException
All of these things are implementation details that are hidden behind the simple "getter and setter" interface. That's what encapsulation is about.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With