良好的类设计的例子 [英] Good class design by example
问题描述
我试图找出最好的方法来设计一个类,它的属性保存在数据库中。让我们举一个 Person
的一个基本例子。要创建一个新的人并将它放在数据库中,我想让 DateOfBirth
属性是可选的(即在数据库中为NULLable)。
I am trying to work out the best way to design a class that has its properties persisted in a database. Let's take a basic example of a Person
. To create a new person and place it in the database, I want the DateOfBirth
property to be optional (i.e. NULLable in the DB).
这是我的示例代码:
namespace BusinessLayer
{
class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
}
}
我不确定字段是否应该公开或不公开。我应该这样做:
I'm unsure as to whether the fields should be public or not. Should I do it like this:
class Program
{
static void Main(string[] args)
{
Person person1 = new Person("Kate","Middleton",null);
}
}
或这样:
class Program
{
static void Main(string[] args)
{
Person person1 = new Person();
person1.FirstName = "Kate";
person1.LastName = "Middleton";
}
}
我也想知道我应该如何处理该类的可选属性。填充字段后,如何将它们保存到DB?我有一个DatabaseComponenet类来保存信息。
I'm also wondering how I should be dealing with the optional properties of the class. Once the fields have been populated how do I then save them to the DB? I have a DatabaseComponenet class to save the information. How do I deal with the optional when saving to the database?
所以,我会这样做:
public int Save()
{
int personId;
personId = DatabaseComponent.InsertPerson(FirstName, LastName, DateOfBirth);
return personId;
}
感谢任何帮助!
推荐答案
首先,我将两个不同的公共构造函数赋给Person:
First, I'd put two distinct public constructor to Person:
namespace BusinessLayer
{
class Person
{
public Person(string firstName, string lastName): this(firstName, lastName, DateTime.Now)
{}
public Person(string firstName, string lastName, DateTime birthDate)
{
FirstName = firstName;
LastName = lastName;
DateOfBirth = birthDate;
}
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
}
}
this allows you to write both
var p = new Person("Marilyin", "Manson");
var p2 = new Person("Alice", "Cooper", new DateTime(...));
和
var p = new Person { FirstName="Marilyn", LastName="Manson" };
我不明白为什么你应该只限制一个表单。
I can't see why you should limit to only one form.
至于DatabaseComponent,我强烈建议你写一个方法,让你保存一个Person,而不是隐式声明的签名。
As for the DatabaseComponent I'd strongly suggest to write a method that allows you to save a Person instead of the signature you are implicitly declaring.
这是因为,如果有一天改变了Person定义的方式,你可能需要改变每个调用 Save()
方法的代码。通过保存一个Person,你只需要改变 Save()
实现。
That's because, should one day change the way a Person is defined, you'd probably have to change the code in each point you invoke Save()
method. By saving just a Person, you only have to change the Save()
implementation.
要使用ORM吗?
这篇关于良好的类设计的例子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!