Why does a DAO have to be an interface or abstract class?

Viewed 2472

I want to understand what is happening behind the scenes in a RoomDatabase, that it requires the DAO to be either an interface or an abstract class. I've been searching for quite a while, but all articles and documentation only explain the how, not the why.

3 Answers

It is not just the Room, Retrofit and other libraries use this pattern too, it is called Programming to an Interface. Instead of just creating a concrete implementation you just specify the stuff you want to do and they provide you with an implementation that will behave as you requested.

For further study you can check this article: https://tuhrig.de/programming-to-an-interface/

The data access object, or Dao, is an annotated class where you specify SQL queries and associate them with method calls.

The DAO must be an interface or abstract class because we want to make sure that the CRUD methods we will be creating inside it are implemented at the Class level. Which is actually the whole idea of having an interface or abstract class.

Mr. @keivan-esbati is correct about the principle, but I believe he is omitting an important fact about Room DAO.

Not everything can be programmed to an interface. Especially systems whose behaviors cannot be accurately predefined.

And this lack of specificity is the absolute case of Database queries. The difference here is that Room, with the help of the IDE, offers a type of code auto generation.

Without this plugin that inspects strings at build time, it would be nearly impossible to encapsulate the functionality of a DAO inside an interface/abstract..., it could be done..., but it would be relegated to the most basic functionality.

In this case the interface is not used for the same goal as the design principle..., the principle is instead used as a vehicle that the plugin uses for code generation, but the end goal is to allow the plugin to autogenerate code.

While the design principle's goal is to keep the application's memory footprint in check, prevent redundancies and a couple of other outcomes (like separation of concerns (the link mr. Keivan posted talks about this)) that inevitably result in "the path of least resistance", the code autogenerated by the plugin may actually have the opposite effect.

Related