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:
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.