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

Más contenido relacionado

La actualidad más candente (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 a Anti-Patterns

2 programming with c# i
2 programming with c# i2 programming with c# i
2 programming with c# isiragezeynu
 
Get started python programming part 1
Get started python programming   part 1Get started python programming   part 1
Get started python programming part 1Nicholas 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#/.NETBlackRabbitCoder
 
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
 
Clean Code Principles
Clean Code PrinciplesClean Code Principles
Clean Code PrinciplesYeurDreamin'
 
TDD Walkthrough - Encryption
TDD Walkthrough - EncryptionTDD Walkthrough - Encryption
TDD Walkthrough - EncryptionPeterKha2
 
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 HumankindPVS-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
 
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 languageMick Andrew
 

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

Más de Robert Brown

High level concurrency
High level concurrencyHigh level concurrency
High level concurrencyRobert Brown
 
Data Source Combinators
Data Source CombinatorsData Source Combinators
Data Source CombinatorsRobert Brown
 
iOS State Preservation and Restoration
iOS State Preservation and RestorationiOS State Preservation and Restoration
iOS State Preservation and RestorationRobert Brown
 
Automatic Reference Counting
Automatic Reference CountingAutomatic Reference Counting
Automatic Reference CountingRobert Brown
 
Grand Central Dispatch Design Patterns
Grand Central Dispatch Design PatternsGrand Central Dispatch Design Patterns
Grand Central Dispatch Design PatternsRobert Brown
 
Grand Central Dispatch
Grand Central DispatchGrand Central Dispatch
Grand Central DispatchRobert Brown
 
Mac/iOS Design Patterns
Mac/iOS Design PatternsMac/iOS Design Patterns
Mac/iOS Design PatternsRobert Brown
 
Quick Look for iOS
Quick Look for iOSQuick Look for iOS
Quick Look for iOSRobert Brown
 

Más de 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
 

Último

Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
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
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
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
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
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
 

Último (20)

Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
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
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
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
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
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
 

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

Notas del editor

  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