Controller and Polymorphism

The Controller principle is the idea that the UI (User Interface) classes should be separate & apart from the non-UI classes. The separation assists the code writing team with debugging & helps make the codebase more organized. More importantly, the separation is essential as the UI should not have direct access to the rest of the program in order to prevent any possible damage from UI infiltration within the written code.

Controller example:

Grand gave a great example in his book when he said, “Suppose you are designing a security system. The security system is attached to numerous devices that sense the opening of doors and windows, motion within a building, and other events. You don’t want the external devices or the objects responsible for receiving the raw input from the devices to send any events directly to the objects within the security system that will handle the events”.

The benefits of implementing the Controller principle are numerous. First off, it allows the program to error checks the input. Secondly, it appropriately relays the input to the correct destination. The third benefit that the Controller principle provides to the written code is that it adds a layer of abstraction to the code that makes it more flexible when it comes to making changes in the future; whether it’s a change to the destination or the how the input is handled.

Polymorphism principle:

Polymorphism is a layer of abstraction that provides assistance when you have classes that contain very similar methods/attributes in several classes. It allows you to write the common methods/attributes i. A single place but have different implementations in the classes that differ.


Polymorphism example:

Let’s say you are creating a program to keep track of all the different animals that exist in the world for scientific simulations. It’s easier if you create an abstract class that contains all the similarities between several classes. In the example below, I placed the attributes that both a bee and a cat have in common in the animal abstract class. Since cats and bees both make different sounds, they will have to implement their own methods for producing sound.

abstract animal UML diagram

The benefit of using the polymorphism principle is that it helps reduce the chore of rewriting code several times when you can simply do it once.  This is because the classes that extend (use), the abstract class, inherit all the attributes/methods that are in common while allowing the differences to have their own implementation. Another benefit of the Polymorphism principle is that it helps make you have a more organized codebase.

Footnote:
I made the abstract animal UML diagram
Grand, Mark. Patterns in Java. 2nd ed. 2 vols. Hoboken, NJ: Wiley, 1999.

Leave a comment