Avoid duplicate code--know your library

Source: Internet
Author: User

Just read a piece of code and see a less interesting way:

C # code

<summary>
///Add enough zeros to a number as to is represented on 4 characters///</summary>
  
   ///<param name= "offset" >///the number that
must is represented on 4 characters
///</param>
// /<returns>
///</returns>
private string Getexpandedoffset (long offset) {
    string result = Offs Et. ToString ();
    for (int i = 0; Length < 4; i++) {Result
        = ' 0 ' + result;
    }
    return result;
}
  

Method has comments. The method body is also a few lines. What is the problem? Without mentioning that this method uses the string + + operator in the loop to generate a lot of unwanted objects ...

The problem is-this is obviously repetitive labor. The BCL in the. NET framework has ample tools to handle the problem of object conversion to strings and the accompanying formatting problems.

One of the most common application scenarios should be the console output, like this:

C # code

System.Console.WriteLine("{0}=0x{0:X}", anIntVariable);

Here are some of the features that are prescribed by IFormatProvider.

More directly, the types such as Int32 and Int64 implement the IFormattable interface, so we can change the way I said before:

C # code

private string GetExpandedOffset( long offset ) {
return offset.ToString( "D4" ); }

One sentence to solve.

The example itself is simple, but one of the problems is that when you are unfamiliar with the library you are using, you will probably write similar duplicate code. It would be nice if there was an automatic way to check out the duplicate code. But what analysis tool is currently available to capture repetitive code like the "Incomplete" feature?

Before the emergence of such a powerful tool, let us know our own library well.

Microsoft's Phoenix compiler framework is really tough, but can not detect such a duplicate code I haven't tried to see ...

P.S. Well, this is the spit. There's too much repetition logic in the code being read!

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.