Clean code bites
Upcoming SlideShare
Loading in...5
×
 

Clean code bites

on

  • 1,477 views

Examples of applying clean code practices in O/O software development

Examples of applying clean code practices in O/O software development

Statistics

Views

Total Views
1,477
Views on SlideShare
1,472
Embed Views
5

Actions

Likes
2
Downloads
32
Comments
0

2 Embeds 5

http://www.linkedin.com 4
https://www.linkedin.com 1

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • 1 slide on why, 3 slides on what, examples are a good way to communicate about clean code. Some examples using code.I use the book Clean code by Robert Martin.
  • 1,2: Communication : So to minimize the cost of maintenance, your code should be clear to those people (or yourself) reading it a later date. It should be nice to read, it should clearly communicate its design, and it should not be overly complex.3: After we all read GoF’sDesign Patterns, a lot of books were talking about design patterns and then about architecture patterns. And after that our attention shifted towards process (XP, Agile). It is good to remember that the “mundane” task of writing code is something we still can and must improve.
  • From the book Clean code by Robert Martin.
  • Does this help ?
  • Clean code – A Handbook of Agile Software Craftsmanship – Robert MartinDon’t use comments to describe code. . Only use comments when the code can not tell it.No magic numbers -> use constantsStyle -> indenting
  • SOLID: SRP, OCP, LSP, DIP, ISP
  • Does two thingsTwo differentreasons to change
  • => Split it up in two classes
  • Only about 10 lines. But it tests for testpage and then also includes pages
  • isTestPage() should be defined just below. And below that should be includeSetup….
  • For loop can have a inti as variable, when the scope is smallEncodings: it should read well (don’t abbriviate). Also don’t use hungarian notation etc.
  • Two/three: ordering of arguments is a problem. => mix upassertEquals(expected, actual);Flag: the call is confusing ! => split it up
  • Duplication is a problem for maintenance. You have to remember to change it in multiple locationsBeck (XP)Also Ron Jeffries says it is the second most important rule, just after getting the tests to passSwitch/case can be solved with polymorphismsDuplication is one of the big code smells that prgrammers have to solve
  • Easy: 3 lines of identical code=> Create new method
  • Higher level of abstraction: new method name describing what it doesTotal is 1 line less code
  • Every time you have an opportunity to change code, make sure it is a little cleaner.

Clean code bites Clean code bites Presentation Transcript

  • Clean code BitesApplying clean codeRoy Nitert28-3-2012
  • Agenda Why clean code What is clean code Examples: o SRP o Small methods o Descriptive names o Parameters o DRY © Sioux 2012 | Confidential | 2
  • Why clean code ? So it is easier to understand (readability) and cheaper to modify (maintainability) software The code you write will be read more times than it was written and by more people. Focus on the small things that make us better programmers. © Sioux 2012 | Confidential | 3
  • What is clean code ? © Sioux 2012 | Confidential | 4
  • What is clean code ?http://en.wiktionary.org/wiki/clean_codeNounclean code (plural clean codes)(idiomatic) software code that is formatted correctly and in an organized manner so that another coder can easily read or modify it. © Sioux 2012 | Confidential | 5
  • What is clean code ?Characteristics of clean code: Small methods and classes Descriptive names Not too many parameters in methods (and no flags) No obvious or irrelevant comments (code must be self describing) No redundancy (DRY: don‟t repeat yourself) No magic numbers Single responsibility principle (SRP) Uniform coding style © Sioux 2012 | Confidential | 6
  • SRP: Single Responsibility Principle every object should have a single responsibility, and that responsibility should be entirely encapsulated by the class. a class or module should have one, and only one, reason to change If class names have „manager‟ or „processor‟ in them, they probably have multiple responsibilities the "S" in "SOLID" stands for the single responsibility principle (“Principles Of OOD”, Robert C. Martin) © Sioux 2012 | Confidential | 7
  • SRP examplePublic class DashboardManager { public Component getLastFocusedComponent(); public void setLastFocused(Component lastFocused); public int getMajorVersionNumber(); public int getMinorVersionNumber(); public int getBuildNumber();} © Sioux 2012 | Confidential | 8
  • SRP examplePublic class FocusedComponent { public Component getLastFocusedComponent(); public void setLastFocused(Component lastFocused);Public class Version { public int getMajorVersionNumber(); public int getMinorVersionNumber(); public int getBuildNumber();} © Sioux 2012 | Confidential | 9
  • Small methods They should be very very small Should do one thing, do it well, do it only One level of abstraction Should read like a narrative Should not have sections Blocks within if, else and while statements should be one line long © Sioux 2012 | Confidential | 10
  • Small methods examplepublic static String renderPageWithSetupsAndTeardowns( PageData pageData, boolean isSuite) throws Exception { boolean isTestPage = pageData.hasAttribute(“Test”); if (isTestPage) { WikiPage testPage = pageData.getWikiPage(); StringBuffer newPageContent = new StringBuffer(); includeSetupPages(testPage, newPageContent, isSuite); newPageContent.append(pageData.getContent()); includeTeardownPages(testPage, newPageContent, isSuite); pageData.setContent(newPageContent.toString()); } return pageData.getHTML();} © Sioux 2012 | Confidential | 11
  • Small methods examplepublic static String renderPageWithSetupsAndTeardowns( PageData pageData, boolean isSuite) throws Exception { if (isTestPage(pageData)) includeSetupAndTeardownPages(pageData, isSuite); return pageData.getHTML();} © Sioux 2012 | Confidential | 12
  • Descriptive names Names make software readable Helps clarify the design in your mind Use long names for long scopes Avoid encodings © Sioux 2012 | Confidential | 13
  • Descriptive names examplePublic int x() { int q = 0; int z = 0; for (int kk = 0; kk < 10; kk++) { if (l[z] == 10) { q += 10 + (l[z + 1] + l[z + 2]); z += 1; } else if (l[z] + l[z + 1] == 10) { q += 10 + l[z + 2]; z += 2; } else { q += l[z] + l[z + 1]; z += 2; } } return q;} © Sioux 2012 | Confidential | 14
  • Descriptive names examplePublic int score() { int score = 0; int frame = 0; for (int frameNumber = 0; frameNumber < 10; frameNumber++) { if (isStrike(frame)) { score += 10 + nextTwoBallsForStrike(frame); frame += 1; } else if (isSpare(frame)) { score += 10 + nextBallForSpare(frame); frame += 2; } else { score += TwoBallsInFrame(frame); frame += 2; } } return score;} © Sioux 2012 | Confidential | 15
  • Parameters / arguments Small number: Zero is best, followed by one, two or three More than three is questionable Output arguments are counterintuitive Boolean arguments (flags) loudly declare than the function does more than one thing Simpler is easy to understand and easy to test Reduce number of arguments by creating objects out of them © Sioux 2012 | Confidential | 16
  • Parameters exampleCircle makeCircle(double x, double y, double radius);public void AlignTaskCanBeStopped(bool useRealXps);AlignTaskCanBeStopped(true); © Sioux 2012 | Confidential | 17
  • Parameters exampleCircle makeCircle(Point center, double radius);public void AlignTaskCanBeStoppedWith RealXps();public void AlignTaskCanBeStoppedWith SimulatedXps(); © Sioux 2012 | Confidential | 18
  • Don‟t repeat yourself Duplication DRY principle (Dave Thomas) Once, and only once (Kent Beck) Duplication is a missed opportunity for abstraction Examples: o Identical code (copy/paste) o Switch/case (or if/else) chains o Similar algorithms Design patterns and OO itself are strategies for eliminating duplication © Sioux 2012 | Confidential | 19
  • DRY examplepublic void scaleToOneDimension( float desiredDimension, float imageDimension) { if (Math.abs(desiredDimension – imageDimension) < errorThreshold) return; float scalingFactor = desiredDimension / imageDimension; scalingFactor = (float)(Math.floor(scalingFactor * 100) * 0.01f); RenderOp newImage = ImageUtilities.getScaledImage( image, scalingFactor, scalingFactor); image.dispose(); System.gc(); image = newImage;}public synchronized void rotate(int degrees) { RenderOp newImage = ImageUtilities.getRotatedImage( image, degrees); image.dispose(); System.gc(); image = newImage;} © Sioux 2012 | Confidential | 20
  • DRY examplepublic void scaleToOneDimension( float desiredDimension, float imageDimension) { if (Math.abs(desiredDimension – imageDimension) < errorThreshold) return; float scalingFactor = desiredDimension / imageDimension; scalingFactor = (float)(Math.floor(scalingFactor * 100) * 0.01f); replaceImage(ImageUtilities.getScaledImage( image, scalingFactor, scalingFactor));}public synchronized void rotate(int degrees) { replaceImage(ImageUtilities.getRotatedImage( image, degrees));}private void replaceImage(RenderedOp newImage) { image.dispose(); System.gc(); image = newImage;} © Sioux 2012 | Confidential | 21
  • Applying clean code Know how to write clean code Think about these small improvements during: o New development o Code reviews o Changing code o Fixing bugs So code will be easier to understand and cheaper to modify © Sioux 2012 | Confidential | 22
  • ConclusionWrite code as if the person who is going to maintain it, is a psychopath who knows where you live. © Sioux 2012 | Confidential | 23
  • Questions? © Sioux 2012 | Confidential | 24
  • +31 (0)40 2677100roy.nitert@sioux.eu © Sioux 2012 | Confidential | 25