3

I have been learning C# for the last year or so and trying to incorporate best practices along the way. Between StackOverflow and other web resources, I thought I was on the right track to properly separating my concerns, but now I am having some doubts and want to make sure I am going down the right path before I convert my entire website over to this new architecture.

The current website is old ASP VBscript and has a existing database that is pretty ugly (no foreign keys and such) so at least for the first version in .NET I do not want to use and have to learn any ORM tools at this time.

I have the following items that are in separate namespaces and setup so that the UI layer can only see the DTOs and Business layers, and the Data layer can only be seen from the Business layer. Here is a simple example:

productDTO.cs

public class ProductDTO
{
    public int ProductId { get; set; }
    public string Name { get; set; }

    public ProductDTO()
    {
        ProductId = 0;
        Name = String.Empty;
    }
}

productBLL.cs

public class ProductBLL
{

    public ProductDTO GetProductByProductId(int productId)
    {
        //validate the input            
        return ProductDAL.GetProductByProductId(productId);
    }

    public List<ProductDTO> GetAllProducts()
    {
        return ProductDAL.GetAllProducts();
    }

    public void Save(ProductDTO dto)
    {
        ProductDAL.Save(dto);
    }

    public bool IsValidProductId(int productId)
    {
        //domain validation stuff here
    }
}

productDAL.cs

public class ProductDAL
{
    //have some basic methods here to convert sqldatareaders to dtos


    public static ProductDTO GetProductByProductId(int productId)
    {
        ProductDTO dto = new ProductDTO();
        //db logic here using common functions 
        return dto;
    }

    public static List<ProductDTO> GetAllProducts()
    {
        List<ProductDTO> dtoList = new List<ProductDTO>();
        //db logic here using common functions 
        return dtoList;
    }

    public static void Save(ProductDTO dto)
    {
        //save stuff here
    }

}

In my UI, I would do something like this:

ProductBLL productBll = new ProductBLL();
List<ProductDTO> productList = productBll.GetAllProducts();

for a save:

ProductDTO dto = new ProductDTO();
dto.ProductId = 5;
dto.Name = "New product name";
productBll.Save(dto);

Am I completely off base? Should I also have the same properties in my BLL and not pass back DTOs to my UI? Please tell me what is wrong and what is right. Keep in mind I am not a expert yet.

I would like to implement interfaces to my architecture, but I am still learning how to do that.

jpshook
  • 4,834
  • 6
  • 36
  • 45
  • At my work, we maintain a project that has an eerily similar architecture and knowing what I know now, I would try to suck it up and use an ORM (I like NHibernate). I am probably biased, but when you start building your architecture like that, you start having classes that just pass info to the next layer. NHibernate has very good query APIs which will buy you a lot and there is no rule saying you *have* to have foreign keys in order to use NHibernate (although they are obviously helpful). – dana Feb 28 '11 at 20:31
  • Trying to learn NHibernate when I don't really have a firm grip of c#/ASP.net is a bit more than I want to take on right now. Plus, the database table names and field names are all across the board. Thanks for your comment. – jpshook Feb 28 '11 at 20:36

4 Answers4

2

Cade has a good explination. In order to avoid the Anemic domain model some things you could consider doing:

  • make the DTO object your domain object (just call it "Product")
  • IsValidProductId could then be on the Product, and when the setter is called you could verify that it is valid, and throw if it is not
  • implement some sort of rules about the Name
  • if there are any other objects that interact with Product we could have more interesting things to talk about
Alex Lo
  • 1,299
  • 8
  • 10
  • So what about when I need a list of 5,000+ items, do I really want to incur the costs of 5000+ copies of all the BLL validations and such? Also, why would I pass a object with other methods to my DAL? Shouldn't I just be passing the data? Should it be more that my BLL should become just Products and then use my DTOs to pass data between it and the DAL? – jpshook Feb 28 '11 at 20:41
  • @Developr If you need a list of 5000+ items - that's a different problem. In that case, you need to look at the process which is going to operate on 5000 items and decide if it can be done closer to the database (i.e. in SQL), and if not, is the operation able to operate on objects which are lighter-weight versions (what I call digests), perhaps for a drop down or lookup cache (where you only need an ID and description). A domain model is a network of classes which encompass the entire problem domain. So one class is really not enough to say the design is bad/anemic. – Cade Roux Feb 28 '11 at 20:53
  • what are the validations that you are worried about running? it has more methods than your DAL needs but so what? you could make a DAL-only interface to it if you want. "shouldnt i just be passing the data?" => no, you want objects with behavior. – Alex Lo Feb 28 '11 at 20:58
  • @Alex Lo - So, basically, I need to combine my BLL and DTO? Or are you saying I should just rename my DTO to Products and add some methods to it? How do I know what methods would go in the BLL then? – jpshook Feb 28 '11 at 21:08
  • @Cade Roux - I have lots of other classes just like those.. most are by database table but some are interconnected. – jpshook Feb 28 '11 at 21:08
  • I would start with having a "Product" and then a "ProductMapper" or "ProductPersistanceService". The Product has data and biz behavior, and if you want seperate, a seperate BBL interface and Data interface. the "ProductPersistanceService" gets the Products from the database and saves them. – Alex Lo Feb 28 '11 at 21:12
2

Things you want to consider adding: validation, property change notification, data binding, etc... One common issue when separating each class in multiple classes (DAL, BLL, etc...) is often you end up with a lot of code you need to duplicate. Another problem is if you need some intimacy between those classes, you'll have to create internal members (interfaces, fields, etc.)

This is what I would do, build a unique consistent Domain Model, something like this:

public class Product: IRecord, IDataErrorInfo, INotifyPropertyChanged
{
    // events
    public event PropertyChangedEventHandler PropertyChanged;

    // properties
    private int _id;
    public virtual int Id
    {
        get
        {
            return _id;
        }
        set
        {
            if (value != _id)
            {
                _id = value;
                OnPropertyChanged("Id");
            }
        }
    }

    private string _name;
    public virtual string Name
    {
        get
        {
            return _name;
        }
        set
        {
            if (value != _name)
            {
                _name = value;
                OnPropertyChanged("Name");
            }
        }
    }

    // parameterless constructor (always useful for serialization, winforms databinding, etc.)
    public Product()
    {
        ProductId = 0;
        Name = String.Empty;
    }

    // update methods
    public virtual void Save()
    {
       ValidateThrow();
       ... do save (insert or update) ...
    }

    public virtual void Delete()
    {
       ... do delete ...
    }    

    // validation methods
    public string Validate()
    {
       return Validate(null);
    }

    private void ValidateThrow()
    {
      List<Exception> exceptions = new List<Exception>();
      SummaryValidate(exceptions,memberName);
      if (exceptions.Count != 0)
         throw new CompositeException(exceptions);
    }

    public string Validate(string memberName)
    {
      List<Exception> exceptions = new List<Exception>();
      SummaryValidate(exceptions,memberName);
      if (exceptions.Count == 0)
        return null;

      return ConcatenateAsString...(exceptions);
    }

    string IDataErrorInfo.Error
    {
      get
      {
         return Validate();
      }
    }

    string IDataErrorInfo.this[string columnName]
    {
      get
      {
        return validate(columnName);
      }
    }

    public virtual void SummaryValidate(IList<Exception> exceptions, string memberName)
    {
       if ((memberName == null) || (memberName == "Name"))
       {
         if (!... validate name ...)
            exceptions.Add(new ValidationException("Name is invalid");
       }
    }

    protected void OnPropertyChanged(string name)
    {
       OnPropertyChanged(new PropertyChangedEventArgs(name));
    }

    // property change notification
    protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        if ((PropertyChanged != null)
            PropertyChanged(this, e);
    }

    // read from database methods
    protected virtual Read(IDataReader reader)
    {
      Id = reader.GetInt32(reader.GetOrdinal("Id"));
      Name = = reader.GetString(reader.GetOrdinal("Id"));
      ...
    }

    void IRecord.Read(IDataReader reader)
    {
      Read(reader);
    }

    // instance creation methods
    public static Product GetById(int id)
    {
        // possibly use some cache (optional)
        Product product = new Product();
        using (IDataReader reader = GetSomeReaderForGetById...(id))
        {
            if (!reader.Read())
              return null;

            ((IRecord)product).Read(reader);
            return product;
        }
    }

    public static List<Product> GetAll()
    {
        // possibly use some cache (optional)
        List<Product> products = new List<Product>(); // if you use WPF, an ObservableCollection would be more appropriate?
        using (IDataReader reader = GetSomeReaderForGetAll...(id))
        {
            while (reader.Read())
            {
              Product product = new Product();
              ((IRecord)product).Read(reader);
              products.Add(product);
            }
        }
        return products;
    }
}

// an interface to read from a data record (possibly platform independent)
public interface IRecord
{
  void Read(IDataReader reader);
}
Simon Mourier
  • 132,049
  • 21
  • 248
  • 298
  • So product can return itself? Why pass the reader, even though it is a IDataReader, seems off to me. Unfortunately, I can only follow about 1/4 of what you said in there... – jpshook Feb 28 '11 at 21:25
  • @Developr - yes, in this case, Product returns itself. Why not? There are many examples of this in the .NET Framework itself. – Simon Mourier Feb 28 '11 at 21:41
  • i disagree with making the object handle its own persistance. in my proposal i suggest that the object persistance is done by another class - this would help if you ever do transition to using an ORM, as the original object is still useful by itself. – Alex Lo Feb 28 '11 at 21:56
  • @Alex - well, I'm sure some people will disagree :-) I don't need any ORM. – Simon Mourier Feb 28 '11 at 22:29
  • @Simon, yes I am sure, and for small problems I'm sure it works well. the OP hints at using an ORM at some point so i mentioned that as a weakness of this approach. how do you handle objects that reference other objects using your scheme? – Alex Lo Feb 28 '11 at 22:35
  • @Alex - Well, my experience shows this can actually work for any project size. Concerning referenced objects, I would use the id of these other objects (so for example 1 property for the ref'd object itself and N property for the N ref'd object's keys), nothing fancy here. – Simon Mourier Feb 28 '11 at 22:42
1

Anemic domain is when a product or other class doesn't really implement anything more than data setters and getters - no domain behavior.

For instance, a product domain object should have some methods exposed, some data validations, some real business logic.

Otherwise, the BLL version (the domain object) is hardly better than a DTO.

http://martinfowler.com/bliki/AnemicDomainModel.html

ProductBLL productBll = new ProductBLL();
List<ProductDTO> productList = productBll.GetAllProducts();

The problem here is that you are pre-supposing your model is anemic and exposing the DTO to the business layer consumers (the UI or whatever).

Your application code generally wants to be working with <Product>s, not any BLL or DTO or whatever. Those are implementation classes. They not only mean little to the application programmer level of thought, they mean little to domain experts who ostensibly understand the problem domain. Thus they should only be visible when you are working on the plumbing, not when you are designing the bathroom, if you see what I mean.

I name my BLL objects the name of the business domain entity. And the DTO is internal between the business entity and the DAL. When the domain entity doesn't do anything more than the DTO - that's when it's anemic.

Also, I'll add that I often just leave out explcit DTO classes, and have the domain object go to a generic DAL with organized stored procs defined in the config and load itself from a plain old datareader into its properties. With closures, it's now possible to have very generic DALs with callbacks which let you insert your parameters.

I would stick to the simplest thing that can possibly work:

public class Product {
    // no one can "make" Products
    private Product(IDataRecord dr) {
        // Make this product from the contents of the IDataRecord
    }

    static private List<Product> GetList(string sp, Action<DbCommand> addParameters) {
        List<Product> lp = new List<Product>();
        // DAL.Retrieve yields an iEnumerable<IDataRecord> (optional addParameters callback)
        // public static IEnumerable<IDataRecord> Retrieve(string StoredProcName, Action<DbCommand> addParameters)
        foreach (var dr in DAL.Retrieve(sp, addParameters) ) {
            lp.Add(new Product(dr));
        }
        return lp;
    }

    static public List<Product> AllProducts() {
        return GetList("sp_AllProducts", null) ;
    }

    static public List<Product> AllProductsStartingWith(string str) {
        return GetList("sp_AllProductsStartingWith", cm => cm.Parameters.Add("StartsWith", str)) ;
    }

    static public List<Product> AllProductsOnOrder(Order o) {
        return GetList("sp_AllProductsOnOrder", cm => cm.Parameters.Add("OrderId", o.OrderId)) ;
    }
}

You can then move the obvious parts out into a DAL. The DataRecords serve as your DTO, but they are very short-lived - a collection of them never really exists.

Here's a DAL.Retrieve for SqlServer which is static (you can see it's simple enough to change it to use CommandText); I have a version of this which encapsulates the connection string (and so it's not a static method):

    public static IEnumerable<IDataRecord> SqlRetrieve(string ConnectionString, string StoredProcName,
                                                       Action<SqlCommand> addParameters)
    {
        using (var cn = new SqlConnection(ConnectionString))
        using (var cmd = new SqlCommand(StoredProcName, cn))
        {
            cn.Open();
            cmd.CommandType = CommandType.StoredProcedure;

            if (addParameters != null)
            {
                addParameters(cmd);
            }

            using (var rdr = cmd.ExecuteReader())
            {
                while (rdr.Read())
                    yield return rdr;
            }
        }
    }

Later you can move on to full blown frameworks.

Cade Roux
  • 88,164
  • 40
  • 182
  • 265
  • Yes, I already know how to use Google... Looking for some responses that can help me move forward. – jpshook Feb 28 '11 at 20:32
  • @Developr I'm not sure what your point is - you've only presented one class and left out the business logic, but indicate that some exists - therefore it may not really be anemic, depending upon what you have left out. – Cade Roux Feb 28 '11 at 20:48
  • @Cade Roux - Save, Get, Update, Validate, etc <- Is this not business logic? – jpshook Feb 28 '11 at 21:09
  • I do understand what you are saying about just using Product, but then I would need mostly the same properties as my DTO repeated for my BLL, correct? How would the entity/domain object return itself from the DAL? or is that a separate service class? I just need a good concrete way to do it that I can repeat and integrate. – jpshook Feb 28 '11 at 21:13
  • @Developr It _is_ business logic, so seems like Product not a good cadidate for being considered anemic. – Cade Roux Feb 28 '11 at 21:29
  • So, you are saying I should merge the DTO with the BLL and treat that as my entity? Or will I still need the DTO to carry data between my domain and DAL? – jpshook Feb 28 '11 at 21:30
  • @Developr I have updated my answer to show the IDataRecord from the DataReader being used as the DTO. – Cade Roux Feb 28 '11 at 21:53
  • Thanks Cade for helping.. It makes some sense. So if I want to still use the DTO and DAL to get/pass data between DAL and BLL/entity, it is ok, as long as I stop relying on the DTO in my UI and concentrate on the domain. So I will need to repeat most of my DTO properties in my BLL/entity/Domain object, correct? – jpshook Feb 28 '11 at 22:24
  • @Developr Anything coming from the DTO which which is part of the domain entity's public interface will need to be exposed appropriately, and anything which is internal can be private to the domain entity. Because a DTO is usually everything-public, I've been finding that the DataRecord is sufficient in that role, as I gave in my exmaple. So typically all I am implementing is stored procedures at the back end as the database interface changes and business objects and UI code - everything else is generic or code-generated. – Cade Roux Mar 01 '11 at 13:54
  • @Cade Roux - Do I need to setup a mapping layer to map the DTO to the POCO, or can my data layer have knowledge of the POCO and map directly to it? eg - when you have: static public List AllProducts() {} does the data layer map to the domain object or some transitional layer? I am not a big fan of stored procedures, so would rather use parameterized queries. Am I better off just moving to Entity Framework, Nhibernate or Linq2SQL for my data access? – jpshook Mar 22 '11 at 21:07
  • @Developr The Product can have knowledge of the DAL, but not the other way around. In my example, the DAL is very slim, just providing that retrieve. It can just as easily do a parameterized query as CommandText instead of a stored proc. DAL.Retrieve is going to yield an IEnumerable and Product knows how to make itself from an IDataRecord. I'll edit to show an example if DAL.Retrieve. – Cade Roux Mar 22 '11 at 21:26
  • @Developr I have a problem with people using frameworks without understanding the rationales for the issues they solve (and those they don't). It will eb better for you to at least see some of the issues underneath, so that when you reach pain points in someone else's abstraction, you'll be able to recognize it and perhaps get yourself out a little easier. – Cade Roux Mar 22 '11 at 21:31
  • @Cade Roux - Thanks for your continued support. Just to clarify, when you bring the IDataReader/Records back to your BLL/Domain object, doesn't the db connection stay open during all of that? Is there some way you are disconnecting it? Normally, in my current code, the DAL maps a reader to a DTO and returns that to the BLL. In your examples the BLL/DO actually submits the query to the DAL directly, correct? – jpshook Mar 23 '11 at 13:23
  • @Developr The DAL returns an IEnumerable which is treated as a "DTO". You are correct that in this implementation, an entire copy of the set of data is NOT made and then transferred as a whole - effectively only one row is transferred at a time between the layers (through the yield). This will reduce the working set, but could result in the connection being open longer if constructions of the objects is lengthy. There is a tradeoff here, but we are no longer constructing a DataSet or other DTO and THEN constructing the BO, we're just passing the IDataRecord. Less code, less RAM. – Cade Roux Mar 23 '11 at 13:44
  • @Developr You can always put more layers and more copies/serializations of things in any framework, but I think the overhead of copying an entire data set just so you can close the connection quickly before constructing the objects only makes sense if your objects are extremely complex and expensive to build. At that point, it seems like you wouldn't want to be building a lot of them anyway, so your connection time should not be an issue. If the connection for a single row pulls a lot of data, it's probably a BLOB and so simple I/O is the problem. – Cade Roux Mar 23 '11 at 13:47
  • @Developr In summary, "it depends" on your particular usage patterns. Obviously in a more physically separate multi-tier environment where the data is served through a service or portal, the entire thing needs to be serialized out to the consumer, since there is no persistent connection. At that point, hydrating full business objects may or not be reasonable. – Cade Roux Mar 23 '11 at 13:52
  • Also, with this solution the Domain objects are tightly coupled with the database. Our db is pretty legacy and has no naming conventions. I would probably need a mapping layer to decouple the db tables with the BO. – jpshook Mar 23 '11 at 18:40
  • @Developr - All the mapping would be done in private Product(IDataRecord dr) - how you do that is up to you. I tend to do it in code. A BO is a business object, it isn't going to correspond to every column in a table - particularly for lazy-loaded child collections or even simple things like flags or states. (i.e. DateInvoiced IS NULL maps to property bool IsInvoiced = False and property datetime InvoiceDate maybe throwing an exception) – Cade Roux Mar 23 '11 at 18:55
1

What others have said about using an ORM - as your model expands, you are going to have a lot of code repetition without one. But I wanted to comment on your "what about 5,000" question.

Copying a class does not create 5,000 copies of its methods. It only creates a copy of the data structures. There is no lost efficiency to having the business logic in the domain object. If some of the business logic is not applicable, then you could create subclasses that decorate the object for specific purposes, but the purpose of this is to create objects that match your intended use, not efficiency. An anemic design model is not more efficient.

Also, think about how you will use data in your application. I can't think of a single time I've ever used a method like "GetAllOfSomething()", except for maybe a reference list. What is the purpose of retrieving everything in your database? If it's to do some process, data manipulation, report, you should be exposing a method that performs that process. If you need to expose a list for some external use, like populating a grid, then expose an IEnumerable and provide methods for subsetting data. If you start with the idea that you work with complete lists of data in memory you'll have serious performance problems as the data grows.

Jamie Treworgy
  • 23,934
  • 8
  • 76
  • 119
  • I should have listed get all as get many... In my actual code I use ROW_Number and CTEs to do paging and such. – jpshook Feb 28 '11 at 21:17
  • Everything I read about nHibernate says it is extremely slow and I really wanted to learn the best way without just passing it on to a tool. The site is extremely large (think store with 1500 products plus streaming video with comments, forums, etc) and relatively high traffic (up to 500k uniques per month) – jpshook Feb 28 '11 at 21:20
  • OK - but don't return a list, return IEnumerable. It's far more flexible, and otherwise every single time you return a list, you will be iterating through it twice: once when it was created, then again when it's used outside the class. If you actually need a list, then you can just say `List myList = new List(someEntityThatReturnsIEnumerable)` -- which is probably identical cycle-for-cycle compared to `List mylist = someEntityThatReturnsList` – Jamie Treworgy Feb 28 '11 at 21:25
  • I haven't personally used nHibernate so I can't speak to that. But keep in mind that adding CPU power is cheap compared to writing code. Even at the scale you're talking, I bet you wouldn't have much trouble. But as you start to develop your model, e.g. looking at Simon Mourier's answer (which is a fine *model*), think about how much code is repeated in every single property for validations, database operations, exception handling. At least encapsulate common functionality that is part of the mapping into a class, which is really a very basic ORM implementation. – Jamie Treworgy Feb 28 '11 at 21:31