RoCk SOLiD KnOwledge http://www.rocksolidknowledge.com

Code Quality

Steve Rodgers [email protected]

© 2014 RoCk SOLid KnOwledge 1 An Apology

© 2014 RoCk SOLid KnOwledge 2 The Dream Imagine a world where

Metronomic build/fix/deploy cycle Bug count always low per release End users love the app as it never crashes  Stakeholder  QA  Support team  Project Manager  Devs 

© 2014 RoCk SOLid KnOwledge 3 Why Care part 1? Business *MUST* care

© 2014 RoCk SOLid KnOwledge 4 Why Care part 2 Developers *SHOULD* care

© 2014 RoCk SOLid KnOwledge 5 Why Care Part 3 The Quality Trade Off

© 2014 RoCk SOLid KnOwledge 6 The Mission: Build A Maintainable Legacy

Code spends most of its life being maintained How hard is it to learn any new code base? What is your legacy? My $hit code will be your problem tomorrow Your $hit code will be my problem today

© 2014 RoCk SOLid KnOwledge 7 Malleable Code In The Real World

Code is rarely done unless it’s demo code Business requirements change all the time Code must therefore be engineered to handle continual refactor Code must be thought of as highly malleable Every line is always up for possible refactor How will you survive dominate in this world?

© 2014 RoCk SOLid KnOwledge 8 Tip: Write Unit Tests

Why write tests? Validate class behaviour now and future proof it Domain classes with behaviour must have tests Data classes don’t need tests Write meaningful tests Be highly suspicious of 100% unit test coverage  Be judicious; spend money where needed Write tons of tests for critical algorithm Don’t write tons of tests for 3 line method Learn TDD then Practice TDD

© 2014 RoCk SOLid KnOwledge 9 Tip: Avoid writing God classes The disease

“A ‘God Class’ is an object that controls way too many other objects in the system and has grown beyond all logic to become The Class That Does Everything.” [http://c2.com/cgi/wiki?GodClass] The signs 1200 SLOC? 50 private methods? 35 fields? No one in the team understands how it works?

© 2014 RoCk SOLid KnOwledge 10 God class: Unit tests hard to write? Unit test on Elm Street

Class is hard to test? Lots of complicated test setup code? Lots of Asserts per test? A unit test should only have a single Assert

© 2014 RoCk SOLid KnOwledge 11 Tip: Adopt Single Responsibility Principle The cure

Class should have one responsibility Refactor God class into multiple SRP classes Write unit tests for each SRP class

© 2014 RoCk SOLid KnOwledge 12 Tip: Avoid Unmanaged Complexity

Signals: Many lines of code, tons of methods but few classes Avoid function decomposition Private method syndrome Private methods cannot be unit tested Embrace class decomposition Lots of little classes Write battery of unit tests for each little class Refactor big private methods out into their own class (see ‘method-object’ )

© 2014 RoCk SOLid KnOwledge 13 Tip: Use Software Design Patterns

Don’t miss out on GOF patterns Factory, Null Object, Decorator, Adapter etc Patterns signal intent to other developers Use only when needed Don’t force them in when not needed Be suspicious of large code base that doesn’t use patterns  Beware Dunning-Kruger Effect

© 2014 RoCk SOLid KnOwledge 14 Cyclomatic Complexity

“Cyclomatic complexity is a software metric (measurement), used to indicate the complexity of a program. It is a quantitative measure of the number of linearly independent paths through a program's source code.” [https://en.wikipedia.org/wiki/Cyclomatic_co mplexity]

© 2014 RoCk SOLid KnOwledge 15 Tip: Reduce Heavy Use Of Imperative Style

Complicated code is hard to understand Nested if/else with lots of || and && Cyclomatic complexity is the work of the devil Reduce use of imperative programming style e.g. if/else/switch Flock of seagulls lead to the gates to Hades {{{}}} Challenge each other to reduce heavy use of them Good use of OO, LINQ & patterns will help achieve this goal Favour a style e.g. LINQ But avoid nested lambda hell

© 2014 RoCk SOLid KnOwledge 16 Tip: Publish Cyclomatic Complexity

Dashboards like Sonar publish cyclomatic complexity during the build for all to see Visual Studio “Code Metrics” gives cyclomatic complexity drill down ReSharper add-on can graphically show cyclomatic complexity in Visual Studio

© 2014 RoCk SOLid KnOwledge 17 Cyclomatic Complexity Demo

© 2014 RoCk SOLid KnOwledge 18 Tip: Avoid Static

Static references & classes defeat unit testing E.g. How do you mock DateTime.Now for daylight savings unit tests when they run on January 14th? Wrap use of static classes in an injected singleton that delegates to static implementation E.g. Define and implement IDateTime interface Avoid ‘XyzHelper’ or ‘Util’ classes like the plague!

© 2014 RoCk SOLid KnOwledge 19 Tip: Use Awesome Names Everywhere

Take time to name every artefact Class, method, field, property, parameter, automatic variable (prod code + test code) Class name is a noun Method name is a verb E.g. dog.Sleep(), table.Clear(), documentAggregator.Aggregate() Stuck for class name? http://classnamer.com  E.g. for(int p = 0; p < 10; p++) {} for(int personIndex = 0; personIndex < 10; personIndex++) {}

© 2014 RoCk SOLid KnOwledge 20 Tip: Write Clean Code Uncle Bob says ‘Keep it clean!’

Broken Window Theory “maintaining and monitoring urban environmen ts to prevent small crimes such as vandalism, pu blic drinking and toll- jumping helps to create an atmosphere of order and lawfulness, thereby preventing more seriou s crimes from happening” Corollary: Keep code+tests uber clean [https://en.wikipedia.org/wiki/Broken_windows _theory]

© 2014 RoCk SOLid KnOwledge 21 Tip: Avoid Inheritance

Default to avoid inheritance: ‘is-a’ Why? Derived often needs to know base intimately Default to favour composition: ‘has-a’ Only cave-in when ‘is-a’ rule satisfied Dog is-a bone: fail Dog has-a bone: pass Cat is-a mammal: pass Cat has-a mammal: fail

© 2014 RoCk SOLid KnOwledge 22 Tip: Code Review Before Check-in

Ideally every check-in gets peer reviewed prior to check-in Each check-in should have: Description + name of reviewer Over the shoulder review preferential Rotate reviewers and share knowledge and tips within the team == free peer training; level up Also back up with post commit code review tool e.g. Crucible

© 2014 RoCk SOLid KnOwledge 23 Tip: How To Conduct Code Review

1. Park egos at the door 2. Team first attitude 3. Test coverage good? 4. Lots of private methods? God class? 5. Inheritance satisfies ‘is-a’ rule? 6. Interface based programming? Use of ‘new’ operator? 7. Good class/method/field/prop/auto names?

© 2014 RoCk SOLid KnOwledge 24 Tip: Use

Domain class constructor takes interface parameters only (C#) Don’t new domain class from within domain class (fine to new framework classes e.g. List, Hashset etc) Why? Testing class A would be implicit test of B as well Constructor stores interface parameter in field Constructor does nothing else Why? Interface can easily be mocked therefore easy to test Use 2-phase construction via Initialize() method if needed

© 2014 RoCk SOLid KnOwledge 25 Inversion Of Control Demo

© 2014 RoCk SOLid KnOwledge 26 Tip: Avoid Code Comments

Comments are very useful for big and complicated things Warning: Comments quickly get out of date with respect to code during refactor Comments not necessary for small and easy to understand things Corollary: Only create small, easy to understand well named things and therefore ditch comments

© 2014 RoCk SOLid KnOwledge 27 Tip: Avoid Excessive Null Checking

Excessive checking is a Code smell if (dog != null) {} OR if (dog == null) Consider Null Object Pattern

© 2014 RoCk SOLid KnOwledge 28 Demo Null Object Pattern

© 2014 RoCk SOLid KnOwledge 29 Tip: Conform to a simple code standard

Author a 1 page annotated coding standard Why? If it all looks like it was written by one person then it’s going to be easier maintain/learn Get dev buy-in by building team consensus on content Print it off for everyone to put on the wall by their desk Police it with code review Use tooling: e.g. Write a Resharper standard and share with the team

© 2014 RoCk SOLid KnOwledge 30 Tip: Practice Interface Based Programming

Every domain class should should be accompanied by an interface What is a domain class? One that has behaviour Pass IDogController around, not DogController Why? Decrease coupling between classes

© 2014 RoCk SOLid KnOwledge 31 Tip: Use Multiple Method Returns

In the old days single method return was  Why? Because of long complicated methods in God classes Requires carefully nested method if/else hierarchy If you don’t have God classes with long complicated methods then you have no fear of multiple method returns any more  Why? Simpler to read due to dramatic reduction in nested if/else hierarchy

© 2014 RoCk SOLid KnOwledge 32 Tip: Avoid C# Regions

Regions (#region) are a great place to hide code  Often commented out code can be found hiding in them God classes often lurk within regions pretending to not be God classes Grrrrr

© 2014 RoCk SOLid KnOwledge 33 Tip: Avoid Speculative Generality

App developers are often wannabe framework developers Allow base classes to emerge from ongoing requirements Don’t try and predict the future now Avoid marking a method as virtual unless there is a class to override it right now

© 2014 RoCk SOLid KnOwledge 34 Tip: Buy ReSharper Licenses

All C# devs should use ReSharper Essential for quick and accurate refactoring Set up shared team coding style Reformat class(es) automatically before check-in Find type Find implementation of interface/method Refactor name of class/method/field/auto etc

© 2014 RoCk SOLid KnOwledge 35 Tip: Learn All Language Features C#

Polymorphism: check Interface based programming: check Generics: check Iterators: check LINQ: check async/await: check

© 2014 RoCk SOLid KnOwledge 36 Tip: Hire Quality-Minded Engineers

Do they care about code quality? Ask them! When was the last time they checked-in a unit test? Prove it! Get them to write an algorithm on the white board and a unit test for it Get them to come up with the list of tests they would write for the algorithm Ensure good CS background: data structures & algorithms Make sure they really know all the latest stuff (passion) Never hire a ‘maybe’ Ensure good team fit – everyone meets the candidate

© 2014 RoCk SOLid KnOwledge 37 Call To Action

Code quality directly impacts $takeholder through to end user experience Up the ante: Make code quality your mission Write good quality unit tests Maintain a hygienic code base (inc tests) Build a legacy your team is proud of that your users will love

© 2014 RoCk SOLid KnOwledge 38 References

Clean Code: A Handbook of Agile Software Craftsmanship, Robert C Martin aka Uncle Bob Awesome google talk (Misko Hevery) http://www.youtube.com/watch?v=acjvKJiOvXw

© 2014 RoCk SOLid KnOwledge 39