SlideShare a Scribd company logo
1 of 23
Keep Code Left
Mick Andrew
GGMUG
January 8th 2015
2
Speaker Background
• Developing code or managing developers for 25+ years
• .Net developer since 2000
• Unix/C, some Java, some Javascript
• Director of Development at Sage
– Sage is hiring …. Check us out at www.sage.com
3
Agenda
• Can one hour help you write better code?
• The approach of Keep Code Left
• How do this help in Code Reviews?
• Reading the whole code
• Examples
• Worked examples on real production code
• Questions and Discussions welcome throughout the
talk!
4
Keep Code Left
• A style of writing code for better readability
• Goal of KCL is to provide easy-to-apply rules which
foster
– simpler code logic
– which is easier to read
– and leads to fewer bugs during future maintenance
– Simple verification at review time
• Enables us to write code with simpler logic
• Learn to read many lines of code at once
– See the flow
5
Code Reviews / Inspections / Walkthroughs
• There are at least three independent goals for code reviews:
– Share knowledge
– Look for bugs
– Verify standards compliance
• These can be in conflict; dependencies on the reviewing team’s..
– Domain knowledge
– Coding skill level
– Personalities
• Standards compliance is the easiest to apply effectively
– Less dependencies on individual skills
– Spot patterns/anti-patterns without specific domain knowledge
• KCL provides a cookbook approach to assist at both...
– the time of coding, and
– for reviewing with no domain knowledge necessary
6
KCL: Claims and Mindset
• Ideal code has no branches (if statements)
– Few real-world methods are ideal!
• The one “main purpose” of any method should be in code
which is not indented
• If you need to branch, think about why
• Equivalent branch statements can be written several ways
if (condition == true)
if (!condition == false)
– Think about which way you should write any boolean expression
– e.g. if (i > j) versus if (j <= i)
– What should be in the then clause versus the else
clause… and do you need the else clause anyway?
7
Let’s review some code:
what happens in the else?
…
Methoda();
Methodb();
// Some useful comment
var foo = new Whatever(s);
string s = Getastring(foo);
int x = DoSomething(s);
x = Manipulate(x);
return x;
}
int DoSomething(string s)
{
if (s != null)
{
ImportantMethod (s);
int rc = SomethingElse(s);
return modify(rc);
}
else
{
8
We scroll up a bit:
…
int x = DoSomething(s);
x = Manipulate(x);
return x;
}
int DoSomething(string s)
{
if (s != null)
{
ImportantMethod(s);
int rc = SomethingElse(s);
return modify(rc);
}
else
{
throw new ArgumentException("null string");
}
}
9
Let’s review the same logic with KCL
Before..
Methoda();
Methodb();
// Some useful comment
var foo = new Whatever(s);
string s = Getastring(foo);
int x = DoSomething(s);
x = Manipulate(x);
return x;
}
int DoSomething(string s)
{
if (s != null)
{
ImportantMethod(s);
int rc = SomethingElse(s);
return modify(rc);
}
else
{
10
Let’s review the same logic with KCL
After..
Methoda();
Methodb();
// Some useful comment
var foo = new Whatever(s);
string s = Getastring(foo);
int x = DoSomething(s);
x = Manipulate(x);
return x;
}
int DoSomething(string s)
{
if (s == null)
throw new ArgumentException("null string");
ImportantMethod(s);
int rc = SomethingElse(s);
return modify(rc);
}
11
KCL: anti-patterns
• This example show how branch (if) statements are often coded
poorly in code samples (and real code!!)
int DoSomething(string s)
{
if (s != null)
{
Something1(s);
int rc = Something2(s);
return modify(rc);
}
else
{
throw new ArgumentException("null string");
}
}
This is the main body of the
code but it is indented in an if
statement
Why is this condition coded the way it is?
It pushes the main body to the right – anti-pattern
This is a Keep Code Left anti-pattern:
A standalone return or throw in an else block
2
3
1
12
Let’s fix it – Introducing the Filter
pattern
• The first statement in the example method causes all
of our problems. By inverting the if condition we can
apply a KCL pattern called a Filter
int DoSomething(string s)
{
if (s == null)
throw new ArgumentException("null string");
Something1(s);
int rc = Something2(s);
return rc;
}
We have made a Filter. The code “filters out”
non-interesting cases which do not qualify for the
body of the method to be applied. Get out of the
method as quickly as possible
1
Body of the method is now
completely left, with no
branching.
2
13
Examples of good KCL layout
if (condition)
return;
if (condition)
return;
code;
code;
code;
return;
if (condition)
return;
code;
while (condition)
{
if (condition)
continue;
code;
code;
if (condition)
break;
code;
code;
}
return;
if (condition)
return;
code;
code;
if (condition)
return;
code;
code;
return;
14
Examples of KCL red flag layout
if (condition)
{
code;
code;
code;
}
else
{
return error;
}
code;
return typical-case;
if (condition)
{
if (condition)
{
code;
code;
code;
code;
}
else
{
code;
}
}
else
{
code;
}
if (condition)
{
code;
code;
code;
}
else
{
return error;
}
if (condition)
return typical-case;
return error;
15
Keep Code Left rules
• Keep Code Left is for almost any language.
• Filter out uninteresting or inapplicable cases at the start of the method.
– Often return null, zero, false, or empty objects.
• Filter out more cases as soon as possible
– Good KCL code will start with filters, then some logic, then more filters, then more logic,
keeping most of the code left.
• Keep the main body of the code with as few branches as possible. Keep it
to the left.
• Think about each if condition. Should it be inverted?
• Avoid the else keyword (is it really necessary?)
• return statements should always be in the “then” part of a branch, rarely in
the else.
• Put smaller code blocks in the then clause. Don’t leave “hidden” else
clauses after long then clauses.
• Apply Keep Code Left rules in loops, using the continue and break
statements.
– Filter conditions out for each iteration of the loop.
• Look at the code as a whole. Use your eyes to see the structure of several
lines all at once. (Practice!)
– Do this when reviewing all code.
16
… as with all “rules”
• Look to apply them in all cases…
• BUT!
• Be happy with applying the 80/20 rule
– Don’t throw out the approach because you find a difficult case
– KCL does not solve every programming problem
– “red flag” doesn’t mean its wrong… just that it might be, and
is a good place to examine
– Don’t use an exception case as an excuse to discard the
entire approach
17
Keep Code Left red flags
• Watch for these code patterns and statements
– while you are writing code
– When you are code reviewing (easier than reviewing the
logic!)
• if statements which contain many lines of code
• else statements(!)
• else statements which contain one or two lines, often
error handling.
• Methods which end with return 0/false/null/throw
exception/empty objects;
– methods should end with the goal, not an error case
• Code with lots of braces{ { { } } }
18
See all the code at once
• Look at the code in the next two slides and see which
you can grasp as a whole, rather than line-by-line
• How easily can you see the “goal” of this code?
19
Sample A
public static void KeepCodeLeft()
{
foreach (var id in tmpArr)
{
var item = Sitecore.Context.Database.GetItem(id);
if (item != null)
{
MultilistField mf = item.Fields["Templates"];
if (mf != null)
{
foreach (var targetId in mf.TargetIDs)
{
var targetItem = Sitecore.Context.Database.GetItem(targetId);
if (targetItem != null && !string.IsNullOrEmpty(targetItem["Template"]))
{
listContentTypes.Add(targetItem["Template"]);
}
}
}
}
}
}
20
Sample B
public static void KeepCodeLeft()
{
foreach (var id in tmpArr)
{
var item = Sitecore.Context.Database.GetItem(id);
if (item == null)
continue;
MultilistField mf = item.Fields["Templates"];
if (mf == null)
continue;
foreach (var targetId in mf.TargetIDs)
{
var targetItem = Sitecore.Context.Database.GetItem(targetId);
if (targetItem == null || string.IsNullOrEmpty(targetItem["Template"]))
continue;
listContentTypes.Add(targetItem["Template"]);
}
}
}
21
Refactoring for KCL
• If the code is working, think carefully before
refactoring just to satisfy any preferred coding style
– even KCL  !
• Refactor when you are modifying the code for another
reason
– Bug fix
– Enhancement
• Whenever you refactor
– TEST
– TEST
– TEST!
22
Lets refactor some real code!
23
Questions?
• Share good examples
• Share problem cases
• Mick Andrew
• mick.andrew@sage.com
• http://www.linkedin.com/in/mickan
• http://www.slideshare.net
– Search for “Keep Code Left”

More Related Content

What's hot

React-JS Component Life-cycle Methods
React-JS Component Life-cycle MethodsReact-JS Component Life-cycle Methods
React-JS Component Life-cycle MethodsANKUSH CHAVAN
 
UE4 Garbage Collection
UE4 Garbage CollectionUE4 Garbage Collection
UE4 Garbage CollectionQooJuice
 
Git - An Introduction
Git - An IntroductionGit - An Introduction
Git - An IntroductionBehzad Altaf
 
이승재, 사례로 배우는 디스어셈블리 디버깅, NDC2014
이승재, 사례로 배우는 디스어셈블리 디버깅, NDC2014이승재, 사례로 배우는 디스어셈블리 디버깅, NDC2014
이승재, 사례로 배우는 디스어셈블리 디버깅, NDC2014devCAT Studio, NEXON
 
레퍼런스만 알면 언리얼 엔진이 제대로 보인다
레퍼런스만 알면 언리얼 엔진이 제대로 보인다레퍼런스만 알면 언리얼 엔진이 제대로 보인다
레퍼런스만 알면 언리얼 엔진이 제대로 보인다Lee Dustin
 
How to Install numpy, scipy, matplotlib, pandas and scikit-learn on Linux
How to Install numpy, scipy, matplotlib, pandas and scikit-learn on LinuxHow to Install numpy, scipy, matplotlib, pandas and scikit-learn on Linux
How to Install numpy, scipy, matplotlib, pandas and scikit-learn on LinuxVinita Silaparasetty
 
Dependency injection presentation
Dependency injection presentationDependency injection presentation
Dependency injection presentationAhasanul Kalam Akib
 
적당한 스터디 발표자료 만들기
적당한 스터디 발표자료 만들기적당한 스터디 발표자료 만들기
적당한 스터디 발표자료 만들기종빈 오
 
Git One Day Training Notes
Git One Day Training NotesGit One Day Training Notes
Git One Day Training Notesglen_a_smith
 
[C++ korea] effective modern c++ study item 17 19 신촌 study
[C++ korea] effective modern c++ study item 17 19 신촌 study[C++ korea] effective modern c++ study item 17 19 신촌 study
[C++ korea] effective modern c++ study item 17 19 신촌 studySeok-joon Yun
 
An Introduction to Test Driven Development
An Introduction to Test Driven Development An Introduction to Test Driven Development
An Introduction to Test Driven Development CodeOps Technologies LLP
 
Lets make a better react form
Lets make a better react formLets make a better react form
Lets make a better react formYao Nien Chung
 
Turtle graphics
Turtle graphicsTurtle graphics
Turtle graphicsgrahamwell
 
KGC 2016 오픈소스 네트워크 엔진 Super socket 사용하기
KGC 2016 오픈소스 네트워크 엔진 Super socket 사용하기KGC 2016 오픈소스 네트워크 엔진 Super socket 사용하기
KGC 2016 오픈소스 네트워크 엔진 Super socket 사용하기흥배 최
 
Starting with Git & GitHub
Starting with Git & GitHubStarting with Git & GitHub
Starting with Git & GitHubNicolás Tourné
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced JavascriptAdieu
 

What's hot (20)

git and github
git and githubgit and github
git and github
 
React-JS Component Life-cycle Methods
React-JS Component Life-cycle MethodsReact-JS Component Life-cycle Methods
React-JS Component Life-cycle Methods
 
UE4 Garbage Collection
UE4 Garbage CollectionUE4 Garbage Collection
UE4 Garbage Collection
 
Handling I/O in Java
Handling I/O in JavaHandling I/O in Java
Handling I/O in Java
 
Git - An Introduction
Git - An IntroductionGit - An Introduction
Git - An Introduction
 
이승재, 사례로 배우는 디스어셈블리 디버깅, NDC2014
이승재, 사례로 배우는 디스어셈블리 디버깅, NDC2014이승재, 사례로 배우는 디스어셈블리 디버깅, NDC2014
이승재, 사례로 배우는 디스어셈블리 디버깅, NDC2014
 
레퍼런스만 알면 언리얼 엔진이 제대로 보인다
레퍼런스만 알면 언리얼 엔진이 제대로 보인다레퍼런스만 알면 언리얼 엔진이 제대로 보인다
레퍼런스만 알면 언리얼 엔진이 제대로 보인다
 
How to Install numpy, scipy, matplotlib, pandas and scikit-learn on Linux
How to Install numpy, scipy, matplotlib, pandas and scikit-learn on LinuxHow to Install numpy, scipy, matplotlib, pandas and scikit-learn on Linux
How to Install numpy, scipy, matplotlib, pandas and scikit-learn on Linux
 
Dependency injection presentation
Dependency injection presentationDependency injection presentation
Dependency injection presentation
 
적당한 스터디 발표자료 만들기
적당한 스터디 발표자료 만들기적당한 스터디 발표자료 만들기
적당한 스터디 발표자료 만들기
 
Git One Day Training Notes
Git One Day Training NotesGit One Day Training Notes
Git One Day Training Notes
 
[C++ korea] effective modern c++ study item 17 19 신촌 study
[C++ korea] effective modern c++ study item 17 19 신촌 study[C++ korea] effective modern c++ study item 17 19 신촌 study
[C++ korea] effective modern c++ study item 17 19 신촌 study
 
An Introduction to Test Driven Development
An Introduction to Test Driven Development An Introduction to Test Driven Development
An Introduction to Test Driven Development
 
Lets make a better react form
Lets make a better react formLets make a better react form
Lets make a better react form
 
Unit testing with JUnit
Unit testing with JUnitUnit testing with JUnit
Unit testing with JUnit
 
Turtle graphics
Turtle graphicsTurtle graphics
Turtle graphics
 
KGC 2016 오픈소스 네트워크 엔진 Super socket 사용하기
KGC 2016 오픈소스 네트워크 엔진 Super socket 사용하기KGC 2016 오픈소스 네트워크 엔진 Super socket 사용하기
KGC 2016 오픈소스 네트워크 엔진 Super socket 사용하기
 
Starting with Git & GitHub
Starting with Git & GitHubStarting with Git & GitHub
Starting with Git & GitHub
 
Clean code
Clean code Clean code
Clean code
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 

Similar to Keep Code Left - How to write better code in almost any language

Contest Tips and Tricks
Contest Tips and TricksContest Tips and Tricks
Contest Tips and Tricksmbuzdalov
 
Principled And Clean Coding
Principled And Clean CodingPrincipled And Clean Coding
Principled And Clean CodingMetin Ogurlu
 
Dev buchan 30 proven tips
Dev buchan 30 proven tipsDev buchan 30 proven tips
Dev buchan 30 proven tipsBill Buchan
 
Clean code, Feb 2012
Clean code, Feb 2012Clean code, Feb 2012
Clean code, Feb 2012cobyst
 
Improving Code Quality Through Effective Review Process
Improving Code Quality Through Effective  Review ProcessImproving Code Quality Through Effective  Review Process
Improving Code Quality Through Effective Review ProcessDr. Syed Hassan Amin
 
Software Craftmanship - Cours Polytech
Software Craftmanship - Cours PolytechSoftware Craftmanship - Cours Polytech
Software Craftmanship - Cours Polytechyannick grenzinger
 
Clean Code - Part 2
Clean Code - Part 2Clean Code - Part 2
Clean Code - Part 2Knoldus Inc.
 
Software development best practices & coding guidelines
Software development best practices & coding guidelinesSoftware development best practices & coding guidelines
Software development best practices & coding guidelinesAnkur Goyal
 
Scala Bay Meetup - The state of Scala code style and quality
Scala Bay Meetup - The state of Scala code style and qualityScala Bay Meetup - The state of Scala code style and quality
Scala Bay Meetup - The state of Scala code style and qualityJaime Jorge
 
Style & Design Principles 01 - Code Style & Structure
Style & Design Principles 01 - Code Style & StructureStyle & Design Principles 01 - Code Style & Structure
Style & Design Principles 01 - Code Style & StructureNick Pruehs
 
YAGNI Principle and Clean Code
YAGNI Principle and Clean CodeYAGNI Principle and Clean Code
YAGNI Principle and Clean CodeLuan Reffatti
 
Developer Job in Practice
Developer Job in PracticeDeveloper Job in Practice
Developer Job in Practiceintive
 
PVS-Studio and static code analysis technique
PVS-Studio and static code analysis techniquePVS-Studio and static code analysis technique
PVS-Studio and static code analysis techniqueAndrey Karpov
 
Orthogonality: A Strategy for Reusable Code
Orthogonality: A Strategy for Reusable CodeOrthogonality: A Strategy for Reusable Code
Orthogonality: A Strategy for Reusable Codersebbe
 

Similar to Keep Code Left - How to write better code in almost any language (20)

Perfect Code
Perfect CodePerfect Code
Perfect Code
 
Contest Tips and Tricks
Contest Tips and TricksContest Tips and Tricks
Contest Tips and Tricks
 
Principled And Clean Coding
Principled And Clean CodingPrincipled And Clean Coding
Principled And Clean Coding
 
Dev buchan 30 proven tips
Dev buchan 30 proven tipsDev buchan 30 proven tips
Dev buchan 30 proven tips
 
Clean code, Feb 2012
Clean code, Feb 2012Clean code, Feb 2012
Clean code, Feb 2012
 
Writing clean code
Writing clean codeWriting clean code
Writing clean code
 
Improving Code Quality Through Effective Review Process
Improving Code Quality Through Effective  Review ProcessImproving Code Quality Through Effective  Review Process
Improving Code Quality Through Effective Review Process
 
Software Craftmanship - Cours Polytech
Software Craftmanship - Cours PolytechSoftware Craftmanship - Cours Polytech
Software Craftmanship - Cours Polytech
 
Clean Code - Part 2
Clean Code - Part 2Clean Code - Part 2
Clean Code - Part 2
 
Chapter17 of clean code
Chapter17 of clean codeChapter17 of clean code
Chapter17 of clean code
 
Software development best practices & coding guidelines
Software development best practices & coding guidelinesSoftware development best practices & coding guidelines
Software development best practices & coding guidelines
 
Scala Bay Meetup - The state of Scala code style and quality
Scala Bay Meetup - The state of Scala code style and qualityScala Bay Meetup - The state of Scala code style and quality
Scala Bay Meetup - The state of Scala code style and quality
 
DAA Unit 1.pdf
DAA Unit 1.pdfDAA Unit 1.pdf
DAA Unit 1.pdf
 
Style & Design Principles 01 - Code Style & Structure
Style & Design Principles 01 - Code Style & StructureStyle & Design Principles 01 - Code Style & Structure
Style & Design Principles 01 - Code Style & Structure
 
YAGNI Principle and Clean Code
YAGNI Principle and Clean CodeYAGNI Principle and Clean Code
YAGNI Principle and Clean Code
 
Developer Job in Practice
Developer Job in PracticeDeveloper Job in Practice
Developer Job in Practice
 
l2-es6-160830040119.pdf
l2-es6-160830040119.pdfl2-es6-160830040119.pdf
l2-es6-160830040119.pdf
 
PVS-Studio and static code analysis technique
PVS-Studio and static code analysis techniquePVS-Studio and static code analysis technique
PVS-Studio and static code analysis technique
 
Orthogonality: A Strategy for Reusable Code
Orthogonality: A Strategy for Reusable CodeOrthogonality: A Strategy for Reusable Code
Orthogonality: A Strategy for Reusable Code
 
Lecture 2: ES6 / ES2015 Slide
Lecture 2: ES6 / ES2015 SlideLecture 2: ES6 / ES2015 Slide
Lecture 2: ES6 / ES2015 Slide
 

Recently uploaded

办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
software engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptxsoftware engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptxnada99848
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 

Recently uploaded (20)

办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
software engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptxsoftware engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptx
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 

Keep Code Left - How to write better code in almost any language

  • 1. Keep Code Left Mick Andrew GGMUG January 8th 2015
  • 2. 2 Speaker Background • Developing code or managing developers for 25+ years • .Net developer since 2000 • Unix/C, some Java, some Javascript • Director of Development at Sage – Sage is hiring …. Check us out at www.sage.com
  • 3. 3 Agenda • Can one hour help you write better code? • The approach of Keep Code Left • How do this help in Code Reviews? • Reading the whole code • Examples • Worked examples on real production code • Questions and Discussions welcome throughout the talk!
  • 4. 4 Keep Code Left • A style of writing code for better readability • Goal of KCL is to provide easy-to-apply rules which foster – simpler code logic – which is easier to read – and leads to fewer bugs during future maintenance – Simple verification at review time • Enables us to write code with simpler logic • Learn to read many lines of code at once – See the flow
  • 5. 5 Code Reviews / Inspections / Walkthroughs • There are at least three independent goals for code reviews: – Share knowledge – Look for bugs – Verify standards compliance • These can be in conflict; dependencies on the reviewing team’s.. – Domain knowledge – Coding skill level – Personalities • Standards compliance is the easiest to apply effectively – Less dependencies on individual skills – Spot patterns/anti-patterns without specific domain knowledge • KCL provides a cookbook approach to assist at both... – the time of coding, and – for reviewing with no domain knowledge necessary
  • 6. 6 KCL: Claims and Mindset • Ideal code has no branches (if statements) – Few real-world methods are ideal! • The one “main purpose” of any method should be in code which is not indented • If you need to branch, think about why • Equivalent branch statements can be written several ways if (condition == true) if (!condition == false) – Think about which way you should write any boolean expression – e.g. if (i > j) versus if (j <= i) – What should be in the then clause versus the else clause… and do you need the else clause anyway?
  • 7. 7 Let’s review some code: what happens in the else? … Methoda(); Methodb(); // Some useful comment var foo = new Whatever(s); string s = Getastring(foo); int x = DoSomething(s); x = Manipulate(x); return x; } int DoSomething(string s) { if (s != null) { ImportantMethod (s); int rc = SomethingElse(s); return modify(rc); } else {
  • 8. 8 We scroll up a bit: … int x = DoSomething(s); x = Manipulate(x); return x; } int DoSomething(string s) { if (s != null) { ImportantMethod(s); int rc = SomethingElse(s); return modify(rc); } else { throw new ArgumentException("null string"); } }
  • 9. 9 Let’s review the same logic with KCL Before.. Methoda(); Methodb(); // Some useful comment var foo = new Whatever(s); string s = Getastring(foo); int x = DoSomething(s); x = Manipulate(x); return x; } int DoSomething(string s) { if (s != null) { ImportantMethod(s); int rc = SomethingElse(s); return modify(rc); } else {
  • 10. 10 Let’s review the same logic with KCL After.. Methoda(); Methodb(); // Some useful comment var foo = new Whatever(s); string s = Getastring(foo); int x = DoSomething(s); x = Manipulate(x); return x; } int DoSomething(string s) { if (s == null) throw new ArgumentException("null string"); ImportantMethod(s); int rc = SomethingElse(s); return modify(rc); }
  • 11. 11 KCL: anti-patterns • This example show how branch (if) statements are often coded poorly in code samples (and real code!!) int DoSomething(string s) { if (s != null) { Something1(s); int rc = Something2(s); return modify(rc); } else { throw new ArgumentException("null string"); } } This is the main body of the code but it is indented in an if statement Why is this condition coded the way it is? It pushes the main body to the right – anti-pattern This is a Keep Code Left anti-pattern: A standalone return or throw in an else block 2 3 1
  • 12. 12 Let’s fix it – Introducing the Filter pattern • The first statement in the example method causes all of our problems. By inverting the if condition we can apply a KCL pattern called a Filter int DoSomething(string s) { if (s == null) throw new ArgumentException("null string"); Something1(s); int rc = Something2(s); return rc; } We have made a Filter. The code “filters out” non-interesting cases which do not qualify for the body of the method to be applied. Get out of the method as quickly as possible 1 Body of the method is now completely left, with no branching. 2
  • 13. 13 Examples of good KCL layout if (condition) return; if (condition) return; code; code; code; return; if (condition) return; code; while (condition) { if (condition) continue; code; code; if (condition) break; code; code; } return; if (condition) return; code; code; if (condition) return; code; code; return;
  • 14. 14 Examples of KCL red flag layout if (condition) { code; code; code; } else { return error; } code; return typical-case; if (condition) { if (condition) { code; code; code; code; } else { code; } } else { code; } if (condition) { code; code; code; } else { return error; } if (condition) return typical-case; return error;
  • 15. 15 Keep Code Left rules • Keep Code Left is for almost any language. • Filter out uninteresting or inapplicable cases at the start of the method. – Often return null, zero, false, or empty objects. • Filter out more cases as soon as possible – Good KCL code will start with filters, then some logic, then more filters, then more logic, keeping most of the code left. • Keep the main body of the code with as few branches as possible. Keep it to the left. • Think about each if condition. Should it be inverted? • Avoid the else keyword (is it really necessary?) • return statements should always be in the “then” part of a branch, rarely in the else. • Put smaller code blocks in the then clause. Don’t leave “hidden” else clauses after long then clauses. • Apply Keep Code Left rules in loops, using the continue and break statements. – Filter conditions out for each iteration of the loop. • Look at the code as a whole. Use your eyes to see the structure of several lines all at once. (Practice!) – Do this when reviewing all code.
  • 16. 16 … as with all “rules” • Look to apply them in all cases… • BUT! • Be happy with applying the 80/20 rule – Don’t throw out the approach because you find a difficult case – KCL does not solve every programming problem – “red flag” doesn’t mean its wrong… just that it might be, and is a good place to examine – Don’t use an exception case as an excuse to discard the entire approach
  • 17. 17 Keep Code Left red flags • Watch for these code patterns and statements – while you are writing code – When you are code reviewing (easier than reviewing the logic!) • if statements which contain many lines of code • else statements(!) • else statements which contain one or two lines, often error handling. • Methods which end with return 0/false/null/throw exception/empty objects; – methods should end with the goal, not an error case • Code with lots of braces{ { { } } }
  • 18. 18 See all the code at once • Look at the code in the next two slides and see which you can grasp as a whole, rather than line-by-line • How easily can you see the “goal” of this code?
  • 19. 19 Sample A public static void KeepCodeLeft() { foreach (var id in tmpArr) { var item = Sitecore.Context.Database.GetItem(id); if (item != null) { MultilistField mf = item.Fields["Templates"]; if (mf != null) { foreach (var targetId in mf.TargetIDs) { var targetItem = Sitecore.Context.Database.GetItem(targetId); if (targetItem != null && !string.IsNullOrEmpty(targetItem["Template"])) { listContentTypes.Add(targetItem["Template"]); } } } } } }
  • 20. 20 Sample B public static void KeepCodeLeft() { foreach (var id in tmpArr) { var item = Sitecore.Context.Database.GetItem(id); if (item == null) continue; MultilistField mf = item.Fields["Templates"]; if (mf == null) continue; foreach (var targetId in mf.TargetIDs) { var targetItem = Sitecore.Context.Database.GetItem(targetId); if (targetItem == null || string.IsNullOrEmpty(targetItem["Template"])) continue; listContentTypes.Add(targetItem["Template"]); } } }
  • 21. 21 Refactoring for KCL • If the code is working, think carefully before refactoring just to satisfy any preferred coding style – even KCL  ! • Refactor when you are modifying the code for another reason – Bug fix – Enhancement • Whenever you refactor – TEST – TEST – TEST!
  • 22. 22 Lets refactor some real code!
  • 23. 23 Questions? • Share good examples • Share problem cases • Mick Andrew • mick.andrew@sage.com • http://www.linkedin.com/in/mickan • http://www.slideshare.net – Search for “Keep Code Left”