Should DAL classes be public? - c#

Say I've got a DAL that multiple applications use to access the same data. The DAL defines its own classes and interfaces for dealing with that data, but should the applications using the DAL be working with those classes, or just the interfaces?
Another way; should it be:
List<Product> products = MyDAL.Repository.GetProducts();
or:
List<IProduct> products = MyDAL.Repository.GetProducts();
Is it good or bad that each application utilizing the DAL will have to create its own implementation details for Product?

Passing interfaces around, instead of classes, is one (very good) thing. Making your DAL classes private is a different (and not necessarily good) thing.
For instance, what if one of the applications that use your DAL want to change the behavior of Product slightly? How can you subclass or decorate your original class if it's private?
Say one of your apps is a web application, that needs to store a product's image as a url instead of a file path? Or to add caching, logging or something else on top of Product?

There are way too many questions here in order to determine the best way.
If these applications can reuse the additional functionality given by the classes in your DAL, then I'd say absolutely reuse them.
Taking "Product" for example. If the DAL has a definition of Product that is pretty close to or the same as the definition the applications need, then reuse is your best bet.
If the applications explicitly do NOT want the functionality given by the classes and instead want to provide their own implementation, then just use the interfaces.
Again, looking at "Product": if the applications have their own definition of Product with perhaps additional or just plain different properties and methods then they should implement the interface.
It's really a question of how the classes in question are going to be used.

Returning interfaces is better but then you will need GetProducts() to know about those implementations to properly query the data store. You might want to use an IOC framework for that.

Related

Is ok to have Entity Framework inside Domain layer?

I have a project with the following structure:
Project.Domain
Contains all the domain objects
Project.EntityFramework, ref Project.Domain
Contains Entity Framework UnitOfWork
Project.Services, ref Project.Domain and Project.EntityFramework
Contains a list of Service classes that perform some operations on the Domain objects
Project.Web.Mvc, ref to all the projects above
I am trying to enforce some Business rules on top of the Domain objects:
For example, you cannot edit a domain object if it's parent is disabled, or, changing the name of an object, Category for example, needs to update recursively all it's children properties (avoiding / ignoring these rules will result in creating invalid objects)
In order to enforce these rules, i need hide all the public properties setters, making them as internal or private.
In order to do this, i need to move the Project.Services and Project.EntityFramework inside the Project.Domain project.
Is this wrong?
PS: i don't want to over complicate the project by adding IRepositories interfaces which would probably allow me to keep EntityFramework and Domain separate.
PS: i don't want to over complicate the project by adding IRepositories interfaces which would probably allow me to keep EntityFramework and Domain separate.
its really a bad idea, once i had this opinion but honestly if you dont program to abstraction it will become a pain when the project becomes larger. (a real pain)
IRepositories help you spread the job between different team members also. in addition to that you can write many helper extensions for Irepository to encapsulate Different Jobs for example
IReopisotry<File>.Upload()
you must be able to test each layer independently and tying them together will let you only do an integration tests with alot of bugs in lower layers :))
First, I think this question is really opinion based.
According to the Big Book the domain models must be separated from the data access. Your domain has nothing to with the manner of how storing the data. It can be a simple text file or a clustered mssql servers.
This choice must be decided based on the actual project. What is the size of the application?
The other huge question is: how many concurrent user use the db and how complex your business logic will be.
So if it's a complex project or presumably frequently modified or it has educational purposes then you should keep the domain and data access separated. And should define the repository interfaces in the domain model. Use some DI component (personally I like Ninject) and you should not reference the data access component in the services.
And of course you should create the test projects also using some moq tools to test the layers separately.
Yes this is wrong, if you are following Domain Driven Design, you should not compromise your architecture for the sake of doing less work. Your data-access and domain should be kept apart. I would strongly suggest that you implement the Repository pattern as it would allow you more flexibility in the long run.
There are of course to right answer to whats the right design...I would however argue that EF is you data layer abstraction, there is no way youre going to make anything thats more powerful and flexible with repositories.To avoid code repetition you can easily write extension methods (for IQueryable<>) for common tasks.Unit testing of the domain layer is easily handled by substituting you big DB with some in-proc DB (SqlLite / Sql Server Compact).IMHO with the maturity of current ORMs like nHibernate and EF is a huge waste of money and time to implement repositories for something as simple as DB access.
Blog post with a more detailed reply; http://ayende.com/blog/4784/architecting-in-the-pit-of-doom-the-evils-of-the-repository-abstraction-layer

ASP.NET 3-Tier / 3-Layer architecture - how to separate UI and BLL

I am currently studying towards my final year of a Computer Science degree, and working on my final project and dissertation. I will be using ASP.NET Web Forms and C# to create a 3-Layer project - I can't really call it 3-Tier as it will most likely never be hosted on anything other than my local PC for testing as it is for uni purposes only.
My main question is this:
From my understanding, the idea of 3-Layer is that the BLL references the DAL, and the UI references the BLL to create complete separation of concerns. However I have made a small mock up project following a few tutorials so get the hang of 3-Layer, and most basic tutorials still require a reference between the UI and BLL.
For example in the project I have created, which is a very basic Products and Categories type e-commerce system, I have created the Product and ProductDAL classes in the DAL, then the ProductBLL class in the BLL. With this setup, of only using one database table (forget categories for now), the BLL seems to only serve as a sort of interface between the UI and DAL, the methods are exactly the same as those in the DAL and only call the DAL version.
The problem is that to access the DAL via the BLL, I have to pass in a Product object to the BLL method arguments, which means creating a Product object in the UI first, which means referencing the DAL from the UI. Is this the correct way of doing things?
I can get around simple cases like this by creating a method in the BLL that takes the appropriate fields, e.g. strings and ints to create the Product Object and returns it to the AddProduct method. However when it comes to binding different product attributes to labels in the UI, I still need access to the Product object.
So essentially, do I need to make a load of methods in the BLL to access properties of the Product Object? If not, what kind of methods would actually go there, can you give me any examples of methods that may go in the BLL in this kind of Product scenario?
Thanks in advance, and apologies if this has been asked before - I did read through a lot of posts about 3-Layer architecture but most are very basic and only access one table.
the BLL seems to only serve as a sort of interface between the UI and DAL
This is only because this application is very simple - just a CRUD interface at the moment. More complex applications have business rules that would be encapsulated in the BLL (and not be in the UI or DAL).
I have to pass in a Product object to the BLL method arguments, which means creating a Product object in the UI first, which means referencing the DAL from the UI. Is this the correct way of doing things?
Well, there are several different options here:
You can have a Product data access object (DAO) that is shared between the different layers. This object is not a DAL object, but the DAL uses it. It is called a DTO - Data Transfer Object.
You can have several different Product object - one to be consumes by the UI, one by the BLL and one by the DAL and have mapping layers to translate between the different objects.
Some combination of the above.
A common way of separating concerns is to start by having a project called YourProject.Entities or something of the like. This contains the main class definitions and you reference it when you need to get a large entity like a customer or a product or something of the like. Alongside, you have another project which acts as a repository. Depending on the technology that you are using this can either implement something like EF to get your objects from your DB or can contain methods which query your DB directly using straight SQL or stored procedures.
What you have to keep in mind is that these projects are primarily going to function based on user input. Your users will act and your program will respond. The idea though is that the actual business logic is separated from your UI and your data access. You can mix and match these ideas as you wish, but what I have tended to see in my professional experience is basic data constraint enforcement done on the DB access side of things, and data validation either done directly when creating your objects in the Entities project or in a separate EntitiesValidation project which takes entities as a parameter.
If you don't want to have a separate validation project, something to keep in mind is that you can implement business logic directly in objects using constructors and properties. Constructors can enforce logic on inputs before creating objects, and using full properties--that is to say this...
private string myProp
public string MyProp
{
get
{
// Some code
}
set
{
// Some code
}
}
instead of this...
public string MyProp { get; set; }
Allows you to implement rules when accessing the data associated with those properties.
In the end, these questions can be answered many different ways and I am sure that every response to this question will give you different ideas and opinions on the best way to do things. For me, the two rules I always follow are DRY (do not repeat yourself) and code maintainability. By separating logic from data access from object design from UI, you will have a much easier time maintaining and updating your program when that time comes... even if it is just a school project ;).

Help with creating a base interface for my classes

I want to create an interface or base class (not sure I want to go this route) for all my business entities. For each business entity I need the following:
Id - primary key of the entity
Type - type of the entity, e.g. User, just a string
Name - name of the entity, e.g. John Doe
Description - short description of the entity, e.g. Senior Programmer
CreatedDate - date the entity was created
ModifiedDate - date the entity was modified
All classes support a single primary key.
Most of my classes have these fields, though in most cases, the primary key would be something like UserId.
One of the reasons I want to create some commonality in my business entities is I want implement a search function that returns a list of IEntity (or Entity class, if leveraging inheritance) objects.
My questions are ...
Is is the more correct way to leverage an interface as opposed to a base class?
If I do create this as an interface should I keep the property simples, e.g. Id and Name ... which would minimize me having to code each property implementation OR is it better to append "Entity" to each proper name so it's easier to work with the business entity, e.g. MyEntity.EntityId verses MyEntity.EntityId
I realize this could be considered subjective, but I really need to get some guidance on this, so any ideas to make this not be so subjective would be much appreciated.
Thanks in advance!
In my opinion...
If your classes are going to have some common implementation of some of their methods, then a base class makes more sense. Because you can't implement inside an interface, and if you were to implement an interface, you'd have the same common implementation in multiple classes, instead of a single base class.
I think appending "Entity" to each property is pointless. You already imply that it's an entity property by either the name of the entity object or its underlying type. I say avoid redundancy and keep it simple.
In my opinion, if you want many objects to have this functionality, you should avoid base-class inheritance at all costs. Once you decide that you're gonna inherit all of the classes in your project from a certain base-class, it's hard to go back. Remember, C# only lets you have single-inheritance.
A better solution might be to implement an interface which lets classes specify the properties they have to anyone who might be interested in those data.
Another reason to avoid base-classing is that it's going to be harder to unit-test, if your'e interested in that. It's also going to be hard to change custom behaviors without affecting many areas of your application.
In short, what you can do is have objects which you have clearly recognized as needing that interface implement that interface, and have another manager-type class ask for that information from those other classes, and be the adapter or gateway between your modular, single-purpose objects, and a database (or something like that).
Hope I've made myself clear enough.
Consider whether it would be better to keep the business data as isolated classes in your data access layer, and provide a common wrapper in your presentation layer that provides the common feature set you're thinking about. Maybe your solution isn't complicated enough to warrant a fully-tiered architecture - which I'm sure quite a few people would disagree with - but I feel that making your application tiered is a good approach. This means that the data access classes get to be seperate, avoiding the conundrum altogether at this tier, and the presentation class(es) only expose the functionality you actually need - but take on whatever inheritance regime you choose. My reasoning is that considering the problem in this way might make it easier to decide.

C# Data Layer and Dto's

I have recently joined a company that using typed datasets as their 'Dto'. I think they are really rubbish and want to change it to something a little more modern and user friendly. So, I am trying to update the code so that the data layer is more generic, i.e. using interfaces etc, the other guy does not know what a Dto is and we are having a slight disagreement about how it should be done.
Without trying to sway people to my way of thinking, I would like to get impartial answers from you people as to what layers the Dto can be present in. All layers; DAL, BL and Presentation or a small sub set within these layers only.
Also, whether IList objects should or should not be present in the DAL.
Thanks.
It really depends on your architecture.
For the most point you should try to code to interfaces then it doesn't really matter what your implementation is. If you return ISomething it could be your SomethingEntity or your SomethingDTO but your consuming code doesn't care less as long as it implements the interface.
You should be returning an IList/ICollection/IEnumerable over a concrete collection or array.
Properties should not return arrays
Do not expose generic lists
What you should try to do first is separate your code and make it loosely coupled by inserting some interfaces between your layers such as a repository for your DataAccess layer. Your repository then returns your entities encapsulated by an interface. This will make your code more testable and allow you to mock more easily. Once you have your tests in place you can then start to change the implementations with less risk.
If you do start to use interfaces I would suggest integrating an IoC such as Windsor sooner rather than later. If you do it from the get go it will make things easier later on.
One thing is DataSets are poor to achieve interoperability. Even typed datasets are also not so compatible when it comes to consuming typed datasets from a non .net client. Refer this link. If you have to achieve interoperability then fight hard for DTOs otherwise try to make your team understand DTOs over a period of time because datasets are not so bad after all.
On part of interfaces, yes you should be exposing interfaces. For example - If you are returning List<T> from DAL, instead you should return IList<T>. Some people go to extent of returning only IEnumerable<T> because all you need is capability to enumerate. But then while doing it don't become astronaut architect.
In my applications I have figured out that returning IList<T> instead of List<T> pollutes my code base with codes like this:
//consider personCollection as IList<Person>
(personCollection as List<Person>).ForEach(//Do Something)
So I personally try to maintain a balance between returning interface or concrete object. If you ask me what I am doing right now, then I will tell you I am returning List<T>. I am influenced to not to become astronaut architect.
I always use DTOs, never DataTable. But I only use them to transfer from BL to DL and the other way around. My presentation layers are often only aware of the business and service layers in case of service oriented.
The benefits I can see to use DTOs rather than datatables:
easy refactoring
easy diagram production
cleaner more readable code, especially in the DAL's unit tests
By definition a DTO is a data transfer object, used to (wait for it) transfer data from one layer to another.
DTOs can be used across all layers and I have used them well with web services.

name of class that manipulates the entities

i have a general question regarding naming convention.
if I separate the data and operations into two separate classes. one has the data elements (entity), the other class manipulates the entity class. what do we usually call that class that manipulates the entity class?
(the entity I am referring to has nothing to do with any kind of entity framework)
manager? controller? operator? manipulator?
thanks in advance
It depends on what kind of operations you're doing on those data contracts/entities. Here are some of my conventions. Let's use the example of a Fruit entity (and I'm not trying to imply these are all static methods, just pseudocode):
Repository: provides CRUD operations on a piece of fruit
FruitRepository.Save(Fruit item);
Manager: operations outside of simple CRUD.
InventoryManager.ShipFruit(Fruit[] items, string address);
Controller: reserved for use in the interface, as in Model-View-Controller. Makes interface or flow decisions how to display or operate on fruit.
FruitController.ShowDetails(string fruitId);
Processor: used on operations that are "batched" together. Often these are long-running or done offline.
FruitProcessor.RemoveSeeds(Fruit[] lotsOfFruit);
Manipulator: provides specific operations on a single entity or a collection of them.
FruitManipulator.PeelFruit(Fruit item);
Provider: provide more generalized or global operations.
FruitProvider.GetAllTypesOfFruit();
FruitProvider.IsInSeason(string fruitName);
Exporter: Convert some fruit into a format intended for file storage or perhaps transfer.
FruitExporter.Save(string spreadsheet);
Analyzer: Provides results about an individual piece of fruit or a quantity.
FruitAnalyzer.Weigh(Fruit[] items);
Service: exposes functionality in a loosely coupled or remotely accessible kind of way.
Assembler: Creates fruit by combining different data sources.
FruitAssembler.Combine(string speciesFile, string quantitiesFile);
Factory: responsible for creating/instantiating fruit.
FruitFactory.CreateApple(); // red delicious, McIntosh, etc
Builder: Provides a way to build up fruit by individual parts/properties.
FruitBuilder.AddSeeds(5); FruitBuilder.AddStem();
These are all somewhat loose. The main goal is to stay consistent within your own codebase and avoid conflicts with the technologies you're using-- ie. don't have a lot of Controller classes that aren't controllers if you're doing ASP.NET MVC.
I usually go with Manager.
Call it whatever you are comfortable with, just make sure you use that name consistently throughout your project. The closest thing we have is a Capability or a Receiver but even then these aren't quite what you're talking about.
However.
Do you have a specific reason for separating the data from the methods? Unless you talking about a class and its factory I'd be really surprised if this separation is truly warranted.
Let's reason like following:
If the logic uses only one entity, move it to the entity itself (See rich domain model vs. anemic domain model).
So most of these classes are those which implement logic which deal with more than one entity, hence represent a collaboration.
Such class should not be named according to their responsibility. A technical term such as manager, controller, manipulator, etc. can still be use for naming convention, but the important part is first part of the name.
Example:
Entities: Product and Customer
Collaboration between the two: PurchaseService <-- what's important is Purchase, not Service
I separate the data and operations into two separate classes.
Don’t. This flies in the face of object-oriented design.

Categories