Open Closed Principle with Delegates.

Ronald Rex 1,666 Reputation points
2023-08-15T18:47:18.39+00:00

Hi Friends. I am trying to get a very good understanding of Delegates and i came across an article and thought I would share a snippet below to see if anyone could help me to understand better. Thanks !

If you are building a library that can be used by any developers, then if you code against delegates your code will be loosely coupled with the user's code and every other developer can use that method with their own function definition. In Short Open Closed Principle with Delegates.

Developer technologies | C#
0 comments No comments
{count} votes

Accepted answer
  1. P a u l 10,761 Reputation points
    2023-08-15T20:07:54.8133333+00:00

    Correct, delegates define a contract (e.g. a function that accepts an int and returns a string). The function implementation is interchangeable. In your example a method/class that executes a delegate provided by consumer code is defining the contract, and it's the consumers responsibility to provide an implementation.

    This means that the code entity that our library author has made is "Open to extension, since we're extending the library behaviour with no need to change the library implementation, as it's Closed to modification.

    This principle can be applied to many places where a contract can be defined, such as the contract provided by an interface or base class.

    You can imagine that designing an entire system by a loosely coupled set of contracts would make individual code entities much easier to change the implementation of without breaking the contract. It can also hinder readability having too many abstractions, so there's definitely some discretion required.

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 77,766 Reputation points Volunteer Moderator
    2023-08-15T20:13:57.74+00:00

    for example is most Sort libraries use a delegate to compare two items. this allows the caller of sort maximum flexibility. also sort does not need to know anything about the data its sorting.

    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.