Code Golf: Pros and Cons

Jacob on Software
Dec 20, 2020 · 6 min read

As programmers, we often aspire to be the good kind of lazy. It’s what attracted many of us to the tech sector in the first place. With code we’re able to optimize and in many cases automate our daily tasks, leaving us to spend our time how we please. The same rules apply to the way we write code. Why write dozens of lines — meticulously checking every possible spelling mistake, unaccounted for white space, or forgotten colon until you can feel your eyes beating— when a shorter solution works just as well? While most people envision lazy programmers as people who sit around playing Fortnite with Jake Paul fans all day, experienced engineers know what can be accomplished with relatively few lines of code.

Image for post
Image for post
h/t JAXenter

In fact, coders are so obsessed with who can do what with the least amount of code that they’ve created their own game out of it: code golf. As in regular golf, the goal of code golf is to produce a working solution to a problem while typing the fewest number of characters (or utilizing the smallest amount of memory). Originally conceived by a small group of Perl programmers in the late 1990’s, code golf has since spawned crowded message boards and competitions, with skillful programmers vying for who can come up with the most creative, (and technically “simplest”) solutions to incredibly complex problems.

Example: Caesar Cipher

A good example of what can be done with code golf is illustrated by the caesar cipher problem. Taking its name from the way Roman emperor Julius Caesar communicated with his soldiers on the battlefield, the caesar cipher takes in words and or complete sentences (what programmers commonly think of as strings) as well as a number, and then shifts each letter in that string up or down the alphabet by that number . For example, with a right shift of 3, an “A” would become a “D,” a “B” would become a “E,” and so on.

Image for post
Image for post

The caesar cipher is a common interview question for computer programmers, wherein interviewees are asked to write a function that emulates a caesar cipher. A typical caesar cipher solution in Ruby might look something like this:

def caesar_cipher (string, number)
caesar_string = ""

string.scan (/./) do |i|
if ("a".."z").include? (i.downcase) # Identify letters only.
number.times {i = i.next}
end
caesar_string << i[-1]
end
return caesar_string

end
caesar_cipher("abc", 10)
# => "klm"

While this is a perfectly reasonable piece of code to solve this problem, at 267 characters it is a bit verbose. Compare this with a typical example of a code golf solution to the same problem:

# h/t github.com/JoshCheekdef c(s,n)s.gsub(/./){|c|(c.ord+n).chr}endc("abc", 10)
# => "klm"

At only 42 characters, this solution demonstrates the creative ways in which code golfers solve problems.

The Benefits of Code Golf

To be sure, most code golf solutions look like unintelligible gibberish, and you probably don’t want to use it in your production code. However, there can be some benefits to practicing code golf solutions beyond saving yourself a dozen keystrokes or so. Some of the benefits are:

  1. Learning about more esoteric aspects of a particular language: While all programming languages have roughly the same bare bones and follow similar patterns of logic, every language has its advantages and disadvantages. As programmers, it’s our responsibility to train ourselves in the relative merits of each language, ensuring that we know which tool to reach for at the proper time. When practicing code golf in Ruby, for example, programmers may come to learn that Ruby allows for multiple variable assignment on one line, or that the *Splat operator can make the number of arguments a method takes flexible (among other things). While these facets of the language may seem arcane, code golfers by and large report that they take skills they learn from recreational coding into their day jobs.
  2. Practicing intimidating programming concepts: Even learning the basics of computer programming can be daunting, and it can be especially difficult for self-taught programmers to push themselves to learn more difficult computer programming techniques without extrinsic motivation. By competing with other code golfers, programmers can introduce that much needed incentive to their learning process. Who knows, with an upcoming code golf competition to motivate you, you might finally learn how to use a ternary operator.
  3. Restricting your typical coding process: Like elite athletes that train at high altitudes to improve their physical conditioning, putting additional constraints on how you code can ultimately improve your ability to think of creative solutions. Although code golfing might feel like programming with one hand tied behind your back, forcing yourself to be innovative and utilize lateral thinking will only improve your programming abilities when you remove those limitations, building up previously unforeseen mental models to help you grow as a developer.
Image for post
Image for post
h/t Outside Magazine

WARNING: Code Golf is For Fun

While it may seem obvious, programmers should not write all of their code as though they’re in a code golf challenge, and it’s not likely to advance your professional career beyond bragging rights. Imagine walking into a code review with your boss, eager to show them the innovative way you’ve printed “Hello, World!” to the screen in this nifty little language called Brainf***. It only takes up 72 bytes of memory! It’s amazing! Then, you pull this up on your screen:

--<-<<+[+[<+>--->->->-<<<]>]<<--.<++++++.<<-..<<.<+.>>.>>.<<<.+++.>>.>>-.<<<+.

A million things are probably racing through your manager’s head at this moment. Maybe they’re asking themselves what all this code is supposed to mean, or how they’re possibly going to maintain code like this if you ever leave the team, or why they hired you. More than anything, they’re probably thinking this:

Image for post
Image for post

Knowing the shortest or least memory-intensive ways to write code won’t do us much good in an interview or on the job. As programmers, our primary job is not to write the shortest solutions to a given problem, but to write clean, readable code. As Jon Bentley writes in Programming Pearls, “elegant code is the result of careful analysis of the problem, and finding an algorithm and design which simplifies the code greatly.” In following sound design principles, programmers have built incredible inventions and revolutionized the world. So while code golf may be a fun party trick and a way to win free internet points amongst your friends, it’s probably not your best bet for your day-to-day work.

Still, code golf can be a fun exercise, and it will undoubtedly make you a better programmer overall. Learning to test yourself in new and interesting ways is a big part of what makes programming interesting, and code golf offers an experience like almost nothing else. Luckily, there are a number of options today for people interested in challenging themselves with code golf. Thousands of developers post problems and solutions on communities like StackExchange and reddit, coding competitions increasingly add code golf challenges to their slate of contests, and some companies even host fun tournaments for employees. Hopefully this inspires you to get out there and start golfing!

Image for post
Image for post

The Startup

Medium's largest active publication, followed by +773K people. Follow to join our community.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store