DEV Community

Cover image for Sliding Idiomatic Code
Prayson Wilfred Daniel
Prayson Wilfred Daniel

Posted on

Sliding Idiomatic Code

Writing efficient and concise code starts with a solid understanding of programming fundamentals and ends with mastering the syntax, structure, and idioms of a specific language. Idiomatic code is easy for other programmers to understand and recognize patterns in, making it a valuable tool for any developer.

As programming languages evolve, so do the best practices and idioms. In Python, for example, the way to read a file has changed over time. An old, anti-pattern way of reading a file would be:

_FILE = "data/pears.png"

# anti-pattern 😫
f = open(_FILE, mode="rb")
img_bytes = f.read()
# do awesome things
f.close()
Enter fullscreen mode Exit fullscreen mode

This way of reading a file is considered an anti-pattern because it doesn't ensure that the file is properly closed. A better way to read a file would be:

# O.K. Meh 😒
try:
    f = open(_FILE, mode="rb")
    img_bytes = f.read()
    # do something awesome

finally:
    f.close()
Enter fullscreen mode Exit fullscreen mode

Even better would be to use the with statement:

# better 😏
with open(_FILE, mode="rb") as f:

    img_bytes = f.read()
    # do something awesome

Enter fullscreen mode Exit fullscreen mode

Or even better yet, using the Path class from pathlib:

# awesomeness 🤗
from pathlib import Path

img_bytes = Path(_FILE).read_bytes()
# do something awesome 
Enter fullscreen mode Exit fullscreen mode

By staying up-to-date with the latest idioms and best practices, you can write code that is more efficient, concise, and easy to read for other programmers. Keep learning, keep experimenting, and keep writing idiomatic code.

Until then, keep on coding, idiomatically!

Top comments (0)