Anti-Patterns

1,444 views
1,318 views

Published on

Published in: Technology
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
1,444
On SlideShare
0
From Embeds
0
Number of Embeds
32
Actions
Shares
0
Downloads
26
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • Expected answer: 15\nReal answer: 11\n
  • Expected answer: 21\nReal answer: 11\n
  • Expected answer: 3\nReal answer: 4\n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • 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
  • \n\n
  • \n
  • \n
  • \n
  • \n
  • \n
  • 100 lines is roughly one computer screen of code.\n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • Anti-Patterns

    1. 1. Anti-PatternsRobert Brown@robby_brown
    2. 2. Ask QuestionsMy best presentations are not from what I say butrather what you askIt’s also fine not to agree with me
    3. 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. 4. Principles to RememberForm good habitsOptimize to humansLearn the rules well so you know when and how tobreak them.
    5. 5. Magic NumbersMagic numbers are evilThey don’t convey any contextThey are like numbers with out units
    6. 6. #define#define is a simple copy-and-paste operation with nosense of contextThere are lots of gotchasRule of thumb: If #if isn’t involved, don’t use #define
    7. 7. #define#define MY_CONSTANT 1 + 2MY_CONSTANT * 5 = ?
    8. 8. #define#define MULTIPLY(A, B)MULTIPLY(1 + 2, 3 + 4) = ?
    9. 9. #define#define MAX(A, B) ((A) > (B) ? (A) : (B))int x = 1;int y = 2;MAX(++x, ++y) = ?
    10. 10. #defineProper constants: const NSUInteger kTheAnswer = 42u; NSString * const kGreeting = @”Hello World!”;In header file: extern const NSUInteger kTheAnswer; extern NSString * const kGreeting;
    11. 11. Mass Constant FilesConstant files make code less reusableConstants should be as close possible to their relevantcodeCategories are often a good place for constants
    12. 12. Implicit Type Conversions Operations must be performed on the same primitive types Type conversions may not be what you expect
    13. 13. Implicit Type Conversions Common mistakes: (-1 < 0u) => False (1 / 2) => 0 for (uint32 i = 10; i >= 0; i--) { } => Infinite loop
    14. 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. 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. 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. 17. Implicit Type Conversions Rules: Downcast Upper bits dropped, may cause truncation
    18. 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. 19. Bit Fields Using hard-code binary numbers in a bit field can be error prone
    20. 20. Bit Fields enum { BitFieldNone = 0ull, BitFieldOne = 1ull, BitFieldTwo = 2ull, ... BitFieldThirtyThree = 8589934592ull, BitFieldAll = 18446744073709551615ull, }; typedef UInt64 BitField;
    21. 21. Bit Fields enum { BitFieldNone = 0ull, BitFieldOne = 1ull << 0, BitFieldTwo = 1ull << 1, ... BitFieldThirtyThree = 1ull << 32, BitFieldAll = ~BitFieldNone, }; typedef UInt64 BitField;
    22. 22. Unenforced AssumptionsIf you ever make an assumption, assert itIf the assertion fails, you immediately know either yourcode or your assumption is wrongAssertions help catch bugs closer to the sourceAssumptions should also be documented
    23. 23. Unenforced AssumptionsNSParameterAssert(number > 0 && number < 100);NSCParameterAssert([string length] > 0u);NSAssert([NSThread isMainThread], @”Oops”);NSCAssert(value != nil, @”Oops”);
    24. 24. Short Variable NamesVariable names should be descriptive andunambiguousModern IDEs provide auto-completion
    25. 25. Short Variable NamesBad examples: m temp billy var3 NINE abs
    26. 26. Short Variable NamesGood examples: accountNumber firstName x (when used as a cartesian coordinate)
    27. 27. Overly Intimate CodeOutside classes should only know what they needEncapsulation is one of the key principles of OOPClass extensions are great for private methods/dataCategories are great for protected methods/data
    28. 28. Overly Intimate Code@interface MyObject ()// Private properties// Private methods@end
    29. 29. Overly Intimate Code@interface MyObject (Protected)// Protected properties// Protected methods@end
    30. 30. Dead CodeDead code is just clutterIncreases compile timeEven though the code is no longer used, it still hasmental maintenance costsMassive commented out methods are just as bad
    31. 31. Instance Variables Instance variables should not be accessed directly Getters and setters should be used instead Essentially internal encapsulation
    32. 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. 33. Branching on ClassesBranching on classes is essentially reimplementingpolymorphismCategories solve this problemNot all languages support categories
    34. 34. Branching on Classes// Bad exampleif ([asset isKindOfClass:[Video class]]) [asset processVideo]; else if ([asset isKindOfClass:[Photo class]]) [asset processPhoto];
    35. 35. Branching on Classes// Good example[asset processAsset];
    36. 36. Branching on Classes// Categories@implementation Video (Processing)- (void)processAsset { }@end@implementation Photo (Processing)- (void)processAsset { }@end
    37. 37. Oversized MethodsShort methods are easier to read and reuseRule of thumb: 1-20 lines is optimal 100+ lines is excessive
    38. 38. Long LinesShorter lines are easier to readNot everyone has 27+ inch screensXcode doesn’t auto-wrap text very wellRule of thumb: 80-100 characters per line
    39. 39. WhitespaceWhitespace makes code more readableIt separates parts of methods into natural sectionsThese sections are best accompanied with comments
    40. 40. Name SpacingOften classes have the same name Example: User, Tweet, PhotoNaming conflicts are painful to fix
    41. 41. Name SpacingSome languages, such as C++, include name spacesThe convention in Objective-C is to use 2-3 characterprefixes
    42. 42. Want to Learn More?Code Complete24 Deadly Sins of Software Securityhttp://www.cprogramming.com/tutorial/cpreprocessor.html
    43. 43. Questions?

    ×