Friday, May 29, 2015

Why Java Code's 'Instanceof' and 'Reflection' have a "smell"

In my 16 years of writing code, I was privileged to work under some very talented developers.  These mentors were often some of the harshest critics of the code I was writing and I feel that they helped sculpt my code style over the years.  They all had different styles, some took me "under their wings", others took a more direct approach, still others were more like the Drill Sargent that is portrayed in the movies when the youth join the military and are shipped out to boot camp.

One of the staples of the lessons I learned over the years is to recognize what I refer to as "code smells".  Code smells are pieces of code that are either poorly written, don't solve the solution in an ideal manner, or fail on some level.  Usually, the code smell has to do with someone missing one of the basics of writing good code.

Most of my experience has been writing code in the Java language.  Java is a powerful object oriented programming language with a very diverse tool-set and ecosystem of third-party libraries.  One thing that Java doesn't do is protect you from yourself.  This means that just because the language supports something, doesn't mean you should be using it.

In my time writing code, there are 2 mistakes that I have seen over and over again.  These 2 smells often point to a larger problem within the code base itself.  They are the use of:

instanceof - In java the instanceof keyword can be used to test if an object of a specified type.  This seems harmless at first glance, but it is a code smell because it points to a bigger problem with the code you are writing.  Use of instanceof points to a failure of proper polymorphism, a pillar of object oriented programming.  Deficiencies within your object model are something that should be addressed as a top concern.  Ensuring that the logic you write meets the basics will lead to a better solution over the long term.  There is one exception to the rule.  The instanceof keyword is fine to use within an "equals" method.


reflection - in java the java.lang.reflect package is a series of utility classes that allow introspection on running code.  It is an extremely powerful concept, but generally should be avoided within production code.  I often see developers using reflection as a swiss army knife within the jvm.  Not only is this bad practice, but it has a significant code smell.  Reflection breaks several of the pillars of object oriented programming.  It overrides encapsulation and it can work around both inheritance and polymorphism.

There are many other code smells and perhaps we will be able to touch on some of them in the future.  Today we covered two of the most common coding mistakes I have seen in my career, the use of the instanceof keyword and leveraging the java.lang.reflect package of utilities in production code.

No comments:

Post a Comment