r/learnjava • • Dec 20 '21

When to use Abstract Classes vs Interfaces?

The two concepts are very similar, which is why I'm confused on why you should choose one over the other.

49 Upvotes

26 comments sorted by

51

u/Jezoreczek Dec 20 '21

My rule of thumb:

  1. Use composition.

  2. If you cannot use composition (e.g. need polymorphic behavior), use interfaces.

  3. If you cannot use interfaces, don't use abstract classes. Instead, refactor your code to make it compatible with interfaces.

Here's why: abstract classes are a mess and (almost) never necessary. Some problems when using them include:

  • Should I use super implementation before or after calling my own logic? (see Java's Swing for examples)

  • Which constructor do I need to call to get the behavior I need?

  • Are the protected members meant for me to use or for some other particular implementation?

  • Should I restrict the throws signature if I am handling exceptions from super implementation?

If you have any particular example of class hierarchy that confuses you, please post it here and I'll be happy to show you how to refactor it (:

6

u/MSUC123 Dec 20 '21

Sorry but this gonna be a noobie question, when you say composition you just mean inheritance right?

37

u/Jezoreczek Dec 20 '21 edited Dec 20 '21

Absolutely nothing to be sorry about, I've been in your shoes before and inheritance in Java left me just as confused!

Inheritance means IS-A relationship. When you write class A extends B or class A implements B, it means that instance of A is also an instance of B and can be used interchangeably:

package com.example;

interface B { }
class A implements B { }

interface InheritanceExample {

    static void main(final String... args) {
        final A a = new A();

        useB(a); // OK, we can use instance of A where instance of B is expected
    }

    static void useB(final B b) {
        b.doSomething();
    }

}

Composition means HAS-A relationship; is one class a member of another class? Example:

package com.example;

final class B {
    void doSomething() { /* some behavior */ }
}

final class A {

    private final B b; // B is composed by A

    A(final B b) {
        this.b = b;
    }

    void doSomething() {
        // add extra behavior here
        b.doSomething();
    }

}

interface CompositionExample {

    static void main(final String... args) {
        final B b = new B();
        final A a = new A(b);

        useB(a); // uh-oh, can't do! A is not B!
    }

    static void useB(final B b) {
        b.doSomething();
    }

}

Notice how both A and B are final classes. Yet we can still add behavior on top of them with what is called a decorator pattern.

Still, there is the issue that now you cannot use A in place of B. We've got a simple solution to this, however! If such behavior is needed, just add an interface C that both classes implement:

package com.example;

interface C {
    void doSomething(); // defines common behavior
}

final class B implements C {
    @Override
    public void doSomething() { /* some behavior */ }
}

final class A implements C {

    private final C delegate; // C is composed by A

    A(final C delegate) {
        this.delegate = delegate;
    }

    @Override
    public void doSomething() {
        // add extra behavior here
        delegate.doSomething();
    }

}

interface CompositionWithInterfaceExample {

    static void main(final String... args) {
        final B b = new B();

        useC(b); // OK, B IS-A C
        
        final A a = new A(b); // OK, B IS-A C

        useC(a); // OK, A IS-A C
    }

    static void useC(final C c) {
        c.doSomething();
    }

}

And voilà, no abstract classes needed!

Additional benefit: A is not highly coupled with B anymore, which means you can provide any other implementation of C and still get the desired extra behavior of A.

Real life example: I recently made a library that allows for plotting relationship between classes based on their ownership. The ClassOwnershipExtractor is an interface (C) that says "given some class, returns information about who owns this class". An implementation of this interface, AnnotationBasedClassOwnershipExtractor (B) checks if given class contains annotation that defines its' owner. However, for large projects I'd like this information to be cached, so I created another implementation, CachedClassOwnershipExtractor (A), which simply caches the results. With this setup, you can cache information from AnnotationBasedClassOwnershipExtractor as well as from any custom implementation (:

5

u/glorioushubris Dec 20 '21

This is an excellent and helpful reply. Thank you for writing it.

4

u/Jezoreczek Dec 20 '21

Happy to help anytime, good luck with your learning journey!

3

u/SsoulBlade Dec 20 '21

At what stage did you feel senior?

So many things I learned as a student and forgot most yhings 15 years later because I never had to use any of it.

Makes you feel junior even after 15 years.

I am going to relearn java or c# after many years of Delphi.

3

u/Jezoreczek Dec 20 '21

At what stage did you feel senior?

It's a very difficult question because there is no one thing that truly determines seniority. Guess it's a combination of skills and work ethics.

1 - I can build any application, in any language (except Haskell, am yet to master pure functional stuff) (and maybe Rust, that shit is as intense as it is beautiful)

With all the libraries, frameworks and hardware there is no end to learning programming. However, at one point you realize that if you wanted to and put enough effort, you can create anything. It might take a day, it might take a month, but you know it can be done - and that's a very freeing feeling.

2 - Have strong opinions but always consider opposite points of view.

I am always right, about everything, all the time. Wanna know how? Because if you prove me wrong, I will be happy to admit I was wrong and adjust my approach… and then I can be right again.

This one is really hard to pull off, and I am still personally having lots trouble with it but hey - trying to be better every day is what matters (;

3 - Get the fuck out of your comfort zone as often as possible.

That thing that looks scary and complex when you first get into it? It will get easier. Try it out and give it time, it will pay off.

4 - Consider the people on the other side of the screen.

One thing we tend to forget is that our work is maybe 20% code, 80% human interaction. Especially now with the virus going around, lockdowns and working from home. Take a 15 minute break, and invite a colleague for a coffee over whatever video chat app you are using. Be a person, get your weekly dose of small talk.

… so yeah, I think this sums it up. Not sure if it's helpful at all, but that's how I see it.

Makes you feel junior even after 15 years. I am going to relearn java or c# after many years of Delphi.

As a wise man once said, "sucking at something is the first step to becoming sorta good at something".

Also, it's never too late to start learning. I know a guy who worked as a diving instructor for many years, but today is a very successful front-end contractor. You'll get there my dude, just give it time. (;

2

u/SsoulBlade Dec 21 '21

Thanks for the wise words sir.

5

u/le_bravery Dec 20 '21

I 100% agree with this.

The only time I have ever seen deep class hierarchies actually work well was for actually modeling pure data during transport. Ex: all requests have the same base fields and all responses have these other base fields and they should always be treated exactly the same. When the contract is designed to be hierarchical with its data, then class hierarchies work well in all cases where behavior is involved they create such a mess.

2

u/Jezoreczek Dec 21 '21

The only time I have ever seen deep class hierarchies actually work well was for actually modeling pure data during transport.

Really? In my experience using inheritance in data classes leads to a whole lot of problems.

For example, we have a User class in my company that is extended by specific roles, like Administrator, Customer etc. Now all code that handles User has to essentially have a bunch of if (user instanceof …) cases. Also, it is not possible for a single User to have multiple roles, so we workaround this with email aliases.

Instead, I think it might be better to have AdministratorPrivileges class composed by User (and null if user is not an administrator), or better yet, this class having a user ID and fetching it separately from the DB.

Do you have an example of how you modeled your data? I'm really curious how it worked for you!

2

u/le_bravery Dec 21 '21

From memory, we had something like this:

There were like 10 request types the service could accept.

There was like a base request class which had a time stamp in it. The time stamp was checked to ensure the request wasn’t a replay.

Then there was a subclass to that which had a User Identifier in it.

Then there was a subclass which allowed interactions between exactly 2 users. This had an additional user ID.

There was a request to create a new user in our system which was related to another system using some user ID. This was basically just the one user request type, and the response was a basic success.

Then there was some request to query stuff about a user. This was the same request type with a basic user ID only. The response then had the requested data in it.

For interactions with multiple users, the request would extend from the multi user class.

Because these all extended, the time stamp verification logic was just in one place. And because all the requests used the same base class for user IDs, we could do a bunch of querying up front and cache the users account early.

The real reason for this design though was that we were basically required to implement an API that another company had designed previously. Our system at the time was being used to replace the other one because there were scalability issues with the other. So we implemented the same API and put it on top of our much better backend. The API was really designed with a lot of repeating elements like this which all needed the same validation and error handling. Because we were a drop in replacement we had to handle errors in the same way (I think I had to implement 1-3 bugs if I remember right!).

So, while it worked really well where we needed it, I’m not sure if this design would work any better for any other applications without our constraints.

3

u/lechnito Dec 20 '21

I agree with you in spirit and I also prefer using only composition & interfaces where possible as there are many ways to go wrong with abstract classes.

However, I would argue there are overlooked benefits to using a combination of both interface and abstract classes in a very limited way. Consider something like this:

public interface EntityProcessingService<T> {
   void process(T entity);    
}

public abstract AbstractEntityProcessingService<T> {
  private static logger = LoggerFactory.getLogger(AbstractEntityProcessingService.class);

  protected logProcessingSuccess(T entity) {
     logger.info("Successfully processed entity={}", entity);
  }

  protected logProcessingError(T entity, Throwable exception) {
     logger.error("Error processing entity={}", entity, exception);
  }
}

In this contrived example, every concrete implementation of EntityProcessingService can uniformly use the same logging strategies without any code duplication.

The same behavior could of course be accomplished in the interface using the static or default keywords, but then you have exposed the internal logging mechanics on the public interface which is undesirable.

Some rules I follow when I decide to write an abstract class:

  • Don't include a constructor

  • All methods should be private or protected

Would be interested in knowing if you agree with the above reasoning or if you still think composition is preferable with, for example, a package-private EntityProcessingServiceLogger class.

4

u/Jezoreczek Dec 20 '21 edited Dec 21 '21

This is a fantastic example! It looks convenient to use abstract class at first, but consider the following cases:

  1. Say we have a bunch of pre-existing EntityProcessingService implementations and we want to add logging to them only now. First, you'd need to modify each implementation to extend AbstractEntityProcessingService (open/closed violation). After that, you'd need to duplicate the logging code.

  2. Say we have another abstract class EntityProcessingServiceWithRetry that adds a retry functionality. Should it extend AbstractEntityProcessingService? If it doesn't, then no implementation can have both a retry and logging functionality at the same time. If it does, then we violate single responsibility.

  3. Say we used this abstract class in a few implementations already. What if we want to add a new log? Say if last 10 entities failed to process, we want to write additional log saying the service is unstable. To do that, we will now need to add this new log in each implementation! (another violation of open/closed)

What do you think about this alternative?

public class LoggingEntityProcessingService<T> implements EntityProcessingService<T> {

    private static final Logger LOGGER = LoggerFactory.getLogger(LoggingEntityProcessingService.class);

    private final EntityProcessingService<T> delegate;

    LoggingEntityProcessingService(final EntityProcessingService<T> delegate) {
        this.delegate = delegate;
    }

    @Override
    public final void process(final T entity) {
        try {
            delegate.process(entity);
            LOGGER.info("Successfully processed entity={}", entity);
        } catch (final Exception exception) {
            LOGGER.error("Error processing entity={}", entity, exception);
        }
    }

}

Now all the above issues are easily mitigated:

  1. Wrap each implementation in LoggingEntityProcessingService.

  2. Wrap implementation in EntityProcessingServiceWithRetry, and then wrap the result in LoggingEntityProcessingService… or the other way around! Perhaps we only want to log exceptions if processing failed after X retries, perhaps we want to log exceptions after each retry. Now we have a choice (;

  3. Add a new field private final AtomicLong failedProcessingCount = new AtomicLong(0); in LoggingEntityProcessingService. Then add the following in the catch and all implementations will benefit from the new behavior:

.

final long failuresCount = failedProcessingCount.incrementAndGet();
if (failuresCount >= 10) {
    LOGGER.error("{} failed to process {} entities!", delegate.getClass().getSimpleName(), failuresCount);
}

Some rules I follow when I decide to write an abstract class

These are certainly very good rules to keep in mind if you really must create an abstract class!

a package-private EntityProcessingServiceLogger class

It really depends on what you're trying to achieve. If it's common behavior you're after, decorators are IMO the way to go. If you want to allow more flexibility, a sort-of utility class could be desirable. For example, the aforementioned EntityProcessingServiceWithRetry could use an utility class RetryAction, which could be a generalized implementation:

final class RetryAction<Output> {

    Output executeWithRetries(final Supplier<Output> action, final int retriesLimit) throws Exception {
        Exception lastException = null;
        for (int retriedTimes = 0; retriedTimes < retriesLimit; ++retriedTimes) {
            try {
                return action.get();
            } catch (final Exception exception) {
                lastException = exception;
            }
        }
        throw lastException;
    }

}

Now EntityProcessingServiceWithRetry can use RetryAction, but other classes can use it, too!

1

u/lechnito Dec 21 '21

Thanks for taking the time to write back and provide a thoughtful examples! You've definitely given me some things to think about regarding abstract classes.

The alternative class you shared is essentially identical to the concrete class I had in mind:

public class FooEntityProcessorService<Foo> extends AbstractEntityProcessorService<Foo> implements EntityProcessorService<Foo> {

   @Override
   public void process(Foo entity) {
      try {
         doProcess(entity);
         logProcessingSuccess(entity); 
      } catch(Exception e) {
         logProcessingError(entity, e);
      }
   }

   private void doProcess(Foo entity) {
      // ...
   }
}

So to phrase it differently, would you say that the concrete class here violates open/closed because it may need to change whenever the abstract class changes?

2

u/Jezoreczek Dec 21 '21

The alternative class you shared is essentially identical to the concrete class I had in mind

Notice the doProcess method - it's a very common pattern with this type of design. Don't think there's anything inherently wrong with it, but it often indicates that the class now has more than one responsibility.

would you say that the concrete class here violates open/closed because it may need to change whenever the abstract class changes?

I would say the abstract class violates it, as it wasn't designed for extensibility.

Sometimes violating these principles is desirable, e.g. you may want to have a strict contract that is not meant to be extended, and that's fine. It all depends on what we're trying to achieve.

2

u/[deleted] Dec 20 '21

seems, this answer is almost as general as possible.
for expert level -> we need to be more problem specific.

4

u/sweetno Dec 20 '21

You'll have to use abstract classes if there are instance variables.

Multiple inheritance is only possible via interfaces.

1

u/[deleted] Dec 20 '21 edited Dec 20 '21

Interfaces can be used like instance variables, it just implies an anonymous implementation of the interface (just as instantiating an abstract class instantiates a concrete anonymous subtype).

Example:

interface Animal {
    void talk();
}
public static void main(String[] args) {
    HashMap<String, Animal> animals = new HashMap<>();
    animals.put("Duck", new Animal() {
        @Override
        public void talk() {
            System.out.println("Quack");
        }
    });
    animals.get("Duck").talk();
}

This creates an anonymous (i.e. unnamed) concrete class which implements Animal, like you would do by saying class Duck implements Animal. Since it's an interface with a single method (which is implicitly abstract), you can also simplify with a lambda, like

animals.put("Duck", () -> System.out.println("Quack"));
animals.get("Duck").talk();  // Quack

edit: Not sure why it's downvoted, maybe I should put 'instantiated' in quotes or something, but I thought it was clear that what actually gets instantiated is an anonymous concrete class which implements the interface.

1

u/Jezoreczek Dec 21 '21

I believe they meant the fields of the abstract class when they said "instance variables" (;

1

u/[deleted] Dec 21 '21

Ah. Yes, any fields of an interface would be static and final.

1

u/dhawal0008 Dec 20 '21

Suppose you are writing a code for RBI and RBI share this code with other banks. Now the generic methods in this class would be - Add User, Deposit, Withdraw, Inquiry. All these will be abstract methods.

Now suppose SBI also use this code and they have come up with a wallet scheme. Now since this wallet scheme is exclusive to SBI, they will write a interface which will be used by them only.

Similarly other banks, with their own added features can create interfaces.

Common functionalities among various classes - Abstract class/methods Feature exclusive to certain classes - Interface

1

u/[deleted] Dec 20 '21

One use case for an abstract class rather than interface would be if you didn't want it to have only abstract methods. An abstract class can have abstract or concrete methods, whereas interface methods are all implicitly abstract.

1

u/Jezoreczek Dec 21 '21

interface methods are all implicitly abstract

What about default methods?

1

u/[deleted] Dec 21 '21 edited Dec 21 '21

Good point. Default methods don't work the same way as regular 'concrete' methods though, because you wouldn't define those in the implementation class, they would already be defined with an implementation in the interface. [Though I guess the abstract class could have non-abstract method which would have an implementation in the class. Still, there are differences, like that the interface could be a functional interface, so maybe there should be different use cases for one or the other along those lines.]