How to Write high-quality code during the interview

Source: Internet
Author: User

The author summarizes his many years of experience interviewing others and being interviewed by others, and finds that candidates can improve the quality of code from three aspects: Code standardization, integrity, and robustness.

Programmers will inevitably have to undergo programming interviews in their careers. Some programmers do not develop good programming habits at ordinary times, and the quality of the code written during the interview is not high, so they finally feel sorry to miss their favorite companies and positions. Therefore, writing high-quality code during the interview is a concern of many programmers.

  Code Standardization

The interviewer determines whether to hire a candidate based on the code written by the candidate. The applicant must first standardize the code to avoid many low-level errors. If the code is not properly written, it will affect the interviewer's interest in reading the Code, at least the impression branch will be compromised. Writing, layout, and naming all determine the code standardization.

  Standardized Code is clearly written.Most interviews require applicants to write on white paper or whiteboard. Because modern people are used to typing on the keyboard, handwriting becomes increasingly unaccustomed, so the words written are hard to distinguish. Although it is not necessary for the applicant to practice the words for the interview, it is necessary to slow down the writing speed during the interview and try to clearly write each letter. Don't worry about having no time to write code. Generally, there will be no more than 50 lines of code for programming interviews, and it does not take much time to write. The key is to build a clear idea before writing the code and clearly write the ideas in programming languages.

  The standardized code layout is clear.Programmers usually write code in an integrated development environment, such as Visual Studio. They rely on professional tools to adjust the code layout, add reasonable indentation, and align brackets in pairs. If you leave these tools, you must pay special attention to layout issues. When the loop and judgment logic are complex, there may be more indentation layers. If the layout is not clear enough, indentation does not reflect the logic of the Code. Such code will make people dizzy.

  The standardized code is named properly.Many Programming beginners always use the simplest names when writing code. The variable names are I, j, and K, and the function names are f, g, and H. Because such a name cannot tell the reader the meaning of the corresponding variable or function, the code will become very obscure after a long time. It is strongly recommended that you use a complete combination of English words to name variables and functions when writing code. For example, a function needs to input the root node of a binary tree as a parameter, you can name this parameter binarytreenode * proot. Don't worry about writing a few more letters. If you can see the use of variables and functions at a glance, the applicant can avoid confusion and make some low-level errors. At the same time, a reasonable name also allows the interviewer to understand the intent of the code at a glance, rather than asking him to guess whether the variable is the maximum or minimum value in the array.

  Code integrity

During the interview, the interviewer will be very concerned about the candidates to consider whether the problem is comprehensive. The interviewer checks whether the code is complete to check whether the candidate's thinking is comprehensive. Usually, the interviewer checks whether the applicant's code has completed the basic functions, whether the input boundary value can be correctly output, and whether reasonable error handling has been made for various nonstandard illegal inputs.

  Three test cases ensure code integrity

Before writing code, the applicant should first think about all possible input, so as to avoid various quality vulnerabilities in the program. That is to say, unit testing should be considered before encoding. If a comprehensive unit test case can be designed and embodied in the Code, the written code is naturally complete and correct. Generally, programmers can design test cases from three aspects: functional testing, boundary testing, and negative testing to ensure code integrity.

  • First, consider the test cases of common function testing. The applicant must first ensure that the written code can complete the basic functions required by the interviewer. For example, the function required by the interview questions is to convert the string into an integer, and the applicant can consider entering the string "123" to test the code written by himself. Here we need to take zero, positive (such as 123), and negative (such as-123) into account.

When considering functional testing, candidates should try to break through the limitations of conventional thinking to avoid ignoring some implicit functional requirements. For example, "printing from 1 to the largest N-digit number" is quite simple. The maximum 3-digit is 999, and the maximum 4-digit is 9999. These numbers are easy to calculate. But can the maximum n digits be expressed in int type? If the value exceeds the int range, you can consider the long type. Beyond the range that long can represent? Does the interviewer need to consider any big number? If the interviewer determines that the question requires any big number, this question is a big number problem. In this case, a special data structure is required to represent numbers. For example, strings or arrays are used to represent large numbers to ensure that they do not overflow.

  • Next, we need to consider test cases with various boundary values. Many codes contain loops or recursion. If the code is based on a loop, is the boundary condition for ending the loop correct? For cyclic code, pay special attention to the use of open and closed intervals (that is, distinguish between <and <=,> and> = ). If the code is based on recursion, is the Boundary Value of recursive termination correct? These are all use cases to be considered during the border test. Take the problem of converting a string to an integer as an example. The code written by the applicant should ensure that the maximum positive integer and the smallest negative integer can be correctly converted.
  • We also need to consider various possible incorrect input, that is, the negative test case. In addition to successfully completing the required functions, the interviewer also hopes that the applicant can properly handle errors when the input does not meet the requirements. When designing a function to convert a string to an integer, the applicant should consider how to tell the function caller that the input is illegal when the input string is not a number, such as "1a2b3c.

We have discussed various possible inputs for the current requirement. In the software development process, the demand will always change. If the code written by the applicant during the interview can take into account all possible changes to the future requirements, the risk of code changes should be minimized when the requirements change, then he showed the interviewer his understanding of program scalability and maintainability, which will surely be favored by the interviewer. If the applicant can consider scalability when answering the question "Adjusting the array order so that the odd number is in front of the even number", the Code he wrote not only solves the problem of adjusting the odd and even numbers, we can also consider decoupling the function of adjusting the numerical order from the function of judging whether a number is an odd or even number. In this way, in the future, function expansion is required to solve similar problems, such as adjusting the order of negative numbers and non-negative numbers
The order of numbers not divisible by 3 and numbers not divisible by 3 can be achieved only by adding a few codes, which improves the scalability and maintainability of the Code.

  Three error handling methods

There are usually three methods to pass the error message to the function caller.

  • The function uses the return value to indicate whether the caller has 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. If the return value is not 0, an error occurs during the API call. Microsoft defines different meanings for different non-zero return values. The caller can determine the cause of the Error Based on these return values. The biggest problem with this method is that it is inconvenient to use because the function cannot directly assign values to other variables through the return value, at the same time, the results of this function calculation cannot be directly passed to other functions as parameters.
  • Set a global variable when an error occurs. In this case, the calculation result can be passed in the return value. This method is more convenient to use than the first method, because the caller can directly assign values to other variables or pass the values to other functions as parameters. When many APIs in Windows run incorrectly, a global variable is also set. Function callers can call the getlasterror function to analyze the global variables that indicate errors and learn the cause of the error. However, this method has a problem: the caller may easily forget to check the global variables. Therefore, when an error occurs in a call, the caller forgets to handle the corresponding errors, leaving a security risk.
  • Exception. When a function fails to run, the program throws an exception. Programmers can define different types of exceptions based on different causes of errors. Therefore, the caller of the function can know the cause of the Error Based on the exception type, so that the corresponding processing can be done. In addition, the logic of the Code is clear because the code blocks (try module) and the code blocks (catch module) that handle exceptions are explicitly divided. Exceptions are strongly recommended in advanced languages such as C #, but some early languages such as C do not support exceptions. In addition, when an exception is thrown, the execution of the program will disrupt the normal sequence and have a great impact on the program performance.

The preceding three methods have their respective advantages and disadvantages. In the interview, which method should the applicant use? This depends on the interviewer's needs. After hearing the interviewer's questions, the applicant should analyze the possible illegal inputs as soon as possible and discuss with the interviewer how to deal with these illegal inputs. This discussion with the interviewer is helpful 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 refers to the ability of a program to determine whether the input meets the specifications and to properly process the input that does not meet the requirements. Fault tolerance is an important embodiment of robustness. When an abnormal event occurs in an insecure software, such as a user entering the wrong user name, the file to be opened does not exist, or the network cannot be connected, unexpected and strange behavior may occur, or the entire software crashes. Such software is no less of a disaster for users.

Since robustness is very important to software development, the interviewer is also very concerned about the robustness of the code written by the applicant during recruitment. An Effective Way to Improve code robustness is to implement defensive programming. Defensive Programming is a programming habit that predicts where problems may occur and develops solutions for these problems.

During the interview, the simplest and most practical Defensive Programming is to add code at the function entry to verify that user input meets the requirements. Generally, the interview requires writing one or two functions. Candidates need to pay special attention to the input parameters of these functions. If the input is a pointer, what should I do if the pointer is a null pointer? If the input is a string, what should I do if the content of the string is null? If a candidate can take these questions into consideration in advance and handle them accordingly, the interviewer will feel that he has the habit of Defensive Programming and can write robust software.

Of course, not all issues related to robustness are just as simple as checking input parameters. When you see a question, you need to ask a few more questions ...... So ......" This is a problem. For example, the question "The Last K nodes in the linked list" implies that the number of nodes in the linked list is greater than K. If the number of nodes in the linked list is not greater than K, what will happen to the code? This way of thinking can help you discover potential problems and solve them in advance. This is much better than asking the interviewer to analyze the code to find the root cause of the problem after discovering the problem.

  Summary

This article describes how to write high-quality code during an interview from three aspects: Standardization, integrity, and robustness (as shown in ).


First, the applicant should pay attention to standardization when writing code on white paper or whiteboard, write every letter as clearly as possible, and make the code layout reasonable through indentation and alignment brackets, we also need to reasonably name the variables and functions in the code. Second, it is recommended that you fully consider all possible inputs before coding, ensure that the written code has completed the basic functions, also considered the boundary conditions, and completed error handling. Only the code that fully considers these three aspects is the complete code. Third, candidates should pay attention to the robustness of the Code to ensure that the programs they write will not crash easily. When writing code, it is best for applicants to develop defensive programming habits, judge whether the input is valid at the function entry, and handle various invalid inputs properly. If the applicant can do these three things, they will naturally be able to write high-quality code and finally get it through the interview.
Offer is also a matter of course.

He Haitao, Cisco Senior Software Engineer, previously worked in Autodesk and Microsoft. Focus on the development technology of C ++/C # And be interested in the design mode and project management.

Address: http://news.cnblogs.com/n/133658/

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.