SlideShare a Scribd company logo
Tell me and I'll forget.
Show me and I might remember.
But involve me and I will understand.

1
A misconception

2
A misconception

3
Puzzle
Imagine arranging 6 glasses in a row and filling three
of them with water like this….

Every time you pick up a glass it counts as a move.
What is the smallest number of moves that needs to be
made in order to leave the glasses alternating full and
empty? -– Explain your answer.
4
Conditionals and Polymorphism

Presented by

Ashok Guduru
Technical Architect
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore

5
Inheritance & Polymorphism

Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore

6
Premise

Most ifs can be replaced with
polymorphism

Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore

7
Introduction
- Not all ifs but most of them cab be
replaced by polymorphism

- It is kind of fun to write code without ifs
(e.g. Smalltalk )

Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore

8
Conditionals and Polymorphism
• Why?: Why we need to avoid ifs
-

Functions without ifs are easier to read

-

Functions without ifs are easier to test

-

Functions without ifs are easier to
maintain and extend
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore

9
Conditionals and Polymorphism
NOTE: One of the grandest sounding words in object jargon is polymorphism.

• Polymorphism: What it is?:
-

-

You dispatch into a method who’s binding
not known at compile time (a good old
polymorphism)
E.g. a Class and a bunch of sub-classes
inheriting from for printing
You say print and its not known it is
printing to printer, screen or to a PDF
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore

10
Conditionals and Polymorphism
•

How do we get rid of ifs?
•

Use Polymorphism

-

If an object should behave differently
based on its state
If you have to check the same condition in
multiple places
Usually happens using flags and your code
is sprinkled with a bunch of ifs all over the
codebase

-

Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore

11
Conditionals and Polymorphism

• But… Use Conditionals
-

-

Mainly to do comparisons of primitive
objects: >, <, >=, <=, ==, != etc.
There are other uses but today we focus
only on avoiding ifs

Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore

12
Conditionals and Polymorphism

We’re going to focus on business logic that
should behave differently based on
conditionals

Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore

13
Conditionals and Polymorphism
•

To be if free…
-

Never return a null, instead return NullObject (Typically
an object that doesn’t do anything)
-

e.g. An empty list, A null logger

-

Nulls are your friends inside of a development test but
enemies in production code

-

When you return a null from a method you can’t
dispatch on null. You get a null pointer exception

-

Don’t return error codes, instead throw an exception
(Java RunTime Exception only.)
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore

14
Conditionals and Polymorphism

• What is a subclass?
- aka Base Class, Super Class, Parent Class etc.

Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore

15
Conditionals and Polymorphism

• Polymorphism uses subclassing
WARNING:
- Be careful about runaway subclassing
- Not to go and crazy on using more subclassing
- Deep inheritance hierarchies creates problems on
testability, understandability and couple of other
abilities as well.
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore

16
Conditionals and Polymorphism

State Based Behavior

Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore

17
Replace Conditionals with Polymorphism

Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore

18
Replace Conditionals with Polymorphism
•

You have a conditional that chooses different
behavior depending on the type of an object
- Move each leg of the conditional to an overriding
method in a subclass. Make the original method
abstract.
- The common logic stays in base class (super class)

Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore

19
Replace Conditionals with Polymorphism
public double GetSpeed() {
switch(_type)
{
case EUROPEAN:
return getBaseSpeed();
case AFRICAN:
return getBaseSpeed() – getLoadFactor() * _numberOfCoconuts;
case NORWEGIAN_BLUE:
return isNailed ? 0 : getBaseSpeed(_voltage)
default:
throw new ArgumentException(“Should be unreachable”);
// Java RuntimeException(“Should be unreachable”);
}
}

Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore

20
Replace Conditionals with Polymorphism

Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore

21
Replace Conditionals with Polymorphism
public abstract class Bird {
public abstract double GetSpeed();
protected double getBaseSpeed();
}
public class EuropeanBird : Bird {
public double GetSpeed() {
return getBaseSpeed()
}
}
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore

22
Replace Conditionals with Polymorphism
public class AfricanBird : Bird {
public double GetSpeed() {
return getBaseSpeed() – getLoadFactor() * _numberOfCoconuts;
}
}
public class NorwegianBlueBird : Bird {
public double GetSpeed() {
return isNailed ? 0 : getBaseSpeed(_voltage)
}

}

Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore

23
Replace Conditionals with Polymorphism
public class BirdFactory {
public double createInstance(_type) {
switch (_type)
case EUROPEAN
return new EuropeanBird();
case AFRICAN:
return new AfricanBird()
case NORWEGIAN_BLUE:
return new NorwegianBlueBird();
default:
throw new ArgumentException(“Should be unreachable”);
//Java RuntimeException(“Should be unreachable”);
}
}

Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore

24
Replace Conditionals with Polymorphism
public static main() {
Bird bird = BirdFactory.createInstance(BirdType.EUROPEAN);
SpeedCalculator sc = new SpeedCalculator(bird);
sc.Calculate();
}
public class SpeedCalculator {
private Bird _bird;
void SpeedCalculator(Bird bird) {
_bird = bird;
}
public void Calculate() {
return _bird.GetSpeed();
}
}
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore

25
Summary
•

A Polymorphic solution is often better
because
- New behavior can be added without having the
original source code, and
- Each operation/concern is separated in a separate
file which makes it easy to test/understand and
maintain

Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore

26
Summary
•

Prefer polymorphic over conditionals:
- Switch almost always means you should use
polymorphism
- Sometimes if…elseif… means same as switch
- In both of above cases the code is begging for
polymorphism. It is almost a rule… I can say!
- if is more subtle… sometimes an if is just and if
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore

27
Simple things should be simple and complex things
should be possible.
- Alan Kay

28
Puzzle
Imagine arranging 6 glasses in a row and filling three of them
with water like this….

Every time you pick up a glass it counts as a move. What is the
smallest number of moves that needs to be made in order to leave
the glasses alternating full and empty? -– Explain your answer.
29
Puzzle
Imagine arranging 6 glasses in a row and filling three of them
with water like this….

Every time you pick up a glass it counts as a move. What is the
smallest number of moves that needs to be made in order to leave
the glasses alternating full and empty? -– Explain your answer.
30
Puzzle
… and the answer is ONE

31
Books:
1. Agile Software Development
Principles, Patterns, and Practices
by Robert C. Martin (aka Bob Martin or Uncle Bob)

2. Effective Java by Joshua Bloch
3. Code Complete (2nd Edition) by Steve McConnell
Code Complete: A Practical Handbook of Software Construction

Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore

32
33
The amateur software engineer is always in
search of magic.
-- Grady Booch

Thank you!
Ashok Guduru
Blog: http://www.ashokg.com
Twitter: @AshokGudur

Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore

34

More Related Content

Similar to Conditionals and Polymorphism

SOLID, DRY, SLAP design principles
SOLID, DRY, SLAP design principlesSOLID, DRY, SLAP design principles
SOLID, DRY, SLAP design principles
Sergey Karpushin
 
SOLID design
SOLID designSOLID design
Core Java Programming Language (JSE) : Chapter IV - Expressions and Flow Cont...
Core Java Programming Language (JSE) : Chapter IV - Expressions and Flow Cont...Core Java Programming Language (JSE) : Chapter IV - Expressions and Flow Cont...
Core Java Programming Language (JSE) : Chapter IV - Expressions and Flow Cont...
WebStackAcademy
 
You shouldneverdo
You shouldneverdoYou shouldneverdo
You shouldneverdo
daniil3
 
Protecting JavaScript source code using obfuscation - OWASP Europe Tour 2013 ...
Protecting JavaScript source code using obfuscation - OWASP Europe Tour 2013 ...Protecting JavaScript source code using obfuscation - OWASP Europe Tour 2013 ...
Protecting JavaScript source code using obfuscation - OWASP Europe Tour 2013 ...
AuditMark
 
Owaspeutour2013lisbon pedrofortunaprotectingjavascriptsourcecodeusingobfuscat...
Owaspeutour2013lisbon pedrofortunaprotectingjavascriptsourcecodeusingobfuscat...Owaspeutour2013lisbon pedrofortunaprotectingjavascriptsourcecodeusingobfuscat...
Owaspeutour2013lisbon pedrofortunaprotectingjavascriptsourcecodeusingobfuscat...
Thiện Dương
 
Writing Readable Code
Writing Readable CodeWriting Readable Code
Writing Readable Code
eddiehaber
 
New Ideas for Old Code - Greach
New Ideas for Old Code - GreachNew Ideas for Old Code - Greach
New Ideas for Old Code - Greach
HamletDRC
 
Making an Exception
Making an ExceptionMaking an Exception
Making an Exception
Kevlin Henney
 
Property based tests and where to find them - Andrzej Jóźwiak - TomTom Webina...
Property based tests and where to find them - Andrzej Jóźwiak - TomTom Webina...Property based tests and where to find them - Andrzej Jóźwiak - TomTom Webina...
Property based tests and where to find them - Andrzej Jóźwiak - TomTom Webina...
Andrzej Jóźwiak
 
How Functional Programming Made Me a Better Developer
How Functional Programming Made Me a Better DeveloperHow Functional Programming Made Me a Better Developer
How Functional Programming Made Me a Better Developer
Cameron Presley
 
Clean code - DSC DYPCOE
Clean code - DSC DYPCOEClean code - DSC DYPCOE
Clean code - DSC DYPCOE
Patil Shreyas
 
Open Closed Principle kata
Open Closed Principle kataOpen Closed Principle kata
Open Closed Principle kata
Paul Blundell
 
Kernel Recipes 2014 - Writing Code: Keep It Short, Stupid!
Kernel Recipes 2014 - Writing Code: Keep It Short, Stupid!Kernel Recipes 2014 - Writing Code: Keep It Short, Stupid!
Kernel Recipes 2014 - Writing Code: Keep It Short, Stupid!
Anne Nicolas
 
CFCamp 2012 - Great Coding Guidelines - V1.0
CFCamp 2012 - Great Coding Guidelines - V1.0CFCamp 2012 - Great Coding Guidelines - V1.0
CFCamp 2012 - Great Coding Guidelines - V1.0
Aurélien Deleusière
 
Kotlin+MicroProfile: Ensinando 20 anos para uma linguagem nova
Kotlin+MicroProfile: Ensinando 20 anos para uma linguagem novaKotlin+MicroProfile: Ensinando 20 anos para uma linguagem nova
Kotlin+MicroProfile: Ensinando 20 anos para uma linguagem nova
Víctor Leonel Orozco López
 
Design patterns - The Good, the Bad, and the Anti-Pattern
Design patterns -  The Good, the Bad, and the Anti-PatternDesign patterns -  The Good, the Bad, and the Anti-Pattern
Design patterns - The Good, the Bad, and the Anti-Pattern
Barry O Sullivan
 
SOLID
SOLIDSOLID
Kotlin+MicroProfile: Enseñando trucos de 20 años a un nuevo lenguaje
Kotlin+MicroProfile: Enseñando trucos de 20 años a un nuevo lenguajeKotlin+MicroProfile: Enseñando trucos de 20 años a un nuevo lenguaje
Kotlin+MicroProfile: Enseñando trucos de 20 años a un nuevo lenguaje
Víctor Leonel Orozco López
 
Switch case and looping
Switch case and loopingSwitch case and looping
Switch case and looping
aprilyyy
 

Similar to Conditionals and Polymorphism (20)

SOLID, DRY, SLAP design principles
SOLID, DRY, SLAP design principlesSOLID, DRY, SLAP design principles
SOLID, DRY, SLAP design principles
 
SOLID design
SOLID designSOLID design
SOLID design
 
Core Java Programming Language (JSE) : Chapter IV - Expressions and Flow Cont...
Core Java Programming Language (JSE) : Chapter IV - Expressions and Flow Cont...Core Java Programming Language (JSE) : Chapter IV - Expressions and Flow Cont...
Core Java Programming Language (JSE) : Chapter IV - Expressions and Flow Cont...
 
You shouldneverdo
You shouldneverdoYou shouldneverdo
You shouldneverdo
 
Protecting JavaScript source code using obfuscation - OWASP Europe Tour 2013 ...
Protecting JavaScript source code using obfuscation - OWASP Europe Tour 2013 ...Protecting JavaScript source code using obfuscation - OWASP Europe Tour 2013 ...
Protecting JavaScript source code using obfuscation - OWASP Europe Tour 2013 ...
 
Owaspeutour2013lisbon pedrofortunaprotectingjavascriptsourcecodeusingobfuscat...
Owaspeutour2013lisbon pedrofortunaprotectingjavascriptsourcecodeusingobfuscat...Owaspeutour2013lisbon pedrofortunaprotectingjavascriptsourcecodeusingobfuscat...
Owaspeutour2013lisbon pedrofortunaprotectingjavascriptsourcecodeusingobfuscat...
 
Writing Readable Code
Writing Readable CodeWriting Readable Code
Writing Readable Code
 
New Ideas for Old Code - Greach
New Ideas for Old Code - GreachNew Ideas for Old Code - Greach
New Ideas for Old Code - Greach
 
Making an Exception
Making an ExceptionMaking an Exception
Making an Exception
 
Property based tests and where to find them - Andrzej Jóźwiak - TomTom Webina...
Property based tests and where to find them - Andrzej Jóźwiak - TomTom Webina...Property based tests and where to find them - Andrzej Jóźwiak - TomTom Webina...
Property based tests and where to find them - Andrzej Jóźwiak - TomTom Webina...
 
How Functional Programming Made Me a Better Developer
How Functional Programming Made Me a Better DeveloperHow Functional Programming Made Me a Better Developer
How Functional Programming Made Me a Better Developer
 
Clean code - DSC DYPCOE
Clean code - DSC DYPCOEClean code - DSC DYPCOE
Clean code - DSC DYPCOE
 
Open Closed Principle kata
Open Closed Principle kataOpen Closed Principle kata
Open Closed Principle kata
 
Kernel Recipes 2014 - Writing Code: Keep It Short, Stupid!
Kernel Recipes 2014 - Writing Code: Keep It Short, Stupid!Kernel Recipes 2014 - Writing Code: Keep It Short, Stupid!
Kernel Recipes 2014 - Writing Code: Keep It Short, Stupid!
 
CFCamp 2012 - Great Coding Guidelines - V1.0
CFCamp 2012 - Great Coding Guidelines - V1.0CFCamp 2012 - Great Coding Guidelines - V1.0
CFCamp 2012 - Great Coding Guidelines - V1.0
 
Kotlin+MicroProfile: Ensinando 20 anos para uma linguagem nova
Kotlin+MicroProfile: Ensinando 20 anos para uma linguagem novaKotlin+MicroProfile: Ensinando 20 anos para uma linguagem nova
Kotlin+MicroProfile: Ensinando 20 anos para uma linguagem nova
 
Design patterns - The Good, the Bad, and the Anti-Pattern
Design patterns -  The Good, the Bad, and the Anti-PatternDesign patterns -  The Good, the Bad, and the Anti-Pattern
Design patterns - The Good, the Bad, and the Anti-Pattern
 
SOLID
SOLIDSOLID
SOLID
 
Kotlin+MicroProfile: Enseñando trucos de 20 años a un nuevo lenguaje
Kotlin+MicroProfile: Enseñando trucos de 20 años a un nuevo lenguajeKotlin+MicroProfile: Enseñando trucos de 20 años a un nuevo lenguaje
Kotlin+MicroProfile: Enseñando trucos de 20 años a un nuevo lenguaje
 
Switch case and looping
Switch case and loopingSwitch case and looping
Switch case and looping
 

Recently uploaded

“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
Edge AI and Vision Alliance
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
Daiki Mogmet Ito
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
Zilliz
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
kumardaparthi1024
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
Mariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceXMariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceX
Mariano Tinti
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
danishmna97
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
tolgahangng
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
panagenda
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Malak Abu Hammad
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
Kumud Singh
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
Tomaz Bratanic
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
DianaGray10
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
Neo4j
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 

Recently uploaded (20)

“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
Mariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceXMariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceX
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 

Conditionals and Polymorphism

  • 1. Tell me and I'll forget. Show me and I might remember. But involve me and I will understand. 1
  • 4. Puzzle Imagine arranging 6 glasses in a row and filling three of them with water like this…. Every time you pick up a glass it counts as a move. What is the smallest number of moves that needs to be made in order to leave the glasses alternating full and empty? -– Explain your answer. 4
  • 5. Conditionals and Polymorphism Presented by Ashok Guduru Technical Architect Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 5
  • 6. Inheritance & Polymorphism Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 6
  • 7. Premise Most ifs can be replaced with polymorphism Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 7
  • 8. Introduction - Not all ifs but most of them cab be replaced by polymorphism - It is kind of fun to write code without ifs (e.g. Smalltalk ) Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 8
  • 9. Conditionals and Polymorphism • Why?: Why we need to avoid ifs - Functions without ifs are easier to read - Functions without ifs are easier to test - Functions without ifs are easier to maintain and extend Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 9
  • 10. Conditionals and Polymorphism NOTE: One of the grandest sounding words in object jargon is polymorphism. • Polymorphism: What it is?: - - You dispatch into a method who’s binding not known at compile time (a good old polymorphism) E.g. a Class and a bunch of sub-classes inheriting from for printing You say print and its not known it is printing to printer, screen or to a PDF Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 10
  • 11. Conditionals and Polymorphism • How do we get rid of ifs? • Use Polymorphism - If an object should behave differently based on its state If you have to check the same condition in multiple places Usually happens using flags and your code is sprinkled with a bunch of ifs all over the codebase - Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 11
  • 12. Conditionals and Polymorphism • But… Use Conditionals - - Mainly to do comparisons of primitive objects: >, <, >=, <=, ==, != etc. There are other uses but today we focus only on avoiding ifs Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 12
  • 13. Conditionals and Polymorphism We’re going to focus on business logic that should behave differently based on conditionals Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 13
  • 14. Conditionals and Polymorphism • To be if free… - Never return a null, instead return NullObject (Typically an object that doesn’t do anything) - e.g. An empty list, A null logger - Nulls are your friends inside of a development test but enemies in production code - When you return a null from a method you can’t dispatch on null. You get a null pointer exception - Don’t return error codes, instead throw an exception (Java RunTime Exception only.) Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 14
  • 15. Conditionals and Polymorphism • What is a subclass? - aka Base Class, Super Class, Parent Class etc. Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 15
  • 16. Conditionals and Polymorphism • Polymorphism uses subclassing WARNING: - Be careful about runaway subclassing - Not to go and crazy on using more subclassing - Deep inheritance hierarchies creates problems on testability, understandability and couple of other abilities as well. Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 16
  • 17. Conditionals and Polymorphism State Based Behavior Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 17
  • 18. Replace Conditionals with Polymorphism Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 18
  • 19. Replace Conditionals with Polymorphism • You have a conditional that chooses different behavior depending on the type of an object - Move each leg of the conditional to an overriding method in a subclass. Make the original method abstract. - The common logic stays in base class (super class) Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 19
  • 20. Replace Conditionals with Polymorphism public double GetSpeed() { switch(_type) { case EUROPEAN: return getBaseSpeed(); case AFRICAN: return getBaseSpeed() – getLoadFactor() * _numberOfCoconuts; case NORWEGIAN_BLUE: return isNailed ? 0 : getBaseSpeed(_voltage) default: throw new ArgumentException(“Should be unreachable”); // Java RuntimeException(“Should be unreachable”); } } Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 20
  • 21. Replace Conditionals with Polymorphism Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 21
  • 22. Replace Conditionals with Polymorphism public abstract class Bird { public abstract double GetSpeed(); protected double getBaseSpeed(); } public class EuropeanBird : Bird { public double GetSpeed() { return getBaseSpeed() } } Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 22
  • 23. Replace Conditionals with Polymorphism public class AfricanBird : Bird { public double GetSpeed() { return getBaseSpeed() – getLoadFactor() * _numberOfCoconuts; } } public class NorwegianBlueBird : Bird { public double GetSpeed() { return isNailed ? 0 : getBaseSpeed(_voltage) } } Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 23
  • 24. Replace Conditionals with Polymorphism public class BirdFactory { public double createInstance(_type) { switch (_type) case EUROPEAN return new EuropeanBird(); case AFRICAN: return new AfricanBird() case NORWEGIAN_BLUE: return new NorwegianBlueBird(); default: throw new ArgumentException(“Should be unreachable”); //Java RuntimeException(“Should be unreachable”); } } Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 24
  • 25. Replace Conditionals with Polymorphism public static main() { Bird bird = BirdFactory.createInstance(BirdType.EUROPEAN); SpeedCalculator sc = new SpeedCalculator(bird); sc.Calculate(); } public class SpeedCalculator { private Bird _bird; void SpeedCalculator(Bird bird) { _bird = bird; } public void Calculate() { return _bird.GetSpeed(); } } Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 25
  • 26. Summary • A Polymorphic solution is often better because - New behavior can be added without having the original source code, and - Each operation/concern is separated in a separate file which makes it easy to test/understand and maintain Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 26
  • 27. Summary • Prefer polymorphic over conditionals: - Switch almost always means you should use polymorphism - Sometimes if…elseif… means same as switch - In both of above cases the code is begging for polymorphism. It is almost a rule… I can say! - if is more subtle… sometimes an if is just and if Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 27
  • 28. Simple things should be simple and complex things should be possible. - Alan Kay 28
  • 29. Puzzle Imagine arranging 6 glasses in a row and filling three of them with water like this…. Every time you pick up a glass it counts as a move. What is the smallest number of moves that needs to be made in order to leave the glasses alternating full and empty? -– Explain your answer. 29
  • 30. Puzzle Imagine arranging 6 glasses in a row and filling three of them with water like this…. Every time you pick up a glass it counts as a move. What is the smallest number of moves that needs to be made in order to leave the glasses alternating full and empty? -– Explain your answer. 30
  • 31. Puzzle … and the answer is ONE 31
  • 32. Books: 1. Agile Software Development Principles, Patterns, and Practices by Robert C. Martin (aka Bob Martin or Uncle Bob) 2. Effective Java by Joshua Bloch 3. Code Complete (2nd Edition) by Steve McConnell Code Complete: A Practical Handbook of Software Construction Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 32
  • 33. 33
  • 34. The amateur software engineer is always in search of magic. -- Grady Booch Thank you! Ashok Guduru Blog: http://www.ashokg.com Twitter: @AshokGudur Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 34