Nice programing

관용 부호 란 무엇입니까?

nicepro 2020. 11. 7. 10:28
반응형

관용 부호 란 무엇입니까?


저는 C # 전후의 몇 가지 예, 비 관용적 대 관용적 예에 관심이 있습니다. 비 c # 예제도 아이디어를 얻을 수 있다면 괜찮을 것입니다. 감사.


관용적이란 언어의 규칙을 따르는 것을 의미합니다. 다른 언어에서 지식을 이식하는 대신 작업을 수행하는 가장 쉽고 일반적인 방법을 찾고 싶습니다.

추가와 함께 루프를 사용하는 비 관용적 파이썬 :

mylist = [1, 2, 3, 4]
newlist = []
for i in mylist:
    newlist.append(i * 2)

목록 이해력을 사용하는 관용적 파이썬 :

mylist = [1, 2, 3, 4]
newlist = [(i * 2) for i in mylist] 

몇 가지 예 :

자원 관리 , 비 관용적 :

string content;
StreamReader sr = null;
try {
    File.OpenText(path);
    content = sr.ReadToEnd();
}
finally {
    if (sr != null) {
        sr.Close();
    }
}

관용적 :

string content;
using (StreamReader sr = File.OpenText(path)) {
    content = sr.ReadToEnd();
}

반복 , 비 관용적 :

for (int i=0;i<list.Count; i++) {
   DoSomething(list[i]);
}

또한 비관 상적 :

IEnumerator e = list.GetEnumerator();
do {
   DoSomenthing(e.Current);
} while (e.MoveNext());

관용적 :

foreach (Item item in list) {
   DoSomething(item);
}

비 관상적인 필터링 :

List<int> list2 = new List<int>();
for (int num in list1) {
  if (num>100) list2.Add(num);
}

관용적 :

var list2 = list1.Where(num=>num>100);

Idiomatic code is code that does a common task in the common way for your language. It's similar to a design pattern, but at a much smaller scale. Idioms differ widely by language. One idiom in C# might be to use an iterator to iterate through a collection rather than looping through it. Other languages without iterators might rely on the loop idiom.


In PHP I sometimes encounter code like:

foreach ($array as $value) {
    $trimmed[] = trim($value);
}
return $trimmed;

Which idiomatically can be implemented with:

return array_map('trim', $array);

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++)

참고URL : https://stackoverflow.com/questions/84102/what-is-idiomatic-code

반응형