Why you should stop using loops

If you have been programming for more than 2 secs. You are probably already familiar with loops.

In PHP (which is the language we will be talking about in this post) there are three common methods to run a loop.

  • While
  • For
  • Foreach

Even seasoned programmers make generous use of this constructs. While they still have their use, I am here to tell you that their more functional equivalents

  • array_map
  • array_walk
  • array_filter

are far much better.

To demonstrate this point here is a gist showing a snapshot of a short demo. The full demo can be found here https://github.com/prodeveloper/array_compares This code capitalizes first name of each string.

Here is a the snapshot

Just from the code above you see the following benefits:

  1. Functional constructs are are far more concise: From our example above there we’re 2 more lines in the loop constructs than in functional ones. This may seem trivial but a typically project has thousands of lines of code. You do the math.
  2. Functional construct enforces single logic for a function: It may not seem like it at first glance but loop constructs are in fact executing two pieces of logic in that one function. The first one to loop through an array the second to actually deliver the payload to the string.

 

  1. Less variables in functional constructs: You note we needed to create a variable to hold the value that the pointer is currently pointing to. Its usually best to reduce variables where it makes sense. If nothing else to save ourselves the hustle of coming up with names
  2. Readability is compromised in loop constructs: To understand what is happening we must understand both the function being called and how the looping works. Case in point did you notice the name variable was passed by reference?

Well I am sure there are far more benefits to the functionals. If you have something to add, would love to hear from you.

Thank you!

Chencha Jacob

Facebooktwittergoogle_plusredditpinterestlinkedinmail

Published by

jchencha

API Engineer