-1

At my org we extensively use @Value.Immutable annotation from the Immutables library to generate Immutable classes (usually with builders) for our internal business objects (BOs). In our codebase I've seen both interfaces and abstract classes being used for such BO definitions.

For example for a DeviceData BO we could have an interface as follows

@Value.Immutable
@JsonDeserialize(as = ImmutableDeviceData.class)
public interface DeviceData {

    @Value.Parameter
    DeviceIdentifier deviceIdentifier();

    @Value.Parameter
    DeviceType deviceType(); // enum
}

or equivalently we could have abstract class with identical body as above interface

public abstract class DeviceData {


Either ways, we instantiate the BO as follows

final var myDeviceData = ImmutableDeviceData.builder()
                             .deviceIdentifier(ImmutableDeviceIdentifier.of("xxxx-xxxx")
                             .deviceType(DeviceType.Tablet)
                             .build();


At times we also add certain precondition checks using @Value.Check annotations such as following, which again work identically with both interface and abstract classes

@Value.Immutable(builder = false)
public abstract class DeviceIdentifier {
    @Value.Parameter
    public String value();

    @Value.Check
    default void validate() {
        Validate.notBlank(value(), "DeviceIdentifier cannot be blank");
    }
}

Additionally there are situations where we have to declare static fields such as regex Pattern in case of EmailAddress BO; here again Java17 makes it possible in both abstract class and interfaces alike.


Considering this specific use case of Immutable business objects, are there any pros or cons of preferring abstract class over interface or vice-versa?

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
y2k-shubham
  • 10,183
  • 11
  • 55
  • 131
  • 1
    Using an interface or abstract class is a *functional* choice. If the code doesn't immediately make it obvious which one you need, you probably need neither, and just have a single implementation class. – Jorn Aug 25 '23 at 13:24
  • Have [posted this](https://softwareengineering.stackexchange.com/questions/447242) on SoftwareEngineering instead – y2k-shubham Aug 29 '23 at 11:28
  • They seem to be coming to the same conclusion :-) – Jorn Aug 29 '23 at 11:52

0 Answers0