SlideShare a Scribd company logo
Anti-Patterns
Robert Brown
@robby_brown
Ask Questions


My best presentations are not from what I say but
rather what you ask
It’s also fine not to agree with me
What is an anti-pattern?

 James Dempsey:
  Good intentions gone awry
  Code and practices you should avoid
  The code you write when you are writing it wrong
Principles to Remember


Form good habits
Optimize to humans
Learn the rules well so you know when and how to
break them.
Magic Numbers


Magic numbers are evil
They don’t convey any context
They are like numbers with out units
#define


#define is a simple copy-and-paste operation with no
sense of context
There are lots of gotchas
Rule of thumb: If #if isn’t involved, don’t use #define
#define


#define MY_CONSTANT 1 + 2
MY_CONSTANT * 5 = ?
#define


#define MULTIPLY(A, B)
MULTIPLY(1 + 2, 3 + 4) = ?
#define

#define MAX(A, B) ((A) > (B) ? (A) : (B))
int x = 1;
int y = 2;
MAX(++x, ++y) = ?
#define
Proper constants:
  const NSUInteger kTheAnswer = 42u;
  NSString * const kGreeting = @”Hello World!”;
In header file:
  extern const NSUInteger kTheAnswer;
  extern NSString * const kGreeting;
Mass Constant Files


Constant files make code less reusable
Constants should be as close possible to their relevant
code
Categories are often a good place for constants
Implicit Type Conversions


 Operations must be performed on the same primitive
 types
 Type conversions may not be what you expect
Implicit Type Conversions

  Common mistakes:
   (-1 < 0u) => False
   (1 / 2) => 0
   for (uint32 i = 10; i >= 0; i--) { } => Infinite loop
Implicit Type Conversions

 Rules:
   Signed int to larger signed int
     The smaller value is sign-extended
   Signed int to same-sized unsigned int
     Bit pattern preserved
Implicit Type Conversions

 Rules:
   Signed int to larger unsigned int
     Sign-extended then interpreted as unsigned
   Signed int to larger unsigned int
     Zero-extended
Implicit Type Conversions

 Rules:
   Unsigned int to same-sized int
     Interpreted as signed, may become negative
   Unsigned into to larger-sized int
     Zero-extended, then interpreted as signed
Implicit Type Conversions


 Rules:
   Downcast
     Upper bits dropped, may cause truncation
Implicit Type Conversions
 int: 42              float: 2.0f
 unsigned int: 2u     double: 3.14
 long: 3l
 unsigned long: 5ul
 long long 10ll
 unsigned long long
 100ull
Bit Fields



 Using hard-code binary numbers in a bit field can be
 error prone
Bit Fields
 enum {

          BitFieldNone = 0ull,

          BitFieldOne = 1ull,

          BitFieldTwo = 2ull,

          ...

          BitFieldThirtyThree = 8589934592ull,

          BitFieldAll = 18446744073709551615ull,

 };

 typedef UInt64 BitField;
Bit Fields
 enum {

          BitFieldNone = 0ull,

          BitFieldOne = 1ull << 0,

          BitFieldTwo = 1ull << 1,

          ...

          BitFieldThirtyThree = 1ull << 32,

          BitFieldAll = ~BitFieldNone,

 };

 typedef UInt64 BitField;
Unenforced Assumptions

If you ever make an assumption, assert it
If the assertion fails, you immediately know either your
code or your assumption is wrong
Assertions help catch bugs closer to the source
Assumptions should also be documented
Unenforced Assumptions

NSParameterAssert(number > 0 && number < 100);
NSCParameterAssert([string length] > 0u);
NSAssert([NSThread isMainThread], @”Oops”);
NSCAssert(value != nil, @”Oops”);
Short Variable Names


Variable names should be descriptive and
unambiguous
Modern IDEs provide auto-completion
Short Variable Names
Bad examples:
  m             temp
  billy         var3
  NINE          abs
Short Variable Names

Good examples:
  accountNumber
  firstName
  x (when used as a cartesian coordinate)
Overly Intimate Code

Outside classes should only know what they need
Encapsulation is one of the key principles of OOP
Class extensions are great for private methods/data
Categories are great for protected methods/data
Overly Intimate Code

@interface MyObject ()
// Private properties
// Private methods
@end
Overly Intimate Code

@interface MyObject (Protected)
// Protected properties
// Protected methods
@end
Dead Code

Dead code is just clutter
Increases compile time
Even though the code is no longer used, it still has
mental maintenance costs
Massive commented out methods are just as bad
Instance Variables


 Instance variables should not be accessed directly
 Getters and setters should be used instead
 Essentially internal encapsulation
Instance Variables
 Benefits of accessors:
   Enforce constraints      KVO
   Protect data integrity   Accessors don’t need
                            to be backed by an
   Provide flexibility
                            ivar
   Only minimal efficiency
   loss
Branching on Classes


Branching on classes is essentially reimplementing
polymorphism
Categories solve this problem
Not all languages support categories
Branching on Classes

// Bad example
if ([asset isKindOfClass:[Video class]])
     [asset processVideo];
 else if ([asset isKindOfClass:[Photo class]])
     [asset processPhoto];
Branching on Classes


// Good example
[asset processAsset];
Branching on Classes

// Categories

@implementation Video (Processing)

- (void)processAsset { }

@end

@implementation Photo (Processing)

- (void)processAsset { }

@end
Oversized Methods

Short methods are easier to read and reuse
Rule of thumb:
  1-20 lines is optimal
  100+ lines is excessive
Long Lines

Shorter lines are easier to read
Not everyone has 27+ inch screens
Xcode doesn’t auto-wrap text very well
Rule of thumb:
  80-100 characters per line
Whitespace


Whitespace makes code more readable
It separates parts of methods into natural sections
These sections are best accompanied with comments
Name Spacing


Often classes have the same name
  Example: User, Tweet, Photo
Naming conflicts are painful to fix
Name Spacing


Some languages, such as C++, include name spaces
The convention in Objective-C is to use 2-3 character
prefixes
Want to Learn More?


Code Complete
24 Deadly Sins of Software Security
http://www.cprogramming.com/tutorial/
cpreprocessor.html
Questions?

More Related Content

What's hot

C++
C++C++
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programming
SaranyaK68
 
Introduction to c
Introduction to cIntroduction to c
Introduction to c
Veeresh Metigoudar
 
What is identifier c programming
What is identifier c programmingWhat is identifier c programming
What is identifier c programming
Rumman Ansari
 
Parsing
ParsingParsing
Lecture 8
Lecture 8Lecture 8
Lecture 8
Tanveer Malik
 
Burst Error Correction
Burst Error CorrectionBurst Error Correction
Burst Error CorrectionAditi Singhal
 
Ic lecture7
Ic lecture7  Ic lecture7
Ic lecture7
AttaullahRahimoon
 
Impact of indentation in programming
Impact of indentation in programmingImpact of indentation in programming
Impact of indentation in programming
ijpla
 
ACM init() Spring 2015 Day 1
ACM init() Spring 2015 Day 1ACM init() Spring 2015 Day 1
ACM init() Spring 2015 Day 1
UCLA Association of Computing Machinery
 
ForecastIT Course Outline
ForecastIT Course OutlineForecastIT Course Outline
ForecastIT Course Outline
DeepThought, Inc.
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
marvellous2
 
Recursion with Python [Rev]
Recursion with Python [Rev]Recursion with Python [Rev]
Recursion with Python [Rev]
Dennis Walangadi
 
07 -pointers_and_memory_alloc
07  -pointers_and_memory_alloc07  -pointers_and_memory_alloc
07 -pointers_and_memory_allocHector Garzo
 

What's hot (20)

C++
C++C++
C++
 
Session02 c intro
Session02 c introSession02 c intro
Session02 c intro
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programming
 
Introduction to c
Introduction to cIntroduction to c
Introduction to c
 
What is identifier c programming
What is identifier c programmingWhat is identifier c programming
What is identifier c programming
 
Datatypes
DatatypesDatatypes
Datatypes
 
Parsing
ParsingParsing
Parsing
 
5 introduction-to-c
5 introduction-to-c5 introduction-to-c
5 introduction-to-c
 
Lecture 8
Lecture 8Lecture 8
Lecture 8
 
2 1 data
2 1  data2 1  data
2 1 data
 
Burst Error Correction
Burst Error CorrectionBurst Error Correction
Burst Error Correction
 
Ic lecture7
Ic lecture7  Ic lecture7
Ic lecture7
 
Impact of indentation in programming
Impact of indentation in programmingImpact of indentation in programming
Impact of indentation in programming
 
ACM init() Spring 2015 Day 1
ACM init() Spring 2015 Day 1ACM init() Spring 2015 Day 1
ACM init() Spring 2015 Day 1
 
Csharp4 basics
Csharp4 basicsCsharp4 basics
Csharp4 basics
 
ForecastIT Course Outline
ForecastIT Course OutlineForecastIT Course Outline
ForecastIT Course Outline
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
 
Tech tut
Tech tutTech tut
Tech tut
 
Recursion with Python [Rev]
Recursion with Python [Rev]Recursion with Python [Rev]
Recursion with Python [Rev]
 
07 -pointers_and_memory_alloc
07  -pointers_and_memory_alloc07  -pointers_and_memory_alloc
07 -pointers_and_memory_alloc
 

Similar to Anti-Patterns

Code Metrics
Code MetricsCode Metrics
Code Metrics
Attila Bertók
 
Clean code
Clean codeClean code
Clean code
Henrique Smoco
 
2 programming with c# i
2 programming with c# i2 programming with c# i
2 programming with c# i
siragezeynu
 
Get started python programming part 1
Get started python programming   part 1Get started python programming   part 1
Get started python programming part 1
Nicholas I
 
Code Smells and Its type (With Example)
Code Smells and Its type (With Example)Code Smells and Its type (With Example)
Code Smells and Its type (With Example)
Anshul Vinayak
 
More Little Wonders of C#/.NET
More Little Wonders of C#/.NETMore Little Wonders of C#/.NET
More Little Wonders of C#/.NET
BlackRabbitCoder
 
C Sharp Nagina (1)
C Sharp Nagina (1)C Sharp Nagina (1)
C Sharp Nagina (1)
guest58c84c
 
C Sharp Jn (1)
C Sharp Jn (1)C Sharp Jn (1)
C Sharp Jn (1)jahanullah
 
Unit 1 introduction to visual basic programming
Unit 1 introduction to visual basic programmingUnit 1 introduction to visual basic programming
Unit 1 introduction to visual basic programmingAbha Damani
 
Presentation 2nd
Presentation 2ndPresentation 2nd
Presentation 2ndConnex
 
Maintainable code
Maintainable codeMaintainable code
Maintainable codeRiverGlide
 
Tdd in practice
Tdd in practiceTdd in practice
Tdd in practice
Andrew Meredith
 
Clean Code Principles
Clean Code PrinciplesClean Code Principles
Clean Code Principles
YeurDreamin'
 
Tdd is not about testing
Tdd is not about testingTdd is not about testing
Tdd is not about testing
Gianluca Padovani
 
TDD Walkthrough - Encryption
TDD Walkthrough - EncryptionTDD Walkthrough - Encryption
TDD Walkthrough - Encryption
PeterKha2
 
Accord.Net: Looking for a Bug that Could Help Machines Conquer Humankind
Accord.Net: Looking for a Bug that Could Help Machines Conquer HumankindAccord.Net: Looking for a Bug that Could Help Machines Conquer Humankind
Accord.Net: Looking for a Bug that Could Help Machines Conquer Humankind
PVS-Studio
 
Roy Osherove on Unit Testing Good Practices and Horrible Mistakes
Roy Osherove on Unit Testing Good Practices and Horrible MistakesRoy Osherove on Unit Testing Good Practices and Horrible Mistakes
Roy Osherove on Unit Testing Good Practices and Horrible MistakesRoy Osherove
 
Good++
Good++Good++
Keep Code Left - How to write better code in almost any language
Keep Code Left - How to write better code in almost any languageKeep Code Left - How to write better code in almost any language
Keep Code Left - How to write better code in almost any language
Mick Andrew
 
Writing clean code
Writing clean codeWriting clean code
Writing clean code
Angel Garcia Olloqui
 

Similar to Anti-Patterns (20)

Code Metrics
Code MetricsCode Metrics
Code Metrics
 
Clean code
Clean codeClean code
Clean code
 
2 programming with c# i
2 programming with c# i2 programming with c# i
2 programming with c# i
 
Get started python programming part 1
Get started python programming   part 1Get started python programming   part 1
Get started python programming part 1
 
Code Smells and Its type (With Example)
Code Smells and Its type (With Example)Code Smells and Its type (With Example)
Code Smells and Its type (With Example)
 
More Little Wonders of C#/.NET
More Little Wonders of C#/.NETMore Little Wonders of C#/.NET
More Little Wonders of C#/.NET
 
C Sharp Nagina (1)
C Sharp Nagina (1)C Sharp Nagina (1)
C Sharp Nagina (1)
 
C Sharp Jn (1)
C Sharp Jn (1)C Sharp Jn (1)
C Sharp Jn (1)
 
Unit 1 introduction to visual basic programming
Unit 1 introduction to visual basic programmingUnit 1 introduction to visual basic programming
Unit 1 introduction to visual basic programming
 
Presentation 2nd
Presentation 2ndPresentation 2nd
Presentation 2nd
 
Maintainable code
Maintainable codeMaintainable code
Maintainable code
 
Tdd in practice
Tdd in practiceTdd in practice
Tdd in practice
 
Clean Code Principles
Clean Code PrinciplesClean Code Principles
Clean Code Principles
 
Tdd is not about testing
Tdd is not about testingTdd is not about testing
Tdd is not about testing
 
TDD Walkthrough - Encryption
TDD Walkthrough - EncryptionTDD Walkthrough - Encryption
TDD Walkthrough - Encryption
 
Accord.Net: Looking for a Bug that Could Help Machines Conquer Humankind
Accord.Net: Looking for a Bug that Could Help Machines Conquer HumankindAccord.Net: Looking for a Bug that Could Help Machines Conquer Humankind
Accord.Net: Looking for a Bug that Could Help Machines Conquer Humankind
 
Roy Osherove on Unit Testing Good Practices and Horrible Mistakes
Roy Osherove on Unit Testing Good Practices and Horrible MistakesRoy Osherove on Unit Testing Good Practices and Horrible Mistakes
Roy Osherove on Unit Testing Good Practices and Horrible Mistakes
 
Good++
Good++Good++
Good++
 
Keep Code Left - How to write better code in almost any language
Keep Code Left - How to write better code in almost any languageKeep Code Left - How to write better code in almost any language
Keep Code Left - How to write better code in almost any language
 
Writing clean code
Writing clean codeWriting clean code
Writing clean code
 

More from Robert Brown

High level concurrency
High level concurrencyHigh level concurrency
High level concurrency
Robert Brown
 
Data Source Combinators
Data Source CombinatorsData Source Combinators
Data Source Combinators
Robert Brown
 
Elixir
ElixirElixir
Elixir
Robert Brown
 
MVVM
MVVMMVVM
Reactive Cocoa
Reactive CocoaReactive Cocoa
Reactive Cocoa
Robert Brown
 
UIKit Dynamics
UIKit DynamicsUIKit Dynamics
UIKit Dynamics
Robert Brown
 
iOS State Preservation and Restoration
iOS State Preservation and RestorationiOS State Preservation and Restoration
iOS State Preservation and Restoration
Robert Brown
 
Pragmatic blocks
Pragmatic blocksPragmatic blocks
Pragmatic blocks
Robert Brown
 
Automatic Reference Counting
Automatic Reference CountingAutomatic Reference Counting
Automatic Reference Counting
Robert Brown
 
Grand Central Dispatch Design Patterns
Grand Central Dispatch Design PatternsGrand Central Dispatch Design Patterns
Grand Central Dispatch Design Patterns
Robert Brown
 
Grand Central Dispatch
Grand Central DispatchGrand Central Dispatch
Grand Central Dispatch
Robert Brown
 
Mac/iOS Design Patterns
Mac/iOS Design PatternsMac/iOS Design Patterns
Mac/iOS Design Patterns
Robert Brown
 
Core Data
Core DataCore Data
Core Data
Robert Brown
 
Quick Look for iOS
Quick Look for iOSQuick Look for iOS
Quick Look for iOS
Robert Brown
 

More from Robert Brown (14)

High level concurrency
High level concurrencyHigh level concurrency
High level concurrency
 
Data Source Combinators
Data Source CombinatorsData Source Combinators
Data Source Combinators
 
Elixir
ElixirElixir
Elixir
 
MVVM
MVVMMVVM
MVVM
 
Reactive Cocoa
Reactive CocoaReactive Cocoa
Reactive Cocoa
 
UIKit Dynamics
UIKit DynamicsUIKit Dynamics
UIKit Dynamics
 
iOS State Preservation and Restoration
iOS State Preservation and RestorationiOS State Preservation and Restoration
iOS State Preservation and Restoration
 
Pragmatic blocks
Pragmatic blocksPragmatic blocks
Pragmatic blocks
 
Automatic Reference Counting
Automatic Reference CountingAutomatic Reference Counting
Automatic Reference Counting
 
Grand Central Dispatch Design Patterns
Grand Central Dispatch Design PatternsGrand Central Dispatch Design Patterns
Grand Central Dispatch Design Patterns
 
Grand Central Dispatch
Grand Central DispatchGrand Central Dispatch
Grand Central Dispatch
 
Mac/iOS Design Patterns
Mac/iOS Design PatternsMac/iOS Design Patterns
Mac/iOS Design Patterns
 
Core Data
Core DataCore Data
Core Data
 
Quick Look for iOS
Quick Look for iOSQuick Look for iOS
Quick Look for iOS
 

Recently uploaded

UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
Matthew Sinclair
 
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
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
Alex Pruden
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 
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
 
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
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
Neo4j
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Nexer Digital
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
Neo4j
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
Pierluigi Pugliese
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
nkrafacyberclub
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
Neo4j
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
RinaMondal9
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
名前 です男
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 

Recently uploaded (20)

UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
 
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...
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 
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
 
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
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 

Anti-Patterns

  • 2. Ask Questions My best presentations are not from what I say but rather what you ask It’s also fine not to agree with me
  • 3. What is an anti-pattern? James Dempsey: Good intentions gone awry Code and practices you should avoid The code you write when you are writing it wrong
  • 4. Principles to Remember Form good habits Optimize to humans Learn the rules well so you know when and how to break them.
  • 5. Magic Numbers Magic numbers are evil They don’t convey any context They are like numbers with out units
  • 6. #define #define is a simple copy-and-paste operation with no sense of context There are lots of gotchas Rule of thumb: If #if isn’t involved, don’t use #define
  • 7. #define #define MY_CONSTANT 1 + 2 MY_CONSTANT * 5 = ?
  • 9. #define #define MAX(A, B) ((A) > (B) ? (A) : (B)) int x = 1; int y = 2; MAX(++x, ++y) = ?
  • 10. #define Proper constants: const NSUInteger kTheAnswer = 42u; NSString * const kGreeting = @”Hello World!”; In header file: extern const NSUInteger kTheAnswer; extern NSString * const kGreeting;
  • 11. Mass Constant Files Constant files make code less reusable Constants should be as close possible to their relevant code Categories are often a good place for constants
  • 12. Implicit Type Conversions Operations must be performed on the same primitive types Type conversions may not be what you expect
  • 13. Implicit Type Conversions Common mistakes: (-1 < 0u) => False (1 / 2) => 0 for (uint32 i = 10; i >= 0; i--) { } => Infinite loop
  • 14. Implicit Type Conversions Rules: Signed int to larger signed int The smaller value is sign-extended Signed int to same-sized unsigned int Bit pattern preserved
  • 15. Implicit Type Conversions Rules: Signed int to larger unsigned int Sign-extended then interpreted as unsigned Signed int to larger unsigned int Zero-extended
  • 16. Implicit Type Conversions Rules: Unsigned int to same-sized int Interpreted as signed, may become negative Unsigned into to larger-sized int Zero-extended, then interpreted as signed
  • 17. Implicit Type Conversions Rules: Downcast Upper bits dropped, may cause truncation
  • 18. Implicit Type Conversions int: 42 float: 2.0f unsigned int: 2u double: 3.14 long: 3l unsigned long: 5ul long long 10ll unsigned long long 100ull
  • 19. Bit Fields Using hard-code binary numbers in a bit field can be error prone
  • 20. Bit Fields enum { BitFieldNone = 0ull, BitFieldOne = 1ull, BitFieldTwo = 2ull, ... BitFieldThirtyThree = 8589934592ull, BitFieldAll = 18446744073709551615ull, }; typedef UInt64 BitField;
  • 21. Bit Fields enum { BitFieldNone = 0ull, BitFieldOne = 1ull << 0, BitFieldTwo = 1ull << 1, ... BitFieldThirtyThree = 1ull << 32, BitFieldAll = ~BitFieldNone, }; typedef UInt64 BitField;
  • 22. Unenforced Assumptions If you ever make an assumption, assert it If the assertion fails, you immediately know either your code or your assumption is wrong Assertions help catch bugs closer to the source Assumptions should also be documented
  • 23. Unenforced Assumptions NSParameterAssert(number > 0 && number < 100); NSCParameterAssert([string length] > 0u); NSAssert([NSThread isMainThread], @”Oops”); NSCAssert(value != nil, @”Oops”);
  • 24. Short Variable Names Variable names should be descriptive and unambiguous Modern IDEs provide auto-completion
  • 25. Short Variable Names Bad examples: m temp billy var3 NINE abs
  • 26. Short Variable Names Good examples: accountNumber firstName x (when used as a cartesian coordinate)
  • 27. Overly Intimate Code Outside classes should only know what they need Encapsulation is one of the key principles of OOP Class extensions are great for private methods/data Categories are great for protected methods/data
  • 28. Overly Intimate Code @interface MyObject () // Private properties // Private methods @end
  • 29. Overly Intimate Code @interface MyObject (Protected) // Protected properties // Protected methods @end
  • 30. Dead Code Dead code is just clutter Increases compile time Even though the code is no longer used, it still has mental maintenance costs Massive commented out methods are just as bad
  • 31. Instance Variables Instance variables should not be accessed directly Getters and setters should be used instead Essentially internal encapsulation
  • 32. Instance Variables Benefits of accessors: Enforce constraints KVO Protect data integrity Accessors don’t need to be backed by an Provide flexibility ivar Only minimal efficiency loss
  • 33. Branching on Classes Branching on classes is essentially reimplementing polymorphism Categories solve this problem Not all languages support categories
  • 34. Branching on Classes // Bad example if ([asset isKindOfClass:[Video class]]) [asset processVideo]; else if ([asset isKindOfClass:[Photo class]]) [asset processPhoto];
  • 35. Branching on Classes // Good example [asset processAsset];
  • 36. Branching on Classes // Categories @implementation Video (Processing) - (void)processAsset { } @end @implementation Photo (Processing) - (void)processAsset { } @end
  • 37. Oversized Methods Short methods are easier to read and reuse Rule of thumb: 1-20 lines is optimal 100+ lines is excessive
  • 38. Long Lines Shorter lines are easier to read Not everyone has 27+ inch screens Xcode doesn’t auto-wrap text very well Rule of thumb: 80-100 characters per line
  • 39. Whitespace Whitespace makes code more readable It separates parts of methods into natural sections These sections are best accompanied with comments
  • 40. Name Spacing Often classes have the same name Example: User, Tweet, Photo Naming conflicts are painful to fix
  • 41. Name Spacing Some languages, such as C++, include name spaces The convention in Objective-C is to use 2-3 character prefixes
  • 42. Want to Learn More? Code Complete 24 Deadly Sins of Software Security http://www.cprogramming.com/tutorial/ cpreprocessor.html

Editor's Notes

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. Expected answer: 15\nReal answer: 11\n
  8. Expected answer: 21\nReal answer: 11\n
  9. Expected answer: 3\nReal answer: 4\n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. By default, all code is compiled and the dead code is stripped. This keeps the app size smaller, but requires extra time. Just leave out dead code in the first place.\nEmpty -viewDidUnload, -viewDidLoad, etc should removed.\n
  31. \n\n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. 100 lines is roughly one computer screen of code.\n
  38. \n
  39. \n
  40. \n
  41. \n
  42. \n
  43. \n