Avoiding nesting

One of my goals when coding is to reduce the amount of nesting in the code I write.

I mean both in my PHP code where if conditions and foreach loops can be nested within each other, and CSS and Sass files, which support nesting CSS rules.

My aim is to have a maximum of two or three levels of indentation, though sometimes this isn't possible.

Doing so where I can, though, makes my code easier to read and understand and encourages other clean code approaches, such as having small and well-named functions.

In CSS or Sass, avoiding nesting makes it easier to find a rule I'm looking for instead of having to find how rules have been nested or names have been concatenated - making it hard to search or grep for a string.

This approach is part of "object callisthenics", which was introduced by Jeff Bay and includes other approaches that I like to follow, such as not using the else keyword and other good practices that I like to try and implement when possible.--

- Oliver

P.S. There's less than a year until Drupal 7's end-of-life date. Plan your upgrade to Drupal 10 now!

Was this interesting?

Sign up here and get more like this delivered straight to your inbox every day.

About me

Picture of Oliver

I'm an Acquia-certified Drupal Triple Expert with 17 years of experience, an open-source software maintainer and Drupal core contributor, public speaker, live streamer, and host of the Beyond Blocks podcast.