SlideShare a Scribd company logo
Humane Code
Mark Seemann
http://blog.ploeh.dk
@ploeh
@ploeh
Software construction
@ploeh
@ploeh
Software development is
not a science
@ploeh
@ploeh
Software development is
not engineering
@ploeh
@ploeh
Measurements
@ploeh
@ploeh
Measurements
@ploeh
@ploeh
Measurements
Lines of code
Code coverage
Cyclomatic complexity
Afferent coupling
Efferent coupling
@ploeh
@ploeh
public class GoldCustomerSpecification : ICustomerSpecification
{
public bool IsSatisfiedBy(Customer candidate)
{
bool retVal;
if (candidate.TotalPurchases >= 10000)
retVal = true;
else
retVal = false;
return retVal;
}
}
@ploeh
public class GoldCustomerSpecification : ICustomerSpecification
{
public bool IsSatisfiedBy(Customer candidate)
{
return candidate.TotalPurchases >= 10000;
}
}
read
written
@ploeh
Code is
more than it’s
@ploehhttps://www.flickr.com/photos/adewale_oshineye/2933030620
“Any fool can
write code that a
computer can
understand. Good
programmers
write code that
humans can
understand.”
@ploeh
@ploeh
Technology
@ploeh
@ploeh
Technology
@ploeh
Technology
Empathy
Cognition
Psychology
Neuroscience
@ploeh
7 items
±2
@ploeh
@ploeh
public class Odin
{
private bool isEven;
private string email;
private decimal silverThreshold;
private decimal z;
private bool isValid;
private string userName;
private decimal y;
private Tier tier;
private decimal goldThreshold;
private decimal x;
private decimal totalPurchases;
private IEnumerable<int> primes;
private decimal goldDiscountRate;
private string displayName;
private DateTimeOffset t;
private decimal silverDiscountRate;
@ploeh
public class Odin
{
private bool isEven;
private string email;
private decimal silverThreshold;
private decimal z;
private bool isValid;
private string userName;
private decimal y;
private Tier tier;
private decimal goldThreshold;
private decimal x;
private decimal totalPurchases;
private IEnumerable<int> primes;
private decimal goldDiscountRate;
@ploeh
public class Odin
{
private string userName;
private string displayName;
private string email;
private Tier tier;
private decimal totalPurchases;
private decimal silverThreshold;
private decimal silverDiscountRate;
private decimal goldThreshold;
private decimal goldDiscountRate;
private decimal x;
private decimal y;
private decimal z;
private DateTimeOffset t;
@ploeh
Code should be humane
@ploeh
@ploeh
Productivity?
@ploeh
!= typingProductivity
@ploeh
@ploeh
read
written
@ploeh
@ploeh
Code is a liability
@ploeh
@ploeh
Software is an asset
@ploeh
@ploeh
Code is a liability
@ploeh
@ploeh
What can be done?
@ploeh
Abstraction
@ploeh
@ploeh
public class GoldCustomerSpecification : ICustomerSpecification
{
public bool IsSatisfiedBy(Customer candidate)
{
return candidate.TotalPurchases >= 10000;
}
}
@ploeh
.method public hidebysig newslot virtual final
instance bool IsSatisfiedBy(class Ploeh.Samples.LoCSample.Customer ca
{
// Code size 22 (0x16)
.maxstack 2
.locals init ([0] bool V_0)
IL_0000: nop
IL_0001: ldarg.1
IL_0002: callvirt instance int32 Ploeh.Samples.LoCSample.Customer::get_
IL_0007: ldc.i4 0x2710
IL_000c: clt
IL_000e: ldc.i4.0
IL_000f: ceq
IL_0011: stloc.0
IL_0012: br.s IL_0014
IL_0014: ldloc.0
IL_0015: ret
} // end of method GoldCustomerSpecification::IsSatisfiedBy
@ploeh
8945 ec89 4dfc 8955 f88b 05a8 1300 1083
3800 7405 e88f d7ff ff0f b645 fc89 45f4
0fb6 45f8 8945 f033 c933 d2e8 c0d6 ffff
8945 ecff 75ec 8b4d f48b 55f0 e8b7 d6ff
ff90 8be5 5dc3 cccc 558b ec57 5683 ec20
8bf1 8d7d d8b9 0500 0000 33c0 f3ab 8bce
894d f489 55f0 8b05 a813 0010 8338 0074
05e8 32d7 ffff 8b05 1018 0010 8b08 8b55
08e8 7ad6 ffff 0fb6 45f0 500f b655 f48b
4d08 ff15 3817 0010 8945 ec83 7dec 0075
5f8b 0dfc 1600 10e8 0cd7 ffff 8945 e88b
0dfc 1600 10e8 fed6 ffff 8945 e48b 0db0
1700 10e8 f0d6 ffff 8945 e08b 45e0 8945
dc8b 45e8 8b55 f488 5004 8b45 e889 45d8
8b45 e48b 55f0 8850 048b 45e4 508b 4ddc
8b55 d8e8 10d6 ffff 8b4d e0e8 c8d6 ffff
908d 65f8 5e5f 5dc2 0400 cccc 558b ec83
ec0c 33c0 8945 f489 4dfc 8955 f88b 05a8
1300 1083 3800 7405 e87b d6ff ff8b 0db4
@ploeh
00000000 00000000 00000000 00000000 00000000 00000000
00000000 00000000 00000000 00000000 00000000 00000000
00000000 00000000 00000000 00000000 00000000 00000000
00000000 00000000 01010000 01000101 00000000 00000000
01001100 00000001 00000100 00000000 10101001 11101111
00100101 01010110 00000000 00000000 00000000 00000000
00000000 00000000 00000000 00000000 11100000 00000000
00000010 00100001 00001011 00000001 00001011 00000000
00000000 00000000 00000000 00000000 00000000 00000000
00000000 00000000 00000000 00000000 00000000 00000000
00000000 00000000 00000000 00000000 00000000 00000000
00000000 00000000 00000000 00000000 00000000 00000000
00000000 00000000 00000000 00010000 00000000 00010000
00000000 00000000 00000000 00000010 00000000 00000000
00000101 00000000 00000000 00000000 00000000 00000000
00000000 00000000 00000101 00000000 00000000 00000000
00000000 00000000 00000000 00000000 00000000 10010000
00000000 00000000 00000000 00000100 00000000 00000000
00000000 00000000 00000000 00000000 00000011 00000000
@ploeh
@ploeh
@ploeh
public class GoldCustomerSpecification : ICustomerSpecification
{
public bool IsSatisfiedBy(Customer candidate)
{
return candidate.TotalPurchases >= 10000;
}
}
@ploeh
Abstraction
@ploeh
@ploeh
public class MethodInvoker : ISpecimenBuilder
{
private readonly IMethodQuery query;
public MethodInvoker(IMethodQuery query)
{
if (query == null)
{
throw new ArgumentNullException("query");
}
this.query = query;
}
public IMethodQuery Query
{
get { return this.query; }
}
public object Create(object request, ISpecimenContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
foreach (var ci in this.GetConstructors(request))
{
var paramValues = (from pi in ci.Parameters
select context.Resolve(pi)).ToList();
if (paramValues.All(MethodInvoker.IsValueValid))
{
return ci.Invoke(paramValues.ToArray());
}
}
return new NoSpecimen(request);
}
private IEnumerable<IMethod> GetConstructors(object request)
{
var requestedType = request as Type;
if (requestedType == null)
{
return Enumerable.Empty<IMethod>();
}
return this.query.SelectMethods(requestedType);
}
private static bool IsValueValid(object value)
{
return !(value is NoSpecimen)
&& !(value is OmitSpecimen);
}
}
@ploeh
public class MethodInvoker : ISpecimenBuilder
{
private readonly IMethodQuery query;
public MethodInvoker(IMethodQuery query)
{
if (query == null)
{
throw new ArgumentNullException("query");
}
this.query = query;
}
public IMethodQuery Query
{
get { return this.query; }
}
public object Create(object request, ISpecimenContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
foreach (var ci in this.GetConstructors(request))
{
var paramValues = (from pi in ci.Parameters
select context.Resolve(pi)).ToList();
if (paramValues.All(MethodInvoker.IsValueValid))
{
return ci.Invoke(paramValues.ToArray());
}
}
return new NoSpecimen(request);
}
private IEnumerable<IMethod> GetConstructors(object request)
{
var requestedType = request as Type;
if (requestedType == null)
{
return Enumerable.Empty<IMethod>();
}
return this.query.SelectMethods(requestedType);
}
private static bool IsValueValid(object value)
{
return !(value is NoSpecimen)
&& !(value is OmitSpecimen);
}
} @ploeh
Encapsulation
@ploeh
“An abstraction is
the amplification
of the essential
and the
elimination of the
irrelevant.”
https://commons.wikimedia.org/wiki/
File:Robert_Cecil_Martin.png @ploeh
@ploeh
the amplification
of the irrelevant
and the
elimination of the
essential
@ploeh
@ploeh
“An abstraction is
the amplification
of the essential
and the
elimination of the
irrelevant.”
@ploeh
@ploeh
What is the value of cust.Tier?
var cust =
new Customer
{
Tier = Tier.Silver,
TotalPurchases = 20000
};
var orders = GetOrders(cust);
1
2
@ploeh
public IReadOnlyCollection<Order> GetOrders(Customer customer)
{
Adjust(customer);
return RetrieveOrdersFromDatabase(customer);
}
private static void Adjust(Customer customer)
{
if (customer.TotalPurchases >= 10000)
customer.Tier = Tier.Gold;
// Many more similar checks go here...
}
@ploeh
public IReadOnlyCollection<Order> GetOrders(Customer customer)
{
Adjust(customer);
return RetrieveOrdersFromDatabase(customer);
}
private static void Adjust(Customer customer)
{
if (customer.TotalPurchases >= 10000)
customer.Tier = Tier.Gold;
if (customer.RecentOrders <= 0)
customer.NeedsPromo = true;
if (customer.LovesHaskell)
@ploeh
Adjust(customer);
return RetrieveOrdersFromDatabase(customer);
}
private static void Adjust(Customer customer)
{
if (customer.TotalPurchases >= 10000)
customer.Tier = Tier.Gold;
if (customer.RecentOrders <= 0)
customer.NeedsPromo = true;
if (customer.LovesHaskell)
customer.Segment = Segment.Omg;
if (customer.TotalPurchases >= 20000)
customer.Tier = Tier.Platinum;
@ploeh
private static void Adjust(Customer customer)
{
if (customer.TotalPurchases >= 10000)
customer.Tier = Tier.Gold;
if (customer.RecentOrders <= 0)
customer.NeedsPromo = true;
if (customer.LovesHaskell)
customer.Segment = Segment.Omg;
if (customer.TotalPurchases >= 20000)
customer.Tier = Tier.Platinum;
if (customer.RecentOrders <= 0)
customer.Tier = Tier.Basic;
if (customer.KnowsCobol)
@ploeh
public IReadOnlyCollection<Order> GetOrders(Customer customer)
{
Adjust(customer);
return RetrieveOrdersFromDatabase(customer);
}
private static void Adjust(Customer customer)
{
if (customer.TotalPurchases >= 10000)
customer.Tier = Tier.Gold;
if (customer.RecentOrders <= 0)
customer.NeedsPromo = true;
if (customer.LovesHaskell)
@ploeh
Some code forces you to read it
@ploeh
Not
humane
@ploeh
read
written
@ploeh
@ploeh
Not
humane
@ploeh
How can we make code more humane?
@ploeh
@ploeh
Command Query Separation
Example
@ploeh
Commands
change the state
of the system
Queries
return data
An operation should be either a
Command or a Query but not both
@ploeh
change the state of the system
private static void Adjust(Customer customer)
{
if (customer.TotalPurchases >= 10000)
customer.Tier = Tier.Gold;
// Many more similar checks go here...
}
Commands
@ploeh
public IReadOnlyCollection<Order> GetOrders(Customer customer)
{
// Adjust(customer);
return RetrieveOrdersFromDatabase(customer);
}
Queries
return data
@ploeh
public IReadOnlyCollection<Order> GetOrders(Customer customer)
{
Adjust(customer);
return RetrieveOrdersFromDatabase(customer);
}
@ploeh
Command Query Separation
Just one example
Challenging enough already
@ploeh
Command Query Separation
@ploehReused Abstractions Principle
Command Query Separation
Liskov Substitution Principle
Interface Segregation Principle
Dependency Inversion Principle
Separation of Concerns
Single Responsibility PrincipleCohesion
You Aren’t Going to Need It
Open Closed Principle Law of Demeter
Principle of Least Surprise
Don’t Repeat YourselfHollywood Principle
@ploeh
There are many ways
to do things
if you know them
@ploeh@ploeh
@ploeh@ploeh
@ploeh@ploeh
@ploeh
read
written
@ploeh
@ploeh
Code should be humane
@ploeh
@ploeh
The more
code you
have, the
worse
Programming
is mostly a
soft skill
Programming
is learning,
thinking, and
teaching
@ploeh
@ploeh
The more
code you
have, the
worse
Programming
is mostly a
soft skill
Programming
is learning,
thinking, and
teaching
@ploeh
@ploeh
The more
code you
have, the
worse
Programming
is mostly a
soft skill
Programming
is learning,
thinking, and
teaching
@ploeh
@ploeh
The more
code you
have, the
worse
Programming
is mostly a
soft skill
Programming
is learning,
thinking, and
teaching
@ploeh
@ploeh
@ploeh
@ploeh
@ploeh
@ploeh
Mark Seemann
http://blog.ploeh.dk
http://bit.ly/clean-humane-code
http://bit.ly/ploehralsight
@ploeh

More Related Content

PDF
RESTful API Design & Implementation with CodeIgniter PHP Framework
PDF
Функциональный микроскоп: линзы в C++
PDF
JVM code reading -- C2
PDF
Notes for xx_use_serialgc
PDF
Make Your SW Component Testable
PDF
Michał Kopacz: Ports and adapters architecture for business processes
PDF
Do more with less code in a serverless world
PPSX
โปรแกรมภาษาซีเบื้องต้น
RESTful API Design & Implementation with CodeIgniter PHP Framework
Функциональный микроскоп: линзы в C++
JVM code reading -- C2
Notes for xx_use_serialgc
Make Your SW Component Testable
Michał Kopacz: Ports and adapters architecture for business processes
Do more with less code in a serverless world
โปรแกรมภาษาซีเบื้องต้น

What's hot (19)

PDF
Web Development Paradigms and djangoic approach to deal with them
PDF
Analysis of Microsoft Code Contracts
PDF
HotSpot template interpreter memos
PDF
Security Slicing for Auditing XML, XPath, and SQL Injection Vulnerabilities
PDF
Input sanitization
PPTX
From clever code to better code
PDF
Python 炒股指南
PDF
Cracking JWT tokens: a tale of magic, Node.js and parallel computing - WebReb...
PPTX
Jenny Donnelly
PPTX
Azure Video Analyzer OpenVino Extension Module on Raspberry Pi with Movidius
PDF
7 rules of simple and maintainable code
PDF
How to build an AOP framework in ActionScript
PPT
Jquery presentation
PDF
SDKs, the good the bad the ugly - Japan
PDF
Hidden rocks in Oracle ADF
PPT
Zend Framework
PPTX
Basics of Java Script (JS)
PDF
Message in a bottle
PPTX
Hack ASP.NET website
Web Development Paradigms and djangoic approach to deal with them
Analysis of Microsoft Code Contracts
HotSpot template interpreter memos
Security Slicing for Auditing XML, XPath, and SQL Injection Vulnerabilities
Input sanitization
From clever code to better code
Python 炒股指南
Cracking JWT tokens: a tale of magic, Node.js and parallel computing - WebReb...
Jenny Donnelly
Azure Video Analyzer OpenVino Extension Module on Raspberry Pi with Movidius
7 rules of simple and maintainable code
How to build an AOP framework in ActionScript
Jquery presentation
SDKs, the good the bad the ugly - Japan
Hidden rocks in Oracle ADF
Zend Framework
Basics of Java Script (JS)
Message in a bottle
Hack ASP.NET website
Ad

Similar to [FDD 2017] Mark Seemann - Humane code (20)

PDF
Cache is King - RailsConf 2019
PDF
CloudML talk at DevFest Madurai 2016
PDF
PHP Secure Programming
PDF
Automating Cloud Operations - Everything you wanted to know about cURL and RE...
KEY
Zendcon 09
PPTX
Select * from internet
PPT
neiljaysonching
PDF
What the Heck is OAuth and OIDC - UberConf 2018
PDF
Udi Dahan Intentions And Interfaces
PDF
GraphQL - when REST API is not enough - lessons learned
PDF
Cache is King - RubyHACK 2019
PDF
The vJUG talk about jOOQ: Get Back in Control of Your SQL
ODP
Static Analysis in IDEA
PPTX
Domain Driven Design 101
PDF
14147503 Intentions Interfaces Making Patterns Concrete
ODP
Runtime Symbol Resolution
PPTX
RSROC 2015 - AutoHotKey
PDF
Como NÃO testar o seu projeto de Software. DevDay 2014
PDF
What the Heck is OAuth and OIDC - Denver Developer Identity Workshop 2020
PDF
Dependency rejection and TDD without Mocks
Cache is King - RailsConf 2019
CloudML talk at DevFest Madurai 2016
PHP Secure Programming
Automating Cloud Operations - Everything you wanted to know about cURL and RE...
Zendcon 09
Select * from internet
neiljaysonching
What the Heck is OAuth and OIDC - UberConf 2018
Udi Dahan Intentions And Interfaces
GraphQL - when REST API is not enough - lessons learned
Cache is King - RubyHACK 2019
The vJUG talk about jOOQ: Get Back in Control of Your SQL
Static Analysis in IDEA
Domain Driven Design 101
14147503 Intentions Interfaces Making Patterns Concrete
Runtime Symbol Resolution
RSROC 2015 - AutoHotKey
Como NÃO testar o seu projeto de Software. DevDay 2014
What the Heck is OAuth and OIDC - Denver Developer Identity Workshop 2020
Dependency rejection and TDD without Mocks
Ad

More from Future Processing (20)

PDF
DPTO_Inżynieria oprogramowania to proces uczenia się.pdf
PDF
DPTO_QA w świecie wartości biznesowych.pdf
PDF
DPTO_Hello_Clean_Architekture.pdf
PDF
[Quality Meetup #20] Michał Górski - Continuous Deployment w chmurze
PDF
[Quality Meetup #20] Dorota Tadych - Hyperion - wystarczy jeden shake
PDF
[Quality Meetup #19] Magdalena Drechsler-Nowak - Tester w pułapce myślenia
PDF
[Quality Meetup #19] Adrian Gonciarz - Testerska ruletka
PDF
[FDD 2018] Krzysztof Sikora - Jak Service Fabric rozwiąże twoje problemy z mi...
PDF
[FDD 2018] Ł. Turchan, A. Hulist, M. Duchnowski - CUDA - results over coffee ...
PDF
[FDD 2018] Lech Kalinowski - Prywatny Blockchain
PPTX
[FDD 2018] W. Malara, K. Kotowski - Autoenkodery – czyli zalety funkcji F(X)≈X
PPTX
[FDD 2018] Jarosław Ogiegło - Ludzie, zabezpieczajcie się! Wprowadzenie do OA...
PDF
[JuraSIC! Meetup] Krzysztof Sikora- Jak Service Fabric rozwiąże twoje problem...
PDF
[JuraSIC! Meetup] Mateusz Stasch - Monady w .NET
PDF
[QE 2018] Aleksandra Kornecka – Kognitywne podejście do testowania aplikacji ...
PDF
[QE 2018] Adam Stasiak – Nadchodzi React Native – czyli o testowaniu mobilnyc...
PDF
[QE 2018] Łukasz Gawron – Testing Batch and Streaming Spark Applications
PDF
[QE 2018] Marek Puchalski – Web Application Security Test Automation
PDF
[QE 2018] Rob Lambert – How to Thrive as a Software Tester
PDF
[QE 2018] Paul Gerrard – Automating Assurance: Tools, Collaboration and DevOps
DPTO_Inżynieria oprogramowania to proces uczenia się.pdf
DPTO_QA w świecie wartości biznesowych.pdf
DPTO_Hello_Clean_Architekture.pdf
[Quality Meetup #20] Michał Górski - Continuous Deployment w chmurze
[Quality Meetup #20] Dorota Tadych - Hyperion - wystarczy jeden shake
[Quality Meetup #19] Magdalena Drechsler-Nowak - Tester w pułapce myślenia
[Quality Meetup #19] Adrian Gonciarz - Testerska ruletka
[FDD 2018] Krzysztof Sikora - Jak Service Fabric rozwiąże twoje problemy z mi...
[FDD 2018] Ł. Turchan, A. Hulist, M. Duchnowski - CUDA - results over coffee ...
[FDD 2018] Lech Kalinowski - Prywatny Blockchain
[FDD 2018] W. Malara, K. Kotowski - Autoenkodery – czyli zalety funkcji F(X)≈X
[FDD 2018] Jarosław Ogiegło - Ludzie, zabezpieczajcie się! Wprowadzenie do OA...
[JuraSIC! Meetup] Krzysztof Sikora- Jak Service Fabric rozwiąże twoje problem...
[JuraSIC! Meetup] Mateusz Stasch - Monady w .NET
[QE 2018] Aleksandra Kornecka – Kognitywne podejście do testowania aplikacji ...
[QE 2018] Adam Stasiak – Nadchodzi React Native – czyli o testowaniu mobilnyc...
[QE 2018] Łukasz Gawron – Testing Batch and Streaming Spark Applications
[QE 2018] Marek Puchalski – Web Application Security Test Automation
[QE 2018] Rob Lambert – How to Thrive as a Software Tester
[QE 2018] Paul Gerrard – Automating Assurance: Tools, Collaboration and DevOps

Recently uploaded (20)

PPTX
Reimagine Home Health with the Power of Agentic AI​
PPTX
Patient Appointment Booking in Odoo with online payment
PDF
Nekopoi APK 2025 free lastest update
PDF
Tally Prime Crack Download New Version 5.1 [2025] (License Key Free
PPTX
Log360_SIEM_Solutions Overview PPT_Feb 2020.pptx
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PDF
iTop VPN 6.5.0 Crack + License Key 2025 (Premium Version)
PDF
Website Design Services for Small Businesses.pdf
PDF
AutoCAD Professional Crack 2025 With License Key
PDF
Product Update: Alluxio AI 3.7 Now with Sub-Millisecond Latency
PDF
CapCut Video Editor 6.8.1 Crack for PC Latest Download (Fully Activated) 2025
PPTX
assetexplorer- product-overview - presentation
PDF
Download FL Studio Crack Latest version 2025 ?
PPTX
Operating system designcfffgfgggggggvggggggggg
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PDF
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
PDF
iTop VPN Crack Latest Version Full Key 2025
PDF
Cost to Outsource Software Development in 2025
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
Reimagine Home Health with the Power of Agentic AI​
Patient Appointment Booking in Odoo with online payment
Nekopoi APK 2025 free lastest update
Tally Prime Crack Download New Version 5.1 [2025] (License Key Free
Log360_SIEM_Solutions Overview PPT_Feb 2020.pptx
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
iTop VPN 6.5.0 Crack + License Key 2025 (Premium Version)
Website Design Services for Small Businesses.pdf
AutoCAD Professional Crack 2025 With License Key
Product Update: Alluxio AI 3.7 Now with Sub-Millisecond Latency
CapCut Video Editor 6.8.1 Crack for PC Latest Download (Fully Activated) 2025
assetexplorer- product-overview - presentation
Download FL Studio Crack Latest version 2025 ?
Operating system designcfffgfgggggggvggggggggg
Internet Downloader Manager (IDM) Crack 6.42 Build 41
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
iTop VPN Crack Latest Version Full Key 2025
Cost to Outsource Software Development in 2025
Design an Analysis of Algorithms I-SECS-1021-03
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025

[FDD 2017] Mark Seemann - Humane code