Is overloading an example of the Open/closed principle

design-patternsopen-closesolid

Wikipedia says

"software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification"

The word functions caught my eyes, and I now wonder if we can assume that creating an overload for a method can be regarded as an example of the Open/closed principle or not?

Let me explain an example. Consider that you have a method in your service layer, which is used in almost 1000 places. The method gets userId and determines whether user is admin or not:

bool IsAdmin(userId)

Now consider that somewhere it's necessary to determine if the user is admin or not, based on username, not userId. If we change the signature of the above-mentioned method, then we've broken code in 1000 places (functions should be closed to modification). Thus we can create an overload to get the username, find the userId based on username, and the original method:

public bool IsAdmin(string username)
{
    int userId = UserManager.GetUser(username).Id;
    return IsAdmin(userId);
}

This way, we've extended our function through creating an overload for it (functions should be open to extension).

Is it an Open/closed principle example?

Best Answer

I would personally interpret the wiki statement thusly:

  • for a class: feel free to inherit the class and override or extend its functionality, but don't hack the original class thereby changing what it does.
  • for a module (maybe a library for instance): feel free to write a new module/library that wraps the original, merges functions into easier to use versions or extends the original with extra features, but don't change the original module.
  • for a function (ie a static function, not a class method): your example is reasonable to me; reuse the original IsAdmin(int) function inside the new IsAdmin(string). the original does not change, the new func extends its functionality.

the shot in the foot however is that if your code is using the 'cUserInfo' class wherein IsAdmin(int) resides, you are essentially breaking the rule and changing the class. the rule would sadly only be kept if you made a new class cUserWithNameInfo : public cUserInfo class and put your IsAdmin(string) override there. If I owned the code base I'd never obey the rule. I'd say bollocks and just make the change you suggest.

Related Topic