6 Anal-saglabājošs veidi, kā uzlabot savu C # kodu

Nekas irks man vairāk, nekā ir rakt cauri atkritumu kods. Strādā pie programmatūras konsultāciju uzņēmums, es esmu redzējis visai liels par to. Un es esmu meta manā datorā pārraudzīt pietiekami kā rezultātā, lai dotu tai skaistā, brūni iekrāsoti zaļā krāsā. Slikts kods iznīcina aparatūru. Un dvēseles.

Lielākais pavediens, ka attīstītājs nu nav ne jausmas, ko viņi dara, vai vienkārši nav rūp viņu kods ir pretruna. Mums visiem ir dažādas vēlmes un kodēšanas stilus, bet, kad attīstītājs nevar izvēlēties konkrētu pieeju, lai viņi nāk pie kā neticami amatieru, un par labu iemeslu dēļ. Nekonsekventa kods ir grūti izlasīt, un tādējādi ir grūti mainīt nākotnē.

Vairums (vai pat pilnībā) no saraksta zemāk griežas ap rakstot konsekventi veidoti un konsekventi pildīt C # kodu. Liela daļa šī saraksta, protams anālais aizturošs, bet viss tiek garantēta, lai uzlabotu kvalitāti un salasāmību jūsu kodu.

1. Izmantojiet kods analīze funkcijas Visual Studio.

Kodeksa analīzes iespējas ir anālais saglabājošs raksturs, kā jūs ātri atklāt, kad jūs sākat izmantot tos pirmo reizi. Tie tomēr ir vērts savu svaru zelta, tie ir visvairāk nekavējoties efektīvs veids, kā uzlabot savu C # kodu.

Katru reizi, kad jūs veidot savu kodu, kods Analīze to tomēr pārbaudīs, lai pārliecinātos, ka liels un augošs saraksts "labākās prakses" ir izpildīti, un radīs brīdinājumus savā kļūdu sarakstā, ja tie nav. Jūs nevarat izsauktu kodu "labajiem" kodu, ja vien tas iet Visual Studio s koda analīzi ar peld krāsas. Ir izņēmumi, bet tie ir maz un rets.

Ļaujot kods analīze savā C # Visual Studio 2005 vai 2008 projektam ir atkarīgs no tā, vai jūs strādājat ar Windows vai tīmekļa pieteikumu.

Par Windows pieteikumu, dodieties uz Solution Explorer un veiciet dubultklikšķi uz projekta Rekvizīti mezglā. No šejienes, izvēlieties kods analīze cilnes kreisajā pusē. Pārbaudiet Enable kods analīze par Build rūtiņu, un jūs pa ceļam. Jūs pamanīsiet, ka jūs varat iespējot un atspējot jebkuru no dažādu pārbaužu individuāli, bet es ieteiktu atstājot tos visus pārbaudīt, ja vien jūs esat atradis brīdinājumu, ka jūs esat pārliecināts, ka jūs varat ignorēt. Kā es esmu norādījusi iepriekš, kodeksa analīze ir gandrīz vienmēr ir taisnība.

Par Web pieteikumu, dodieties uz Solution Explorer un izvēlieties saknes mezglu jūsu mājas lapā. Tad aiziet līdz Analizēt un izvēlieties kods analīze Configuration. No šejienes, pārbaudiet Enable kods analīze par Build rūtiņu un jūs pa ceļam.

2. Izmantot reģionus konsekventi un efektīvi.

Neviens patīk rakt caur milzīgu kodu failā, lai atrastu īpašu metodi, un C # 's reģioni palīdzēt atrisināt šo problēmu. Šeit ir piemērs:


#region Private Variables

private int x;
private int y;

#endregion

#region Public Properties

public int X
{
    get
    {
        return x;
    }
}

public int Y
{
    get
    {
        return y;
    }
}

#endregion

In Visual Studio, regions can be collapsed or expanded using the +/- buttons to the left of the region names in the code window. This helps to make it much easier to find a particular method you are looking for. There are many ways to organize your code with region statements, but I prefer to separate the code by type of construct (variables, constructors, event handlers, methods, properties, etc.) and access modifier (public, internal, protected, or private).

3.  Handle white space consistently.

C# ignores white space, which means you can put extra spaces and lines pretty much wherever you like.  Or, if you’re insane, you can jam ten-thousand lines of code into a very angry single line of actual text, separated only by semicolons.

Here are a few things to consider, though:

  • Code with more white space is generally much easier to read.  Less condensed code is easier on the eyes and with screen real estate being as ample as it is these days, there’s little reason to try and jam your code into as few lines as possible.  For the most part, bigger is better.
  • Even though code blocks, such as if and while statements, do allow you to omit the curly braces, this generally makes your code harder to read.  The general consensus is to always use curly braces even when there is only one line of code you are executing between them.
  • Consistency, consistency, consistency.  If you put new lines after you close blocks of code, be sure you do it everywhere.  Don’t “feel it out.”  Come up with your own strategy (preferably similar or the same to most other peoples’ strategies) and stick to it.

4.  Always specify your access modifiers and choose them carefully.

C# access modifiers are simply the public, internal, protected, and private keywords that you typically place in front of variables, properties, and methods.  Though these are often overlooked, they provide meaning to the functionality behind your code and help to better define the structure of your code through encapsulation.

Here are some grossly oversimplified definitions and uses for the four modifiers.  These definitions are lacking some detail, but should be plenty of information to handle the vast majority of circumstances:

Private members are only accessible to the class in which they live.  All variables, properties, methods, etc. that do not need to be accessed outside the immediate class should be marked as private.

Protected members are accessible to the class in which they live, as well as any classes that derive from (extend) the class.  The protected modifier should be used on variables, properties, methods, etc. that may need to be accessed by classes that may derive from (extend) the current class.

Internal members are accessible everywhere within the current project, but are inaccessible by other projects that might reference the current project.  In other words, using the internal modifier specifies that only classes within the current EXE or DLL file can access the member.  The internal modifier should be used on all variables, properties, methods, etc. that need to be available to other classes within the project, but should not be available outside the project.

Public members are accessible everywhere, period.  There are no restrictions to their access.  This particular modifier is often overused, as the internal modifier is overlooked.  The public modifier should only be used for members or classes that are or would possibly be needed outside of the current project.

As far as defining classes, typically only internal or public are used, depending on if they need to be accessible outside the project.  This, however, does not account for nested classes, which can have any of the four access modifiers.  Always specify your access modifiers to avoid confusion as to when and where the class or member can be used.

5.  Learn the ways to properly use exceptions and stick to them.

C# exceptions are extremely powerful and convenient, but when used incorrectly, they can both slow your application down and hinder output to the end user.

There are two basic rules of thumb to using exceptions properly:

  • Never catch an exception when you can check for and prevent the error instead.  A typical scenario is trying to open a file that you’re not entirely sure really exists.  You can wrap the file open code in a try catch, or you can use File.Exists to determine if the file exists before attempting to open it.  Exceptions in C# are expensive, so you only want an exception to be raised if a true error occurs.  If you can predict that it might happen for a particular reason, you should be able to check to make sure that it won’t happen before proceeding.  This will help to improve performance significantly.
  • Also, never catch the root Exception class, or any high-level, broad exception.  If you catch an Exception class, and you incorrectly assume that the user didn’t fill in a particular field as a result, the user will see your incorrect error message and be unable to see the actual error that occurred.  This is unacceptable.  Instead, research the methods you are calling to determine the particular types of exceptions they raise, and catch these specific exceptions.  This way, if something occurs that you didn’t expect, the end user will see the detailed error message anyway.  The MSDN documentation does a great job of providing you with all of the details you need regarding every exception that is possible for every single method in the .NET framework.

6.  ALWAYS use using statements.

In case you’re not familiar with the syntax of using statements, here is an example:


using (StreamWriter writer = new StreamWriter("C:\\file.txt"))
{
    writer.WriteLine("Hello!");
}

Using statements can be used wherever you’re instantiating an object that is IDisposable (can be disposed using the Dispose method).  If you don’t actively dispose objects that support the IDisposable interface, you’re asking for all sorts of performance and memory leak trouble.  Here are the advantages of using statements over calling the Dispose method directly:

  • Even if an exception is raised within your using statement block, the runtime will still ensure that the object gets properly disposed.  This is automatic with the using statement and is impossible without it.  Before using statements were added in .NET 2.0, you had to attempt to dispose of your objects within a catch block, which was far from error-prone.  Never take this approach.
  • Using statements help to visually define the scope of a variable that requires disposing.  You can quickly and easily se Šeit ir piemērs:

    
    #region Private Variables
    
    private int x;
    private int y;
    
    #endregion
    
    #region Public Properties
    
    public int X
    {
        get
        {
            return x;
        }
    }
    
    public int Y
    {
        get
        {
            return y;
        }
    }
    
    #endregion
    

    In Visual Studio, regions can be collapsed or expanded using the +/- buttons to the left of the region names in the code window. This helps to make it much easier to find a particular method you are looking for. There are many ways to organize your code with region statements, but I prefer to separate the code by type of construct (variables, constructors, event handlers, methods, properties, etc.) and access modifier (public, internal, protected, or private).

    3.  Handle white space consistently.

    C# ignores white space, which means you can put extra spaces and lines pretty much wherever you like.  Or, if you’re insane, you can jam ten-thousand lines of code into a very angry single line of actual text, separated only by semicolons.

    Here are a few things to consider, though:

    • Code with more white space is generally much easier to read.  Less condensed code is easier on the eyes and with screen real estate being as ample as it is these days, there’s little reason to try and jam your code into as few lines as possible.  For the most part, bigger is better.
    • Even though code blocks, such as if and while statements, do allow you to omit the curly braces, this generally makes your code harder to read.  The general consensus is to always use curly braces even when there is only one line of code you are executing between them.
    • Consistency, consistency, consistency.  If you put new lines after you close blocks of code, be sure you do it everywhere.  Don’t “feel it out.”  Come up with your own strategy (preferably similar or the same to most other peoples’ strategies) and stick to it.

    4.  Always specify your access modifiers and choose them carefully.

    C# access modifiers are simply the public, internal, protected, and private keywords that you typically place in front of variables, properties, and methods.  Though these are often overlooked, they provide meaning to the functionality behind your code and help to better define the structure of your code through encapsulation.

    Here are some grossly oversimplified definitions and uses for the four modifiers.  These definitions are lacking some detail, but should be plenty of information to handle the vast majority of circumstances:

    Private members are only accessible to the class in which they live.  All variables, properties, methods, etc. that do not need to be accessed outside the immediate class should be marked as private.

    Protected members are accessible to the class in which they live, as well as any classes that derive from (extend) the class.  The protected modifier should be used on variables, properties, methods, etc. that may need to be accessed by classes that may derive from (extend) the current class.

    Internal members are accessible everywhere within the current project, but are inaccessible by other projects that might reference the current project.  In other words, using the internal modifier specifies that only classes within the current EXE or DLL file can access the member.  The internal modifier should be used on all variables, properties, methods, etc. that need to be available to other classes within the project, but should not be available outside the project.

    Public members are accessible everywhere, period.  There are no restrictions to their access.  This particular modifier is often overused, as the internal modifier is overlooked.  The public modifier should only be used for members or classes that are or would possibly be needed outside of the current project.

    As far as defining classes, typically only internal or public are used, depending on if they need to be accessible outside the project.  This, however, does not account for nested classes, which can have any of the four access modifiers.  Always specify your access modifiers to avoid confusion as to when and where the class or member can be used.

    5.  Learn the ways to properly use exceptions and stick to them.

    C# exceptions are extremely powerful and convenient, but when used incorrectly, they can both slow your application down and hinder output to the end user.

    There are two basic rules of thumb to using exceptions properly:

    • Never catch an exception when you can check for and prevent the error instead.  A typical scenario is trying to open a file that you’re not entirely sure really exists.  You can wrap the file open code in a try catch, or you can use File.Exists to determine if the file exists before attempting to open it.  Exceptions in C# are expensive, so you only want an exception to be raised if a true error occurs.  If you can predict that it might happen for a particular reason, you should be able to check to make sure that it won’t happen before proceeding.  This will help to improve performance significantly.
    • Also, never catch the root Exception class, or any high-level, broad exception.  If you catch an Exception class, and you incorrectly assume that the user didn’t fill in a particular field as a result, the user will see your incorrect error message and be unable to see the actual error that occurred.  This is unacceptable.  Instead, research the methods you are calling to determine the particular types of exceptions they raise, and catch these specific exceptions.  This way, if something occurs that you didn’t expect, the end user will see the detailed error message anyway.  The MSDN documentation does a great job of providing you with all of the details you need regarding every exception that is possible for every single method in the .NET framework.

    6.  ALWAYS use using statements.

    In case you’re not familiar with the syntax of using statements, here is an example:

    
    using (StreamWriter writer = new StreamWriter("C:\\file.txt"))
    {
        writer.WriteLine("Hello!");
    }
    

    Using statements can be used wherever you’re instantiating an object that is IDisposable (can be disposed using the Dispose method).  If you don’t actively dispose objects that support the IDisposable interface, you’re asking for all sorts of performance and memory leak trouble.  Here are the advantages of using statements over calling the Dispose method directly:

    • Even if an exception is raised within your using statement block, the runtime will still ensure that the object gets properly disposed.  This is automatic with the using statement and is impossible without it.  Before using statements were added in .NET 2.0, you had to attempt to dispose of your objects within a catch block, which was far from error-prone.  Never take this approach.
    • Using statements help to visually define the scope of a variable that requires disposing.  You can quickly and easily see the start and end of the lifetime of the variable.  Once you are in the habit of consistently using using statements to dispose of objects you will very rarely (if ever) forget to dispose of an object, because of the block nature of the statement.
    • Using statements even allow you to return from a method within the statement.  The object is still disposed of properly in this situation.  In other words, if you use a using statement, the object is GUARANTEED to be disposed of despite any and all circumstances.  That’s a pretty big and valuable promise.

    There is much more to writing good C# code than these 6 rules, but these are the rules that I see consistently broken that are driving me to an early grave.  Let me know in the comments if you think I’m missing something important or disagree with any of my statements.

This entry was posted in C# , Technology , Visual Studio 2008 . Bookmark the permalink .

4 Responses to 6 Anal-Retentive Ways To Improve Your C# Code

  1. Josh says:

    Look into StyleCop ( http://code.msdn.microsoft.com/sourceanalysis ), it’s just as anal as code analysis except on code style (whitespace, comments, etc.). Another tool to add to clean code.

  2. Jason Carr says:

    Wow…I’ve been wondering about something like that for a long time. Thanks for the addition, Josh. :)

  3. Justin Chmura says:

    That thing is kind of neat. It does seem to be quite anal though.

  4. Jason Carr says:

    Haha…that thing?  Yes…anal it is, and anal it must be. ;)

Leave a Reply

Your email address will not be published. Required fields are marked *

*