Getters and setters are used when data needs to be encapsulated and/or validated. For instance, if you wanted to get someone's age, you should have something like
rather than just having a public int age field. There are other situations where you might want encapsulation, without necessarily providing validation. For instance
In this case, we want to provide a method for setting a new password, and checking against the current one. If you had a public field, this sensitive information could leak.
Web developer at Greggs, UK with a proficiency in VueJS, Tailwind, and Storyblok, as well as other frameworks. I'm also passionate about web design, and mobile app development.
It's unusual, for sure, but so is directly getting and setting any state of a particular object, I'd say. The user usually doesn't interact directly with objects, but with some UI layer which then manipulates the objects, and -- as you say -- the validation is usually performed in that UI layer.
This might occur when trying to create objects without user input, like when reading serialized objects from a database. If your object schema has changed, you'll need to validate it before you can deserialize it. Slightly different from a setter, but the same general idea.
You're right that it's uncommon, but it's necessary.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Getters and setters are used when data needs to be encapsulated and/or validated. For instance, if you wanted to get someone's age, you should have something like
rather than just having a
public int age
field. There are other situations where you might want encapsulation, without necessarily providing validation. For instanceIn this case, we want to provide a method for setting a new password, and checking against the current one. If you had a public field, this sensitive information could leak.
Seconding this. Encapsulation is very important for protecting sensitive data.
Yeah, I totally understand why it is theoretically needed.
But have you ever had such validation in setters?
or was it in some validation 'business' logic outside domain class?
regarding 'password' use case:
yes, of course, you should use setters where it is really needed, but in 99% you can have public fields without any problem.
It's unusual, for sure, but so is directly getting and setting any state of a particular object, I'd say. The user usually doesn't interact directly with objects, but with some UI layer which then manipulates the objects, and -- as you say -- the validation is usually performed in that UI layer.
This might occur when trying to create objects without user input, like when reading serialized objects from a database. If your object schema has changed, you'll need to validate it before you can deserialize it. Slightly different from a setter, but the same general idea.
You're right that it's uncommon, but it's necessary.