Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use Interfaces for domain entities?

What is the purpose of using interfaces for domain entities?

In our project, we are using interface for domain entities. Inside the interface, there are only getter and setter methods, not even any domain logic.

Is using an interface for entities like this useful? Is this good practice?

Thanks.

like image 241
magicbacon Avatar asked Dec 12 '25 13:12

magicbacon


1 Answers

There are plenty of reasons why it's a good idea sometimes but it really depends on the scope of the project.

First of all: your statement "...not even any domain logic." doesn't make sense, there can't be any logic in an interface, interfaces can't have any logic, only method signatures.

The main reason why this is done is to support multiple implementations of the domain objects for different uses.

Reasons why you might want to code your domain objects to interfaces:

  1. Serialization - sometimes you want to create serializable versions of your domain objects but don't want to mix that code up with the code you use for your core app. For example, you might have an implementation of your Person object that you just use to serialize to JSON for your webapp.

  2. Shared API - you might want to distribute a public API version of your code that has different implementations of your objects, or you might even just want to make the interfaces available to another group (or client, or vendor)

  3. Support for a legacy implementation - maybe you have some data in an old database that you need to build a connector for that involves a different implementation of your domain objects to pull the data out.

  4. Testing - having interfaces for your core classes makes unit testing a lot easier since you can quickly stub out methods you don't need for testing.

like image 108
Rick Mangi Avatar answered Dec 15 '25 08:12

Rick Mangi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!