Existing issues with type testing

As a Java developer, you should have worked with code such as the one highlighted in bold in the following block:

Object obj = new Ocean();                         // variable type - Object 
if (obj instanceof Ocean) { // check instance type System.out.println(((Ocean)obj).getBottles()); // cast & extract value } // A basic class - Ocean class Ocean { private long bottles; public long getBottles() { return bottles; } }

The preceding code includes three steps to use the value of the bottles variable:

  1. obj instanceof Ocean: Testing of the type of the obj variable 
  2. (Ocean)obj: Casting of the reference variable, obj, to Ocean
  3. ((Ocean)obj).getBottles(): Destruction of the instance to get a value

As developers, we have been writing similar code for a long time, but have also been hating it secretly. It is like repeating the same instructions again and again. These steps to test, cast, and deconstruct an instance to extract a value are unnecessarily verbose. We all know that code repetition is one of the best ways for errors to go unnoticed. To add to this, it only gets bigger with multiple instances of code repetition in one place. Take the following code sample as an example:

void dyingFish(Object obj) { 
    if (obj instanceof Ocean) {                          // test 
        System.out.println(((Ocean)obj).getBottles());   // cast & 
// destruct } else if (obj instanceof Sea) { // test System.out.println(((Sea)obj).getDeadFish()); } else if (obj instanceof River) { // test if ( ((Ocean)obj).getPlasticBags() > 100) { // cast &
// destruct System.out.println("Say no to plastic bags. Fish are dying!"); } } } class Ocean { .. } class Sea { .. } class River { .. }

As you add more occurrences of the testing-casting-instance destruction pattern to retrieve the field values, you lose the business logic in the complexity that is induced by the language. It is very common for developers to literally copy and paste such code and modify the pieces that aren't the sameā€”but it is also common for some code parts to be left unchanged (which either become logic errors or should be labeled as copy and paste errors).

This code is also less optimizable; it will have O(n) time complexity, even though the underlying problem is often O(1).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.179.35