Need Of Dao And Service Interfaces - java

I am new to spring Mvc and in a lot of tutorials, I found there is a Dao interface like this
public interface StudentDAO {
public List<Student> getStudents();
public void addEntry(Student student);
public void updateEntry(Student student);
public void deleteEntry(Student student);
public Student getStudentById(int id);
}
and also services like this
public interface StudentService {
public List<Student> getStudents();
public void addEntry(Student student);
public void updateEntry(Student student);
public void deleteEntry(Student student);
public Student getStudentById(int id);
}
And there are implementations for these interfaces.
My question is why we need interfaces rather than direct implementation classes?

I'm glad to see someone questioning that practice.
Spring Framework introduced long time ago the pattern of defining interfaces for their managed service / DAO beans. I think that practice was introduced due to limitations in the technology they used to create dynamic proxies.
When a Spring-managed bean is defined, the framework creates a proxy to the underlying instance with the purpose of decorating it with cross-cutting functionality using AOP techniques. Apparently, the tools they used to implement those proxies in the early versions of Spring Famework required an interface to create the proxy out of it.
This requirement no longer holds in the latest versions of Spring Framework and you're safe to dispose of those useless interfaces.
The reason for ease of testing does not hold nowadays, either, as mocking frameworks like Mockito are also capable of mocking concrete classes.
In addition, you can use the #Primary annotation to replace the real implementation with a custom mock in a testing context.
For those reasons, I would scrap interfaces for internal service and DAO classes that will never have multiple co-existing valid implementations.
Keep interfaces for design patterns that really need them.

In theory, it creates interfaces to decrease the coupling. In other words you create interfaces that are the communication contracts. And with that you can have more of an implementation for the same contract. Example: In PersonDao you can have implementation with hibernate and one with native SQL. With that in places where you used, you only inject interace and CDI itself solves the implementation, then you easily change the implementation without affecting the places where it is used interfaces.
In practice in my projects, depending on the situation, do not create the interfaces, but I will emphasize, it depends on the project. Example: A DAO in the majority of the time it never changed its implementation, that is, I see no need to create the interfaces in these cases directly implement the concrete classes.
The post Jiri Tousek is an example for the use of interfaces. However in my tests, I always use the complete flow, including the database.

Perhaps the simplest concrete illustration for the need is testing.
With the DAO interface, you can test your application's logic without the need to have a DB running that's accessible from the machine running tests, simply by swapping your DAO implementation for a dummy one during tests. That dummy implementation can then provide consistent data for tests that doesn't change between test runs, cannot be overwritten in DB by accident, is versioned in you Git/SVN/whatever etc.
In general, this is part of the Program to an interface, not an implementation design principle.
In my experience, this separation of interface vs. implementation is a good idea even if you're never going to have multiple implementations, because it encourages programmers to think more deeply about the contract of the class.
Note that the principle is not universally accepted, here are some counter-arguments for example.

if you are doing project it includes some database so you must define function in interface in this way Which you use is easily seen.

Related

What's the pattern name for wrapping access to static methods/variables?

Following on from the question How do the Proxy, Decorator, Adapter, and Bridge Patterns differ?, how would you describe the following pattern which I've needed to implement on several occasions?
The scenario is that I'm referencing a static method or variable from a third-party class, but I want to hide it behind an interface so that I can mock it for testing.
For example, in Java the commons-lang library has a SystemUtils class with constants IS_OS_WINDOWS etc. I want to run tests which are independent of the underlying OS and mimic various OSs, so I wrap access to the constant as follows:
interface ISystemUtils {
boolean isOsWindows();
}
class SystemUtilsImpl implements ISystemUtils {
#Override
public boolean isOsWindows() {
return SystemUtils.IS_OS_WINDOWS;
}
}
Is this a Proxy, a generic "wrapper", or something else?
This is called a Facade:
A facade is an object that provides a simplified interface to a larger
body of code, such as a class library. A facade can:
make a software library easier to use, understand and test, since the
facade has convenient methods for common tasks;
make the library more readable, for the same reason
reduce dependencies of outside code on the inner workings of a library, since most code uses the facade, thus allowing more flexibility in developing the system
wrap a poorly designed collection of APIs with a single well-designed API.
The Facade pattern is a good answer, although I do agree that it normally (in my experience at least) expose a number of different operations/classes. With that said, a number of other patterns can also serve the same purpose - Proxy would likely be my first choice, but Adaptor or Mediator could also be a good fit. Another term for this that you may also come across is a "delegate".

Why we are using interface in spring MVC pattern?

I am new to spring MVC , I have downloaded a small spring MVC project . The project is executing fine but it this project interfaces and classes are being used .
like
public interface EmployeeService {
public void addEmployee(Employee employee);
public List listEmployeess();
public Employee getEmployee(int empid);
public void deleteEmployee(Employee employee);
}
And
public class EmployeeServiceImpl implements EmployeeService {
#Autowired
private EmployeeDao employeeDao;
#Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public void addEmployee(Employee employee) {
employeeDao.addEmployee(employee);
}
public List listEmployeess() {
return employeeDao.listEmployeess();
}
public Employee getEmployee(int empid) {
return employeeDao.getEmployee(empid);
}
public void deleteEmployee(Employee employee) {
employeeDao.deleteEmployee(employee);
}
}
My doubt is if we are using EmployeeServiceImpl what is the need of implementing EmployeeService ? same thing is there in EmployeeDao and EmployeeDaoImpl.
Interfaces are always a good practice for decoupling, but also, when speaking about Spring, there are several features you can use having interfaces rather than concrete classes.
A big advantage is proxying - Spring AOP.
You can find more information here: http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/aop.html
There are other advantages, like post processing and things like that, but I think you will have an interesting reading on Spring AOP.
Weather spring mvc or not, one should always code to interface. Interface gives me better readability when i just want to see what the class does instead of worrying about how it does it, kind of API exposed to outer world.
Another benefit is there could be multiple implementations of 'how to do' it and spring helps to switch easily between multiple implementations. For e.g. you could have one more implementation of EmployeeService say FullTimeEmployeeServiceImpl, RemoteEmployeeServiceImpl.
Now if you have client class which uses EmployeeService:
class EmployeeManager{
private EmployeeService service;
}
you can inject any of bean here
<bean id="employeeManager" class="com.abc.EmployeeManager">
<property name="service" ref="fullTimeEmployee | remoteEmployee" >
</bean>
<bean id="fullTimeEmployee" class="com.abc.FullTimeEmployeeServiceImpl" />
<bean id="remoteEmployee" class="com.abc.RemoteEmployeeServiceImpl" />
A few principles that are part of the SOLID acronym for OO design apply to this:
Liskov substitution principle - you should be able substitute any subtype of T without affecting the outcome of the problem. E.g., if you call a method that returns a List<>, and the underlying implementation switches from returning an ArrayList<> to a LinkedList<>, your program should still perform in the same manner. Basically, you should design your classes so that client dependencies can be substituted with subclasses without the client knowing about the change. Here is a short snippet from the wiki page:
Substitutability is a principle in object-oriented programming. It
states that, in a computer program, if S is a subtype of T, then
objects of type T may be replaced with objects of type S (i.e.,
objects of type S may substitute objects of type T) without altering
any of the desirable properties of that program (correctness, task
performed, etc.)
Dependency inversion principle - The main idea is that you isolate the class behind a boundary based upon the abstractions it depends on. That way if any of the details that sit behind those abstractions change, the class will be unaffected.
In object-oriented programming, the dependency inversion principle
refers to a specific form of decoupling software modules. When
following this principle, the conventional dependency relationships
established from high-level, policy-setting modules to low-level,
dependency modules are inverted (i.e. reversed), thus rendering
high-level modules independent of the low-level module implementation
details. The principle states
A. High-level modules should not depend on low-level modules.
Both should depend on abstractions.
B. Abstractions should not depend on details.
Details should depend on abstractions.
It don't have much .to do with Spring or MVC.It is good practice to design with interfaces, so that implementation can be changes easily. It provides loose coupling and if you are using spring you can siimply change implementation. Whenver needed.
Also , it helps during testing with Junit. You can easily mockup your dao.
It is recommended to write code against interfaces instead specific implementations.
This way, the client code doesn't know the specific implementations but only knows the contract.
Regarding Spring, you generally have to use interfaces since Spring often needs to create Java proxies and this can be done only for classes that implement interfaces.

How does the JVM represent an enum with one value vs multiple values? (Breaking Singleton rules?)

Specifically, I am using a Singleton model using an enum. I have an enum singleton service (business logic) calling into an enum singleton dao. I would like to do write unit tests for my service but I can not mock my enum dao because, well, it's an enum and final. Yes, I saw the article about doing it with reflection, but I'd rather avoid that if possible.
So my thought was this, why not add another value TEST_INSTANCE to my enum? (And that really is the core question.)
public enum MyDao {
INSTANCE,
TEST_INSTANCE;
public boolean methodIWouldMockIfICould()
{
if(this == TEST_INSTANCE) { return true; }
... //method code here
}
}
Trying this seems to work initially, but I'm hesitant.
This has a bad smell to me.
Assuming the code deployed to my web application uses only INSTANCE and that the only place TEST_INSTANCE is ever used is in tests, will this enum still follow the singleton model?
Is there anything else bad about this that I am not considering?
Thank you much in advance,
-Matt
Edit I would love to use Spring for DI, but I am not allowed to. Legacy system and the higher ups have simply said "no, not yet." I have hopes that it will come, but I'm not allowed to yet, so this is my solution effort in the meantime.
I wouldn't bother to enforce the singleton pattern in your code using an Enum. Instead, just create a DAO interface and a corresponding concrete implementation.
In your unit tests, mock your DAO interface. In your production code, use dependency injection (DI) to stuff your concrete implementation into your other classes. Most DI frameworks will allow you to enforce the singleton property via configuration settings.

Dependency Injection - Proper use of interfaces? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I've been reading about DI and best practices, and still haven't found the answer to this question. When should I use interfaces?
Some developers suggest to add interface for every object that is being injected. This would make a modular application.
Some other are against this.
So my question is which one is correct?
EDIT:
Below are the two sides, I still don't see the advantage of using interfaces. In both cases I can easily mock classes, and change the implementations
Using interfaces
bind(IUserStorage.class).to(UserStorage.class);
// Unit test
bind(IUserStorage.class).to(Mock(UserStorage.class));
Not using interfaces
bind(UserStorage.class).to(UserStorage.class);
// Unit test
bind(UserStorage.class).to(Mock(UserStorage.class));
I can't believe using interfaces is againt OOP principles!
I would definitely use interfaces in this scenario. It means you're loosely coupling your components and can easy mock and/or substitute alternatives. Lots of DI frameworks will use the interfaces in order to provide additional functionality (e.g. create proxy objects mapped to the real objects, but with additional features).
As such I would try and use interfaces for all but the most trivial of injected objects. At some stage you're going to want to make use of substitutability, framework code generation etc. and retrofitting interface usage is an additional pain that it's easy to avoid at the beginning of a project.
Interface based design is the cornerstone of IoC, here is a short description of Interface-based design (Sorry that I'm referencing my own blog, but I just finished an article about this, it was an extract from my MS Thesis):
Nandigam et al. defines Interface-based design as "a way of developing
object-oriented systems where one consciously and proactively defines
and uses interfaces wherever possible in a design to reap the benefits
of designing with interfaces" [Nan09]. Applications with an
interface-based design follow the principle "program to an interface,
not an implementation". This principle brings the following benefits
to the resulting system [Dav03]: flexibility (describes the system
robustness to change), extensibility (the ease with which a system may
accommodate additions) and pluggability (the ability that allows
substitutions of objects with identical interfaces at run-time).
Once you mix interface design with IoC you obtain the following benefits:
Tasks are decoupled from the implementation.
Increases modularity where modules rely on other modules solely on their contracts (interfaces).
Increases pluggability and replacing a module does not have a cascading effect on other modules.
To answer your question, I would use interfaces for different types of modules. For example, one per service or repository.
I do not create interfaces for controllers or Model classes (MVC apps).
All this, as a side effect, facilitates testing.
If you use interfaces or at least abstract/inheritable classes you can change the behaviour of the program by an easy exchange of the implementation (inject another class) in the DI/IoC config.
Using interfaces is a good practice (imho). This is especially very important if you are writing UnitTests which needs mocks. It is much harder to write UnitTests with a good coverage (not to say impossible in most "real world" cases) if you're not using interfaces.
I think you should use an interface if there might be a chance that the injected part could change. It should be easy to extend your implementation, see Open-Closed-Principle. => This will require the exchange of modules/parts/implementations... ask yourself what would happen if your class has no virtual functions to override and you are forced to change the implementation.
I would use interfaces at least for the public classes / parts of your code (the parts other programmers would use).
Having a look at your sample. The problem is at the wiring part and not only the binding of a class as (default) implementation of an interface (binding works, but wiring could break).
For example if you have 2 implementations (C# sample here, should be the same in Java etc., too):
public interface IUserStorage
{
void Write(object something);
}
public class UserStorageTextFile : IUserStorage
{
public void Write(object something) { ... }; // stores to text file
}
public class UserStorageDB : IUserStorage
{
public void Write(object something) { ... }; // stores to DB
}
public class MyStorageClient
{
public MyStorageClient(IUserStorage storage) { ... } // copy to private field and use it etc.
}
Depending on your IoC it should be easy to wire
an instance of MyStorageClient to your binding of IUserStorage.
bind(IUserStorage.class).to(UserStorageDB.class); // Java sample, eh?
But if your MyStorageClient is strongly forced to use DB already...
public class MyStorageClient
{
public MyStorageClient(UserStorageDB storage) { ... } // copy to private field and use it etc.
}
... it is imposible to wire it up with the UserStorageTextFile class except the UserStorageTextFile is inherited from UserStorageDB... but why should you have a dependency to e.g. Oracle drivers (required by UserStorageDB) if you only want to write a simple text file?
I think the sample is clear enough and shows up the benefits of using interfaces...
but if not... try to do this:
bind(UserStorageDB.class).to(UserStorageTextFile.class);
// and in another config/module/unitTest
bind(UserStorageTextFile.class).to(Mock(UserStorageDB.class));
// and try to wire it against your client class, too (both ways, meaning one config for TextFile and load a config for the DB after changing only the configuration)
Your question states "some developers [are for this]" and "some developers [are against this]", so there is no right answer. But this is why I agree that interfaces are overused
If you are creating a library, choosing when to use interfaces is important. It is harder to create a maintainable contract when you don't control how your code is consumed.
If, however, you are creating an application, it less likely to require an interface, because the public interface of a class can serve as the maintainable contract to consuming code. Let's say version 1 looks like this:
public class UserStorage
{
public void Store(User user) { /* ... */ }
}
You don't even need refactoring tools to change it to this:
public interface UserStorage
{
public void Store(User user);
}
class TheImplementation implements IUserStorage
{
public void Store(User user) { /* ... */ }
}
Then you can easily use refactoring tools to rename the interface to IUserStorage.
So when you are writing non-library code, you can usually get away with a class until you need swappable implementations, decorators, etc. You should use an interface when the public interface of the class does not suit your needs. (For example, see the interface segregation principle)
In short - having an interface that is 1:1 with a class is unnecessary indirection in application code.

Why does dependecy injection use public methods?

Why does dependecy injection use public methods?
Correct me if I'm wrong, but it's possible to change the implementation using reflexion.
DI is not a goal in itself. The purpose of DI is to enable loose coupling through favoring composition over inheritance, and that's only possible if you expose a public API for the purpose.
You can't recompose components in new and exiting ways without the public API.
That's a pretty blanket statement and isn't true. My preference is generally to use package-private constructors (or public constructors on package-private classes, since it doesn't matter then) for dependency injection since that allows you to instantiate and inject a class yourself (with no reflection or injector) for testing in a test class in the same package.
Keep in mind that the security policy may prevent one from calling protected, package private, or private methods even via the reflection API. If the DI framework is to work in all environments, then it can only rely on public methods.
Just to elaborate on the answer ColinD gave (I never even knew about package-private classes until a year of programming Java). With an app developed with a DI framework I believe you would make interfaces public and perhaps some abstract classes and Enums:
package org.my.service;
public interface Service {
public void process();
}
Then, the concrete implementation would be package-private (no public keyword)
package org.my.service;
class RealService {
public void process() {/*do something*/}
}
This enforces the concept of information hiding and means implementation details do not leak into the public API. It also means you cannot use the class outside of that package (compile-time error if you try -- you can't "new" it anywhere).
Again as ColinD said, you can unit test it because your unit test will reside in org.my.service.
DI frameworks have many ways to inject dependencies
constructor injection
setter injection
initializer injection
field injection
By using the first three, with modifier public you can set the dependencies manually even if the class is used outside a DI framework.
However, the 4th option is widely used. The most common scenario where you may need to manually set the dependencies are unit tests. For that spring, for example, offers ReflectionTestUtils, so that you can inject into fields with 1 line, and that is more or less fine.

Categories