Anti-Patterns

  • 733 views
Uploaded on

 

More in: Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads

Views

Total Views
733
On Slideshare
0
From Embeds
0
Number of Embeds
0

Actions

Shares
Downloads
18
Comments
0
Likes
2

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    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

Transcript

  • 1. Anti-PatternsRobert Brown@robby_brown
  • 2. Ask QuestionsMy best presentations are not from what I say butrather what you askIt’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 RememberForm good habitsOptimize to humansLearn the rules well so you know when and how tobreak them.
  • 5. Magic NumbersMagic numbers are evilThey don’t convey any contextThey are like numbers with out units
  • 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. #define#define MY_CONSTANT 1 + 2MY_CONSTANT * 5 = ?
  • 8. #define#define MULTIPLY(A, B)MULTIPLY(1 + 2, 3 + 4) = ?
  • 9. #define#define MAX(A, B) ((A) > (B) ? (A) : (B))int x = 1;int y = 2;MAX(++x, ++y) = ?
  • 10. #defineProper constants: const NSUInteger kTheAnswer = 42u; NSString * const kGreeting = @”Hello World!”;In header file: extern const NSUInteger kTheAnswer; extern NSString * const kGreeting;
  • 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. 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 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. Unenforced AssumptionsNSParameterAssert(number > 0 && number < 100);NSCParameterAssert([string length] > 0u);NSAssert([NSThread isMainThread], @”Oops”);NSCAssert(value != nil, @”Oops”);
  • 24. Short Variable NamesVariable names should be descriptive andunambiguousModern IDEs provide auto-completion
  • 25. Short Variable NamesBad examples: m temp billy var3 NINE abs
  • 26. Short Variable NamesGood examples: accountNumber firstName x (when used as a cartesian coordinate)
  • 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. Overly Intimate Code@interface MyObject ()// Private properties// Private methods@end
  • 29. Overly Intimate Code@interface MyObject (Protected)// Protected properties// Protected methods@end
  • 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. 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 ClassesBranching on classes is essentially reimplementingpolymorphismCategories solve this problemNot all languages support categories
  • 34. Branching on Classes// Bad exampleif ([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 MethodsShort methods are easier to read and reuseRule of thumb: 1-20 lines is optimal 100+ lines is excessive
  • 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. WhitespaceWhitespace makes code more readableIt separates parts of methods into natural sectionsThese sections are best accompanied with comments
  • 40. Name SpacingOften classes have the same name Example: User, Tweet, PhotoNaming conflicts are painful to fix
  • 41. Name SpacingSome languages, such as C++, include name spacesThe convention in Objective-C is to use 2-3 characterprefixes
  • 42. Want to Learn More?Code Complete24 Deadly Sins of Software Securityhttp://www.cprogramming.com/tutorial/cpreprocessor.html
  • 43. Questions?