tags:

views:

74

answers:

4

I am working on a asp.net project having a three-layered implementation. DataAccess Layer is there.DataAccessContract is a layer which contains all the interfaces which classes in dataaccess layer implement.Similarly we have a business layer and a businessLayer contract.

Now when we call Data Access from Business Layer, we call

IUserDAL userControllerDAL=new UserDAL();

UserDAL is inside DataAccess and IUserDAL is inside DataAccessContract.

I could have done it this way

UserDAL user=new UserDAL();

What is the difference between these two approaches and how first one is better than second. is it some pattern in the first case.Please explain with some examples.

+2  A: 

The object is instantiated in exactly the same way, however what you can access from that object is different. Usually the interface offers less functionality, which can be a good thing if you don't want developers doing certain things. Or there could be explicit declarations for some methods in the object that can only be accessed through the interface.

pdr
Also method dispatching takes that into account.i.e.void Do(IUserDAL u)void Do(UserDAL u)
Sergey Mirvoda
A: 

See Why are interfaces important

It should answer your question :D

PieterG
A: 

The purpose is separating contract (the interface you are working with) from implementation (the class that implements that interface).

Suppose you want to implement a Result Randomizing DAL (just for the heck of it). Wiht option 1, you'd need to either inherit from DAL, or modify all places where DAL is used.

Inheritance is problematic: DAL implementation might be sealed, you might want to inherit from something else, etc.

In the second case, you make your class standalone and just change the instantiation:

IUserDAL dal;
if (AprilFirst)
   dal = new ReasultRandomizingUserDAL();
else
   dal = new UserDAL();

The object instantiated itself is identical.

peterchen
A: 

I would like to add that working with interfaces is better for implementing a IoC container.

Pablo Castilla