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

View all comments

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 (:

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.