What is idiomatic code?

后端 未结 5 932
时光说笑
时光说笑 2020-12-07 14:22

I\'d be interested in some before-and-after c# examples, some non-idiomatic vs idiomatic examples. Non-c# examples would be fine as well if they get the idea across. Thanks.

5条回答
  •  天涯浪人
    2020-12-07 15:13

    Practically speaking, it means writing code in a consistent way, i.e. all developers who work on your code base should follow the same conventions when writing similar code constructs.

    So the idiomatic way is the way that matches the style of the other code, non-idiomatic way means you are writing the kind of function but in a different way.

    e.g. if you are looping a certain number of items, you could write the loop in several ways:

    for (int i = 0; i < itemCount; i++)
    
    for (int i = 1; i <= itemCount; i++)
    
    for (int i = 0; i < itemCount; ++i)
    

    etc

    What is most important is that the chosen style is used consistently. That way people become very familiar and confident with how to use it, and when you spy a usage which looks different it can be a sign of a mistake being introduced, perhaps an off by one error, e.g.

    for (int i = 1; i < itemCount; i++)
    

提交回复
热议问题