šŸ² OOP soup - you donā€™t need so much code!

Gabriel McCallin
2 min readMay 24, 2020

--

Photo by Steve Tsang on Unsplash

Recently I read an article about how to ā€œget rid of if / else statements with OOPā€.

Oh, I thought, probably thereā€™s a map / associative array to match an input to an output instead of a switch or nested ifs. Cool! Letā€™s check it out. Wonder what the OOP bit isā€¦

Of course, our old friend polymorphism. Turns out the advice was to write a big if / else and return a different class for each condition. The classes extend the same parent so can be consumed by the caller with the magic of polymorphism. (I did it in bold again so you canā€™t miss it).

That didnā€™t get rid of any if / else statementsā€¦ But what really surprised me was the code to support all of the classes and subclasses. So much! Extending and overriding and constructors and public and private and, oh god.

Of course, I couldnā€™t resist rewriting the code more simply; one function and one map (and a couple of enums šŸ˜€).

The original example was written to display different colours for courses sold in an online store. There was also an added layer to display different colours depending on a price threshold.

The problem can be solved simply by considering how the data needs to be manipulated; why try and model the world with classes and how they relate to each other? Why write all that code!? šŸ²

Tests

Example

Demonstrating getColourMap: https://bitbucket.org/gabrielmccallin/course-oop-attack

--

--

Gabriel McCallin
Gabriel McCallin

No responses yet