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.
could some body explain me abstraction and interface in asp.net, C# by taking an apprpriate example...pleasse
i am not understanding it for long
I often find the following sample quite illuminating when it comes to explaining this:
Disclaimer: the code examples are written directly into the text, and may contain errors that I have overseen. Please let me know if you find such errors.
Let's say you have a database with a Customer table, and in your code you have a customer class:
class Customer
{
public int Id { get; set; }
public string Name { get; set; }
}
In order to provide a mechanism to get customer data from the database, you need to write some class doing that. This can be placed in something called a repository. Now, we don't want our code to rely too much on what exact database we use. It could be SQL server, it could be a text file. So we want an abstraction layer shielding the code from this knowledge. All we need to know is what such a repository looks like:
public interface ICustomerRepository
{
Customer GetCustomer(int id);
IEnumerable<Customer> FindCustomers(string beginningOfName);
}
We can now implement this interface for the data storage that we use:
public class SqlServerCustomerRepository : ICustomerRepository
{
public Customer GetCustomer(int id)
{
using(SqlConnection connection = new SqlConnection(connectionString))
{
// code to fetch data and populate Customer objects go here
}
}
// implementations of other members of ICustomerRepository
// left out to keep code short. Just imagine they are here :)
}
Finally, when we want to use this code, we can have a factory create the concrete ICustomerRepository implementation to use:
public static class RepositoryFactory
{
public static ICustomerRepository CreateCustomerRepository()
{
return new SqlServerCustomerRepository();
}
}
...and in our code where we need the data:
ICustomerRepository repository = RepositoryFactory.CreateCustomerRepository();
IEnumerable<Customer> customers = repository.FindCustomers("A");
This way, there is no hard coupling between the consuming code, and the particular kind of repository in use (except for in the factory method, but that is the one and only place where this knowledge exists). This makes it easy to replace the concrete repository implementation. This is also useful for testing, where you can easily create a mock repository returning hard coded results for given input, so that you can unit test the code that needs data from the repository.
Well abstract classes and interfaces are not strictly asp.net technic they are OOP concept.
Interface
An interface is like a class but all the methods and properties are abstract. An Interface cannot be instantiated like abstract class. All the methods and properties defined in Interface are by default public and abstract.
Interface generally refers to an abstraction that an entity provides of itself to the outside. Interface can help in separating the methods for external and internal communication without effecting in the way external entities interact with the type..
Example:
If you have interface IDoSomething { void Do(); }
The class that implements the interface must provide a body for Do() method e.g.
class SomeClass : IDoSomething
{
public void Do()
{
//body of the method
}
}
The advantage of this is when you make something that need only Do method you pass the interface not the class.
public static void SomeMethod(IDoSomething obj)
{
obj.Do();
}
Now SomeMethod(IDoSomething obj) will work with any class that implements IDoSomething
Abstract Class
An abstract class is a class with at least one method defined as abstract. This type of class cannot be instantiated. An abstract class can have one or more abstract methods and properties and other methods and properties like normal classes.
The idea is the same but in abstract class you can have methods with implemented logic, fields and so on.
Abstraction
Abstraction is the process of hiding how the object is working, and its only showing the information of the object the way we can understand it. Means it represent the essential details with out showing ground details. We putting all variables and method in a class which are necessary.
Eg: Employee and Patient.
Company interested to fill about the Employee details like Name, Address, Qualification, DOB, Age, Mobile, Marks, Experience etc
Hospital interested to fill about the patient details like Name, DOB, Height, Weight, Age, Address, Mobile, Blood Group etc.
Both Company and hospital interested to fill some common fields like Name, Age, DOB, Address, Mobile etc. So we can create a class which consist of common thing that is called abstract class. This class wont be complete but can inherit by other class.
Abstract vs Interface
You cannot create an object of abstract class , but can make derivations of this.
An abstract class can contain either abstract methods or non abstract methods. Abstract members do not have any implementation in the abstract class, but the same has to be provided in its derived class.
An abstract class can have abstract members as well non abstract members. But in an interface all the members are implicitly abstract and all the members of the interface must override to its derived class.
Defining an abstract class with all the abstract members is similar to defining an interface. i.e we can say an interface is an abstract class with all the abstract members
Classes may inherit from only one base class, so if you want to use abstract classes to provide polymorphism to a group of classes, they must all inherit from that class.
Abstract classes may also provide members that have already been implemented. Therefore, you can ensure a certain amount of identical functionality with an abstract class, but cannot with an interface.
Here are some recommendations to help you to decide whether to use an interface or an abstract class to provide polymorphism for your components.
1). If you anticipate creating multiple versions of your component, create an abstract class. Abstract classes provide a simple and easy way to version your components. By updating the base class, all inheriting classes are automatically updated with the change. Interfaces, on the other hand, cannot be changed once created. If a new version of an interface is required, you must create a whole new interface.
2). If the functionality you are creating will be useful across a wide range of disparate objects, use an interface. Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing common functionality to unrelated classes.
3). If you are designing small, concise bits of functionality, use interfaces. If you are designing large functional units, use an abstract class.
4). If you want to provide common, implemented functionality among all implementations of your component, use an abstract class. Abstract classes allow you to partially implement your class, whereas interfaces contain no implementation for any members.
Related
Are helpers in MVC3 used in the controller as well as the views?
Is a helper the right place to put commonly used controller methods?
I want to create a common method to get all sub children IDs in a database and make sure it is in the right area. I just want to make sure I am putting my logic in the right area.
Thanks
You could implement a base Controller for that logic. Helpers, or extension methods, are good for when you don't want to change the interface for something.
The HtmlHelper is not available to the controller, because the controller should not be responsible for generating HTML, but the UrlHelper is available within the controller.
A method to get specific data from your database does not belong in your controller, or in a UrlHelper or an HtmlHelper. You should create a separate class for this logic, and then call the method on this class from within your controller. If you are using Dependency Injection, which I suggest, your controller code might look like this:
public class MyController
{
IMyDataUtil _dataUtil;
public MyController(IMyDataUtil dataUtil)
{
_dataUtil = dataUtil;
}
public ActionResult SomeAction(int parentId)
{
var childIds = _dataUtil.GetChildIds(parentId);
...
}
}
As you can see, this allows you to keep the data-access code in a class specifically designed for that purpose. The fact that this controller depends on that utility class is immediately obvious, and doesn't take that much more code than calling an extension method on a helper. Controllers that don't deal with that class's methods won't need to have it available.
On the other hand, if there are methods that are likely to be used by a bunch of different controllers, injecting this same data class into all of them may become cumbersome. In that case, you could:
Extend a base class that has an instance of the data-access class injected into it via method or property injection, and which then exposes it to sub-classes via a protected or public property, or
Create your own helper class that wraps the classes and methods you're likely to use in all your controllers, and inject that class so you only have one dependency for a variety of common functions, or
Combine steps 1 and 2.
If by "helpers" you're referring to things such as HtmlHelper then, no, these aren't used by the controller as in theory you could take your controllers and re-use them with an entirely different rendering engine (for example WPF) as the controller isn't responsible for rendering.
If you're talking about, as I think you are, helper classes/methods that manipulate your data ready for it to be put into a Model by a Controller and then handed off to a View for presentation, then you could consider a "business logic" layer. For example, if you were talking about (the ever typical) Bank Account example, you could have a:
public class BankAccountService
{
public IEnumerable<string> GetAllAccountIdsForCustomer(int customerId)
{
// Talk to the database here and retrieve the account id's for a customer
}
public string GetCustomerName(int customerId)
{
// Talk to the database here and retrieve the customer's name
}
}
Your controller would then:
public ActionResult AccountNumbers(int customerId)
{
var model = new AccountNumbersModel();
model.CustomerId = customerId;
model.AccountNumbers = BankAccountService.GetAllAccountIdsForCustomer(customerId);
return View(model);
}
Obviously in this example you'd need to have a class called AccountNumbersModel defined and you'd also probably want to consider using Dependency Injection to provide an instance of BankAccountService to your controller, but describing how to go about all that is kinda outside the scope of this answer.
The advantages this approach gives you are testability and separation, each piece of code is responsible for one task, and you reduce the complexity of each individual piece and make it easier to make changes without breaking things.
I want to create a common method to get all sub children IDs in a database and make sure it is in the right area. I just want to make sure I am putting my logic in the right area.
That sounds like a job for an ActionFilter.
Could anyone tell me where is the best place to put my business methods when using EF4 code first POCOs? Should they go in the POCO class? E.g.
public class customer
public property Id as int32
public property Name as string
public property Archived as boolean
public sub MarkAsArchived
me.Archived = true
end sub
public function EmailAllInvoices as boolean
...
end function
end class
Or should the POCO class be as clean as possible and a seperate class be used for business logic which accepts an instance of a customer POCO in the constructor to work on?
Thanks.
#Ladislav Mrnka is right, it depends on your architecture.
How complex are your business rules? Are they likely to change often? What clients will consume your Model, just your own Web Site, or are you exposing API's, OData, etc?
All questions that need to be answered.
Personally, we have simple business rules, and a fairly straightforward architecture.
Therefore, i do all validation in a service layer, and i create partial classes for my POCO's to faciliate the business rules, and throw Custom Exceptions.
E.g
public void Add(Order order)
{
try
{
order.Validate(); // method in Order.cs partial class
repository.Add(order);
}
catch (InvalidOrderOperationException exc) // custom exc
{
// do something
}
}
As i said - depends on your architecture.
If you have very complicated business rules, consider using the Specification pattern.
The "DDD-God" (Martin Fowler) has a good write-up on it here.
That is definitely dependent on "architecture" of your business layer. You can use POCO as data transfer object and have some upper level business layer class which will handle business operations - basically we can talk about Transaction script pattern. Or you can place methods to your POCO objects and "promote" them to Domain objects. Then your business logic will be inside your domain objects and domain services (some business logic functionality is for several domain objects so it should be placed to separate class). This is called Domain driven design (but it suggests much more architecture related ideas).
I know that my this question may sound pathetic to you but as a beginner in .NET, it means a lot to me.
I just want to know that how can I utilize the concept of Abstract class, virtual class etc. in my shopping cart website. I have read the tutorial out there on internet and I saw some examples too, but those examples are so general that they dosen't fit into real world scenerio like I am searching for a shopping website. Same questions again and again comes to my mind that why to made a class only to give the declaration of methods and property.
I understand that most of you are Gurus of .NET and have ample knowlesge in it but if you could just help me out in thinking the logic behind this i'll be very greatfull.
If possible, please recommend me nice books for asp.net design patterns, from which I can learn design patterns.
Thanks in advance
Your one stop resource and guide is Head First - OOAD.
alt text http://i36.tinypic.com/8y6luo.jpg
If you can't see why to use them then don't for now. Never use a design pattern just for the sake of it.
As for their purpose however, imagine that you want to allow different types of products, but you never have something that is just a "Product" - it's always something specific like a "Book" or "Car". In that case you can put the common properties in an abstract Product class like this:
public abstract class Product
{
/* Abstract Price allows Car/Book to apply their own category discounts */
public abstract decimal Price { get; }
public string Title { get; }
public void AddReview(int userId, string reviewText)
{
/* Add review */
}
public abstract List<Product> Recommendations(int userId);
}
which your Book and Car classes can then extend.
Here is a good design patterns book with examples in C#.
C# 3.0 Design Patterns
Its not ture that for every desing you have to use Abstarct class or define virtual methods.
Basically virtual keyword is used to modify a method, property, indexer or event declaration, and allow it to be overridden in a derived class, and Abstarct keyword enables you to create classes and class members solely for the purpose of inheritance—to define features of derived, non-abstract classes
In your case you can have an abstract class called CartItem which works as a base class for all the types of items you are supposed to support in you cart. All types of items will inherit the CartItem class. You can’t directely create the instance of CartItem class but you can use this as a reference to achieve the Polymorphism.
You can define some concrete methods/properties like ItemId, ItemName, Price etc in the CartItem class which are common to all the types of items and you can also define some of the methods a virtual for which you have a default implementation but the child classes can override the implementation.
What's the best object layout in ASP.net or at least.. what are the advantages and disadvantages of either case:
Public Class Dog
Public Breed as String
Public Type as String
Etc....
OR the use of properties and keeping variables private
Somewhat of a debate among our team about it. Just wanted to hear thoughts.
Never expose fields directly.
Use properties with private backing fields. This allows you to change implementation and to encapsulate logic around getting/setting them.
See what the Visual Basic Team have to say on this.
Also, read about the differences between fields and properties.
Just as the title asks, when should a trigger in your head go off signifying "Aha! I should use the factory pattern here!"? I find these moments will occur with many other design patterns, but never do I stop myself and think about this pattern.
Whenever you find yourself with code that looks something like this, you should probably be using a factory:
IFoo obj;
if ( someCondition ) {
obj = new RegularFoo();
} else if ( otherCondition ) {
obj = new SpecialFoo();
} else {
obj = new DefaultFoo();
}
The factory pattern is best employed in situations where you want to encapsulate the instantiation of a group of objects inside a method.
In other words, if you have a group of objects that all inherit from the same base class or all implement the same interface that would be an instance where you would want to use the factory pattern (that would be the "pattern" you would look for).
I can think of two specific cases that I think of the factory pattern:
When the constructor has logic in it.
When I don't want the application to worry about what type gets instantiated (eg, I have an abstract base class or interface that I am returning).
Quoted from GoF:
Use the Factory Method pattern when
a class can't anticipate the class of objects it must create
a class wants its subclasses to specify the object it creates
classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate.
I highly recommend the GoF book. It has a section on the applicability of each of the 23 patterns it covers.
Are you talking about Factory Method or Abstract Factory?
The basic problem that both solve is letting clients specify the exact class that framework code constructs. For example, if you provide an interface, that clients can implement, and then in your code have something like:
IMyInterface x = new ConcreteClass();
There is no way for clients to change the exact class that was created without access to that code.
A Factory Method is a virtual method that constructs a concrete class of a specific interface. Clients to your code can provide an object that overrides that method to choose the class they want you to create. It might look like this in your code:
IMyInterface x = factory.Create();
factory was passed in by the client, and implements an interface that contains Create() -- they can decide the exact class.
Abstract Factory should be used if you have hierarchies of related objects and need to be able to write code that only talks to the base interfaces. Abstract Factory contains multiple Factory Methods that create a specific concrete object from each hierarchy.
In the Design Patterns book by the Gang of Four, they give an example of a maze with rooms, walls and doors. Client code might look like this:
IRoom r = mazeFactory.CreateRoom();
IWall nw = mazeFactory.CreateWall();
IWall sw = mazeFactory.CreateWall();
IWall ew = mazeFactory.CreateWall();
IWall ww = mazeFactory.CreateWall();
r.AddNorthWall(nw);
r.AddSouthWall(sw);
r.AddEastWall(ew);
r.AddWestWall(ww);
(and so on)
The exact concrete walls, rooms, doors can be decided by the implementor of mazeFactory, which would implement an interface that you provide (IMazeFactory).
So, if you are providing interfaces or abstract classes, that you expect other people to implement and provide -- then factories are a way for them to also provide a way for your code to construct their concrete classes when you need them.
Factories are used a lot in localisation, where you have a screen with different layouts, prompts, and look/feel for each market. You get the screen Factory to create a screen based on your language, and it creates the appropriate subclass based on its parameter.