0

I want to define a class in C#. I found these two methods:

Method 1 :

public class customer
{
   private string _name ;
   private string _family;

   public string Name
   {
      get { return __name; }
      set { if(value=="")message(" نام کارخانه را وارد کنید ");
          _name= value; }
   }

   public string Family
   {
      get { return _family; }
      set { if(value=="")message(" نام کارخانه را وارد کنید ");
          _family= value; }
   }

   public void AddCustomer() 
   {
      add _name and _family to database
   }
}

Method 2:

public class customer
{
   public void AddCustomer(string name ,string family) 
   {
      //code to add a customer
   }
}

I am confused; which one should be used, and what the difference between these two methods? Which one is better and is more commonly used?

2
  • This is more of a matter of preference and context. Commented Feb 6, 2014 at 18:44
  • 2
    Except that in method 1, _name and _family are private. How would they ever get set? Commented Feb 6, 2014 at 18:45

2 Answers 2

10

I wouldn't do either of these. You're introducing a method called AddCustomer on a customer class. I wouldn't expect a Customer to know about a database - I'd expect some sort of data access layer or customer repository to know about it instead.

A Customer may well have a constructor taking a name and family, or whatever, and then your CustomerRepository would have an Add(Customer) method.

To think of it another way: I would expect it to make perfect sense to use the Customer class (which should have a capital C to conform with .NET naming conventions) without any knowledge of a database, therefore it probably shouldn't know about the database.

Admittedly I do break these own rules myself in terms of custom XML serialization, allowing a static FromXElement method and an instance method of ToXElement... but at least that doesn't involve external dependencies.

Sign up to request clarification or add additional context in comments.

1 Comment

I couldn't have said it any better myself, +1.
2

First of all, _name and _family are private in method 1. There is no way to set those. You would need to define them as public.

Second, that is a very loaded question. Sometimes it makes sense to encapsulate members and sometimes you want to pass them inline in the method call itself. There is no "better way".

2 Comments

So when we should pass it in inline and when it should be encapsulate?
I can't condense years of programming experience down to an answer on StackOverflow. Trial and error are your best friends now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.