top | item 19418184

(no title)

wtroughton | 7 years ago

100% agree that in object-oriented programming, only the object itself should care about its internal state. The object should know about its behaviors and what state changes are actually valid.

In Java, many projects overuse getters and setters. Getters and setters break encapsulation. More so public setters since they allow any piece of code anywhere can change the value of an object's internal state at any time.

Consider a class Person. A person has a name, SSN, salary. Let's assume name and SSN cannot be changed. What about salary? We don't have to add a setSalary() method. Instead, we should have something like: public void acceptNewJob(Job newJob) { salary = newJob.getSalary(); }

discuss

order

mav3rick|7 years ago

This is one more layer of abstraction that was unneeded. In your example you went through all the trouble to get the same result. Where as there is no notion of a Job inside the person encapsulation (since you don't set a job field ). It's just the salary the object cares about. So why pass in a Job. It so confusing for the reader.

miskin|7 years ago

That example is correct, because in OOP you should not simply change state/value inside other object, because you pretty much end up with anemic domain model where classes are just structs and code that modify it is not part of the class. What parent meant was that you call "accept new job" on person object and then use this object instead of just setting the salary. Maybe it was oversimplified, though.