C# Design Patterns – Should Code Be in Business Objects or Separate Class?

asp.netcdesign-patternsdomain-driven-design

I have created a small application which has a three tier architecture and I have business object classes to represent entities such as User, Orders, UserType etc. In these classes I have methods that are executed when the Constuctor method of, for example, User is called. These methods perform calculations and generate details that setup data for attributes that are part of each User object.

Here is the structure for the project in Visual Studio:

enter image description here

Here is some code from the business object class User.cs:

Public Class User
{
    public string Name { get; set; }
    public int RandomNumber { get; set; }
    etc

        public User
        {
            Name = GetName();
            RandomNumber = GetRandomNumber();
        }

        public string GetName()
        { 
          ....
          return name;
        }

        public int GetRandomNumber()
        {
           ...
           return randomNumber;
        }

    }

Should this logic be included in the Business Object classes or should it be included in a Utilities class of some kind? Or in the business rules?

Best Answer

The theory:
A class should be responsible for its data and know what to do with its data. Any methods that the class needs to enforce that responsibility should be within the class.

In Practice:
So the class will have User.Name and it should also have User.GetName(), User.GetFirstName(), User.GetLastName() as Name belongs to the User and the User should know how to manipulate its Name property.
You should not have a UserUtils.GetFirstNameFromName() for example.

Let's also say that we have User.TaxID and there should be appropriate get / set statements in order to retrieve that property. However, we should not have User.CreateTaxID as the User class wouldn't / shouldn't have anything to do with getting a foreign identifier to the class.
Instead, this is a great case for UserUtils.CreateTaxID.

So the answer to your question is both "yes" and "no" depending upon what the functions are actually doing.