What is idiomatic code?
Idiomatic means following the conventions of the language. You want to find the easiest and most common ways of accomplishing a task rather than porting your knowledge from a different language.
non-idiomatic python using a loop with append:
mylist = [1, 2, 3, 4]
newlist = []
for i in mylist:
newlist.append(i * 2)
idiomatic python using a list comprehension:
mylist = [1, 2, 3, 4]
newlist = [(i * 2) for i in mylist]
Some examples:
Resource management, non idiomatic:
string content;
StreamReader sr = null;
try {
File.OpenText(path);
content = sr.ReadToEnd();
}
finally {
if (sr != null) {
sr.Close();
}
}
Idiomatic:
string content;
using (StreamReader sr = File.OpenText(path)) {
content = sr.ReadToEnd();
}
Iteration, non idiomatic:
for (int i=0;i<list.Count; i++) {
DoSomething(list[i]);
}
Also non-idiomatic:
IEnumerator e = list.GetEnumerator();
do {
DoSomenthing(e.Current);
} while (e.MoveNext());
Idiomatic:
foreach (Item item in list) {
DoSomething(item);
}
Filtering, non-idiomatic:
List<int> list2 = new List<int>();
for (int num in list1) {
if (num>100) list2.Add(num);
}
idiomatic:
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.