Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In OOP, Private membes are private for who?

Tags:

java

c++

oop

In OOP why need to put something Private , for example. I know that any private member can not be accessed but with the same class objects. But why I need to do that while I am the only coder of my project. The same question extends to Protected, protected from who!

like image 996
Aan Avatar asked Oct 15 '11 10:10

Aan


2 Answers

private and protected are not there to prevent other coders from accessing the internals of a class, but (also) to prevent yourself from creating a program without clearly defined interfaces.

If every class in your project can modify every other class, you're not only prone to introduce bugs because of the huge state space, but also preventing yourself from:

  • Changing the implementation (while keeping the interface the same) of any class.
  • Ever introducing anyone not familiar with all the internals of all the classes to the project. Unless you have a perfect memory and can recite every line of code you've ever written, that includes future you.
  • Mocking up objects for unit testing
  • Interacting with other versions of your program/library. Suppose you do change internals of one class, and you manage to track down every reference to that internal property in your project. Even then, you may need to interface with the old version of your program again. This becomes especially hard if used properties instead of getter/setter methods.
like image 163
phihag Avatar answered Sep 28 '22 13:09

phihag


Access modifiers achieve two different things:

  1. They limit the amount of code that can cause side effects, making it easier to establish invariants.

  2. They protect clients of the class from changes to the internal representation.

For small projects, these advantages might not be immediately visible, especially for beginners.

like image 20
fredoverflow Avatar answered Sep 28 '22 12:09

fredoverflow