How Good Design Implementation Prevents Errors
Over this semester I’m taking Object Oriented Programming and Design and till now, I’ve learned a lot. I now have a better viewpoint of what good code is supposed to look like, what it consists of, and how to write it. To do this, I turn to implement the concepts I learned in class.
One thing I thought was very interesting was the concept of annotations. Now great design doesn’t just restrict itself to having compatible, abstract, non-complex, and “less-taxing” code, but it also means documenting your work succinctly so every aspect of your code is clear. You want to be able to come back and work on your code, but at that point in time, you also need to make sure you still understand what your program does, and how your code works. The way the different components of your program interact with each other is important and has a reason. Documentation can also include a plethora of things like making UML diagrams, comments, tags, annotations, sample code and so on.
However, annotations are pretty interesting. There are many types of annotations but @override which is a “marker” annotation is cool. It’s a small aspect but it can help you miss some pretty hard to see unchecked errors.
Let’s say you want to override the toString() method.
class ride{
//some random class
@Override
public String toString(){
return (“overriden toString in class ride.”);
}
}
This is what the very rudimentary code would look like. However, let’s say you have a typo which says “tostring()”. Now this isn’t wrong at all. If we’re not overriding, then it’s just another new method. However, when you make a reference to the class and call toString(), you’ll actually still be calling the superclass method offered by the Object class and not the overriden one, because it just doesn’t exist. This is not what you wanted to do.
With @Override, the compiler will understand that you wish to “override” the method. So, it will look for the same method in the super class and if it doesn’t find it, it’ll give you an error. This saves you from unchecked errors that can very easily get past you.
The error says - The method <method_name()> of type <Type>, must override or implement a super type method.
Now it is understandable that due to the scale of this example it can be easy to think, oh well what’s the big deal, I can just figure out which method gets called by looking at the output, and for this example that is possible. However, thinking large scale with many classes, interfaces, extensions, implementations etc. things can get very very fuzzy, if you’re expecting one process to happen when in reality something much different is going on. Moreover, for no overhead expense, we get this great functionality which helps us avoid errors!