Hidden Loops
Alex Bolboacă, @alexboly, alex.bolboaca@mozaicworks.com
May 2017
1
What is it?
Why is it a problem?
How to remove it
Advantages and Disadvantages of the final design
To Close. . .
2
What is it?
3
Say whaaa?
A repetitive code structure that can be turned into a loop,
usually with the help of higher abstraction data structures.
4
Typical example
if(firstCondition)){
// do anything here
}
if(secondCondition){
// do something else here
}
if(thirdCondition){
// even something else here
}
5
Equivalent example
if(firstCondition)){
// do anything here
}
else if(secondCondition){
// do something else here
}
else if(thirdCondition){
// even something else here
}
6
What is else if?
if(firstCondition)){
// do anything here
}
if(!firstCondition && secondCondition){
// do something else here
}
if(!firstCondition && !secondCondition && thirdCondition){
// even something else here
}
// Structurally equivalent with the first example
7
Second equivalent example
switch(variable){
case firstCondition:
// do anything here
break;
case secondCondition:
// do something else here
break;
default:
// even something else here
break;
}
8
Why is it a problem?
9
Tends to grow in complexity
if(firstCondition)){
for(....){
if(...){
....
}
}
}
else if(secondCondition){
if(...){
...
}
}
10
Tends to grow in size
if(firstCondition)){
// do anything here
}
else if(secondCondition){
// do something else here
}
else if(thirdCondition){
// even something else here
}
else if ....
else if ...
11
Often violates Open Closed Principle
Figure 1: Design entities should be open to extension and closed to
modification
12
It’s a risk
Figure 2: Be aware of the risks and ready to respond. Don’t remove all
risks today.
source: https://www.blackline.com/blog/wp-content/uploads/2014/12/Risk1.jpg
13
How to decide if it needs to be removed
if( numberOfConditionals >= 3 &&
weExpectToAddMoreConditionals ||
weHaveTheSamePatternInMorePlacesInCode ||
judgementCall ){
considerRemovingIt()
}
14
How to remove it
15
Removal steps
1. Remove similarity
2. Make the loop explicit
3. Refactor for statement
4. (Optional) Make it configurable
16
An example would be good
Figure 3: TicTacToe Board and pieces made of Lego 17
Decide winner for TicTacToe
Result winner(Board board){
if(anyLineFilledWith('x') || anyColumnFilledWith('x')
|| anyDiagonalFilledWith('x'))
return Result.XWins;
if(anyLineFilledWith('0') || anyColumnFilledWith('0')
|| anyDiagonalFilledWith('0'))
return Result.0Wins;
if(board.notFilledYet())
return Result.GameNotOverYet;
return Result.Draw;
}
18
1. Remove similarity
Result winner(Board board){
if(xWinsRule.matchesFor(board))
return Result.XWins;
if(0WinsRule.matchesFor(board))
return Result.0Wins;
if(notGameOverRule.matchesFor(board))
return Result.GameNotOverYet;
return Result.Draw;
}
19
2. Make the loop explicit
Map rulesToResult = new HashMap{
{new XWinsRule(), Result.XWins},
{new OWinsRule(), Result.OWins},
{new NotOverGameRule(), Result.GameNotOverYet)},
{new DefaultRule(), Result.Draw)}
};
Result winner(Board board, Map rulesToResult){
for(Rule rule in rulesToResult.keys()){
if(rule.applies(board)
return rulesToResult[rule];
}
}
20
3. Refactor for statement
Result winner(Board board, Map rulesToResult){
Entry<Rule, Result> firstItemWhoseRuleMatches =
rulesToResults.find{
ruleToResult->(
ruleToResult.key.matchesFor(board)
)
}
return firstItemWhoseRuleMatches.value
}
21
4. (Optional) Make it configurable
• At compile time, use DependencyInjection to inject the map
of rules to results
• At run time, use plugins or reflection to instantiate rules and a
configuration file
22
Advantages and Disadvantages of
the final design
23
Advantages
• Short methods
• Easy to change:
• To add a new rule, create a new class and add an object of that
class to the map
• No change in winner() function to configure the algorithm for
another board & set of rules
• Follows Open Closed Principle and Single Responsibility
Principle
• Very easy to unit test in isolation
24
Disadvantages
• Requires developers to understand functional constructs
• In this particular case, it has an internal logical coupling:
rules have to be logically exclusive. Can deal with this by using
single() instead of first() or by using a smarter map
• Uses higher level abstractions(rules, result) that can be
harder to understand depending on context
25
To Close. . .
26
Recap
• Hidden loops is a pervasive code smell
• Like any smell, it points to potential problems, it doesn’t
mean it should always be removed
• When removed, you should obtain code that is more easily
extensible and testable
• But you need to know functional constructs and be careful
when changing code. But you have tests, don’t you? :)
27
Find Me
Twitter: alexboly
LinkedIn:
https://www.linkedin.com/in/alexandrubolboaca/
Blog: http://alexbolboaca.ro
Mozaic Works Blog: https://mozaicworks.com/blog
eventriX: https://eventrix.co/s/alexandru-bolboaca-56
LeanPub: https://leanpub.com/u/alexbolboaca
28
Q&A
29

More Related Content

PDF
Ah unit 1 differentiation
PDF
LEC 6-DS ALGO(updated).pdf
PPT
The chain rule
DOCX
graficas matlab
PPTX
adders/subtractors, multiplexers, intro to ISA
 
PPT
Chain Rule
DOCX
Chain rule
PDF
CRL 1.8 Functions
Ah unit 1 differentiation
LEC 6-DS ALGO(updated).pdf
The chain rule
graficas matlab
adders/subtractors, multiplexers, intro to ISA
 
Chain Rule
Chain rule
CRL 1.8 Functions

What's hot (18)

PPTX
The Chain Rule Powerpoint Lesson
PDF
CRL 1.8 functions MrG 2011.0920 - sage
PDF
The Ring programming language version 1.5.3 book - Part 69 of 184
PPTX
Scrollytelling
PPT
Compfuncdiff
PDF
12X1 T01 03 integrating derivative on function
PDF
03 chain rule
PDF
The Ring programming language version 1.8 book - Part 66 of 202
DOCX
PDF
Christian Gill ''Functional programming for the people''
PDF
ゲーム理論BASIC 演習4 -交渉集合を求める-
PDF
Lesson 10: The Chain Rule
PDF
Clase 16 dsp
PDF
ゲーム理論BASIC 演習5 -カーネルを求める-
PDF
Clase 15 dsp
PDF
Regras diferenciacao
PPTX
Rules of derivatives 2.2
PPTX
Python data structures
The Chain Rule Powerpoint Lesson
CRL 1.8 functions MrG 2011.0920 - sage
The Ring programming language version 1.5.3 book - Part 69 of 184
Scrollytelling
Compfuncdiff
12X1 T01 03 integrating derivative on function
03 chain rule
The Ring programming language version 1.8 book - Part 66 of 202
Christian Gill ''Functional programming for the people''
ゲーム理論BASIC 演習4 -交渉集合を求める-
Lesson 10: The Chain Rule
Clase 16 dsp
ゲーム理論BASIC 演習5 -カーネルを求める-
Clase 15 dsp
Regras diferenciacao
Rules of derivatives 2.2
Python data structures
Ad

Similar to Hidden loops (20)

PPTX
Yin Yangs of Software Development
PPTX
FPL -Part 2 ( Sem - I 2013)
PPTX
module1 new c programming for begginers.pptx
PPTX
Introduction to frameworks
PPTX
04. introduction to frameworks
PDF
Mpg Feb08 Gian Lorenzetto
PDF
Algorithms and how to write an algorithms
PPTX
CSE-113 UNIT-1 with the basic knowledge of the computer science.pptx
PPTX
6. using control structures, conditional statements and loops
PPT
Unit 1 psp
PPTX
2 Years of Real World FP at REA
PDF
Counter design.pdf
PDF
Patterns, Code Smells, and The Pragmattic Programmer
PPTX
Daa unit 1
PDF
Android Application Development - Level 3
ODP
Interview questions slide deck
PPTX
Data Structures_Introduction to algorithms.pptx
PPTX
Algorithm and flowchart with pseudo code
PPTX
Introduction to Functional Programming
PPTX
Fuel Up JavaScript with Functional Programming
Yin Yangs of Software Development
FPL -Part 2 ( Sem - I 2013)
module1 new c programming for begginers.pptx
Introduction to frameworks
04. introduction to frameworks
Mpg Feb08 Gian Lorenzetto
Algorithms and how to write an algorithms
CSE-113 UNIT-1 with the basic knowledge of the computer science.pptx
6. using control structures, conditional statements and loops
Unit 1 psp
2 Years of Real World FP at REA
Counter design.pdf
Patterns, Code Smells, and The Pragmattic Programmer
Daa unit 1
Android Application Development - Level 3
Interview questions slide deck
Data Structures_Introduction to algorithms.pptx
Algorithm and flowchart with pseudo code
Introduction to Functional Programming
Fuel Up JavaScript with Functional Programming
Ad

More from Alexandru Bolboaca (20)

PDF
Refactor legacy code through pure functions
PDF
Design Without Types
PDF
Thinking in Functions
PDF
Raising the Bar
PDF
The Journey to Master Code Design
PDF
What is good software design? And why it matters?
PDF
Functional programming in C++
PDF
Agile Technical Leadership
PDF
TDD As If You Meant It
PDF
Usable Software Design
PDF
Removing structural duplication
PDF
Continuous delivery
PDF
Why You Should Start Using Docker
PDF
Pyramid of-developer-skills
PDF
Applied craftsmanship
PDF
Pyramid of-developer-skills
PDF
Stay focused
PDF
Kanban intro
ODP
Unit testing-patterns
ODP
Incremental design, simply explained
Refactor legacy code through pure functions
Design Without Types
Thinking in Functions
Raising the Bar
The Journey to Master Code Design
What is good software design? And why it matters?
Functional programming in C++
Agile Technical Leadership
TDD As If You Meant It
Usable Software Design
Removing structural duplication
Continuous delivery
Why You Should Start Using Docker
Pyramid of-developer-skills
Applied craftsmanship
Pyramid of-developer-skills
Stay focused
Kanban intro
Unit testing-patterns
Incremental design, simply explained

Recently uploaded (20)

PPTX
Chapter 1 - Transaction Processing and Mgt.pptx
PPTX
Streamlining Project Management in the AV Industry with D-Tools for Zoho CRM ...
PDF
Mobile App for Guard Tour and Reporting.pdf
PPT
3.Software Design for software engineering
PDF
Top 10 Project Management Software for Small Teams in 2025.pdf
PPTX
Chapter_05_System Modeling for software engineering
PPTX
Foundations of Marketo Engage: Nurturing
PDF
Odoo Construction Management System by CandidRoot
PDF
Mobile App Backend Development with WordPress REST API: The Complete eBook
PPTX
Bandicam Screen Recorder 8.2.1 Build 2529 Crack
PDF
Sanket Mhaiskar Resume - Senior Software Engineer (Backend, AI)
PDF
Multiverse AI Review 2025_ The Ultimate All-in-One AI Platform.pdf
PDF
Streamlining Project Management in Microsoft Project, Planner, and Teams with...
PPTX
UNIT II: Software design, software .pptx
PPTX
HackYourBrain__UtrechtJUG__11092025.pptx
PDF
Ragic Data Security Overview: Certifications, Compliance, and Network Safegua...
PPTX
Human-Computer Interaction for Lecture 1
PPTX
Comprehensive Guide to Digital Image Processing Concepts and Applications
PPTX
ESDS_SAP Application Cloud Offerings.pptx
PPTX
Folder Lock 10.1.9 Crack With Serial Key
Chapter 1 - Transaction Processing and Mgt.pptx
Streamlining Project Management in the AV Industry with D-Tools for Zoho CRM ...
Mobile App for Guard Tour and Reporting.pdf
3.Software Design for software engineering
Top 10 Project Management Software for Small Teams in 2025.pdf
Chapter_05_System Modeling for software engineering
Foundations of Marketo Engage: Nurturing
Odoo Construction Management System by CandidRoot
Mobile App Backend Development with WordPress REST API: The Complete eBook
Bandicam Screen Recorder 8.2.1 Build 2529 Crack
Sanket Mhaiskar Resume - Senior Software Engineer (Backend, AI)
Multiverse AI Review 2025_ The Ultimate All-in-One AI Platform.pdf
Streamlining Project Management in Microsoft Project, Planner, and Teams with...
UNIT II: Software design, software .pptx
HackYourBrain__UtrechtJUG__11092025.pptx
Ragic Data Security Overview: Certifications, Compliance, and Network Safegua...
Human-Computer Interaction for Lecture 1
Comprehensive Guide to Digital Image Processing Concepts and Applications
ESDS_SAP Application Cloud Offerings.pptx
Folder Lock 10.1.9 Crack With Serial Key

Hidden loops

  • 2. What is it? Why is it a problem? How to remove it Advantages and Disadvantages of the final design To Close. . . 2
  • 4. Say whaaa? A repetitive code structure that can be turned into a loop, usually with the help of higher abstraction data structures. 4
  • 5. Typical example if(firstCondition)){ // do anything here } if(secondCondition){ // do something else here } if(thirdCondition){ // even something else here } 5
  • 6. Equivalent example if(firstCondition)){ // do anything here } else if(secondCondition){ // do something else here } else if(thirdCondition){ // even something else here } 6
  • 7. What is else if? if(firstCondition)){ // do anything here } if(!firstCondition && secondCondition){ // do something else here } if(!firstCondition && !secondCondition && thirdCondition){ // even something else here } // Structurally equivalent with the first example 7
  • 8. Second equivalent example switch(variable){ case firstCondition: // do anything here break; case secondCondition: // do something else here break; default: // even something else here break; } 8
  • 9. Why is it a problem? 9
  • 10. Tends to grow in complexity if(firstCondition)){ for(....){ if(...){ .... } } } else if(secondCondition){ if(...){ ... } } 10
  • 11. Tends to grow in size if(firstCondition)){ // do anything here } else if(secondCondition){ // do something else here } else if(thirdCondition){ // even something else here } else if .... else if ... 11
  • 12. Often violates Open Closed Principle Figure 1: Design entities should be open to extension and closed to modification 12
  • 13. It’s a risk Figure 2: Be aware of the risks and ready to respond. Don’t remove all risks today. source: https://www.blackline.com/blog/wp-content/uploads/2014/12/Risk1.jpg 13
  • 14. How to decide if it needs to be removed if( numberOfConditionals >= 3 && weExpectToAddMoreConditionals || weHaveTheSamePatternInMorePlacesInCode || judgementCall ){ considerRemovingIt() } 14
  • 15. How to remove it 15
  • 16. Removal steps 1. Remove similarity 2. Make the loop explicit 3. Refactor for statement 4. (Optional) Make it configurable 16
  • 17. An example would be good Figure 3: TicTacToe Board and pieces made of Lego 17
  • 18. Decide winner for TicTacToe Result winner(Board board){ if(anyLineFilledWith('x') || anyColumnFilledWith('x') || anyDiagonalFilledWith('x')) return Result.XWins; if(anyLineFilledWith('0') || anyColumnFilledWith('0') || anyDiagonalFilledWith('0')) return Result.0Wins; if(board.notFilledYet()) return Result.GameNotOverYet; return Result.Draw; } 18
  • 19. 1. Remove similarity Result winner(Board board){ if(xWinsRule.matchesFor(board)) return Result.XWins; if(0WinsRule.matchesFor(board)) return Result.0Wins; if(notGameOverRule.matchesFor(board)) return Result.GameNotOverYet; return Result.Draw; } 19
  • 20. 2. Make the loop explicit Map rulesToResult = new HashMap{ {new XWinsRule(), Result.XWins}, {new OWinsRule(), Result.OWins}, {new NotOverGameRule(), Result.GameNotOverYet)}, {new DefaultRule(), Result.Draw)} }; Result winner(Board board, Map rulesToResult){ for(Rule rule in rulesToResult.keys()){ if(rule.applies(board) return rulesToResult[rule]; } } 20
  • 21. 3. Refactor for statement Result winner(Board board, Map rulesToResult){ Entry<Rule, Result> firstItemWhoseRuleMatches = rulesToResults.find{ ruleToResult->( ruleToResult.key.matchesFor(board) ) } return firstItemWhoseRuleMatches.value } 21
  • 22. 4. (Optional) Make it configurable • At compile time, use DependencyInjection to inject the map of rules to results • At run time, use plugins or reflection to instantiate rules and a configuration file 22
  • 23. Advantages and Disadvantages of the final design 23
  • 24. Advantages • Short methods • Easy to change: • To add a new rule, create a new class and add an object of that class to the map • No change in winner() function to configure the algorithm for another board & set of rules • Follows Open Closed Principle and Single Responsibility Principle • Very easy to unit test in isolation 24
  • 25. Disadvantages • Requires developers to understand functional constructs • In this particular case, it has an internal logical coupling: rules have to be logically exclusive. Can deal with this by using single() instead of first() or by using a smarter map • Uses higher level abstractions(rules, result) that can be harder to understand depending on context 25
  • 26. To Close. . . 26
  • 27. Recap • Hidden loops is a pervasive code smell • Like any smell, it points to potential problems, it doesn’t mean it should always be removed • When removed, you should obtain code that is more easily extensible and testable • But you need to know functional constructs and be careful when changing code. But you have tests, don’t you? :) 27
  • 28. Find Me Twitter: alexboly LinkedIn: https://www.linkedin.com/in/alexandrubolboaca/ Blog: http://alexbolboaca.ro Mozaic Works Blog: https://mozaicworks.com/blog eventriX: https://eventrix.co/s/alexandru-bolboaca-56 LeanPub: https://leanpub.com/u/alexbolboaca 28