Did I break encapsulation?

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 cannot determine valid points that can justify that I broke the encapsulation or it could be otherwise. According to my understanding, I break encapsulation as a private method receives a call from another class. This is enough to justify that I violated the laws of the PLO. It is necessary to collect some more internal concepts and descriptions for the code above.

+6
source share
3 answers

It really depends on why you have the Raise method in class A.

If it exists only to enable access to a private member, then the answer will be: yes, your encapsulation has been compromised.
The onChanged event should occur when something has changed, and not when some external class decides what it should.

However, if this is just a simple snapshot to create a point, and the Raise event is a method that triggers the event as a side effect to the action taken (something like changing text in a Textbox and then running onTextChanged ) than your encapsulation is still in tact .

Note:

I break encapsulation as private call are called from another class

From Wikipedia :

Encapsulation is used to hide the values ​​or state of structured data in an object within a class, which prevents direct access to unauthorized parties. Publicly accessible methods are usually provided in classes (called getters and setters) to access values ​​and others. Client classes call these methods to retrieve and change values ​​within an object.

This is normal if the private method is called from the public. How else could it be called? It is up to you, the programmer, to get the logic of your methods and make sure they name the appropriate methods.

+2
source

You did not break encapsulation in class B, since instances of B only modify themselves, but yes, you break encapsulation in class A. Anything that has a reference to instance A can raise the onChanged event.

+1
source

No, you did not break encapsulation, and the private method receives a call from another class in this case is incorrect. Class B creates its own A and calls its Raise method, which raises the onChanged event.
You are registering for this event from B , so it is completely beautiful.

0
source

Source: https://habr.com/ru/post/971201/


All Articles