2

Accorinding to the Open/Closed principle

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

So can I say that the Category is a strong violation to this principle?

Prasad Devadiga
  • 2,573
  • 20
  • 43
Howard
  • 19,215
  • 35
  • 112
  • 184
  • 2
    You could also say that all of Objective-C's dynamic runtime violates this principle, but that doesn't mean that either can't be used effectively. – cobbal Apr 21 '11 at 15:22

2 Answers2

3

I don't see how. Categories allow you to add functionality which depends on the existing interface. They don't allow you to make any real changes to the original class, they just provide some syntactic sugar which gives you the illusion that new methods have been added to the class.

In other words, categories help you extend a class. They do not modify it. Seems like they reinforce the open/closed principle.

Ferruccio
  • 98,941
  • 38
  • 226
  • 299
3

I think the standard interpretation of "closed for modification" means "adding new features doesn't require modifying existing code." Using that interpretation, categories don't violate the Open/Closed Principle because writing new category methods doesn't constitute modifying existing code.

As for the special case where category methods can replace existing methods on a class, it may not violate the Open/Closed Principle but it is frowned upon because it's dangerous. It's one of those "it's possible to do this, but don't" features of the language.

Tom Dalling
  • 23,305
  • 6
  • 62
  • 80