I would probably consider it a code smell or even an anti-pattern to have a class that implements 23 interfaces. If it is indeed an anti-pattern, what would you call it? Or is it simply just not following the Single responsibility principle?

Well, it's questionable either way. If the class has 23 methods which all serve a single responsibility (not all classes need so many methods, but it' not impossible - especially if most are three-line convenience wrappers around other methods), you just have too fine-grained interfaces ;)
–
delnanNov 3 '11 at 13:09

The class in question is a kind of entity and the interfaces are mostly to properties. There are 113 of those and only four methods.
–
Jonas ElfströmNov 3 '11 at 13:15

6

I thought interfaces are essentially used for duck typing in statically-compiled languages. What's the problem? :)
–
ashes999Nov 3 '11 at 14:30

2

just a question: are all the 113 properties populated for each instance of this entity ? Or is it some kind of "common entity" used in different contexts with only some properties filled ?
–
DavidNov 3 '11 at 16:38

The more I look at it, the more it seems @ashes999 has a point. Partly there seems to be something close to duck typing going on there.
–
Jonas ElfströmNov 3 '11 at 18:12

@FrustratedWithFormsDesigner A Swiss Army Knife would never have the bad taste of having an interface named IValue that contains 30 properties of which 20 are preceded by the new modifier keyword.
–
Jonas ElfströmNov 3 '11 at 18:35

In Greek mythology, the Lernaean Hydra (Greek: Λερναία Ὕδρα) was an ancient nameless serpent-like chthonic water beast, with reptilian traits, (as its name evinces) that possessed many heads — the poets mention more heads than the vase-painters could paint, and for each head cut off it grew two more — and poisonous breath so virulent even her tracks were deadly.

Of particular relevance is the fact that it not only has many heads, but keeps growing more and more of them and is impossible to kill because of it. That's been my experience with these kinds of designs; developers just keep jamming more and more interfaces into it until it has too many to fit on the screen, and by then it's become so deeply entrenched in the program's design and assumptions that splitting it up is a hopeless prospect (if you try, you actually often end up needing more interfaces to bridge the gap).

One early sign of impending doom due to a "Hydra" is frequent casting of one interface to another, without much sanity checking, and often to a target that makes no sense, as in:

It's obvious when taken out of context that there's something fishy about this code, but the likelihood of this happening goes up with the more "heads" an object grows, because developers intuitively know that they're always dealing with the same creature.

Good luck ever doing any maintenance on an object that implements 23 interfaces. The chances of you not causing collateral damage in the process are slim to none.

The God Object comes to mind; a single object that knows how to do EVERYTHING. This comes from low adherence to the "cohesion" requirements of the two major design methodologies; if you have an object with 23 interfaces, you have an object that knows how to be 23 different things to its users, and those 23 different things are likely not along the lines of a single task or area of the system.

In SOLID, while the creator of this object has obviously tried to follow the Interface Segregation Principle, they have violated a prior rule; Single Responsibility Principle. There's a reason it's "SOLID"; S always comes first when thinking about design, and all the other rules follow.

In GRASP, the creator of such a class has neglected the "High Cohesion" rule; GRASP, unlike SOLID, teaches that an object doesn't HAVE to have a single responsibility, but at most it should have two or three very closely related responsibilities.

I am not sure that this is the God Object anti-pattern, since God is not constrained by any interfaces. Being constrained by so many interfaces could reduce God's omnipotence. ;) Maybe this is a Chimera Object?
–
FrustratedWithFormsDesignerNov 3 '11 at 14:22

God has many faces, and can be many things to many people. If the functionality of the combined interfaces makes the object "all-knowing" it's not really constraining God, is it?
–
KeithSNov 3 '11 at 14:41

1

Unless that which created the interfaces modifies them. Then God might have to be reimplemented to conform to interface changes.
–
FrustratedWithFormsDesignerNov 3 '11 at 15:16

2

It hurts that you think that it was me that created the class.
–
Jonas ElfströmNov 3 '11 at 15:40

The use of "you" is more the plural you, referring to your dev team. SOMEONE on that team, past or present, created this class. I will edit, though.
–
KeithSNov 9 '11 at 23:35

23 is Just a number! In most likely scenario, it is high enough to alarm. However, if we ask, what is the highest number of methods/interfaces before it can get a tag to be called as an "anti-pattern"? Is it 5 or 10 or 25? You realize that number is really not an answer because if 10 is good, 11 can also be - and then any integer after that.

The real question is about complexity. And we should point out that lengthy code, number of methods or large size of the class by any measures is actually NOT the definition of complexity. Yes, a larger and bigger the code (larger number of methods) does make it difficult to read and grasp for a new beginner. It also handles potentially varied functionality, large number of exceptions, and quite evolved algorithms for various scenarios. This doesn't mean it is complex - it is only difficult to digest.

On the other hand, relatively small size code which one can hope to read out in a few hours in and out- can still be complex. Here is when I think the code is (unnecessarily) complex.

Every piece of wisdom of Object-oriented design can be put in here to define "complex" but I would restrict here to show when "so many methods" is an indication of complexity.

Mutual Knowledge. (a.k.a coupling)
Many a times when things are written as classes, we all think it is "nice" object oriented code. But assumption about the other class essentially breaks the real needed encapsulation. When you have methods which "leak" deep details about the internal state of the algorithms - and the application is built with key assumption about the internal state of the serving class.

Too many repeats (breaking in )
When methods which have similar names but do contradicting work - or contradicting names with similar functionality. Many a times codes evolve to support slightly different interfaces for different applications.

Too many roles
When class keeps adding side functions and keep expanding more as people like it, only to know that the class indeed is now a two class. Surprisingly these all start with genuine requirements and no other class exist to do this.
Consider this, there is a class Transaction, which tell details of transaction. Looks good so far, now someone requires format conversion on the "time of transaction" (between UTC and like), later on, people add rules to check if certain thing were on certain dates to validate invalidate transactions. - I wont write the whole story but eventually, the transaction class builds the entire calender with in it and then people start using "only the calender" part of it! This is very complex (to imagine) why will I instantiate "transaction class" to have functionality that a "calender" would provide me!

(In)consistency of API
When I do book_a_ticket() - I book a ticket! That's very simple irrespective of how many checks and processes it goes to make it happen. Now it becomes complex when time flow starts effecting this. Typically one would allow "search" and possible available/unavailable status, then to reduce back-n-forth you start saving some context pointers inside the ticket an then refer that to book the ticket. Search is not the only functionality- things become worse after many such "side functionality". In the process the meaning of book_a_ticket() implies book_that_ticket()! and that can be unimaginably complex.

Probably there are many such situations you would see in a very evolved code and I am sure that many people can add scenarios, where "so many methods" just doesn't make sense or doesn't do what you would obviously think. This is the anti-pattern.

My personal experience is that when projects that starts reasonably bottom up, many things for which there should have been genuine classes on their own -remains buried or worse still remains split between different classes and coupling increases. Most often what would have deserved 10 classes, but has only 4, it is likely that many of them have multi-purpose confusing and large number of methods. Call it a GOD and DRAGON, this is what is BAD.

BUT you do come across VERY LARGE classes which are neatly consistent, they do have 30 methods - and are still very CLEAN. They can be good.

The class in questions has 23 interfaces and these contains, all in all, 113 public properties and four methods. Only some of them are readonly. C# has auto-implemented properties, that's why I differ between methods and properties msdn.microsoft.com/en-us/library/bb384054.aspx
–
Jonas ElfströmNov 10 '11 at 13:07

Classes should have exactly the right number of interfaces; no more, no less.

Saying "too many" would be impossible without looking at whether or not all of those interfaces serve a useful purpose in that class. Declaring that an object implements an interface means that you have to implement its methods if you expect the class to compile. (I presume the class you're looking at does.) If everything in the interface is implemented and those implementations do something relative to the innards of the class, it would be hard to say that implementation shouldn't be there. The only case I can think of where an interface meeting those criteria wouldn't belong there is external: when nobody uses it.

Some languages allow interfaces to be "subclassed" using a mechanism like Java's extends keyword, and whoever wrote it may not have known that. It also might be that all 23 are sufficiently far-flung that aggregating them didn't make sense.

I figured this question was pretty language agnostic. The actual code is in C#.
–
Jonas ElfströmNov 3 '11 at 18:22

I haven't done any C#, but it appears to support a similar form of interface inheritance.
–
BlrflNov 3 '11 at 18:37

Yes, an interface can "inherit" other interfaces and so on.
–
Jonas ElfströmNov 3 '11 at 18:42

I find it interesting that many discussions focus on what classes should do, rather than what instances should do. A robot with a variety of imaging and audio sensors attached to a common chassis should be modeled as an entity that has a location and orientation, and that can see, and hear, and associate sights and sounds. All of the real logic behind those functions may be in other classes, but the robot itself should support methods like "see if any objects are ahead", "listen for any noises in the area", or "see if object ahead looks like it's generating the detected sounds."
–
supercatOct 11 '14 at 16:14

It may well be that a particular robot should be subdivide its functionality into subsystems a particular way, but to the extent practical code which uses the robot shouldn't have to know or care about how the functionality within a particular robot is subdivided. If the "eyes" and "ears" were exposed to the outside world as separate objects, but the corresponding sensors were on a shared extension arm, outside code might ask to "ears" to listen for sounds at ground level at the same time as it asked the "eyes" to look above an obstacle.
–
supercatOct 11 '14 at 16:20

Its sounds as thought they have a "getter"/"setter" pair for each property, as is normal for a typical "bean" and promoted all these methods to the interface. So how about calling it a "has bean". Or the more Rabelaisian "Flatulence" after the well known affects of too many beans.

The number of interfaces often grows when a generic object is used in different environments. In C# the variants of IComparable, IEqualityComparer and IComparer allow sorting in distinct setups, so you might end up implementing all of them, some of them maybe more than once since you can implement the generic strongly typed versions as well as the non-generic versions, additionally you can implement more than one of the generics.

Let's take an example scenario, let's say a webshop where you can buy credits with which you can buy something else (stock photo sites often use this scheme). You might have a class "Valuta" and a class "Credits" that inherit form the same base. Valuta has some nifty operator overloads and comparison routines that allow you to do calculations without worrying about the "Currency" property (adding pounds to dollars for example). Credits are allot simpler but have some other distinct behavior. Wanting to be able to compare these with each other, you could end up implementing IComparable as well as IComparable and the other variants of comparison interfaces on both (even though they use a common implementation whether it be in the base class or somewhere else).

When implementing serialization, ISerializable, IDeserializationCallback get implemented.
Then implementing undo-redo stacks: IClonable is added.
IsDirty functionality: IObservable, INotifyPropertyChanged.
Allowing users to edit the values using strings: IConvertable...
The list can go on and on...

In modern languages we see a different trend that helps separate these aspects and place them in their own classes, outside the core class. The outside class or aspect is then associated with the target class by using annotation (attributes). Often it is possible to make the outer aspect classes more or less generic.

The use of attributes (annotation) is subject to reflection. One drawback is minor (initial) performance loss. An (often emotional) drawback is that principles such as encapsulation need to be relaxed.

There are always other solutions, but for every nifty solution there is a tradeoff or a catch. For example, using an ORM solution might demand all properties to be declared virtual. Serialization solutions might demand default constructors on your classes. If you are utilizing dependency injection you might end up implementing 23 interfaces on a single class.

In my eyes, 23 interfaces does not have to be bad by definition. There might a well thought out scheme behind it, or some principle determination such as avoiding the use of reflection or extreme encapsulation beliefs.

Whenever switching a job, or having to build on an existing architecture. My advice is to first get fully acquainted, do not try to refactor everything too quickly. Listen to the original developer (if he's still there) and try to figure out the thoughts and ideas behind what you see. When asking questions, do so not for the sake of breaking it down, but to learn... Yes, everyone has their own golden hammers, but the more hammers you can collect the easier you will get along with fellow colleagues.

So long as your code behaves right and presents no maintainability issues, 23 could even be the new norm. Someday I could then say, "You can do an excellent piece of work with 23 interfaces, see: Jonas Elfström".

I would say that the limit should be a smaller number than 23 - more like 5 or 7,
however, this does not include any number of interfaces that those interfaces inherit or any number of interfaces implemented by base classes.

(So altogether, N + any number of inherited interfaces, where N <= 7.)

If your class implements too many interfaces, it is probably a god-class.