How to write robust code

Source: Internet
Author: User

Whether in the process-oriented or object-oriented era, any function is implemented by the collaboration of several functions. A function consists of input, processing, and output. The code segment that implements this function assumes that the input parameters have already met several rules. When executing this function, the function code obtains the input parameters and then executes the agent logic. Let's look at the code of a function.

 

1 private static void ParseArgs (string [] arguments)
2 {
3 if (_ parsedArgs)
4 {
5 return;
6}
7 if (arguments = null)
8 {
9 arguments = CommandLineArgs;
10}
11 // command line format:
12 const string usage = "[-initial 5] [-level 2]";
13 for (int I = 0; I <arguments. Length; I ++)
14 {
15 // match the leading character
16 if (arguments [I]. CompareTo (InitialStartLevelLead) = 0)
17 {
18 // step forward
19 if (++ I <arguments. Length)
20 {
21 // Value
22 _ initialBundleStartLevel = Convert. ToInt32 (arguments [I]);
23 continue;
24}
25 else
26 {
27 goto fail;
28}
29
30}
31 if (arguments [I]. CompareTo (StartLevelLead) = 0)
32 {
33 // step forward
34 if (++ I <arguments. Length)
35 {
36 // Value
37 _ startLevel = Convert. ToInt32 (arguments [I]);
38. continue;
39}
40 else
41 {
42 goto fail;
43}
44}
45}
46 _ parsedArgs = true;
47 return;
48 fail:
49 throw new Exception ("Invalid args, usage:" + usage );
50}

 

The general purpose of this function is to allow users to change the behavior of a program by taking a parameter similar to "-initial 5-level 2" when starting the program. It is estimated that we often write programs similar to the above. Sometimes it may be due to lack of experience or laziness. Can you find out the problems with this small program?

 

Next, I will mark every small detail problem in the function using the annotation method. If any problem is left blank, please add it.

 

Private static void ParseArgs (string [] arguments)
{
If (_ parsedArgs) // The name of this parameter does not comply with the rules. The correct name should be _ isArgsParsed. if you want to make the parameter more readable, you can declare the parameter qualifier to _ is ×× ArgsParsed.
{
Return;
}
If (arguments = null)
{
Arguments = GetCommandLineArgs ();
}
// Command line format:
Const string usage = "[-initial 5] [-level 2]";

// 2 hard-coded string.
For (int I = 0; I <arguments. length; I ++) // 3 if the returned value of GetCommandLineArgs is null, NullReferenceException will occur in this line of code; in addition, if arguments. if the Length is greater than 4, we need to prompt the user; if the parameter is repeated or does not meet the requirements, we also need to prompt the user.
{
// Match the leading character
If (arguments [I]. CompareTo (InitialStartLevelLead) = 0) // 4 if arguments [I] allows spaces, this line of code produces incorrect execution results
{
// Step forward
If (++ I <arguments. Length)
{
// Value
_ InitialBundleStartLevel = Convert. ToInt32 (arguments [I]); // 5 If arguments [I] is not a valid integer, this line of code will generate an exception in conversion failure.
Continue;
}
Else
{
Goto fail;
}

}
If (arguments [I]. CompareTo (StartLevelLead) = 0) // 6 the problem is the same as 3
{
// Step forward
If (++ I <arguments. Length)
{
// Value
_ StartLevel = Convert. ToInt32 (arguments [I]); // Problem 4
Continue;
}
Else
{
Goto fail;
}
}
}
_ ParsedArgs = true;
Return;
Fail:
Throw new Exception ("Invalid args, usage:" + usage); // the error message is unfriendly. It is not clear which parameter is incorrect, in addition, there must be spaces between "args" and "usage" in the English grammar. In addition, the user information cannot be abbreviated at will and must use complete words; hard-coded strings must be placed in a unified resource file and supported by I18N and L10N are considered. The strings in question 2 can be directly merged with the Exception string. If necessary, it is best to redefine the Exception type.
}

 

A robust function is not only a correct function. The above Code only considers that user input is correct. When a user inputs an error, either the above Code displays an exception without any friendly prompts or only provides an unfriendly error message. To make a function robust, we must keep in mind when coding: (1) We cannot assume that the input parameters of the function are correct. We must check whether the input parameters of the function comply with the rules; (2) when the function input does not conform to the rules, you must tell the user where the error is and how to enter the correct parameters. (3) consider the readability of the code and follow the code specifications. In addition, during the test, you need to determine the input parameter boundary and test all the parameters in and out of the boundary to ensure that the function provides a friendly prompt when the function parameters are incorrect.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.