SlideShare a Scribd company logo
Tech Talk: Coding
Guidelines - enum
Agenda

Definition / Motivation

Syntax in:
–
C
–
C#
–
Python
–
Java

Examples: good and not-so-good

Summary and guidelines
Define Enum

So.. what's an enum?
Define Enum

A set of constants

Rarely changes, if at all
Motivation

Avoid "magic numbers":
int color = 3;
Color color = Color.GREEN;
Motivation

Code Safety:
Compilation passes:
Color color = Color.GREEN; // 3
Compilation fails:
Color color = Shape.SQUARE; // 3
Motivation

Readability:
openFile1(true, true)
openFile2(
Permission.WRITE,
SeekMode.FORWARD_ONLY)
Examples: Good? Bad?

Spade, Heart, Diamond, Club

January, February, … , December

Mercury, Venus, … , Pluto

Supported formats:
JPG, GIF, … , PNG

Sunday, Monday, … , Saturday

[web]
Syntax - C
// without typedef
enum strategy { RANDOM, IMMEDIATE, SEARCH };
enum strategy my_strategy = IMMEDIATE;
Syntax - C#
public enum Importance {
None,
Trivial,
Regular,
Important,
Critical
};
Syntax - Python
class Importance(Enum):
none = 0
trivial = 1
regular = 2
important = 3
critical = 4
Syntax - Java
public enum Direction {
NORTH,
EAST,
SOUTH,
WEST
}
Enum in Java

Enum in Java is not only a constant

Enum in Java is a single instance of
a class, shared by all consumers

The class, as any class, can have:
–
Additional members
–
Functions → behavior (!)
Enum in Java – ex. 1
public enum Direction {
NORTH(0),
EAST(90),
SOUTH(180),
WEST(270);
private int angle;
public int getAngle() {
return this.angle;
}
Direction(int angle) {
this.angle = angle;
}
}
Enum in Java – ex. 1

Additional data is bound to each enum
member

Reverse lookup can be implemented
within the class itself:
public static Direction getByDeg(int d)
–
But.. consider the outcome of an invalid
input (e.g. getByDeg(30)):
–
Throw an exception?
–
Add an artificial enum member such as
UNKNOWN?
Enum in Java – ex. 2
public enum ArithmeticOp {
ADD {
@Override
public Double operate(Double a, Double b) {
return a + b;
}
},
MULTIPLY {
@Override
public Double operate(Double a, Double b) {
return a * b;
}
};
public abstract Double operate(Double x, Double y);
}
Enum in Java – ex. 2
// in main...
ArithmeticOp.ADD.operate(2.0, 3.0);
// 5.0
ArithmeticOp.MULTIPLY.operate(2.0, 3.0);
// 6.0
Enum in Java – ex. 2

Polymorphism is implemented in
enum

Enum class is now responsible to:
–
Data
–
Implementation

Polymorphism is better
implemented using a factory
and/or an IoC container
Special Uses of Enum

Singleton
–
Specifically in Java
–
Nice for PoC
–
In real code, use an IoC

Bitwise flags
Enum – When to use

A set of constants,

Related to each other

Small set

Rarely changes, if at all

Selecting one of the enum
members means not selecting any
other member
Enum – When not to use

Not related to each other
–
Ask:
●
Should I choose one, and only one value,
in every code scenario?
●
Do I use the enum just for convenience of
code completion (IDE)?
Enum – When not to use

Large set, say > 10 members
Enum – When not to use

Occasionally changes:
–
Ask: will I add new members to this
enum in the next 1-2 years?
–
This means that we enum data.
–
DON'T enum data
Enum – When not to use

Flags. Don't use bitwise flags
Summary

From now on...

Enum should be used properly:
–
A small, (almost) never-changing
set of constants, related to each
other

Other uses might be wrong:
–
Consider a design meeting
Thank you :)

More Related Content

Similar to Enum - Coding Guidelines

오토인코더의 모든 것
오토인코더의 모든 것오토인코더의 모든 것
오토인코더의 모든 것
NAVER Engineering
 
Data structures and algorithms lab2
Data structures and algorithms lab2Data structures and algorithms lab2
Data structures and algorithms lab2Bianca Teşilă
 
Kotlin
KotlinKotlin
Kotlin
BoKaiRuan
 
Static types on javascript?! Type checking approaches to ensure healthy appli...
Static types on javascript?! Type checking approaches to ensure healthy appli...Static types on javascript?! Type checking approaches to ensure healthy appli...
Static types on javascript?! Type checking approaches to ensure healthy appli...
Arthur Puthin
 
Basics of Java
Basics of JavaBasics of Java
Basics of Java
Sherihan Anver
 
05a-enum.ppt
05a-enum.ppt05a-enum.ppt
05a-enum.ppt
MuthuMs8
 
Programming intro variables constants - arithmetic and assignment operators
Programming intro variables   constants - arithmetic and assignment operatorsProgramming intro variables   constants - arithmetic and assignment operators
Programming intro variables constants - arithmetic and assignment operators
Osama Ghandour Geris
 
deepnet-lourentzou.ppt
deepnet-lourentzou.pptdeepnet-lourentzou.ppt
deepnet-lourentzou.ppt
yang947066
 
JSUG - Effective Java Puzzlers by Christoph Pickl
JSUG - Effective Java Puzzlers by Christoph PicklJSUG - Effective Java Puzzlers by Christoph Pickl
JSUG - Effective Java Puzzlers by Christoph Pickl
Christoph Pickl
 
Task based Programming with OmpSs and its Application
Task based Programming with OmpSs and its ApplicationTask based Programming with OmpSs and its Application
Task based Programming with OmpSs and its Application
Facultad de Informática UCM
 
Coding standard
Coding standardCoding standard
Coding standard
FAROOK Samath
 
Java class 4
Java class 4Java class 4
Java class 4Edureka!
 
Intro to OpenMP
Intro to OpenMPIntro to OpenMP
Intro to OpenMP
jbp4444
 
Introduction to OpenMP
Introduction to OpenMPIntroduction to OpenMP
Introduction to OpenMP
Akhila Prabhakaran
 
MS CS - Selecting Machine Learning Algorithm
MS CS - Selecting Machine Learning AlgorithmMS CS - Selecting Machine Learning Algorithm
MS CS - Selecting Machine Learning Algorithm
Kaniska Mandal
 
Getting Started - Console Program and Problem Solving
Getting Started - Console Program and Problem SolvingGetting Started - Console Program and Problem Solving
Getting Started - Console Program and Problem Solving
Hock Leng PUAH
 
SPF Getting Started - Console Program
SPF Getting Started - Console ProgramSPF Getting Started - Console Program
SPF Getting Started - Console Program
Hock Leng PUAH
 
Polymorphism in java
Polymorphism in java Polymorphism in java
Polymorphism in java
Janu Jahnavi
 
UNIT-1-PPTS-DAA.ppt
UNIT-1-PPTS-DAA.pptUNIT-1-PPTS-DAA.ppt
UNIT-1-PPTS-DAA.ppt
racha49
 

Similar to Enum - Coding Guidelines (20)

오토인코더의 모든 것
오토인코더의 모든 것오토인코더의 모든 것
오토인코더의 모든 것
 
Data structures and algorithms lab2
Data structures and algorithms lab2Data structures and algorithms lab2
Data structures and algorithms lab2
 
Kotlin
KotlinKotlin
Kotlin
 
Static types on javascript?! Type checking approaches to ensure healthy appli...
Static types on javascript?! Type checking approaches to ensure healthy appli...Static types on javascript?! Type checking approaches to ensure healthy appli...
Static types on javascript?! Type checking approaches to ensure healthy appli...
 
Basics of Java
Basics of JavaBasics of Java
Basics of Java
 
05a-enum.ppt
05a-enum.ppt05a-enum.ppt
05a-enum.ppt
 
Programming intro variables constants - arithmetic and assignment operators
Programming intro variables   constants - arithmetic and assignment operatorsProgramming intro variables   constants - arithmetic and assignment operators
Programming intro variables constants - arithmetic and assignment operators
 
deepnet-lourentzou.ppt
deepnet-lourentzou.pptdeepnet-lourentzou.ppt
deepnet-lourentzou.ppt
 
JSUG - Effective Java Puzzlers by Christoph Pickl
JSUG - Effective Java Puzzlers by Christoph PicklJSUG - Effective Java Puzzlers by Christoph Pickl
JSUG - Effective Java Puzzlers by Christoph Pickl
 
Task based Programming with OmpSs and its Application
Task based Programming with OmpSs and its ApplicationTask based Programming with OmpSs and its Application
Task based Programming with OmpSs and its Application
 
Coding standard
Coding standardCoding standard
Coding standard
 
Java class 4
Java class 4Java class 4
Java class 4
 
Intro to OpenMP
Intro to OpenMPIntro to OpenMP
Intro to OpenMP
 
Introduction to OpenMP
Introduction to OpenMPIntroduction to OpenMP
Introduction to OpenMP
 
MS CS - Selecting Machine Learning Algorithm
MS CS - Selecting Machine Learning AlgorithmMS CS - Selecting Machine Learning Algorithm
MS CS - Selecting Machine Learning Algorithm
 
Getting Started - Console Program and Problem Solving
Getting Started - Console Program and Problem SolvingGetting Started - Console Program and Problem Solving
Getting Started - Console Program and Problem Solving
 
SPF Getting Started - Console Program
SPF Getting Started - Console ProgramSPF Getting Started - Console Program
SPF Getting Started - Console Program
 
Lập trình C
Lập trình CLập trình C
Lập trình C
 
Polymorphism in java
Polymorphism in java Polymorphism in java
Polymorphism in java
 
UNIT-1-PPTS-DAA.ppt
UNIT-1-PPTS-DAA.pptUNIT-1-PPTS-DAA.ppt
UNIT-1-PPTS-DAA.ppt
 

Recently uploaded

Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdfGoverning Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
WENKENLI1
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
fxintegritypublishin
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
Kamal Acharya
 
power quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptxpower quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptx
ViniHema
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
Massimo Talia
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
AJAYKUMARPUND1
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
AhmedHussein950959
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Sreedhar Chowdam
 
The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdf
Pipe Restoration Solutions
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
obonagu
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
gerogepatton
 
space technology lecture notes on satellite
space technology lecture notes on satellitespace technology lecture notes on satellite
space technology lecture notes on satellite
ongomchris
 
AP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specificAP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specific
BrazilAccount1
 
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
zwunae
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
thanhdowork
 
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
H.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdfH.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdf
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
MLILAB
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
gdsczhcet
 
ethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.pptethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.ppt
Jayaprasanna4
 
Runway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptxRunway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptx
SupreethSP4
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
Divya Somashekar
 

Recently uploaded (20)

Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdfGoverning Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
 
power quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptxpower quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptx
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
 
The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdf
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
 
space technology lecture notes on satellite
space technology lecture notes on satellitespace technology lecture notes on satellite
space technology lecture notes on satellite
 
AP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specificAP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specific
 
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
 
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
H.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdfH.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdf
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
 
ethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.pptethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.ppt
 
Runway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptxRunway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptx
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
 

Enum - Coding Guidelines

  • 2. Agenda  Definition / Motivation  Syntax in: – C – C# – Python – Java  Examples: good and not-so-good  Summary and guidelines
  • 4. Define Enum  A set of constants  Rarely changes, if at all
  • 5. Motivation  Avoid "magic numbers": int color = 3; Color color = Color.GREEN;
  • 6. Motivation  Code Safety: Compilation passes: Color color = Color.GREEN; // 3 Compilation fails: Color color = Shape.SQUARE; // 3
  • 8. Examples: Good? Bad?  Spade, Heart, Diamond, Club  January, February, … , December  Mercury, Venus, … , Pluto  Supported formats: JPG, GIF, … , PNG  Sunday, Monday, … , Saturday  [web]
  • 9. Syntax - C // without typedef enum strategy { RANDOM, IMMEDIATE, SEARCH }; enum strategy my_strategy = IMMEDIATE;
  • 10. Syntax - C# public enum Importance { None, Trivial, Regular, Important, Critical };
  • 11. Syntax - Python class Importance(Enum): none = 0 trivial = 1 regular = 2 important = 3 critical = 4
  • 12. Syntax - Java public enum Direction { NORTH, EAST, SOUTH, WEST }
  • 13. Enum in Java  Enum in Java is not only a constant  Enum in Java is a single instance of a class, shared by all consumers  The class, as any class, can have: – Additional members – Functions → behavior (!)
  • 14. Enum in Java – ex. 1 public enum Direction { NORTH(0), EAST(90), SOUTH(180), WEST(270); private int angle; public int getAngle() { return this.angle; } Direction(int angle) { this.angle = angle; } }
  • 15. Enum in Java – ex. 1  Additional data is bound to each enum member  Reverse lookup can be implemented within the class itself: public static Direction getByDeg(int d) – But.. consider the outcome of an invalid input (e.g. getByDeg(30)): – Throw an exception? – Add an artificial enum member such as UNKNOWN?
  • 16. Enum in Java – ex. 2 public enum ArithmeticOp { ADD { @Override public Double operate(Double a, Double b) { return a + b; } }, MULTIPLY { @Override public Double operate(Double a, Double b) { return a * b; } }; public abstract Double operate(Double x, Double y); }
  • 17. Enum in Java – ex. 2 // in main... ArithmeticOp.ADD.operate(2.0, 3.0); // 5.0 ArithmeticOp.MULTIPLY.operate(2.0, 3.0); // 6.0
  • 18. Enum in Java – ex. 2  Polymorphism is implemented in enum  Enum class is now responsible to: – Data – Implementation  Polymorphism is better implemented using a factory and/or an IoC container
  • 19. Special Uses of Enum  Singleton – Specifically in Java – Nice for PoC – In real code, use an IoC  Bitwise flags
  • 20. Enum – When to use  A set of constants,  Related to each other  Small set  Rarely changes, if at all  Selecting one of the enum members means not selecting any other member
  • 21. Enum – When not to use  Not related to each other – Ask: ● Should I choose one, and only one value, in every code scenario? ● Do I use the enum just for convenience of code completion (IDE)?
  • 22. Enum – When not to use  Large set, say > 10 members
  • 23. Enum – When not to use  Occasionally changes: – Ask: will I add new members to this enum in the next 1-2 years? – This means that we enum data. – DON'T enum data
  • 24. Enum – When not to use  Flags. Don't use bitwise flags
  • 25. Summary  From now on...  Enum should be used properly: – A small, (almost) never-changing set of constants, related to each other  Other uses might be wrong: – Consider a design meeting