In: Computer Science
why are direct input and outputs highly discouraged in setters and getters
- Setter and getter means that we will not be exposing the
actual fields while instantiating the class.
- We will expose certain methods which will internally set / get
the value of those fields for which the setter/getter are
exposed
Reasons for
using getter/setter instead of direct
input/output
- It controls the lifetime of the objects. In languages like C++
where memory manement is handled by scope , it is important to
define scope of variables only within their use. If we would use
direct appraoch , lifetime would be throughout the life of
program.
- It helps to maintain the code and find issues easily. As there is
only one point in the program where the updates to the fields can
happen.
- We can control the security access level of the fields by making
the getter/setter as per the scope (private, public ....)
- Exposing the fields directly can corrupt the object with
incorrect data / undesired modification.
Even in
setter/getter, direct input/output is
discouraged
- As whatever the value comes, setter directly sets it without
having to validate the data. It might result in inconsistent state
of the system
- It exposes the implementation details.
- It exposes even the private fields to be accessible outside of
the class via methods.
- There are no rules defined to filter out unwanted / malacious
input
Kindly upvote
if it helped