Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Encapsulating code in business objects almost always means better code

5.00/5 (2 votes)
18 Jan 2012CPOL1 min read 14.8K  
Good examples of better coding are not always easy to find, but here is one.

Good examples of better coding are not always easy to find, but here is one. A good coding principal is to encapsulate business logic in business objects instead of including business logic in the user interface. This is the foundation of coding using object oriented principles. One specific example is to compare these two ways to write the same code:

C#
1: buttonDelete_click()
2: {
3:     If myObject.HasChildren then
4:         ShowMessage("You can't delete an object with children.")
5:     End if
6: }
7:
8: buttonDelete_click()
9: {
10:     If myObject.AllowDelete = False then
11:         ShowMessage(myObject.ReasonDeleteNotAllowedMessage)
12:     End if
13: }

The first code sample may be the first to come to mind, but the first solution that comes to mind is often not the best. The second code sample is superior because it places the logic for AllowDelete inside the business object, and thus it makes that logic re-usable in other places. Perhaps you have an import utility that could use the same logic, or perhaps you want to write unit tests. In the second example, you can write unit tests to make sure that the AllowDelete property is being set correctly; but the first example would require UI testing to confirm this.

In my example, the code inside of the .AllowDelete property probably looks like this:

C#
1: Public bool AllowDelete()
2: {
3:     If (this.HasChildren == true)
4:         Return false;
5:     End if
6: }

By placing this logic in the business object, it would be easy to expand it later and the additional logic would apply to all user interface and batch processing code that uses it.

Any time you can encapsulate some logic within an object, it is probably worth the small additional amount of time to do so.


License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)