Download presentation
Presentation is loading. Please wait.
Published byDella Morris Modified over 8 years ago
1
Clean Code “Keep it Clean, Your Mother Doesn’t Work Here”“Keep it Clean, Your Mother Doesn’t Work Here” William PenberthyWilliam Penberthy Application Development ConsultantApplication Development Consultant RBA, Inc.RBA, Inc.
2
Description of the Next 70 Minutes We will discuss the importance of clean codeWe will discuss the importance of clean code What it is What it is Identifying clean vs dirty Identifying clean vs dirty Making it clean Making it clean Keeping it clean Keeping it clean Cleaning up after others Cleaning up after others
3
Intro
4
WTF – Clean Code?? Easy to understand the structure Easy to understand the structure Easy to understand the logic Easy to understand the logic Reasons for the decisions are documented Reasons for the decisions are documented
5
Why Clean Code?? Ability to respond to change requests stays constant Ability to respond to change requests stays constant Comparatively easy to bring new resources into project Comparatively easy to bring new resources into project Unit test code coverage becomes a useful statistic Unit test code coverage becomes a useful statistic Issue detection and resolution is more efficient Issue detection and resolution is more efficient
6
Indications of “Bad” Structure Opacity/Obscurity – a lot of time is spent trying to understand what is happening in the code Opacity/Obscurity – a lot of time is spent trying to understand what is happening in the code Needless complexity – remember KISS! Needless complexity – remember KISS! Magic Numbers / “configuration” items that never change Magic Numbers / “configuration” items that never change Common features built into high level project (logging, data access) Common features built into high level project (logging, data access)
7
Indications of “Good” Structure Loosely coupled projects Loosely coupled projects Dependencies are obvious Dependencies are obvious Names and namespaces are useful and descriptive Names and namespaces are useful and descriptive Consistency Consistency Abstractions rather than concretions Abstractions rather than concretions Logical separation of concern Logical separation of concern
8
Examples of Unclean Logic Fragility – one change breaks many things Fragility – one change breaks many things Rigidity – difficult to change without having to make many other changes Rigidity – difficult to change without having to make many other changes Code Duplication Code Duplication Methods with Too Many Arguments Methods with Too Many Arguments Nesting without implicit ends Nesting without implicit ends
9
More Dirtyness (technical term) Clutter and code that has been commented for a looooong time Clutter and code that has been commented for a looooong time Too much information in an interface Too much information in an interface Unit tests are “turned off” or commented out Unit tests are “turned off” or commented out Unmanaged build warnings Unmanaged build warnings Compound methods – GetList().First(x=>x.IsActive).GetFullName(); Compound methods – GetList().First(x=>x.IsActive).GetFullName();
10
Examples of Clean Logic If your code is clean, it will probably have these…If your code is clean, it will probably have these…
11
Method management Each method does only one thing Each method does only one thing Loops, exception handling, etc should all be encapsulated in other “sub” methods Loops, exception handling, etc should all be encapsulated in other “sub” methods No out variables No out variables No ref variables - Return complex object holding all values, split into several methods. If your method must change the state of something, have it change the state of the object it is called on No ref variables - Return complex object holding all values, split into several methods. If your method must change the state of something, have it change the state of the object it is called on No Selector / Flag Arguments – these should be different methods No Selector / Flag Arguments – these should be different methods
12
Naming Interfaces and Classes in a Related Manner The name of an interface should be derived from its usage by the client The name of an interface should be derived from its usage by the client Name Classes After How They Implement Their Interfaces Name Classes After How They Implement Their Interfaces MemoryStream implementing IStream MemoryStream implementing IStream SqlCommand implementing ICommand SqlCommand implementing ICommand ObservableCollection implementing Ilist (it ain’t perfect) ObservableCollection implementing Ilist (it ain’t perfect)
13
Prefer Dedicated Value Objects to Primitive Types Instead of passing primitive types like strings and integers, use a dedicated type Instead of passing primitive types like strings and integers, use a dedicated type AbsolutePath instead of string AbsolutePath instead of string Uri instead of string Uri instead of string Rather than create a list of parameters, create a class or struct to hold the information Rather than create a list of parameters, create a class or struct to hold the information
14
Supporting Clean Code External Documentation External Documentation Business requirements Business requirements Technical design Technical design Coding standards Coding standards Internal Process Internal Process Continual refactor (10-20% of effort every sprint/cycle) Continual refactor (10-20% of effort every sprint/cycle) Code review Code review Technical debt log Technical debt log
15
Exception Handling Strategy Catch exceptions as specific as possible so you can react in a meaningful manner Catch exceptions as specific as possible so you can react in a meaningful manner If you can’t react in a useful way to an exception, let something up the call stack handle it If you can’t react in a useful way to an exception, let something up the call stack handle it Fail fast – as early in the process as possible Fail fast – as early in the process as possible DON’T SWALLOW EXCEPTIONS! DON’T SWALLOW EXCEPTIONS!
16
Boy Scout Rule Keep the code cleaner then you found it Keep the code cleaner then you found it If there is technical debt in a method you are refactoring, clean it up If there is technical debt in a method you are refactoring, clean it up While you are there, clean up one more level While you are there, clean up one more level Ensure new code is clean Ensure new code is clean
17
Separate and Clarify Multi-Threading Code Do not mix code that handles multi-threading in with non- threading code. Separate them into different classes Do not mix code that handles multi-threading in with non- threading code. Separate them into different classes When using asynchronous methods (async) use Async as part of the name When using asynchronous methods (async) use Async as part of the name DoWorkAsync DoWorkAsync DoDifferentWorkAsync DoDifferentWorkAsync
18
Coding Standards – Have Them Don’t have pages describing what case to use in variables, or how many spaces to indent Don’t have pages describing what case to use in variables, or how many spaces to indent Talk about patterns to use Talk about patterns to use Base classes and their differentiation Base classes and their differentiation How to call the server How to call the server Expected consistent behavior Expected consistent behavior What gotchas there are in the implementation \ architecture \ systems What gotchas there are in the implementation \ architecture \ systems Living document – review frequently to ensure that it is up to date Living document – review frequently to ensure that it is up to date
19
Team Structure Group responsibility – everyone holds everyone else accountable Group responsibility – everyone holds everyone else accountable Have a leadership role(s) responsible for validating cleanliness Have a leadership role(s) responsible for validating cleanliness Run code reviews or Run code reviews or Review check-ins on a regular basis Review check-ins on a regular basis
20
Help your fellows understand the code Documentation is a road map to cleanlinessDocumentation is a road map to cleanliness
21
Documentation Documentation is not just for you Documentation is not just for you The process of documenting helps you better understand what really happens in the business AND in the code The process of documenting helps you better understand what really happens in the business AND in the code Should include: Should include: Input / output expectations (Class & Method) Input / output expectations (Class & Method) Inline logic discussions Inline logic discussions
22
External Documentation – Awesome !! Wiki or some such tool / Automated documentation generators Wiki or some such tool / Automated documentation generators Update it when you update your unit tests Update it when you update your unit tests The most specific and accurate documentation is typically written by the programmers as code is written. The most specific and accurate documentation is typically written by the programmers as code is written. Flow of Execution Flow of Execution Code Organization Code Organization Dependencies Dependencies Class and Method Definitions Class and Method Definitions
23
Code Documentation – Even Awesomer! Code documentation is generally specific to “what is going on right here” Code documentation is generally specific to “what is going on right here” The intended audience is other software developers who will support the project The intended audience is other software developers who will support the project Especially important when: Especially important when: Doing fixes / enhancements that change original code Doing fixes / enhancements that change original code Gnarly code Gnarly code
24
Self Documentation – Is it a Myth? Self-documenting code is the concept that code can be written in such a way that a human can easily understand exactly what the code is doing without added code documentation or code comments.
25
Self Documentation – Never Enough Self Documentation makes several assumptions The reader already knows the “real” business process and already understands all the classes The reader already knows the “real” business process and already understands all the classes The language you use to name objects is understood by all The language you use to name objects is understood by all
26
Process to Clean Up Identify bad code Identify bad code Mark bad code Mark bad code Make plan to remediate bad code Make plan to remediate bad code Documentation of business functionality Documentation of business functionality Create tests to validate refactor Create tests to validate refactor Refactor of code Refactor of code Technical documentation Technical documentation Follow through on the plan Follow through on the plan
27
Cleaning up a mess Sometimes the code gets dirty, it should get fixedSometimes the code gets dirty, it should get fixed
28
Cleaning the code up Always have a running system. Keep changes small and manageable Always have a running system. Keep changes small and manageable Isolate changes before making them Isolate changes before making them Make parallel algorithms Make parallel algorithms Set up tests Set up tests Feature tests – so you can make sure everything works as you make the changes Feature tests – so you can make sure everything works as you make the changes Performance tests – set baseline before you make changes Performance tests – set baseline before you make changes Load tests – if applicable Load tests – if applicable
29
Automated Testing Unit Testing / Integration Testing Unit Testing / Integration Testing While not necessary for clean code, it sure helps… While not necessary for clean code, it sure helps… Supports refactoring to clean up code Supports refactoring to clean up code
30
Questions – Comments ??
31
Contact William PenberthyWilliam Penberthy Applications Development ConsultantApplications Development Consultant RBA, Inc.RBA, Inc. william.penberthy@rbaconsulting.com http://www.linkedin.com/in/billpenberthy/
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.