Replacing loops and conditionals with functions

Adam Whatan recently published book and series of videos named Refactoring with Collections. In his book he talks about replacing loops and conditions using functions. So let’s begin discussing that here.

But first, theory. There are two ways of programming, imperative and declarative programming. Imperative programming is style of programming the focuses on how something is done. This is the way we are taught to program at first. If we have list of players and we want to have their scores we would do something like this.

This is perfectly fine. But we are reveling all the steps of how we get the scores here. That is a wrong approach. We are focused on implementation details and that is not the point. We don’t want to know how we get the scores. We just want them.

That’s why there is a second approach called declarative programming.

Consider SQL equivalent of getting all scores from players.

We don’t know and we don’t care about implementation details here of getting score from players here. We just want the results.

So let’s try and have similar example in PHP.

So here we have a function called map. And in that function we are going to use foreach. But that foreach is going to be generic. When I said that we are going to replace loops and conditions I meant you will have to write them only once and only in one place, inside this functions.

Map function will look like this.

But we may have a bug here. We only want players that have score that is not null. So we need a condition. This is where we come to another problem with imperative programming. We are trying to do too many steps in the same time. We are looping and inside loop we are checking stuff. You would agree that is ugly.

The beauty in declarative programming is that we are always going step by step. So in order to map array and get the scores we first need to filter out all the players that got score equal to null.

We do that with filter function.

So finally we get this

See how much more readable this is and we have hidden all implementation from users.

We can improve this a lot more by introducing Collections, but we are going to talk about that in future blog posts. For now it’s important for You to understand the importance of implementing stuff step by step and hiding implementation, because that would make Your life easier when debugging big applications.

Anel Bejtović

About the Author

Anel Bejtović

29 year old software developer and beer brewer from Mostar, Bosnia and Herzegovina, currently living and working in Frankfurt am Main, Germany.

Follow Anel Bejtović: