YAGNI by NotImplementedException

Using the NotImplemented pattern to ensure you only write the code you need.

thomas michael wallace
tomincode
2 min readMar 29, 2019

--

Yesterday I implemented a new feature. These days there’s a pretty good argument for immediately considering any code you write to be technical debt (especially if it’s in a Javascript framework- amirite!). And so I wanted to make sure I only wrote the code I absolutely needed.

“You ain’t gonna need it” is definitely the coder’s mantra at the fore of my head these days.

Of course, the easiest way to not write something is to, well, never write it at all. This is easy to achieve when you simply don’t implement the “button-that-generates-cats” for your UI framework. However the principle becomes more of a challenge when you’re deeper in the stack.

In my case I was putting in a piece middleware. By definition this could be exposed to every type of request/response our application makes. However, as the developer, I know what it is most likely to need to support. And while I could cater to every case- “you ain’t going to need it”.

In this situation, simply not writing the code is a recipe for disaster. At worse, requests people were expecting to be transformed will silently remain the same, and some poor developer will have to delve into my code to find out why.

When you decide you are never going to need it. It is good to be explicit about your decision. Which is where the NotImplementedException is your friend.

In this pattern, you assert whether your feature is being used in the way it was implemented for. If the requested behaviour is something you don’t think you’ll need, then you throw a NotImpelmentedException (or NotImplementedError, depending on your language naming convention).

For example, if I do not support PATCH requests in my middleware. I should test for the PATCH method and throw. It’s a small assertion. But more than that it ’s a very public declaration of my assumptions. Now when future me attempts to make the first PATCH request in our application I’ll immediately get a NotImplementedException pointing me to the place(s) where I’ll need to do some more work/testing.

The lesson: If you think you ain’t gonna need it, use a NotImplementedException so the next developer will think that too.

--

--