简体   繁体   中英

Spring DAO class method - protected vs public?

In my Java Spring application I have a DAO class with methods. I would like to know which access modifier use: protected or public ?

In which situation we should use protected modifier? I don't know when I should use a protected modifier, so I always use public . Is it proper way?

DAO layer is mostly used for database transactions. For eg: saving, updating, fetching, etc.

Now they don't have any business logic in them, because we put the business logic in the Service layer. Usually this Service layer makes a call to the DAO layer whenever it needs to perform a database related work.

Therefore, public should be used in most cases (as they are getting called from a different layer/package) all together.

Protected is good when you are sure that you will make call only from the same package(or sub classes), which may not always be the case. So no, protected is not recommended.

Protected doesn't really make sense for DAOs, since you need the methods in other packages, in classes which don't implement the DAO. Therefore public is almost always the way to go.

For DAO classes, you should make an interface with Dao methods declared(Which will obviously be public). Your DAO classes should extend the interface. In this way your Dao methods will be accessed from other classes via the interface reference.

It's the better way, because it will be easy to test. You can provide a mock implementation of the DAO interface to test your code. You can do this before you write your actual DAO class. If you are calling DAO methods with interface reference variable, then you can change your DAO class and it will still work because you are changing the class not the interface whose reference you are using for calling the methods(renaming class name for an example).

It's the important design principle that you should always code for interface wherever possible. I recommend you to see this answer to read about why you should code for interfaces in DAO.

You should use protected modifier in case of inheritance. When you want outside the package only child classes should be able to access the methods and properties of your class. when you need to do somethings that should not exposed in public API but still needs to be overriden by subclasses for example template method pattern .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM