2

I'm new in Java and I would like to know what solution is more correct and why.

I have these two interfaces:

interface Account
{
    public double getBalance();
}

interface Taxable
{
    public double calculateTaxes();
}

And I need a class that implements these two interfaces.

For me, is more intuitive this solution:

class TaxableAccount implements Account, Taxable
{
    @Override
    public double calculateTaxes()
    {
        return 10;  //just for example
    }

    @Override
    public double getBalance()
    {
        return 20;
    }

}

But I read a book that has this solution:

interface TaxableAccount extends Account, Taxable
{
}

class AccountWithTaxes implements TaxableAccount
{
    @Override
    public double calculateTaxes()
    {
        return 10;
    }

    @Override
    public double getBalance()
    {
        return 20;
    }
}

Thanks.

2
  • 1
    I do not see any reason to create a third interface here. People often make a class implement more than one interface, without making a new interface extending all the others. Commented Oct 25, 2015 at 1:45
  • 2
    Side comment: NEVER use floating point for money. Float/Double cannot accurately represent most of the numbers you will encounter, and you will end up with rounding errors in your results. Use BigDecimal or scaled long (i.e. cents stored in long variables) instead. Commented Oct 25, 2015 at 2:15

1 Answer 1

3

The TaxableAccount interface would be pointless unless you intend to add something to it -- say at least one extra method. An empty interface is a 'code smell' and should be removed, leaving you with the perfectly fine first example.

Another clue that this is a 'smell' is that you've had trouble coming up with a good, simple name for the class in the second example - mostly, naming should be obvious and self-evident, as it is in the first example.

Sign up to request clarification or add additional context in comments.

4 Comments

+1 but "naming should be obvious and self-evident" -- Oh that it were so simple :-) According to Martin Fowler, the two hardest things about Software Development are cache coherency, naming things and off-by-one errors.
That's three things, and Rabbi Fowler is often wrong. The hardest thing in software development is getting paid what you're worth, the second hardest is not not killing the author of every library you use ;)
erm... the quote is self-referential (off-by-one errors...)
It's 3am for me -- forgive my dumbness -- it was a very good joke :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.