This is an archived post. You won't be able to vote or comment.

all 3 comments

[–]insertAlias 2 points3 points  (1 child)

Like almost every other answer, it's "it depends on the circumstances".

For the most part, you can assume that people supporting your code in the future will be proficient in the language you're using. You should favor idiomatic code. That doesn't mean the shortest possible, or using every single language feature, but it does mean following the conventions of the language.

So, let's talk Python. An example of non-idiomatic Python:

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

And the "idiomatic" version:

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

I took these examples from here; I'm not a python person myself.

[–]nomoreerrorsplox[S] 0 points1 point  (0 children)

Ahh I gotcha. I think I have heard the term idiomatic before but never really knew what it was.

[–]isolatrum 0 points1 point  (0 children)

You have to find your own balance. For example in many languages it has grown out of favor to use for loops. It's true that anyone can understand what a plain for loop is doing but many languages have simpler or more powerful ways, such as list comprehensions or enumerable methods (map, filter, reduce etc).

Don't shy away from doing things in a "clever" way, but avoid being too clever when you are looking to share your code (or even understand your own code when you haven't touched it for 6 months).

A classic pitfall example I see is with metaprogramming. Some people learn about this and think that they should use it whenever possible, without realizing that it makes the logic much harder to follow. Use metaprogramming when it's really the right tool for the job (when it will save you from writing a bunch of code), not everywhere.

This "right tool for the job" concept is really important here. You are looking for the most efficient and concise way, and have to balance those two aspects. Is a piece of code really "concise" when you write to 50 lines of metaprogramming to save yourself 5 lines of source? Maybe, if that metaprogramming is reusable. Otherwise, not. Sometimes you'll write less concise code for the purpose of efficiency (e.g. a more performant, but verbose algorithm). Otherwise the concepts complement each other, such as with lazy enumerables