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++
Session02 c intro
Session02 c introSession02 c intro
Session02 c intro
HarithaRanasinghe
 
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
 
Datatypes
DatatypesDatatypes
Datatypes
ZTE Nepal
 
Parsing
ParsingParsing
5 introduction-to-c
5 introduction-to-c5 introduction-to-c
5 introduction-to-c
Rohit Shrivastava
 
Lecture 8
Lecture 8Lecture 8
Lecture 8
Tanveer Malik
 
2 1 data
2 1  data2 1  data
2 1 data
Ken Kretsch
 
Burst Error Correction
Burst Error CorrectionBurst Error Correction
Burst Error Correction
Aditi 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
 
Csharp4 basics
Csharp4 basicsCsharp4 basics
Csharp4 basics
Abed Bukhari
 
ForecastIT Course Outline
ForecastIT Course OutlineForecastIT Course Outline
ForecastIT Course Outline
DeepThought, Inc.
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
marvellous2
 
Tech tut
Tech tutTech tut
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_alloc
Hector 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 programming
Abha Damani
 
Presentation 2nd
Presentation 2ndPresentation 2nd
Presentation 2nd
Connex
 
Maintainable code
Maintainable codeMaintainable code
Maintainable code
RiverGlide
 
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 Mistakes
Roy 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

Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and BioinformaticiansBiomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Neo4j
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
Jakub Marek
 
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
Alex Pruden
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
ssuserfac0301
 
Leveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and StandardsLeveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and Standards
Neo4j
 
The Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptxThe Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptx
operationspcvita
 
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
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
Zilliz
 
Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |
AstuteBusiness
 
Dandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity serverDandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity server
Antonios Katsarakis
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Alpen-Adria-Universität
 
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their MainframeDigital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Precisely
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
Zilliz
 
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
Jason Yip
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
Zilliz
 
WeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation TechniquesWeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation Techniques
Postman
 
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectorsConnector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
DianaGray10
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
DanBrown980551
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
Jason Packer
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
akankshawande
 

Recently uploaded (20)

Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and BioinformaticiansBiomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
 
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
 
Leveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and StandardsLeveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and Standards
 
The Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptxThe Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptx
 
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
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
 
Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |
 
Dandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity serverDandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity server
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
 
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their MainframeDigital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
 
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
 
WeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation TechniquesWeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation Techniques
 
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectorsConnector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
 

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