David Frame
Lead engineer, NBC Sports Next
Clean Coding
“Any fool can write code that a computer
can understand. Good programmers write
code that humans can understand.”
– Martin Fowler
https://gist.github.com/wojteklu/73c6914cc446146b8b533c0988cf8d29
Part one: Style
• New project? Use the
preferred/popular standard for
your language and/or framework.
• Existing project? Use its
standard.
• Unsure? Ask.
• Still unsure? Match what you
see.
• Don’t mix coding standards!
Coding standard
• Choose descriptive,
pronounceable, unambiguous
names. Don’t abbreviate.
• A variable’s name should
describe what it is, a function’s
name should describe what it
does.
• Be verbose with your naming, but
not too verbose.
• Replace ‘magic numbers /
strings’ with named constants.
Naming Convention
• Don’t use them!
• Clean code is self-documenting.
• There are occasional exceptions
but you will almost never
encounter them.
• Avoid change-related comments,
e.g. ‘DF 12/04/2021: Blah blah’.
Use version control!
• Doc comments can still be useful
- check coding standard!
Comments
• Try to keep code within 80
columns.
• Never exceed 120 columns.
• Scanning your eyes downwards
is more natural than scanning
sideways (think: web browsers,
newspapers, etc).
• Facilitates larger font sizes, split
panes, portrait orientated
monitors, etc.
• Don’t jump through hoops!
Line Lengths
• Makes things more readable
(think paragraphs).
• Use to associate/disassociate
blocks of code.
• Stay consistent!
Whitespace
• Reduce code path as much as
possible.
• Return early.
• Avoid else statements (!)
• Remember: vertical scanning is
better than horizontal scanning.
• See also: cyclomatic complexity
(structural).
Indentation
Part two: Structure
Keep it SOLID
• Single-responsibility principle (SRP)
• Open-closed principle
• Liskov substitution principle
• Interface segregation principle
• Dependency inversion principle
• Keep them small and specific!
• Promotes Single-responsibility
principle.
• Realistically, classes grow over
time.
• Avoid long lists of properties.
• Avoid nondescript ‘service’
classes - BookingService,
TeeTimeManager, etc.
Classes
• "The first rule of functions is that they
should be small. The second rule of
functions is that they should be smaller
than that. Functions should not be 100
lines long. Functions should hardly
ever be 20 lines long.” - Clean Code
• Also promotes Single-responsibility
principle.
• Like classes, these grow over time.
• Always think about refactoring - blocks
of code may be extracted into separate
functions.
• Strike a balance!
Functions
• Remember naming convention!
• Ideally functions should only
have one parameter.
• Two is okay.
• Three at a stretch!
• Try to make use of entity /
parameter objects.
• Avoid boolean parameters (!!)
Function Parameters
• “A 25-dollar term for a 5-cent
concept. [...] Dependency injection
means giving an object its instance
variables.” - James Shore
• Rule of thumb: Only entity objects
should be instantiated within a
class. Service objects should be
injected.
• Reduces coupling.
• Makes testing easier.
• Promotes Open-closed principle
Dependency Injection
• Misused inheritance results in
tight coupling and segregated
interfaces.
• Composition promotes looser
coupling and code reuse.
• Composition is more resilient to
change.
• Composition helps keep classes
small and concise.
• Inheritance is more fragile but
generally easier to read/follow.
Composition vs Inheritance
• Promotes clean code in the right
situation.
• Realistically you only need to be
aware of a handful.
• Singleton (ugh)
• Factory
• Decorator
• Adapter
• Frameworks tend to use them to
promote reuse and extensibility.
Design Patterns
Thanks for attending!
Any questions?

Clean Code (David Frame) - PHPBelfast Meetup 22/02/24

  • 1.
    David Frame Lead engineer,NBC Sports Next Clean Coding
  • 2.
    “Any fool canwrite code that a computer can understand. Good programmers write code that humans can understand.” – Martin Fowler
  • 4.
  • 5.
  • 6.
    • New project?Use the preferred/popular standard for your language and/or framework. • Existing project? Use its standard. • Unsure? Ask. • Still unsure? Match what you see. • Don’t mix coding standards! Coding standard
  • 7.
    • Choose descriptive, pronounceable,unambiguous names. Don’t abbreviate. • A variable’s name should describe what it is, a function’s name should describe what it does. • Be verbose with your naming, but not too verbose. • Replace ‘magic numbers / strings’ with named constants. Naming Convention
  • 8.
    • Don’t usethem! • Clean code is self-documenting. • There are occasional exceptions but you will almost never encounter them. • Avoid change-related comments, e.g. ‘DF 12/04/2021: Blah blah’. Use version control! • Doc comments can still be useful - check coding standard! Comments
  • 9.
    • Try tokeep code within 80 columns. • Never exceed 120 columns. • Scanning your eyes downwards is more natural than scanning sideways (think: web browsers, newspapers, etc). • Facilitates larger font sizes, split panes, portrait orientated monitors, etc. • Don’t jump through hoops! Line Lengths
  • 10.
    • Makes thingsmore readable (think paragraphs). • Use to associate/disassociate blocks of code. • Stay consistent! Whitespace
  • 11.
    • Reduce codepath as much as possible. • Return early. • Avoid else statements (!) • Remember: vertical scanning is better than horizontal scanning. • See also: cyclomatic complexity (structural). Indentation
  • 12.
  • 13.
    Keep it SOLID •Single-responsibility principle (SRP) • Open-closed principle • Liskov substitution principle • Interface segregation principle • Dependency inversion principle
  • 14.
    • Keep themsmall and specific! • Promotes Single-responsibility principle. • Realistically, classes grow over time. • Avoid long lists of properties. • Avoid nondescript ‘service’ classes - BookingService, TeeTimeManager, etc. Classes
  • 15.
    • "The firstrule of functions is that they should be small. The second rule of functions is that they should be smaller than that. Functions should not be 100 lines long. Functions should hardly ever be 20 lines long.” - Clean Code • Also promotes Single-responsibility principle. • Like classes, these grow over time. • Always think about refactoring - blocks of code may be extracted into separate functions. • Strike a balance! Functions
  • 16.
    • Remember namingconvention! • Ideally functions should only have one parameter. • Two is okay. • Three at a stretch! • Try to make use of entity / parameter objects. • Avoid boolean parameters (!!) Function Parameters
  • 17.
    • “A 25-dollarterm for a 5-cent concept. [...] Dependency injection means giving an object its instance variables.” - James Shore • Rule of thumb: Only entity objects should be instantiated within a class. Service objects should be injected. • Reduces coupling. • Makes testing easier. • Promotes Open-closed principle Dependency Injection
  • 18.
    • Misused inheritanceresults in tight coupling and segregated interfaces. • Composition promotes looser coupling and code reuse. • Composition is more resilient to change. • Composition helps keep classes small and concise. • Inheritance is more fragile but generally easier to read/follow. Composition vs Inheritance
  • 19.
    • Promotes cleancode in the right situation. • Realistically you only need to be aware of a handful. • Singleton (ugh) • Factory • Decorator • Adapter • Frameworks tend to use them to promote reuse and extensibility. Design Patterns
  • 20.

Editor's Notes

  • #2 What is clean coding? Best described by way of a famous quote…
  • #3 Clean coding is a set of guidelines for writing code that humans can easily understand and work with. “Clean code”. Where do those guidelines come from?…
  • #4 This book! Written by Bob Martin in 2009 and consisting of 464 pages, which is about 200 pages too many. See the problem with this book is that it’s incredibly verbose and contains a lot of common-sense advice that can easily be summarised. And people have…
  • #5 This presentation is my summary, but it’s not entirely specific to Bob Martin’s book, just based off some of it along with some of my own observations based off 20 years in the industry. IT IS NOT EXHAUSTIVE and this is NOT a set of instructions, it’s just something to be aware of. Do as I say, not as I do… It’s a balancing act between implementing these guidelines and actually getting things done!
  • #6 When I started planning this presentation out I noticed a pattern in some of the notes I made. Many of the guidelines can be split into two categories: Style and Structure. Style-based guidelines make code ‘look nice’ and easy to read at a glance. Structure-based guidelines make code easy to maintain and extend. There CAN be some overlap here! Let’s start with some style…
  • #8 Pronounceable is an interesting idea - pronounceable names can be remembered more easily. Think passwords! A particularly long variable/function name may indicate that it is taking on too much responsibility. User type - USER_TYPE_MEMBER = 4
  • #9 You know how in school or uni you were told how great comments are and you should use them whenever possible?
  • #12 Ignore the dubious code here, globals, etc! Overlaps with structural considerations. We’ve refactored notifyAdmin and notifyUser into sendNotification with a parameter. This DOES NOT move the problematic else into a new function as it too can return early!
  • #13 This is where we start focusing on structure-related guidelines. Rule of thumb: Style guidelines involve changes to one file. Structure guidelines can involve changes to multiple files.
  • #14 These are a subset of many principles promoted by Bob Martin in his “Design Principles and Design Patterns.” paper. He didn’t come up with the ‘SOLID’ acronym himself, that was independently devised a few years later. SRP - There should never be more than one reason for a class to change. OC - Software entities should be open for extension but closed for modification. LSP - Design by contract - use interfaces! ISP - Many client-specific interfaces are better than one general-purpose interface DI - Depend upon abstractions, not concretions
  • #15 Nondescript service classes are essentially reverting to functional programming, dumping bits of logic into a single file without harnessing the strength of OOP. Service classes can sometimes be broken up into other classes, e.g. TeeTimeService.lockTeeTime() and unlockTeeTime() functions might be extracted to a dedicated ‘TeeTimeLocker’ class.
  • #16 Use your IDE for refactoring! Extracted functions provided documentation via function naming.
  • #17 Boolean parameters can indicate a code smell due to code paths, complexity and readability issues. They indicate that a function does more than one thing. Think back to when we replaced notifyAdmin and notifyUser with sendNotification w/ boolean.
  • #18 Not part of Clean Coding but worth a mention here. Dependency injection isn’t the same as Dependency Inversion! Your back-end framework probably has a DI container implementation.
  • #19 Inheritance is still an important, vital component of OOP. Ancedote about MySqlHandler -> Website -> Page -> Subpage -> AboutPage.. stuff in Tibus. And how having an ‘About section’ screws that up.
  • #20 Singleton is usually better achieved via dependency injection / containers. Factory is useful for creating objects without having to specify (or even know) the exact class. Switch statements! Decorator useful for changing a classes’ behaviour at runtime. Adapter is useful for making different classes adhere to the same interface (think travel plug)