skull

Robert Tamayo

R
B
code
skull

Separating Implementation from Interface

Years ago I had to do a C++ project for school. It was my first time working with C++, but I was experienced with Java at the time. What confused me about C++ was that there were two kinds of files, .h files and .cpp files. I couldn't understand why I had to make .h files to define functions and then write their implementation elsewhere. Furthermore, the "magic" of how everything linked up left me bewildered.

Then it finally dawned on me: this is the exact same that happens all the time in Java. Perhaps I wasn't confused by the same practice in Java as it is my "native" language, and also all of the files were .java files. In Java, it's common to use interfaces to define function signatures and then have a class implement that interface. The strength of interfaces in Java is that they can be used by different classes, and for the project I was working on in C++, there were no other implementations of the .h, or header, files.

I find it odd that Java classes often have an interface that they implement even if there is only one implementation and no plans to ever create a separate implementation. In fact, most Java classes seem to be named things like "CircleMathImpl" or "CircleMathDefaultImpl". I realize now that this is the same principle in action with C++'s .h and .cpp files. The only real difference is the "magic" part and the different file extensions.

The "magic" part seems to have been adopted by Java in the form of the Spring Framework, where an implementation is chosen when only the interface is specified.

This is a small realization, but it helped me connect more dots and appreciate C++ a bit more for having some "best practice" principles so firmly built into its ecosystem.
Comments:
Leave a Comment
Submit