Posts

Showing posts with the label Java

Why is composition harder than inheritance?

(just some random thoughts...) Let's take this Java example: class Base { public void method() {} } class Derived extends Base {} See how easy it is for Derived to "reuse" code from Base ? Derived is a subclass of Base , and in its constructor it calls Base 's constructor, constructing a Base before constructing a Derived : class Derived extends Base { // this is what gets generated by the compiler: public Derived() { super(); } // this doesn't exist, but illustrates what happens when we call Derived.method: public void method() { super.method(); } } Also, Derived instances have a "forwarding" method, that, when called, will delegate to the corresponding base method (this is not technically what happens, but I'm looking at the "concept" here). Isn't that convenient? Why isn't the same capability available to compose classes? Composition is always a better strategy than inheritance in "reuse" ...

Java: BigDecimal's Big Problems

In Java, the BigDecimal class has a failed abstraction around equality comparisons that will inevitably lead to bugs. There are 2 problems: 1. the method compareTo is inconsistent with the method equals Equality (equals) of two BigDecimals takes scales (number of decimal places) into account, whereas comparison (compareTo) doesn't. So, new BigDecimal("1.00").equals(new BigDecimal("1.0")) returns false, and new BigDecimal("1.00").compareTo(new BigDecimal("1.0")) returns 0 (zero), indicating that they're equal. I've seen some threads stating that equals is consistent with the way that an engineering (or scientific) quantity should work, where scale is very important. Since operations with numbers with different scales yield different results, it seems reasonable that equals returns false for these numbers. So, from this standpoint, the equals implementation is right, and compareTo should be consistent and retu...