Three elements of code - winning the hearts of interviewers

original
2012/08/02 10:45
Reading 251
Programmers are inevitably interviewed in their career. Some programmers did not develop good programming habits at ordinary times, and the quality of the code they wrote during the interview was not high, so they regrettably missed the company and position they wanted. Therefore, how to write high-quality code in an interview is a concern of many programmers.

Code normalization

The interviewer decides whether to hire a candidate according to the code written by the candidate. Applicants should first write the code in a standard way to avoid many low-level errors. If the code is not written properly, it will affect the interviewer's interest in reading the code, at least the impression will be discounted. Writing, layout and naming all determine the standardization of code.

The standard code is written clearly. Most interviews require candidates to write on white paper or whiteboard. As modern people have become accustomed to typing on the keyboard, handwriting has become more and more unaccustomed, so the words written are illegible. Although it is unnecessary for the applicant to practice calligraphy specially for the interview, it is necessary to slow down the writing speed and write each letter as clearly as possible during the interview. Don't worry about not having time to write code. Usually, the number of code interviewed for programming does not exceed 50 lines. It does not take much time to write. The key is to form a clear idea before writing the code and be able to write the idea clearly in programming language.

The standard code layout is clear. Usually, programmers write code in an integrated development environment such as Visual Studio, rely on professional tools to adjust the layout of code, add reasonable indentation and make brackets align to form pairs. Without these tools, candidates should pay special attention to layout. When there are many loops and judgments and the logic is complex, there may be more indented levels. If the layout is not clear enough and the indentation cannot reflect the logic of the code, such code will make people dizzy.

The standard code name is reasonable. Many beginners are accustomed to using the simplest names when writing code. Variable names are i, j, k, and function names are f, g, h. Because such names cannot tell readers the meaning of the corresponding variable or function, the code will become very obscure once it is long. It is strongly recommended that candidates use a complete combination of English words to name variables and functions when writing code. For example, if a function needs to pass in the root node of a binary tree as a parameter, the parameter can be named BinaryTreeNode * pRoot. Don't bother because you will write more letters. If you can see the use of variables and functions at a glance, you can avoid making some low-level mistakes due to confusion. At the same time, reasonable naming can also make the interviewer understand the purpose of the code at a glance, rather than let him guess whether the variable is the maximum or minimum value in the array.

Code integrity

During the interview, the interviewer will pay close attention to whether the candidate considers the problem comprehensively. The interviewer checks whether the candidate's thinking is comprehensive by checking whether the code is complete. Usually, the interviewer will check whether the candidate's code has completed the basic functions, whether the input boundary value can be correctly output, and whether the illegal input of various irregularities has been properly handled incorrectly.

Three test cases ensure code integrity

Before writing code, applicants should first think about all possible inputs to avoid various quality vulnerabilities in the program. That is to say, unit tests should be considered before coding. If a comprehensive unit test case can be designed and reflected in the code, then the code written will be complete and correct. Generally, programmers can design test cases from three aspects: functional test, boundary test and negative test to ensure the integrity of code.

▲ The first test case to consider is the test case of the general function test. The candidate should first ensure that the code written can complete the basic functions required by the interviewer. For example, the function required by the interview question is to convert the string into an integer. Candidates can consider entering the string "123" to test their own code. Here, zero, positive numbers (such as 123) and negative numbers (such as - 123) should be taken into account.

When considering functional testing, candidates should try to break through the limitations of conventional thinking and avoid ignoring some implicit functional requirements. For example, "printing from 1 to the maximum n digits" is very simple for many people. The maximum 3 digits is 999, and the maximum 4 digits is 9999. These figures can be easily calculated. But can the largest n digits be represented by int? If the range of int is exceeded, consider the long long type. Is it beyond the scope of long long? Does the interviewer ask to consider any large number? If the interviewer confirms that the question requires any large number, then the question is a large number question. At this time, special data structures are needed to represent numbers, such as strings or arrays to represent large numbers, to ensure that no overflow occurs.

▲ Next, test cases with various boundary values need to be considered. Many codes contain loops or recursion. If the code is based on a loop, are the boundary conditions for ending the loop correct? Loop based code should pay special attention to the use of open intervals and closed intervals (that is, distinguish<from<=,>from>=). If the code is based on recursion, is the boundary value of recursion termination correct? These are the use cases to consider when boundary testing. Taking the problem of converting a string to an integer as an example, the code written by the candidate should ensure that the largest positive integer and the smallest negative integer can be converted correctly.

▲ Again, you need to consider all possible wrong inputs, that is, test cases for negative tests. In addition to completing the required function smoothly, the interviewer also hopes that the function written by the candidate can make reasonable error handling when the input does not meet the requirements. When designing a function that converts a string into an integer, the candidate should consider how to tell the function caller that the input is illegal when the input string is not a number, such as "1a2b3c".

The previous discussion is to comprehensively consider various possible inputs corresponding to the current requirements. In the process of software development, requirements will always change. If the code written by the candidate during the interview can take into account the possible changes in future requirements, and minimize the risk of code changes when the requirements change, he will show the interviewer his understanding of program scalability and maintainability, which will certainly be favored by the interviewer. If the candidate can consider scalability when answering the interview question "Adjust the order of the array so that the odd number is in front of the even number", the code he wrote will not only solve the problem of adjusting the odd number and the even number, but also take into account the decoupling of the function of adjusting the order of numbers and the function of judging whether a number is odd or even. In this way, when future demand function expansion requires solving similar problems, such as adjusting the order of negative and non negative numbers, adjusting the order of numbers that can be divided by 3 and numbers that cannot be divided by 3, only a few codes need to be added to do so, thus improving code scalability and maintainability.

Three error handling methods

There are usually three ways to pass error information to function callers.

▲ The function uses the return value to tell the caller whether there is an error. For example, many Windows APIs are of this type. In Windows, if the return value of many APIs is 0, the API call is successful, while if the return value is not 0, an error occurs during the API call. Microsoft has defined different meanings for different non-zero return values, and the caller can judge the cause of the error according to these return values. The biggest problem with this method is that it is inconvenient to use, because the function cannot directly assign the calculation result to other variables through the return value, nor can it directly transfer the calculation result of this function to other functions as parameters.

▲ Set a global variable when an error occurs. At this point, the calculation results can be passed in the return value. This method is more convenient than the first method, because the caller can directly assign the return value to other variables or pass it as a parameter to other functions. After many Windows APIs run incorrectly, a global variable will also be set. The function caller can analyze the global variable representing the error by calling the function GetLastError to know the cause of the error. However, there is a problem with this method: it is easy for the caller to forget to check the global variable, so he or she forgets to do the corresponding error handling when there is an error in the call, leaving a security risk.

▲ Abnormal. When the function runs incorrectly, the program throws an exception. Programmers can define different exception types according to different error causes. Therefore, the caller of the function can know the cause of the error according to the type of exception, so that he can handle it accordingly. In addition, the logic of the code is relatively clear because the code blocks for normal operation of the program (try module) and exception handling (catch module) are explicitly divided. Exceptions are a highly recommended error handling method in high-level languages such as C #, but some early languages such as C still do not support exceptions. In addition, when an exception is thrown, the execution of the program will disrupt the normal order, which has a great impact on the performance of the program.

Each of the above three error handling methods has advantages and disadvantages. So what kind of method should the candidate adopt in the interview? It depends on the needs of the interviewer. After hearing the interviewer's questions, the candidate should analyze the possible illegal inputs as soon as possible, and discuss with the interviewer how to deal with these illegal inputs. This kind of discussion with the interviewer is beneficial to the applicant, because the interviewer will feel that he has a comprehensive understanding of error handling, and that he has good communication skills.

Code robustness

Robustness means that the program can judge whether the input meets the specification requirements, and handle the unqualified input reasonably. Fault tolerance is an important embodiment of robustness. When an abnormal event occurs to an unsound software, such as a user entering an incorrect user name, trying to open a file that does not exist, or the network cannot be connected, unpredictable strange behavior will occur, or the entire software will simply crash. Such software is no less a disaster for users.

Because robustness is very important for software development, interviewers also pay great attention to whether the code written by candidates is robust when recruiting. Defensive programming is an effective way to improve the robustness of code. Defensive programming is a kind of programming habit. It refers to anticipating where problems may occur and formulating solutions for these problems.

During the interview, the simplest and most practical defensive programming is to add code at the function entry to verify whether the user input meets the requirements. The interview usually requires writing one or two functions, and applicants need to pay special attention to the input parameters of these functions. If the input is a pointer, what if the pointer is a null pointer? What if the input is a string and the content of the string is empty? If the candidate can consider these problems in advance and deal with them accordingly, the interviewer will feel that he has the habit of defensive programming and can write robust software.

Of course, not all robustness related problems are as simple as checking the input parameters. When a candidate sees a question, he or she should ask more questions such as "if not... then...". For example, the interview question "the k-th node from the bottom of the list" implies that the number of nodes in the list is greater than k. The candidate must ask himself what would happen to the code if there were no more than k nodes in the linked list? This way of thinking can help find potential problems and solve them in advance. This is much better than letting the interviewer find the problem and then the candidate hurriedly analyze the code to find the root cause of the problem.

Summary

This article introduces how candidates can write high-quality code in interviews from three aspects: normalization, integrity and robustness (as shown in the following figure).

First, applicants should pay attention to the standardization when writing code on white paper or whiteboard, write each letter as clearly as possible, make the code layout reasonable by indenting and aligning brackets, and name variables and functions in the code reasonably.

Second, candidates should consider all possible inputs before coding to ensure that the code written has considered boundary conditions and handled errors in addition to completing basic functions. Only codes that fully consider these three aspects are complete.

Third, the applicant should pay attention to the robustness of the code, and ensure that the program written by himself will not crash easily. When writing code at ordinary times, the candidate had better form the habit of defensive programming, judge whether the input is valid at the function entrance and deal with various invalid inputs accordingly. If applicants can do these three things, they will naturally be able to write high-quality code. Finally, it will be a natural thing to get an offer through an interview.

Expand to read the full text
Loading
Click to lead the topic 📣 Post and join the discussion 🔥
Reward
zero comment
two Collection
zero fabulous
 Back to top
Top