Archive for the ‘Design Patterns’ Category

JavaScript Interfaces

In my personal quest for the “History of Javascript“, one of the first things I wanted to analyze was code maintainability. I tend to favor code maintainability and testability when making architectural decisions in any language. Naturally this lead me to wanting to see if there were any design patterns or anti-patterns in JavaScript. My first choice was  Pro JavaScript Design Patterns: The Essentials of Object-Oriented JavaScript Programming. I must admit when I was browsing through the book I was very skeptical of it when I saw a section on Interfaces in JavaScript. I know that it can be very risky trying to implement non-native functionality into one language from another. It’s even worse when you try to shoe-horn a pattern into a different language where it’s clearly not needed. I also strongly believe that languages evolve to help eliminate the need for developers to implement design patterns and that the languages themselves can have the patterns built in.

My favorite languages are both strongly typed and dynamic so it was a little hard for me to fully let go of types when jumping into JavaScript. When picking out this book, my main mission was “How can you create a large scale JavaScript application while still having it be very maintainable”? Any language can get unwieldly and design patterns aren’t a silver bullet, but I was curious to see enterprise methodologies applied on a free-spirited, hipster language. 😉

After reading it, it’s easy to see their perspective on when it’s necessary and that their implementation was very simple. We simply need to check if an object contains the specific methods defined in an interface. It uses duck typing to determine if the method exists, it doesn’t care about the parameters but just so you don’t get undefined is not a function. We obviously don’t want this everywhere but I find it works in a few scenarios. First, if we need to group classes. Second, if we must implement some design pattern that requires an interface. Third, if we have to invoke methods on a dependency injected object that we want to throw errors if a method does not exist and give other developers working on the same code feedback.

If you’re curious, buy the book or check out my example on GitHub.