I am trying to understand Object oriented programming. With respect to Encapsulation, I understood it like this.
"Encapsulation, refers to an object's ability to hide data and behavior that are not necessary to other classes& assemblies.
With the help of encapsulation, a class can change the internal implementation without hurting the overall functionality of the system.
Prevents code (data) from accidental corruption due to programming errors
Encapsulation enables a group of properties, methods and other members to be considered a single unit or object."
So, when it comes to data hiding/security with encapsulation, I understand it like securing the data from other programmers in the team as there are chances that the data can be corrupted due to programming errors
My question here is, "Is my understanding about data security/data hiding with respect to encapsulation is correct? Or, whether it is not limited to securing data from programmers alone and it enables securing data from hackers as well ?"
The encapsulation has nothing to do with outside hackers, it's not a data security concept, it's more about programming model. Here is an example:
class Engine
{
public bool Running { get; private set; }
public void Start()
{
this.Running = true;
}
public void Stop()
{
this.Running = false;
}
}
It's a simple model, Engine
can Start
/Stop
by its instance methods, which essentially changes the Running
property. If you want to start/stop an Engine
, just invoke the corresponding method. We can say the behaviors of Engine
is well encapsulated.
Let's change the code
class Engine
{
public bool Running { get; set; } //set is changed to public
}
Now the code is shorter and simpler, if we want to start an engine just set Running
to true
(or false when you want to stop). As the project grows, you will have several methods that will change Running
property to start an engine.
Here comes a new case1: sometimes the engine is out-of-control then it can't be started/stopped. If you are using the old version, it's easy to change the code to:
class Engine
{
public bool Running { get; private set; }
public bool OutOfControl { get; private set; }
public void Start()
{
if (this.OutOfControl) return;
this.Running = true;
}
public void Stop()
{
if (this.OutOfControl) return;
this.Running = false;
}
public void SomeOperation()
{
//inside the method sometimes OutOfControl is set to true
}
}
The callers of Engine.Start
and Engine.Stop
will not be affected. What about the "simpler" version? You need to change 10+(or 100+) callers, checking OutOfControl
property before changing Running
property.
And then here comes a new case2, case3...the "simpler" version is becoming harder and harder to maintain. Because it exposes the implementation details to callers. Every time the start/stop implementation changes, the first version (well-encapsulated version) only needs to change the start/stop method, because it's the only place that performs the behavior.