Jump to content
  • Advertisement
Sign in to follow this  

Overusing interfaces?

This topic is 2133 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts


I have interfaces for virtually ( :D ) all classes I use; for example IThread.h, IMutex.h, IConditionVariable.h, IThreadPool.h, ISynchronizationFactory.h, etc.. and then .h/.cpp "-impl" versions of them. I use factory classes to create/destroy the implementations and then just pass around and work through the interfaces.


  • I do it because I find it clean/pleasant to work with, but quite some code I see do not use it. My question is why? Is it just a matter of taste? I know virtual methods adds an additional overhead, but besides that?
  • In my factory classes I do not generally need dynamic class instantiation; for example I just have one "ThreadImpl" for win32/android, so I really could just have it return the ThreadImpl", but I prefer to work through an interface. Is it just a matter of preference or any practical reasons to chose one over the other?


Share this post

Link to post
Share on other sites

I have interfaces for virtually ( biggrin.png ) all classes I use;

Nice! In my experience, interfaces are a way to avoid tight coupling of classes, so you can change the
implementation, add new implementations, and reuse classes without recompiling. However, it is a matter
of taste if you have a written an internal class that no one else will ever see or use, then it depends how you
use it.

I have always tried to follow Kent Beck's idea that only writing the code you need today makes
it easier to re-factor and change the code tomorrow. So I say, use all the interfaces you want to
keep your code clean and your interfaces loose, but don't add the interface until you actually need it. Edited by Glass_Knife

Share this post

Link to post
Share on other sites
Using an abstract base class is one way to implement the idea of "public interfaces with hidden implementations" (a form of information hiding).

The underlying principle isn't really about using one particular implementation of a public interface/hidden implementation, it's about the fact that information hiding / encapsulation are good things, and you should try to reduce dependencies within the physical structure of your code-base.

Yes, hiding the implementations of your classes is a good idea -- it keeps the public header file (which forms the interface) very clean, which makes your code-base compile faster and also makes it less confusing for the user.
However, I personally avoid using abstract-base-classes (classes with virtual methods) to implement this, because I personally like to avoid using virtual/polymorphism except where it's really required. That's just a stylistic choice.
e.g. I posted in your previous thread with an implementation of implementation-hiding that I commonly use.

At one of my previous jobs, we wrote everything in C++, but all of the engine's public interfaces were written in C, so our public headers looked like:
typedef struct {} IMutex;
IMutex* CreateMutex();
void ReleaseMutex(IMutex*);
void LockMutex(IMutex*);
and the private implementation could be anything, e.g.class Mutex { void Lock() {...} };
extern "C" IMutex* CreateMutex() { return (IMutex*)new Mutex; }
extern "C" void ReleaseMutex(IMutex* m) { delete (Mutex*)m; }
extern "C" void LockMutex(IMutex* m) { ((Mutex*)m)->Lock(); }
^^This is still "an interface", even though it's not done in the "typical" C++ style of an ABC.

In C++, it's also quite common to see the PIMPL idiom used instead of ABC's for this purpose.
I know virtual methods adds an additional overhead
The actual overhead differs greatly depending on the situation. In some situations, it's basically zero overhead (e.g. a non-frequently used class, like a Mutex, compiled on x86), in other situations, the overheads are so high that it's practically unusable (e.g. a frequently used class, like float4, compiled for a NUMA SPU).

[edit]As another example of how many different ways there are to implement "interfaces", here's another interesting method:
// N.B. implementor doesn't know about the interface or the user, it's completely decoupled!
class Implementor
int z;
Implementor(int z) : z(z) {}
void OnEvent(int x, int y)
printf( "%d, %d, %d\n", x, y, z );

// This is basically a decoupled vtable that lets us make the above act as if it used virtual functions / inherited an ABC
struct Interface
typedef void (FnOnEvent)(void*, int x, int y);

void* userData;
FnOnEvent* onEvent;

template<class T> static void s_OnEvent(void* o, int x, int y) { ((T*)o)->OnEvent(x, y); }
template<class T> static Interface Bind(T& o)
Interface value =
return value;

// this does something using the above interface, so we can plug the first concrete class into it
class UserOfInterface
Interface i;
UserOfInterface( Interface i ) : i(i) {}

void Event() { i.onEvent(i.userData, 1, 2); }

//like this:
Implementor widget(3);
UserOfInterface user( Interface::Bind(widget) );
user.Event(); //prints 1, 2, 3
Edited by Hodgman

Share this post

Link to post
Share on other sites

[quote name='KaiserJohan' timestamp='1347625645' post='4980028']
My question is why?

Because having an interface with only one implementer means you're writing the code twice for no reason. No, "I might need a second implementation some day!" is not a sufficient answer. YAGNI.[/quote]

I agree with this. If you need a second implementation "some day," you can create the interface on that day.

Because if you allow people to make an implementation of something, they will. Some parts of the design are vital and/or fragile enough that you don't want people changing the behavior (perhaps incorrectly) and introducing widespread subtle bugs.[/quote]

This can happen even if you're supposed to implement an interface: http://blogs.msdn.com/b/oldnewthing/archive/2004/03/26/96777.aspx

Share this post

Link to post
Share on other sites
You want an interface when you will have more than one implementation to choose between at run-time.
Your thread implementation changes at compile-time.

You just need a common header with multiple implementations:
src/osx/mutex.c Edited by Shannon Barber

Share this post

Link to post
Share on other sites
Dynamic allocation of everything has performance consequences on top of that of virtual function overhead. First off, dynamic memory allocation itself is fairly expensive in the general case compared to allocating an object by value. Unless you override the behavior, this will generally involve synchronization so that memory can be safely allocated in multiple threads in the same time, and a search through a list of free memory blocks for available memory. This means that as you allocate and deallocate memory blocks this can get slower and slower. Even when you do override the behavior, it's almost never as cheap as allocating by value which generally just involves increasing the size of an existing allocation.

Secondly, it requires more memory than just allocating by value. First off, you have the additional memory required for the pointer to the object. Then you have book keeping overhead for dynamic allocations and potential internal fragmentation. Finally, if you have an interface with only a single implementation then you've got vptr overhead in each and every object. On top of that you've got potential external fragmentation. In addition to the raw extra memory you're using you also have worse cache performance due to decreased spatial locality. Given that memory is the single greatest performance bottleneck on modern machines, this can really hurt performance.

As an example, on MSVC 2010, 32-bit, Release without the debugger attached on Win 7, a CRITICAL_SECTION by itself is 24 bytes. Put a CRITICAL_SECTION in a class with virtual functions and it takes 28 bytes. Heap allocate that sucker and it takes up a minimum of 40 bytes between book keeping information and internal fragmentation. Then add the pointer you need to keep track of it and you've got 44 bytes, not quite double. Not that big of a deal for a CRITICAL_SECTION since you aren't likely to make many of them, but if you're doing it with everything, like you say you are, then it's going to add up.

Also, the use of interfaces rather than concrete types can inhibit inlining, not just in code using the interface, but in code implementing the interface if you aren't careful. If you have RTTI, exceptions or debugging symbols enabled, then you'll also be adding additional static information to the executable by using additional classes.

A particularly unfun part of this is that many of these performance effects are non-local. In other words, bad decisions in one section of code can affect the performance of unrelated parts of code. For example, if you swiss cheese your memory in one section of code, later code may have things like extra cache misses. You can reduce some of these effects by using pooled allocators, arenas, etc. but preventing problems in the first place is generally more effective than trying to fix side effects later.

Share this post

Link to post
Share on other sites
I don't know how else to put it, but this is serious code smell. It is over-engineering taken dangerously close to the extreme. In my experience, every time I've ignored YGANI, I've been sorry about it. Even if it weren't C++, but a managed environment where memory allocation is done properly (and therefore faster than in C++ unless you do it on your own), it would still be a very bad decision.

If an interface has one and only one implementation, and the reason for its existence is that it is prettier to have its name begin with "I", then you have made a bad design decision. If the code base is small and maintained only by you, it doesn't matter, but if you work on a bigger project with other people, you will be stuck with your decisions for quite a long time. Having to code more for no other reason that aesthetics is pointless waste of time.

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!