Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating subclasses to handle "base-cases"

Tags:

java

class

Every now and then I see code where the programmer has extended a certain class to handle "base cases". For example, if I were creating a Tuple class to represent a tuple of integers, I would have something like

class Tuple {
    private int[] values;

    ...
}

But some people will extend Tuple to accommodate a few base-cases, such as a tuple of length 0, 1 or 2:

class Tuple0 extends Tuple {
    ...
}

class Tuple1 extends Tuple {
    private int value1;

    ...
}

class Tuple2 extends Tuple {
    private int value1;
    private int value2;

    ...
}

Of course, the methods (denoted by ...) of each TupleN class will be much simpler than those of the generic Tuple class. So, my question is: is there any benefit to this type of practice? If so, when and why; if not, why not?

like image 396
arshajii Avatar asked Jun 18 '26 09:06

arshajii


1 Answers

The big drawback of this approach is that it leads to increased code size and less maintainable code. A potential advantage is possibly increased performance, but you really need to profile to make sure.

Personally, I wouldn't do this.

like image 181
Antimony Avatar answered Jun 20 '26 23:06

Antimony



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!