我实际上发现给这个线程一个标题很难。我目前在C#中使用网络编程课程。我们已经完成了使用Windows Forms和Entity Frameworks使用存储库服务模式构建简单库的任务。在课堂上验证项目的好习惯。
我有一个表单,我将一个Book实体添加到数据库,也就是将一本新书添加到库中。我在这个课上做的事情是检查这些字段以确保用户实际输入了一些文本,ISBN号码是正确的格式,这本书不存在....你明白了。我一直试图决定的是如何构建流程的执行方式。当我点击提交新书时,我最初在on_click方法中有一堆if语句,用于验证。
private void btn_bookSubmit_Click(object sender, EventArgs e)
{
string newBookName = this.tb_bookTitle.Text;
string newBookAuthor = this.tb_bookAuthor.Text;
string newBookISBN = this.tb_bookISBN.Text;
string description = this.tb_bookDesc.Text;
if (bookIsNotValid(newBookISBN, newBookName, newBookAuthor))
{
MessageBox.Show(this.validationError);
return;
}
if (bookService.BookTitleExists(newBookName))
{
MessageBox.Show("A book by this title already exists in the library");
return;
}
if (bookService.ISBNExists(newBookISBN))
{
MessageBox.Show("This ISBN belongs to another book in the library. Please double check the ISBN number and try again");
return;
}
if (this.authorService.doesAuthorExistByName(newBookAuthor))
{
DialogResult result = MessageBox.Show
("This author does not exist in the database. Do you want to add this author?",
"Author Does not Exist", MessageBoxButtons.YesNo);
if (result == DialogResult.Yes) this.authorService.addAuthor(newBookAuthor);
if (result == DialogResult.No)
{
MessageBox.Show("New book entry cancled. In order to enter a new book into the system a valid Author must be specified");
return ;
}
}
bookService.addBook(newBookISBN, newBookName, newBookAuthor, description);
MessageBox.Show(
string.Format("{0} succesfully added to the library", newBookName),
string.Format("{0} added Successfully", newBookName),
MessageBoxButtons.OK);
this.clearFields();
}
我心想:这是一种方法的很多代码。所以我把它分解成更多的私有函数在窗体类,并最终与这个样子,而不是一个方法:
private void btn_bookSubmit_Click(object sender, EventArgs e)
{
string newBookName = this.tb_bookTitle.Text;
string newBookAuthor = this.tb_bookAuthor.Text;
string newBookISBN = this.tb_bookISBN.Text;
string description = this.tb_bookDesc.Text;
if (!isBookValid(newBookISBN, newBookName, newBookAuthor)) return;
if (!isTitleValid(newBookName)) return;
if (!isISBNvalid(newBookISBN)) return;
if (!isAuthorNew(newBookAuthor)) return;
bookService.addBook(newBookISBN, newBookName, newBookAuthor, description);
MessageBox.Show(
string.Format("{0} succesfully added to the library", newBookName),
string.Format("{0} added Successfully", newBookName),
MessageBoxButtons.OK);
this.clearFields();
}
现在我已经在我的课了不少方法。这是不错的做法吗?它看起来对我来说更加清洁,但也许在浏览我的课程时,很难通过方法进行筛选,而不是在一个函数中查看所有内容。我想过的另一件事是将所有的验证移入一个函数而不是很多,但是接下来我必须处理布尔返回以及如何以不同的方式停止我的函数。
我一直在研究我的程序2年了,已经试过了,javascript,php,html5,C++,C,现在c#试图找出我最喜欢的东西。我从所有的编程中获得最多的是我喜欢美丽而高效的代码。我可能还无法做到这一点,但我正在尽我所能去学习它。因此,您可能会注意到的任何其他垃圾操作请让我知道。到目前为止,在课堂上一切正常,我真正的问题是,我是如何执行我的验证过程好吗?好?低劣?慢?
嗯,我可以在我的Book Service中轻松添加一个Add方法,它将一本书作为参数,但我认为在服务类中创建新书籍实例更合适。我还认为任何“消息框或反馈”都应包含在界面中,而不是服务类中。实际的验证逻辑本身发生在服务层,只要检查数据库是否有重复等等。但是在我的界面中,我使用对服务层的访问来获取布尔值来作为是否存在例如重复的答案。 –
是的,我明白你来自哪里,我最近一直在努力。看起来你仍然可能遇到一种情况(假设你在某个服务器上有一个数据库后端),在你检查的时间和你保存的时间之间可能会发生变化。我想你可以在那里处理一个异常并显示消息或其他东西。 –