class Program
{
static void Main(string[] args)
{
B b = new B();
b.Run();
Console.Read();
}
}
class A
{
public event Action onChanged;
public void Raise()
{
if (onChanged != null)
onChanged();
}
}
class B
{
public void Run()
{
A a = new A();
a.onChanged += a_onChanged;
a.Raise();
}
private void a_onChanged()
{
Console.WriteLine("Wow! Invoked");
}
}
I am not able to figure out the Valid points which can justify that I broke encapsulation or may be otherwise. As per my understanding I am breaking encapsulation as a private method is getting called from another class, Is this enough for justifying that I broke on the laws of OOP. Need to gather some more inner concepts and descrption for the code above.
This really depends on why do you have a Raise
method in class A.
If it there solely for enabling the access to a private member, then the answer would be: yes, your encapsulation has been compromised.
The onChanged
event should occur when something has changed and not when some external class decides it should.
However, if this is only a simple snapshot for making a point, and the Raise
event is a method that is triggering the event as a side effect to an action taken (something like changing text in a Textbox
and then triggering onTextChanged
) than your encapsulation is still in tact.
Note:
I am breaking encapsulation as a private method is getting called from another class
From Wikipedia:
Encapsulation is used to hide the values or state of a structured data object inside a class, preventing unauthorized parties' direct access to them. Publicly accessible methods are generally provided in the class (so-called getters and setters) to access the values, and other client classes call these methods to retrieve and modify the values within the object.
It is OK for the private method to be called from a public one. How else would it be called? It is up to you, the programmer, to get your methods logic straight and make sure that they call the appropriate methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With