8

I'm watching a C++ tutorial video. It is talking about variables inside classes and assert that variables should be marked private. It explains that if I want to use them publicly, I should do it indirectly through functions.

Why? What's the difference? It looks like the result is the same, except that instead of having one line of code, I now have like 9 or 10 more LOC to do the same thing.

Can someone explain why converting a private variable in a class to public within the class rather than just making it public right out the simple way is any different and more efficient?

Ampt
  • 4,733

2 Answers2

11

There are a few reasons to use setters and accessors as opposed to simply making variables public.

1. Separation of concerns - The consumers of a class shouldn't know, or even care, whether what they're accessing is a primitive variable, or something more complex. For example, let's say I had a Car class, and that car has a horsepower. You can get the horsepower by calling the getHorsepower() method, and you can set it with setHorsepower(int power).

Now, a consumer of this class really doesn't care what goes on under the hood, just that there is a horsepower method. But what if, on the backend, setting the horsepower meant changing the engine? When you call setHorsepower, it will find an engine that can provide that, and call the private method setEngine(Engine newEngine) to make sure that the car's behavior is consistent!

2. Code maintainability - When you set up the class, it may make sense to only have a public variable, but you quickly find that you need to do error checking on the variable, or you need to have a change in that variable update another object. If you provided the public variable, you would need to change all the classes that use that and then have them either A) Implement all the functionality you need them to like error checking, or B) Change them to use an accessor. By having them use the accessor, you can modify all of that in one place instead of having to keep track of all the places that use that variable.

Ampt
  • 4,733
6

Getters and setters are poor design as well. They are better than public variables because they allow the class to enforce invariants. To borrow Ampt's example setHorsepower is better than a public horsepower variable because the car class can ensure that horsepower is never negative with the setter, but can't guaranty anything about a public variable. While that is better than nothing, a better design would have car instances in charge of their own horsepower. Any code that is mucking about with the car's internal state should be apart of the car class. It shouldn't have wondered off and gotten lost somewhere else.

stonemetal
  • 3,381