Interface-InterfaceImpl Anti-Pattern

Interface-InterfaceImpl Anti-Pattern

You don't need to do the Interface - InterfaceImpl anti-pattern. There's a misunderstanding of two design principles:

"Program to an interface, not an implementation." - Gang of Four

and

Interface Segregation Principle: "no code should be forced to depend on methods it does not use" - Robert Martin

Let's remember the context: These people were coding in C and C++. In those languages, header files (interfaces) helped decouple the compilation of components. If one component did an #include of another component directly, then compiling one would require the compilation of the other, as well as any dependencies they directly #included as well. It was common to hear of compile times reaching an hour or more.

Programming to header files (interfaces) meant that only the components that changed needed to be recompiled. Splitting up large header files into smaller ones meant that fewer components would be dependent on each header file, leading to fewer compilations if a header file changed.

This was the origin of Robert Martin's Interface Segregation Principle: He was called into Xerox to figure out how to shorten the compile time of a printer driver, which was taking an hour. He split the header file of a commonly-used component into multiple header files, such that the client components only had the functions or methods that they needed, and therefore didn't need to recompile if a new function was introduced that they didn't need.

Of course, we don't have this problem in dynamically-linked languages like most modern languages today. Only code that changes needs to be recompiled, with or without the use of interfaces.

What about Spring @Transactional, you say? I've tried it on a concrete class with no issues. Just note that @Transactional will only work on public methods.

So when do we use Interfaces? Interfaces are for polymorphism. Java and C# enforce single-inheritance, but often we want to be able substitute components in more than one way. Interfaces allows a class to have more than one type for polymorphic purposes. If an interface only has one implementation, you don't need an interface!

So we can stop using Interface - InterfaceImpl anti-pattern now. It serves no purpose in dynamically-linked languages. It only gives you more code to maintain, and it makes code hard to trace without a good IDE.

Alistair Israel

Staff Engineer at Antimatter

2 年

It makes testing/mocking a lot easier in most cases, though. So, if you consider InterfaceImpl and TestInterfaceImpl as valid polymorphism, then it’s acceptable.

回复

要查看或添加评论,请登录

Calen Martin Legaspi的更多文章

社区洞察

其他会员也浏览了