Object-oriented – Do delegates defy OOP

delegatesnetobject-oriented

I'm trying to understand OOP so I can write better OOP code and one thing which keeps coming up is this concept of a delegate (using .NET). I could have an object, which is totally self contained (encapsulated); it knows nothing of the outside world… but then I attach a delegate to it.

In my head, this is still quite well separated as the delegate only knows what to reference, but this by itself means it has to know about something else outside it's world! That a method exists within another class!

Have I got myself it total muddle here, or is this a grey area, or is this actually down to interpretation (and if so, sorry as that will be off topic I'm sure). My question is, do delegates defy/muddy the OOP pattern?

Best Answer

In my head, this is still quite well separated as the delegate only knows what to reference, but this by itself means it has to know about something else outside it's world!

But it doesn't. Your delegate is just a variable that when invoked calls something. If you have a string variable, it could contain anything. Your class isn't somehow breaking encapsulation if another class sets your string variable to "foobar". Likewise, your class' encapsulation is not broken if your delegate is set to "hide this UI widget when triggered".

Related Topic