接上文
.NET languages
Listing 1. Under-Engineering:
Inexperienced programmers may not put enough thought into the code's intended use and exception handling.
// C# implementation
private bool FileExists()
{
if (System.IO.File.Exists(@"C:\MyFile.txt"))
return true;
else
return false;
}
' VB.NET implementation
Private Function FileExists() As Boolean
If System.IO.File.Exists("C:\MyFile.txt" Then
Return True
Else
Return False
End If
End Function
.NET languages
Listing 2. Over-Engineering:
While this method may handle every conceivable error, it's overkill for the business problem at hand.
// C# implementation
private bool FileExists(string fileName)
{
System.Diagnostics.Debug.Assert(
string.IsNullOrEmpty(fileName),
"The 'fileName' parameter must be passed " +
"into the FileExists method");
try {
return (System.IO.File.Exists(fileName));
}
catch (System.IO.DirectoryNotFoundException ex) {
throw new Exception("The directory from the file name: " +
fileName + " does not exist.", ex);
}
catch (System.IO.DriveNotFoundException ex) {
throw new Exception("The drive from the file name: " +
fileName + " does not exist.", ex);
}
catch (System.IO.PathTooLongException ex) {
throw new Exception("The path from the file name: " +
fileName + " is too long.", ex);
}
catch (Exception ex) {
throw new Exception("The file: " + fileName +
" was checked to see it is exists, but some unknown " +
"problem occurred when calling the File.Exists method", ex);
}
}
' VB.NET implementation
Private Function FileExists(ByVal fileName As String) As Boolean
System.Diagnostics.Debug.Assert( _
String.IsNullOrEmpty(fileName), _
"The fileName parameter must be passed into " & _
"the DoesFileExist method")
Try
Return (System.IO.File.Exists(fileName))
Catch ex As System.IO.DirectoryNotFoundException
Throw New Exception("The directory from the file name: " + _
fileName + " does not exist.", ex)
Catch ex As System.IO.DriveNotFoundException
Throw New Exception("The drive from the file name: " + _
fileName + " does not exist.", ex)
Catch ex As System.IO.PathTooLongException
Throw New Exception("The path from the file name: " + _
fileName + " is too long.", ex)
Catch ex As Exception
Throw New Exception("The file: " + fileName + _
" was checked to see it is exists, but some unknown " & _
"problem occurred when calling the File.Exists method", ex)
End Try
End Function
是的,在Listing 2中的代码是非常好的,而且通过尝试检查文件是否存在而解决了所有可能发生的问题,但是这个代码就是要解决业务问题的代码吗?是有可能的,这个代码只用简单的一个单一的catch块,其中包括文件名和从.NET返回的错误信息,这已经足够了。有些人花费大量时间来创建这个过度设计的方法并且还要测试它。有那些时间可以更好的用在解决业务问题的上面。
拥有强大,灵活而且可以再度使用的软件是一个伟大的目标。但是,如果你不能交付一个产品来帮助你的业务,那么这个目标是无法实现的。开始研发你所需要的软件吧。让你的代码可以扩展以适应未来的需要。使用简单的设计样式,编写你的代码,如果你要把它展示给一个大集团的同行们。如果你遵循这些技术,你会发现你的代码是简单的而且是“正确”的设计。
控件中国网友情提示www.componentcn.com :正确地选择和使用控件可以有效地提高开发的效率