How To Replace Repeated Loops With Higher Order Functions In Python

Pavol Kutaj
2 min readJul 15, 2022

--

The aim of this page📝is to follow Uncle Bob’s dictum of DRY for nested loops where I should pass lambda do to the job. This is the Python implementation of an answer to Uncle Bob’s question raised in Don’t Repeat Yourself (DRY principle)

…but what do you do when it’s not the code that’s duplicated it is the loops that are duplicated; how many of you have seen this problem: you’ve got a complex configuration data structure and to walk this complex configuration data structure, you have to have a big nested bunch of loops; a bunch of while loops and if statements that allow you to walk through the complex configuration data structure and then you finally get to the end nodes in there and you’ve got a bunch of processing code that processes the end nodes and then you see that same loop repeated over and over and over again inside different parts of the system, as the different parts of the system walk different parts of the configuration database; how can you get rid of that duplication ?

1. NOTES

  • Have a top-level parser that goes to the line item of a config file
  • Have a particular query/command that fixes that

2. EXAMPLE

  • I am not parsing a long config file, but a long manifest table listing documents in the knowledge base with the following structure which looks like

2.1. REPEATED LOOP

  • To get a single attribute within the app I need to have an elaborate loop and I need to repeat the looping each time to get down to the article level
  • Or If I want also to save the file

3. SOLUTION

3.1. HIGHER ORDER FUNCTION

3.2. PARTICULAR FUNCTION — QUERY

3.3. CALL

3.4. PARTICULAR FUNCTION — COMMAND

3.5. CALL

  • Once the pattern is established, it is pretty much the same thing

4. LINKS

--

--

No responses yet