Today I Learned - Rocky Kev

TIL about Code Golf

POSTED ON:

TAGS:

My blood level rises every time I see code that tries to reduce character count.

// 31 characters 😞
Math.floor(Math.random() * 100)

// 21 characters 🙂
~~(Math.random()*100)

// 19 characters 😄
Math.random()*100|0

This is known as code golf.

Here's what the problems are:

  1. The code is less readable.
  2. This adds more room for typos/errors/bugs.
  3. Who is this optimizing for?

Written code is for humans, compiled code is for computers.

Maybe there are shorter ways to write a block of code. But it's up to the developer team to make that decision.

My rule of thumb? If you can't understand the code the next day, re-write it. Your future self will thank you.

Code via https://understandlegacycode.com/blog/refactoring-rule-of-three/


Related TILs

Tagged:

TIL about Code Golf

Stop with the code golf. My blood level rises every time I see code that tries to reduce character count.

TIL AHA programming, like WET and DRY

AHA ('Avoid Hasty Abstractions')

TIL Golfing

Recreational programming