SlideShare una empresa de Scribd logo
1 de 34
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

Más contenido relacionado

Similar a Conditionals and Polymorphism

SOLID, DRY, SLAP design principles
SOLID, DRY, SLAP design principlesSOLID, DRY, SLAP design principles
SOLID, DRY, SLAP design principlesSergey Karpushin
 
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 shouldneverdodaniil3
 
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 Codeeddiehaber
 
New Ideas for Old Code - Greach
New Ideas for Old Code - GreachNew Ideas for Old Code - Greach
New Ideas for Old Code - GreachHamletDRC
 
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 DeveloperCameron Presley
 
Clean code - DSC DYPCOE
Clean code - DSC DYPCOEClean code - DSC DYPCOE
Clean code - DSC DYPCOEPatil Shreyas
 
Open Closed Principle kata
Open Closed Principle kataOpen Closed Principle kata
Open Closed Principle kataPaul 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.0Auré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 novaVí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-PatternBarry O Sullivan
 
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 lenguajeVíctor Leonel Orozco López
 
Switch case and looping
Switch case and loopingSwitch case and looping
Switch case and loopingaprilyyy
 

Similar a 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
 

Último

AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 

Último (20)

AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 

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