6 more things C# developers should (not) do

来自:http://blog.goyello.com/2013/01/30/6-more-things-c-developers-should-not-do/

For all wondering what are the things a C# developer should and should not do. As the continuation of my previous post  8 Most common mistakes C# developers make I decided to write another article about the things C# developers should always be aware of.

1. Try to avoid using the “ref” and “out” keywords.

There is rarely a situation that you really have to use “ref” or “out” keywords. It should be avoided as much as possible, because when you use them it means that your method probably tries to do too much (and therefore breaks the  Single Responsibility Principle). It can also make your method less readable. To accomplish the goal of not using ref/out keywords it is usually enough to create a class that will represent multiple return values and then return an instance of this class as a result of the method. There are obviously situations when the usage of ref/out cannot be avoided like when using TryParse method, but these should be treated as exceptions to the rule.

2. Do not use OrderBy before Where

The above statement might sound very obvious but anyway some developers tend to forget about this. Let’s take a look at the following code:
1
2
3
var allCitiesInPoland =
     allCitiesInTheWorld.OrderBy(x => x.Name)
                        .Where(x => x.Country == Country.Poland);
In this hypothetical scenario firstly the collection of all cities in the world (according to some statistics: 2,469,501) will be sorted and then only these from Poland (897) will be returned. The result will be appropriate, the only problem is that it will be simply inefficient. Using the following code:
1
2
3
var allCitiesInPoland =
     allCitiesInTheWorld.Where(x => x.Country == Country.Poland)
                        .OrderBy(x => x.Name);
First of all we will choose only the cities from Poland and then order this significantly smaller collection alphabetically by name.

3. Always use Properties instead of public variables

When using getters and setters you can restrict the user directly from accessing the member variables. Secondly, you can explicitly restrict setting the values. Thanks to this you make your data protected from accidental changes. What is more, when using properties,  it is much easier to validate your data.

4. Take advantage of string.IsNullOrEmpty() and string.IsNullOrWhiteSpace()

Instead of:
1
2
3
4
if (name != null && name != string .Empty)
{
     [...]
}
It’s better to use:
1
2
3
4
if ( string .IsNullOrEmpty(name))
{
     [...]
}
Sometimes we want to make sure that a string is not only not empty and not null, but also does not comprise of whitespaces. In such situation we could of course use the following code:
1
2
3
4
if ( string .IsNullOrEmpty(name.Trim()))
{
     [...]
}
But why not using something that is already provided by the .NET framework (in version 4.0 and higher):
1
2
3
4
if ( string .IsNullOrWhiteSpace(name))
{
     [...]
}
The example above can be treated as a more general principle. You should simply always try to find out whether something that you implemented is not already existing as a ready method in the framework that you use. Make sure that you went through all the methods in such .Net classes as e.g. String or IO.Path. This might potentially save you some time that you could have spent on reinventing the wheel.

5. Understand the difference between First() and Single()

Always remember that First() returns the very first item of the sequence, if no item exists it throws InvalidOperationException, whereas Single() Returns the  only item in the sequence, if no item exists it throws  InvalidOperationException,and if more than one item exists, it also throws  InvalidOperationException.

6. Do not blindly use List

There are some cases when the usage of List is simply not recommended from performance point of view. You should be aware of the existence of e.g. HashSet or SortedSet which can  considerably improve the performance, especially in case of large sets of items. To make you aware of how big the difference in performance between these two is, let’s consider the following piece of code:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class Program
{
     static void Main( string [] args)
     {
         const int COUNT = 100000;
         HashSet< int > hashSetOfInts = new HashSet< int >();
         Stopwatch stopWatch = new Stopwatch();
         for ( int i = 0; i < COUNT; i++)
         {
             hashSetOfInts.Add(i);
         }
 
         stopWatch.Start();
         for ( int i = 0; i < COUNT; i++)
         {
             hashSetOfInts.Contains(i);
         }
         stopWatch.Stop();
 
         Console.WriteLine(stopWatch.Elapsed);
 
         stopWatch.Reset();
         List< int > listOfInts = new List< int >();
         for ( int i = 0; i < COUNT; i++)
         {
             listOfInts.Add(i);
         }
 
         stopWatch.Start();
         for ( int i = 0; i < COUNT; i++)
         {
             listOfInts.Contains(i);
         }
         stopWatch.Stop();
 
         Console.WriteLine(stopWatch.Elapsed);
         Console.Read();
     }
}
After executing it you will see the difference: 
100000 ‘Contains’ operations using HashSet:  0.002 sec
100000 ‘Contains’ operations using List:  28.74 sec

Of course HashSets or SortedSets are not golden means for every possible scenario. HashSet should be used in case when you care about the performance (especially if you know that you will operate on a large set of items) but do not care about the order. SortedSet is a bit slower than HashSet but will give you a sorted collection and is much faster than List.

Use List when you want to iterate through the collection. Iterating through all the items in a List it is generally much faster than through a set (unless you use inside such methods as Contains).

If you know any other thing that C# developers should or should not do feel free to share it with us and leave a comment below!

P.S. What you should be aware of is that the guidelines presented in this (and in the previous post) will not suddenly make you a great C# programmer. What makes someone a good developer is the everyday compliance with the basic principles of creating high quality code which I described in details in the postTop 9 qualities of clean code.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值