Java: Write code that’s more readable, scalable and maintainable

Avoid unnecessary if-else using the Visitor Design Pattern

Anurag Sidana
Javarevisited

--

Quite Confusing, No ????
Photo by Nick Fewings on Unsplash

Redundant and avoidable conditional statements are a Code Smell.
These allow us to selectively execute code based on conditional logic. Overusing conditionals results in code that is hard to understand and difficult to modify.

In some cases, we can avoid these and can make code more modular.

Sometimes we can’t avoid having multiple if-else/switch statements in our code as our code flow required it be there to handle various scenarios based on different conditions.

One common type of problem is when we are dealing with a scenario in which a single object can be of multiple types and these multiple types trigger different flows based on their types at multiple points in our code base.
Now those different flows might be business logic, some utility functions, or anything be it a code block.
Multiple types signify multiple child classes of a parent class.

Common Examples:

  • A bus can be of multiple types: NON_AC_SITTER/AC_SITTER/NON_AC_NON_AC_SLEEPER, all being subclasses of BUS class.
  • An Item superclass…

--

--

Anurag Sidana
Javarevisited

Specialized expertise in agile and structured test-driven software development using Java. Living a life based out of open-closed principal. ;-)