After reading Jeffrey Palermo's essay how to design a single method, most of the principles of his method design agree. The Design of methods is part of the design of classes (on the premise of Object-Oriented Design). It is a matter of detail, but also a matter of whether the design is good or not.
Jeffrey Palermo mentioned the following guidelines (italic is my understanding ):
1,The method name should clearly express what this method does.
Naming is actually a learning-It looks simple, but it is often easier for experienced designers to make appropriate names. Improper naming often makes it difficult for others to understand. The name of a common method is a verb or verb + noun. Such as append, push, showdialog, and getname.
2,One method does only one thing.
Some people often have several things in one method, which is the result of failing to correctly divide the responsibilities of each method. To do a complex task, you may need to take several steps. We split it into several methods (usually private methods), and each method completes one of them. Of course, this requires proper division based on the actual situation.
3,One method either does something or returns something. If this method returns something, calling it countless times should not have a negative impact.
4,The size of a method should not exceed the size of a screen.
This is an experience. If you write a lot of code (for example, more than 50 lines) in a method, You Need To refactor the method. Jeffrey Palermo even said that a method should be less than 10 rows.
5,The number of parameters for the method is small.
If a method requires a large number of parameters, the information can be encapsulated into an object. The existing example is processstartinfo in. NET Framework. In my opinion, it is best to have no more than five parameters for a method.
6,The method only depends on the parameters of the method, or the class members passed in by the constructor.
7,Catch exceptions in the right place.
Capture exceptions where they need to be processed; otherwise, let them spread.
The design principles of methods may vary in different languages. For example. net performs some checks on the passed parameters. In native C/C ++ code (such as the wcscpy function), the caller always thinks that the parameters are correct, without any check, check the following code: wchar_t * _ cdecl wcscpy (wchar_t * DST, const wchar_t * SRC)
{
Wchar_t * CP = DST;
While (* CP ++ = * SRC ++)
;/** // * Copy SRC over DST */
Return (DST );
}
In C:
Public static string copy (string Str)
{
If (STR = NULL)
{
Throw new argumentnullexception ("str ");
}
String text1 = string. fastallocatestring (Str. Length );
String. fillstring (text1, 0, STR );
Return text1;
}
Standards are classified into standards. In actual development, the actual situation depends on the actual situation.
Original article: http://jiezhi.cnblogs.com/archive/2006/04/20/410376.html: