Reputation: 311
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?
Upvotes: 0
Views: 175
Reputation: 11308
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".
Upvotes: 2
Reputation: 1500785
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.
Upvotes: 10