Teach you how to write better C # code examples

Source: Internet
Author: User
Tags coding standards naming convention

Introduction

Developers always like to argue about coding specifications, but it's more important to be able to follow coding specifications throughout the project to ensure consistency of project code. And everyone on the team needs to be clear about the role that coding norms play. In this article, I will introduce some good practices that have been learned and summed up in the course of my years of experience.

For example, first

Let's look at a fizzbuzz example first. Fizzbuzz requires writing a program that traverses numbers from 1 to 100. Where a number is a multiple of 3, the program outputs "Fizz". If a number is a multiple of 5, the output is "Buzz". If a number that is a multiple of 3 is also a multiple of 5, the output is "Fizzbuzz". If the number is neither a multiple of 3 nor a multiple of 5, simply output the number itself.

  Example 1:

public static void Test () {for      (int i = 1; i < 101; i++)      {        if (i% 3 = = 0 && I 5 = = 0)        {          Console.WriteLine ("Fizzbuzz");        }        else if (i% 3 = = 0)        {          Console.WriteLine ("Fizz");        }        else if (i% 5 = = 0)        {          Console.WriteLine ("Buzz");        }        else        {          Console.WriteLine (i);}}      }

What does it feel like? Does this code need to be improved?

  Example 2:

public static void Check () {for      (int i = 1; i <=; i++)      {        string output = "";        if (i% 3 = = 0) {output = "Fizz";}        if (i% 5 = = 0) {output = output + "Buzz";}        if (output = = "") {output = i.ToString ();}        Console.WriteLine (output);}      }

How do you feel now? Can it be further improved?

OK, let's try to improve the next. Code naming is a very difficult task for all software developers. We spend a lot of time doing this, and there are too many elements that need to be named, such as properties, methods, classes, files, projects, and so on. But we do need to spend some effort on these names to make the name in the code more meaningful, which in turn can improve the readability of the code.

public void Dofizzbuzz () {for      (int number = 1; number <=; number++)      {        var output = Getfizzbuzzoutput (nu mber);        Console.WriteLine (output);}      } private static string getfizzbuzzoutput (int number) {      string output = string. Empty;      if (number% 3 = = 0)      {        output = "Fizz";      }      if (number% 5 = = 0)      {        output + = "Buzz";      }      if (string. IsNullOrEmpty (output))      {        output = number. ToString ();      }      return output;}

How did it feel this time? Is it better than the previous example? Is it more readable?

What is the better code?

The first is code to be written for people, followed by machines. In the long run, writing readable code will not take longer than writing confusing code. If you can easily read the code you write, it's easier to make sure it works as expected. This should already be a good enough reason to write easy-to-read code. In many cases, you'll need to read the code, such as reading your code in code review, reading the code you write when you or someone else fixes a bug, and reading the code as it needs to be modified. There is also the ability to read your code first when others are ready to try to reuse your part of your code in a similar project or project with similar functionality.

"If you only write code for yourself, why make your code more readable?" ”

Well, the main reason for writing easy-to-read code is that you'll be working on another project in the next week or so. And then, what happens when someone else needs to fix a bug in the current project? I'm sure he'll be lost in the horror code you wrote yourself.

From my personal point of view, good code should have the following characteristics:

    • The code is easy to write and easy to modify and extend.

    • The code is clean and the presentation is accurate.

    • The code is valuable and quality-oriented.

Therefore, always consider the first person to write code, and then meet the needs of the machine.

How to improve readability?

First, you need to read the code written by other people to learn what good code is and what is bad code. It's the code that you feel very easy to understand, and the code that feels like it's super complex. Then, proceed to practice. Finally, spend some time, experience, and practice to improve the readability of your code. In general, it is difficult to promote coding practices in any software company by training this way alone. such as pairing code review, automated code review tools, etc. can also help you. The current popular tools are:

    • FxCop: Static code Analysis of. NET code that provides a variety of rules for different forms of analysis.

    • STYLECOP: Open source project, which uses code style and conformance specifications to analyze C # code. Can be run in Visual Studio or integrated into MSBuild. StyleCop has also been integrated into a number of third-party development tools.

    • JetBrains ReSharper: A well-known productivity-boosting tool that makes the Microsoft Visual Studio IDE even more powerful. The world's. NET developers may not be able to imagine how the work can be without ReSharper code review, Code Auto-refactoring, fast navigation and coding assistants, and other powerful features.

What is the specification?

  According to the Wikipedia description: "Coding conventions is a set of guidelines for a specific programming language that recommend programming St YLE, practices and methods for each aspect of a piece program written in this language. These conventions usually cover file organization, indentation, comments, declarations, statements, white space, naming co Nventions, programming practices, programming principles, programming rules of thumb, architectural best practices, etc. T Hese is guidelines for software structural quality. Software programmers is highly recommended to follow these guidelines to help improve the readability of their source cod E and make software maintenance easier. Coding conventions is only applicable to the human maintainers and peer reviewers of a software project. Conventions May is formalized in a documented set of rules, a entire team or company follows, or may be as informal a s the habitual coding practices of an inpidual. Coding conventions is not enforced by compilers. As aresult, not following some or all of the rules have no impact on the executable programs created from the source code.

You should be able to tell the difference between attributes, local variables, method names, class names, and so on, because they use different casing conventions, so these conventions are very valuable. With the Internet, you've learned a lot about the appropriate guidelines and specifications, and all you need is to find a specification or build your own, and then always follow that specification.

The source code used below (the class library design guidelines) was developed by Microsoft's Special Interest Group team, and I just made some extensions.

Casing conventions

Here are some examples of C # coding standards, naming conventions, and best practices that you can use according to your own needs.

  Pascal Casing

The initials in the identifier, and the first letter of each word in the subsequent concatenation is capitalized. If necessary, the first few letters of the identifier can be capitalized.

  Camel Casing

The first letter of the identifier is lowercase, and the first letter of each word in the subsequent concatenation is capitalized.

Reference: Designator case rules

Some naming convention examples

On the internet you can find enough resources, I just recommend a few of them which I like best:

    • C # Coding Conventions

    • C # Coding Guidelines

    • C # Coding standards and best practices

    • C # Coding specifications and naming conventions

Here I show some of the most basic examples, but as I've mentioned above, find a spec that fits you and stick with it.

To use Pascal casing, name the class and method.

public class product{public      void Getactiveproducts ()      {        //...      }      public void Calculateproductadditinalcost ()      {        //...      }}

To name the method's parameters and local variables using Camel casing.

public class productcategory{public      void Save (ProductCategory productcategory)      {        //...      }}

Do not use abbreviations.

    Correct    productcategory productcategory;    Avoid    ProductCategory Prodcat;

Do not use underscores in identifiers.

    Correct    productcategory productcategory;    Avoid    ProductCategory product_category;

To use the letter I before the interface name.

    Public interface iaddress    {    }

To define all member variables at the top of the class, define static variables at the top.

public class product{Public    static string brandname;    public string Name {get; set;}    Public DateTime dateavailable {get; set;}    Public Product ()    {      //...    }}

To define an enumeration using the singular vocabulary, unless it is a Bitfield enumeration.

public enum direction{North    ,    East, South    ,    West}

Do not add an enum suffix to the enumeration name.

avoidpublic enum directionenum{North    ,    East, South    ,    West}

Why do we need coding specifications?

In large projects, developers often rely on coding specifications. They have built up a lot of norms and guidelines so that remembering these norms and guidelines has become a part of daily work. The computer is not concerned about the readability of the code you write, and it is easier for the computer to understand the binary machine instructions than to read the Advanced programming language statements.

Coding specifications provide a lot of obvious benefits, and of course it's possible you get more. Typically, the overall scope of these projects will allow you to focus more on the more important parts of your code.

    • The coding specification helps to pass knowledge across projects.

    • Coding specifications can help you understand the code more quickly on new projects.

    • The coding specification emphasizes the relationship between the associated items in an organization.

You need to write high-readability code to help other people understand your code. Code naming is a very difficult thing for our software developers, and we've spent a lot of time on it, and there are too many elements to name, such as properties, methods, classes, files, projects, and so on. So we really need to spend some effort on naming the specification to make the name more meaningful and thus improve the readability of the code.

Also, coding rules can make you sleep more soundly at night.

Several rules that developers should follow most

Always control the size of the class

I've seen it, and I've written some super-big classes. And unfortunately, the results are always bad. And then I found the real reason that those super-big classes are trying to do too much, which violates the single responsibility principle (SRP), which is the object-oriented design principle of S in SOLID.

"The single responsibility principle states that every object should has a single responsibility, and that responsibility Should is entirely encapsulated by the class. All its services should is narrowly aligned with that responsibility. "

or according to Martin Fowler's definition: "There should never is more THAN one REASON for A CLASS-to-change."

Why must you separate two responsibilities into separate classes? Because every duty is the center of change. This change will appear in the class responsible for the requirement change. If a class takes on multiple responsibilities, there will be more than one cause for it to change. If a class has multiple responsibilities, it means that these responsibilities have been coupled together. And a change in one's responsibilities would have the potential to weaken or limit the ability of this class to meet other responsibilities. This coupling will result in a very fragile design, which, in turn, can be unexpectedly damaged in the event of a change in responsibilities.

Avoid outdated annotations

Say something out of the old comment first. According to Robert C. Martin's definition:

"A comment that had gotten old, irrelevant, and incorrect was obsolete. Comments get old quickly. It is the best not-to-write a comment that would become obsolete. If you find a obsolete comment, it is the best to update it or get rid of it as quickly as possible. Obsolete comments tend to migrate away from the code they once described. They become floating islands of irrelevance and misdirection in the code. "

For this topic, different levels of developers may have their own insights. My advice is to try to avoid commenting on a separate method or a short class. Because most of the annotations I've seen are trying to describe the purpose or intent of the code, or some comments may not be meaningful in themselves. Developers often write comments to improve the readability and maintainability of the code, but make sure that the comments you write do not become noise in the code. I think a reasonable method of naming is more effective than commenting, for example, you can make a more meaningful name for a method. Most annotations can become meaningless code noise, so let's take a look at these comments:

Ensure that we is not exporting//deleted products if (product. IsDeleted &&!product. isexported) {       exportproducts = false;}//This was a for loop, prints the 1 million times for (int i = 0; i < 1 000000; i++) {       Console.WriteLine (i);}

What happens if we don't write a comment, but instead name a method, say Cancelexportfordeletedproducts ()? Therefore, the appropriate method of naming is more effective than annotations. In some cases, however, code comments can also be helpful, such as Visual Studio generating API documentation from comments. The comments here are slightly different and you need to annotate with the "///" identifiers so that other developers can see smart hints for the API or class library.

I didn't say always to avoid annotations. As Kent Beck says, you can use more annotations to describe how the whole program works, rather than commenting on individual methods. If the comment is trying to describe the purpose or intent of the code, then it is wrong. If you see a dense list of comments in your code, you may realize that there are so many comments that the code is poorly written. For more information, you can read these books:

    • "Professional refactoring in C # and ASP." By Danijel Arsenovski

    • Refactoring: Improving existing code design by Martin Fowler, Kent Beck, John Brant, William Opdyke, Don Roberts

Avoid unnecessary region

Region is a feature provided by Visual Studio that allows you to block code. The region exists because it makes it easy to navigate large files. The region is also often used to hide ugly code, or the class has expanded so much that it needs to be chunked. And if a class does too much, it means it violates the principle of single responsibility. So the next time you want to add a region, consider whether it's possible to separate the region into a separate class.

Keep the method short

The more code lines in a method, the harder it is to understand the method. We recommend that only 20-25 lines of code be included in each method. But some people say 1-10 lines are more reasonable, it's just personal preference, no hard rules. The extraction method is one of the most common refactoring methods. If you find that a method is too long, or you already need a comment to describe its purpose, then you can apply the extraction method. People always ask how long a method is appropriate, but length is not the root of the problem. When you are dealing with complex methods, tracking all local variables is the most complex and time consuming, and by extracting a method you can save some time. You can use Visual Studio to extract methods that help you track local variables and pass them to a new method or receive the return value of a method.

  Using ReSharper

  Using Microsoft Visual Studio

For more information, refer to MSDN.

As described in "Refactoring: Improving Existing code Design",

Extract Method is one of the most common refactoring I do. I look at a method, which is too long or look at code, needs a comment to understand its purpose. I then turn that fragment of code to its own method. I prefer short, well-named methods for several reasons. First, it increases the chances that and methods can use a method when the method is finely grained. Second, it allows the higher-level methods to read more like a series of comments. Overriding also was easier when the methods was finely grained. It does take a little getting used to if you were used to seeing larger methods. And small methods really work only if you had good names, so you need to pay attention to naming. People sometimes ask me what length I look for in a method. To me length was not the issue. The key is the semantic distance between the method name and the method body. If extracting improves clarity, do it, even if the name was longer than the code you had extracted. "

Avoid too many parameters

Instead of multiple parameters, declare a class. Create a class that contains all the parameters. Generally speaking, this is a good design, and this abstraction is very valuable.

Avoid public    void Checkout (String shippingname, String shippingcity,      string shippingsate, String shippingzip , String billingname,      string billingcity, String billingsate, String billingzip)    {    }    //do    public void Checkout (shippingaddress shippingaddress, billingaddress billingaddress)    {    }

We need to introduce classes to replace all the parameters.

Avoid complex expressions

if (product. price>500 &&!product. IsDeleted &&   !product. Isfeatured && product. isexported) {      //do something}

Complex expressions imply that there are hidden meanings behind them, and we can encapsulate them by using attributes, which makes the code easier to read.

Equate the warning with the error

If you look at the code, you'll notice that a variable is declared but never used. Normally, we get a warning when we compile the project, but we can still run the project without any errors. However, we should remove these warnings as much as possible. You can set the warning to be equivalent to an error on the project by following these steps:

Streamline multiple returns

Reduce the number of functions returned in each program. Assuming you read the code from the bottom, it's hard to realize that it's possible to return somewhere above, and that code would be very difficult to understand.

Using only one return can enhance readability. If the program writes like this, it might look cleaner, but not returning immediately also means writing more code.

Avoid      if (product. price>15)      {         return false;      }      else if (product. IsDeleted)      {         return false;      }      else if (!product. isfeatured)      {         return false;      }      else if ()      {         //...      }      return true;
Do      var isValid = true;      if (product. price>15)      {         isvalid= false;      }      else if (product. IsDeleted)      {         isvalid= false;      }      else if (!product. isfeatured)      {         isvalid= false;      }      return isValid;

You can imagine that there are 4 exit points scattered in these 20-30 lines of code, which makes it very difficult for you to understand exactly what is going on inside the program, what will be executed, and when.

I get a lot of people's response on this point, some people agree with this point, some disagree that this is a good coding standard. To identify potential problems, I did some unit tests and found that if complex methods contain multiple exit points, a set of tests would normally be required to cover all the paths.

if (badfunction () = True)      {          //Expression          if (anotherfunction () = = True)          {           //Expression           return true;          }          else          {               //error          }      }      else      {          //error      }      return false;
if (! Goodfunction ())      {          //error.          return False      }       //Expression      if (! GoodFunction2 ())      {          //error.          return false;      }      More expression      return true;

For further understanding, you can refer to the Code Encyclopedia of Steve McConnell.

Using assertions

In software development, assertion code is often used to check whether program code is executed according to its design. Normally True means that all operations are completed as expected, and False indicates that some unexpected errors have been detected. An assertion typically receives two parameters, and a Boolean expression is used to describe the assumption that the hypothesis is true, and a message parameter is used to describe the reason for the assertion failure.

In particular, in the development of large, complex, high-reliability systems, assertions are often a very useful feature.

For example, if the system assumes that a maximum of 100,000 user records will be supported, an assertion may be included in the system to check that the number of user records is less than or equal to 100,000, in which case the assertion will not work. However, if the number of user records exceeds 100,000, the assertion throws an error telling you that the number of records is out of range.

Check the loop endpoint value

A loop typically involves three criteria values: the first value, the middle value, and the last value. But if you have any other specific conditions, you also need to test. If the loop contains complex calculations, do not use the calculator and manually check the results of the calculations.

Summarize

Often the implementation of coding specifications in any software company needs to be done in terms of organizational behavior, project properties, and areas, where I want to emphasize again "find a coding specification that works for you and follow it all the time."

If you think I've omitted a particularly useful coding guideline, please describe it in the comments and I'll try to add it to the article.

  Coding for fun.

 

Related Article

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.