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

svn 능력자를 위한 git 개념 가이드
svn 능력자를 위한 git 개념 가이드svn 능력자를 위한 git 개념 가이드
svn 능력자를 위한 git 개념 가이드Insub Lee
 
NDC12_Lockless게임서버설계와구현
NDC12_Lockless게임서버설계와구현NDC12_Lockless게임서버설계와구현
NDC12_Lockless게임서버설계와구현noerror
 
Aula04 Sistemas Distribuídos - Processos
Aula04 Sistemas Distribuídos - ProcessosAula04 Sistemas Distribuídos - Processos
Aula04 Sistemas Distribuídos - ProcessosMessias Batista
 
Iocp 기본 구조 이해
Iocp 기본 구조 이해Iocp 기본 구조 이해
Iocp 기본 구조 이해Nam Hyeonuk
 
MMOG Server-Side 충돌 및 이동처리 설계와 구현
MMOG Server-Side 충돌 및 이동처리 설계와 구현MMOG Server-Side 충돌 및 이동처리 설계와 구현
MMOG Server-Side 충돌 및 이동처리 설계와 구현YEONG-CHEON YOU
 
PHPでWebSocketを実装してみてわかったこと
PHPでWebSocketを実装してみてわかったことPHPでWebSocketを実装してみてわかったこと
PHPでWebSocketを実装してみてわかったことksimoji
 
객체지향 개념 (쫌 아는체 하기)
객체지향 개념 (쫌 아는체 하기)객체지향 개념 (쫌 아는체 하기)
객체지향 개념 (쫌 아는체 하기)Seung-June Lee
 
Architecture réparties et les services web
Architecture réparties et les services webArchitecture réparties et les services web
Architecture réparties et les services webCHOUAIB EL HACHIMI
 
중앙 서버 없는 게임 로직
중앙 서버 없는 게임 로직중앙 서버 없는 게임 로직
중앙 서버 없는 게임 로직Hoyoung Choi
 
서비스중인 게임 DB 설계 (쿠키런 편)
서비스중인 게임 DB 설계 (쿠키런 편)서비스중인 게임 DB 설계 (쿠키런 편)
서비스중인 게임 DB 설계 (쿠키런 편)_ce
 
임태현, 게임 서버 디자인 가이드, NDC2013
임태현, 게임 서버 디자인 가이드, NDC2013임태현, 게임 서버 디자인 가이드, NDC2013
임태현, 게임 서버 디자인 가이드, NDC2013devCAT Studio, NEXON
 
Presto As A Service - Treasure DataでのPresto運用事例
Presto As A Service - Treasure DataでのPresto運用事例Presto As A Service - Treasure DataでのPresto運用事例
Presto As A Service - Treasure DataでのPresto運用事例Taro L. Saito
 
테라로 살펴본 MMORPG의 논타겟팅 시스템
테라로 살펴본 MMORPG의 논타겟팅 시스템테라로 살펴본 MMORPG의 논타겟팅 시스템
테라로 살펴본 MMORPG의 논타겟팅 시스템QooJuice
 
소프트웨어 아키텍처 문서화
소프트웨어 아키텍처 문서화소프트웨어 아키텍처 문서화
소프트웨어 아키텍처 문서화영기 김
 
Introdução a Sistemas Distribuídos
Introdução a Sistemas DistribuídosIntrodução a Sistemas Distribuídos
Introdução a Sistemas DistribuídosVictor Hazin da Rocha
 
[KGC 2011]Boost 라이브러리와 C++11
[KGC 2011]Boost 라이브러리와 C++11[KGC 2011]Boost 라이브러리와 C++11
[KGC 2011]Boost 라이브러리와 C++11흥배 최
 
스마트폰 온라인 게임에서 고려해야 할 것들
스마트폰 온라인 게임에서 고려해야 할 것들스마트폰 온라인 게임에서 고려해야 할 것들
스마트폰 온라인 게임에서 고려해야 할 것들Hyunjik Bae
 
양승명, 다음 세대 크로스플랫폼 MMORPG 아키텍처, NDC2012
양승명, 다음 세대 크로스플랫폼 MMORPG 아키텍처, NDC2012양승명, 다음 세대 크로스플랫폼 MMORPG 아키텍처, NDC2012
양승명, 다음 세대 크로스플랫폼 MMORPG 아키텍처, NDC2012devCAT Studio, NEXON
 
NDC 11 자이언트 서버의 비밀
NDC 11 자이언트 서버의 비밀NDC 11 자이언트 서버의 비밀
NDC 11 자이언트 서버의 비밀승명 양
 
Twitter의 snowflake 소개 및 활용
Twitter의 snowflake 소개 및 활용Twitter의 snowflake 소개 및 활용
Twitter의 snowflake 소개 및 활용흥배 최
 

What's hot (20)

svn 능력자를 위한 git 개념 가이드
svn 능력자를 위한 git 개념 가이드svn 능력자를 위한 git 개념 가이드
svn 능력자를 위한 git 개념 가이드
 
NDC12_Lockless게임서버설계와구현
NDC12_Lockless게임서버설계와구현NDC12_Lockless게임서버설계와구현
NDC12_Lockless게임서버설계와구현
 
Aula04 Sistemas Distribuídos - Processos
Aula04 Sistemas Distribuídos - ProcessosAula04 Sistemas Distribuídos - Processos
Aula04 Sistemas Distribuídos - Processos
 
Iocp 기본 구조 이해
Iocp 기본 구조 이해Iocp 기본 구조 이해
Iocp 기본 구조 이해
 
MMOG Server-Side 충돌 및 이동처리 설계와 구현
MMOG Server-Side 충돌 및 이동처리 설계와 구현MMOG Server-Side 충돌 및 이동처리 설계와 구현
MMOG Server-Side 충돌 및 이동처리 설계와 구현
 
PHPでWebSocketを実装してみてわかったこと
PHPでWebSocketを実装してみてわかったことPHPでWebSocketを実装してみてわかったこと
PHPでWebSocketを実装してみてわかったこと
 
객체지향 개념 (쫌 아는체 하기)
객체지향 개념 (쫌 아는체 하기)객체지향 개념 (쫌 아는체 하기)
객체지향 개념 (쫌 아는체 하기)
 
Architecture réparties et les services web
Architecture réparties et les services webArchitecture réparties et les services web
Architecture réparties et les services web
 
중앙 서버 없는 게임 로직
중앙 서버 없는 게임 로직중앙 서버 없는 게임 로직
중앙 서버 없는 게임 로직
 
서비스중인 게임 DB 설계 (쿠키런 편)
서비스중인 게임 DB 설계 (쿠키런 편)서비스중인 게임 DB 설계 (쿠키런 편)
서비스중인 게임 DB 설계 (쿠키런 편)
 
임태현, 게임 서버 디자인 가이드, NDC2013
임태현, 게임 서버 디자인 가이드, NDC2013임태현, 게임 서버 디자인 가이드, NDC2013
임태현, 게임 서버 디자인 가이드, NDC2013
 
Presto As A Service - Treasure DataでのPresto運用事例
Presto As A Service - Treasure DataでのPresto運用事例Presto As A Service - Treasure DataでのPresto運用事例
Presto As A Service - Treasure DataでのPresto運用事例
 
테라로 살펴본 MMORPG의 논타겟팅 시스템
테라로 살펴본 MMORPG의 논타겟팅 시스템테라로 살펴본 MMORPG의 논타겟팅 시스템
테라로 살펴본 MMORPG의 논타겟팅 시스템
 
소프트웨어 아키텍처 문서화
소프트웨어 아키텍처 문서화소프트웨어 아키텍처 문서화
소프트웨어 아키텍처 문서화
 
Introdução a Sistemas Distribuídos
Introdução a Sistemas DistribuídosIntrodução a Sistemas Distribuídos
Introdução a Sistemas Distribuídos
 
[KGC 2011]Boost 라이브러리와 C++11
[KGC 2011]Boost 라이브러리와 C++11[KGC 2011]Boost 라이브러리와 C++11
[KGC 2011]Boost 라이브러리와 C++11
 
스마트폰 온라인 게임에서 고려해야 할 것들
스마트폰 온라인 게임에서 고려해야 할 것들스마트폰 온라인 게임에서 고려해야 할 것들
스마트폰 온라인 게임에서 고려해야 할 것들
 
양승명, 다음 세대 크로스플랫폼 MMORPG 아키텍처, NDC2012
양승명, 다음 세대 크로스플랫폼 MMORPG 아키텍처, NDC2012양승명, 다음 세대 크로스플랫폼 MMORPG 아키텍처, NDC2012
양승명, 다음 세대 크로스플랫폼 MMORPG 아키텍처, NDC2012
 
NDC 11 자이언트 서버의 비밀
NDC 11 자이언트 서버의 비밀NDC 11 자이언트 서버의 비밀
NDC 11 자이언트 서버의 비밀
 
Twitter의 snowflake 소개 및 활용
Twitter의 snowflake 소개 및 활용Twitter의 snowflake 소개 및 활용
Twitter의 snowflake 소개 및 활용
 

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

The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...kalichargn70th171
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnAmarnathKambale
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesVictorSzoltysek
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfVishalKumarJha10
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024Mind IT Systems
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdfPearlKirahMaeRagusta1
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech studentsHimanshiGarg82
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 

Recently uploaded (20)

The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 

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”