Business Objects, some thoughts

Business Objects?

Whether to use business objects seems to be a decision in .NET development that doesn’t appear to have been made unilaterally although it is something I expected would have been. I personally see great advantage in the idea of Business Objects.
The general idea of business objects, incase people don’t know the term, is segregation of "bussiness logic" from "presentation logic". Business Logic is a term banded about which, to me, means: The logic involved in the business process your system is undertaking. For example, if you have a system managing the process of loan applications, they will need to be logic in your system for deciding which interest rate the customer will have, working out the monthly payment and such things. For now, lets take the example working out the payment for a set of loan details (amount, rate, term etc) in a winforms app. The basic design which people normally use before actually thinking about business objects or other design patterns is to have a calculation screen with some input boxes for a user to key in the required information. Then they would hit a button on the form with code behind it similar to the following:
private void button1_Click(object sender, EventArgs e)
 double term = double.Parse(textbox1.Text);
 double loanAmount = double.Parse(textbox2.Text);
 double rate = double.Parse(textbox3.Text);
 double repaymentAmount = /* Formulae for working out repayment payment */ 
 textbox5.Text = repaymentAmount.ToString();

The above code will work for them but isn’t a good design. The obvious problem is that if you also have to make an ASP.NET interface to your application, you will need to find this code behind this form and copy it to run behind a button on your web page. This isn’t to hard but it now means you have two copies of this code to support when there is a change that needs to happen or if you have to perform this logic on another screen, you would need to create a 3rd or 4th copy. Obviously this is not a good design.
What is the next step in designing this one function then? Well most people I see would have shipped this code into a function in a class called something like ‘LoanCalculator’ and then they could just copy that class between windows application and web based application. If they were smart and used source control, they could even share it between the source control projects to help up dates propogate.
If they were a bit smarter then they would put this class in a new project named something like Utilities and then they could add a reference from both applications to this assembly and call the same code from both UI’s. They have now got round the most obvious maintenance issue as they only have one copy of the code to change and all 2,3, or 4 places in their code calls the same one.
Whats wrong with this now then?
Well, the next step in our imaginary systems evolution is that our loans get more complex and we now need have a different type of loan with a slightly different method for payment calculation, part and part loans for example. There are to ways to handle this now, you can change the code where you call the function to split the part and part into its two bits and then call the same function ones for each bit, or option 2, you can extend the parameter list for your utility function to take all the information you now need to do the maths.
The first option once again has the issue that you are now maintaining business logic in several different places in the UI code and would need to rewrite all of this to port the windows application to a new web interface. Option 2 solves this again in part but now you have to go round all the places where you call the function and change the call to pass the new information.
So how do you get round that?
Business Objects. Say we made a business object called Loan. We could give it properties and methods for doing things related to loans and it would group all the of information entered into textboxes into a single usable object. We could then change our utility method to take in a Loan object. That would stop us need to change the parameters in all the different places in the UI again. When the functions information need change, it could just get the different information from the loan object which now contains all loan related information.
One step further we could take on the business object design is to add a property to the loan object called MonthlyPayment. This property could call the function in the get and even cache the result until some vital loan information changes. This would not only remove the need for the UI to know where to go to calculate the payment, but would increase efficiency in working out the payment.
Now when we need to port our winforms to webforms, we only need to worry about presentation issues as when we need to display the payment for the loan, we just ask the loan what its payment is.
This simplication of the UI should be the dream for all developers. It opens up doors for all kind of new things like having your code accessible through winforms, webforms, webservices any other way you can think of without re-implementing large chunks of code. The greatest benefit has to be with testing.
Its very hard to automate the testing of a UI whereas a simple business object can be tested with unit tests, or tied up to a small winform as a test harness. Also when the code it atached to a new UI, you only need to test the interface as you already tested the actual maths last time. It helps reduction and reuse of code and makes it easier to find bugs and fix them as there should only be one part in the codebase where a piece of business logic is coded.

What about data access?

The obvious target of business objects it to simplify the code in the UI of your application. Therefore we split your code into two layers/tiers, the presentation layer which is the winforms code for putting buttons on forms etc, and the business layer which is responsibly for holding information about business entities and making business type decisions. This isnt a complete application though as any non trivial application is more than likely going to need to save data to disk and retrieve it at a later point. This is normally a database and the question now is what do we do to get our business objects in and out of the database.

They are a couple of ways to do data access with business objects all with some pros and cons. The first methods which is possibly the simplest one to come up with is that the business objects all have functions like Save() and Load(someid) which copy them into and out of a database via stored procedure calls or (god forbid) inline sql. This effectively gives you a 3 tier application (Presentation, Business, Database). It means all you database saving code is abstracted (hidden) from the UI so the UI can just all Save() and the object is saved. This is fine for small, never to scale applications in my opinion as it traps the business logic into a specific database implementation on an accessible machine. If the business objects are used in a client server application then the client machine and user will need to have access to the database rather then being able to have a single central server complete the save. It also makes updates harder as you need to depl

The second possibility is to introduce a 4th layer to abstract the interaction with the database away from the business layer with the same benefits as abstracting the business logic from the UI layer. The business objects can then pass all of their relevant information over to the "Data Access" layer by means of a function call and the data access can map that to a call to a stored procedure. The Data Access Layer should be designed to provide a good interface to the database underneath it.
Retrieves from the database can return datatables containing datarows or  basic stucts containing the information held in the BO layer. There is some division of opinion between these two approaches as some people feel datatables are database like, my personal opinion is tables are a real world way of representing information. Therefore the can be used in business layers in the same way as arrays and mulitdimensional arrays. They also dont have to represent DB tables, they could be aggregated data or the result of joins/unions/pivots etc.
The benefits of this as a good seperation of business logic and data access so the change the database provider, you can swap out just the DAL with a new one and the business layer should be oblivious. It would also allow you to go SOA as the DataAccess layer could call web services or WCF services to perform the save. The abstraction for the business layer is still there.

The third option is to introduce a seperate set of classes, or sometimes just one class that effectively act as a "Persistance Service" to the Business Layer. These classes have a good knowledge of the Business Layer objects data, possibly through the business layer implementing interfaces to describe the data held in the objects or by them subclassing some data only classes. The layer then reads through the business objects and issue database commands. This design is very SOA and allows the data access to be completly seperated from the business layer. but not the other way round. It doesnt allow for anything to access the DAL logic without using the business logic.

My prefered option is number 2. I believe it gives the most abstraction for the lowest amount of code and still fits with a nice layered approach. I have even written a code generator for my way of building the BLL and DAL which I might post up with a future blog about home made tools.

Is there a standard pattern for this?

There are a few design patterns and frameworks for business objects floating around on the web. Many of them are just as good as one another. Most are people posting up how they do theirs and some people go a whole lot further. I am going to list a few of these here as a starter for ten for people to look at and see which one they prefer. I personally have my own way of doing business objects which I will post up in more detail in a future blog entry. So anyway here is my list of Business Object patterns to look at, I will add more as I find them so please feel free to post more up to me.:

  • CSLA.NET 2: Rocky Lhotka has derived this business object framework and design for use in .NET 1.1 and 2 (different versions but same framework). He has even gone as far as to write a C# and a VB.NET book guiding you through making business objects in CSLA. Rocky is very well respected (including MVP) and this framework definately works. He also uses winforms databinding well so it you are at step 1 then this should take you all the way.
  • Design Pattern Framework 2.0: I haven’t looked at this framework much as you need to buy it up front before seeing it. It does however get some good recommendations. They are a training company that have effectively collated a lot of different patterns and code samples into a comprehensive coarse for building systems with design patterns.


This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s