SlideShare una empresa de Scribd logo
1 de 87
Your Own Metric System
       Ian Dees ·@undees
          OSCON 2012
pragprog.com/titles/dhwcr
Setting
The forces against us


❥ Entropy drags our code down
❥ Apathy drags us down
Stay engaged and productive
Knowing our code
can help us do our jobs
  and have more fun
Risk #1

Missing or poor information
can waste our time
or lead us to cause harm
Two steps forward


1. Ask questions about your code
2. Choose metrics that answer those questions
Purpose of metrics
purpose of metrics




Help you answer a question
purpose of metrics




What mess should I
 clean up next?
purpose of metrics




The product backlog
  isn’t a substitute
   for your brain
Risk #2

Making structural changes
can introduce new bugs
(or expose existing ones)
purpose of metrics




Where are the bugs
 (likely to be)?
purpose of metrics




/**
 * REMOVE THIS CODE
 * BEFORE WE SHIP!
 */
purpose of metrics




Have we forgotten anything
     for this release?
purpose of metrics




These questions are for us
purpose of metrics




Not for someone else
purpose of metrics




Questions from others:
   (outside the scope of our metrics)
purpose of metrics




Should we hold the release?
purpose of metrics
errors/KLOC →




                time →
purpose of metrics




 Who’s got the best
KLOC or error rate?
purpose of metrics


It was time to fill out the management form for
the first time. When he got to the lines of code
part, he thought about it for a second, and then
wrote in the number: -2000.

After a couple more weeks, they stopped asking
Bill to fill out the form, and he gladly complied.

                                  —folklore.org
purpose of metrics




Have we met our target
complexity or coverage?
purpose of metrics




   Metrics serve you,
not the other way around
purpose of metrics




Keep the job fun
purpose of metrics




  More fun than
actually working?
Risk #3


There is a trap here for the
distractible
Common metrics
common metrics


           Languages
❥ C:
  a case study
❥ Perl:
  the beginner’s experience
❥ <your lang>
  just ask!
common metrics




Repo for this talk
   github.com/undees/oscon
common metrics




Cyclomatic complexity
common metrics




E – N + 2P
common metrics




1. Start with a score of 1

2. Add 1 for each if, case, for, or
   boolean condition
Volume speaking_volume(
        bool correct_room,
        bool correct_time) {
    if (correct_room && correct_time) {
        return INTELLIGIBLE;
    } else {
        // rehearsing
        return INAUDIBLE;
    }
}

                              complexity: 1
Volume speaking_volume(
        bool correct_room,
        bool correct_time) {
    if (correct_room && correct_time) {
        return INTELLIGIBLE;
    } else {
        // rehearsing
        return INAUDIBLE;
    }
}

                              complexity: 2
Volume speaking_volume(
        bool correct_room,
        bool correct_time) {
    if (correct_room && correct_time) {
        return INTELLIGIBLE;
    } else {
        // rehearsing
        return INAUDIBLE;
    }
}

                              complexity: 3
common metrics




     pmccabe
parisc-linux.org/~bame/pmccabe
$ pmccabe *.c | sort -nr | head -10
3 3 3 6 8!oscon.c(6): speaking_volume
1 1 2 16 5!oscon.c(16): main
common metrics




Perl::Metrics::Simple
sub speaking_volume {
    my $correct_room = shift;
    my $correct_time = shift;

    if ($correct_room && $correct_time) {
        return 'intelligible';
    } else {
        # rehearsing
        return 'inaudible';
    }
}
$ countperl lib
...
Tab-delimited list of subroutines, with most complex at top
-----------------------------------------------------------
complexity sub               path          size
4           speaking_volume lib/OSCON.pm 9
...
$ wc -l oscon.c
Risk #4


Blindly reducing one number
can add complexity and bugs
common metrics




Test coverage
common metrics




1. Instrument your program

2. Watch your tests run

3. Report which lines get executed
common metrics



      Addresses
“epic confidence” fail
  opensourcebridge.org/sessions/923
common metrics




Testable code is more...
        testable
common metrics




gcov
int main() {
    assert(speaking_volume(true, true) == INTELLIGIBLE);

    return 0;
}
$ gcc -fprofile-arcs 
      -ftest-coverage 
      -c oscon.c

$ gcc -fprofile-arcs   
      oscon.o
$ gcov oscon.c

$ cat oscon.c.gcov
1:    6:Volume speaking_volume(bool correct_room, bool correct_time) {
   1:    7:    if (correct_room && correct_time) {
   1:    8:        return INTELLIGIBLE;
   -:    9:    } else {
   -:   10:        // rehearsing
####:   11:        return INAUDIBLE;
   -:   12:    }
   -:   13:}
common metrics




Devel::Cover
$ cover -test

$ cat cover_db/coverage.html
Risk #5

High code coverage
can make you think
your code is good
Custom metrics
X-rated-ness
custom metrics


Carlin’s 7 Dirty Words
1.          5.
2.          6.
3.          7.
4.
custom metrics


  Our 7 Dirty Words
1.XXX     5.HACK
2.TODO    6.#if 0
3.FIXME   7.#ifndef TESTING
4.TBD
custom metrics


     Our 7 Dirty Words
1.           5.
2.           6.
3.           7.
4.
$ ack -cl 'XXX|TODO|FIXME'
oscon.c:1
custom metrics




Test::Fixme
use Test::Fixme;
run_tests(where => 'lib',
          match => qr/XXX|TODO|FIXME/);
$ make test
...
t/test-fixme.t .. 1/1
#   Failed test ''lib/OSCON.pm''
#   at t/test-fixme.t line 2.
# File: 'lib/OSCON.pm'
#     34      # XXX:remove the temp limit before we deploy
# Looks like you failed 1 test of 1.
t/test-fixme.t .. Dubious, test returned 1 (wstat 256, 0x100)
Failed 1/1 subtests
custom metrics




Churn
custom metrics




Recently changed code
 may have new bugs
custom metrics




Frequently-changed code
   may have problems
git log --pretty=oneline   
        --since=2012-05-04 
        oscon.c | wc -l
custom metrics




Missing documentation
custom metrics




Errors by time of day
custom metrics




Play by Play: Zed Shaw
 peepcode.com/products/play-by-play-zed-shaw
What do we get
 from all this?
Found a real
dependency problem
   with pmccabe
Found dead code with gcov
Did a quick churn check
  at manual test time
Found places we can
 DRY up the code
Relative, not absolute!
Content-Type:
multipart/wish
❥ Find the answers you need

❥ Look like heroes

❥ Have fun
Fin
Credits


flickr.com/photos/aussiegall/286709039
flickr.com/photos/bensutherland/252230820

Más contenido relacionado

La actualidad más candente

name name2 n2.ppt
name name2 n2.pptname name2 n2.ppt
name name2 n2.pptcallroom
 
Inside Python [OSCON 2012]
Inside Python [OSCON 2012]Inside Python [OSCON 2012]
Inside Python [OSCON 2012]Tom Lee
 
Learn Python The Hard Way Presentation
Learn Python The Hard Way PresentationLearn Python The Hard Way Presentation
Learn Python The Hard Way PresentationAmira ElSharkawy
 
Variables: names, bindings, type, scope
Variables: names, bindings, type, scopeVariables: names, bindings, type, scope
Variables: names, bindings, type, scopesuthi
 
Memory Management In Python The Basics
Memory Management In Python The BasicsMemory Management In Python The Basics
Memory Management In Python The BasicsNina Zakharenko
 
Ti1220 Lecture 2: Names, Bindings, and Scopes
Ti1220 Lecture 2: Names, Bindings, and ScopesTi1220 Lecture 2: Names, Bindings, and Scopes
Ti1220 Lecture 2: Names, Bindings, and ScopesEelco Visser
 
A(n abridged) tour of the Rust compiler [PDX-Rust March 2014]
A(n abridged) tour of the Rust compiler [PDX-Rust March 2014]A(n abridged) tour of the Rust compiler [PDX-Rust March 2014]
A(n abridged) tour of the Rust compiler [PDX-Rust March 2014]Tom Lee
 
Mixing Source and Bytecode: A Case for Compilation By Normalization (OOPSLA 2...
Mixing Source and Bytecode: A Case for Compilation By Normalization (OOPSLA 2...Mixing Source and Bytecode: A Case for Compilation By Normalization (OOPSLA 2...
Mixing Source and Bytecode: A Case for Compilation By Normalization (OOPSLA 2...lennartkats
 
WordPress Plugin Localization
WordPress Plugin LocalizationWordPress Plugin Localization
WordPress Plugin LocalizationRonald Huereca
 
Python Compiler Internals Presentation Slides
Python Compiler Internals Presentation SlidesPython Compiler Internals Presentation Slides
Python Compiler Internals Presentation SlidesTom Lee
 

La actualidad más candente (13)

ppt18
ppt18ppt18
ppt18
 
ppt9
ppt9ppt9
ppt9
 
name name2 n2.ppt
name name2 n2.pptname name2 n2.ppt
name name2 n2.ppt
 
Inside Python [OSCON 2012]
Inside Python [OSCON 2012]Inside Python [OSCON 2012]
Inside Python [OSCON 2012]
 
Learn Python The Hard Way Presentation
Learn Python The Hard Way PresentationLearn Python The Hard Way Presentation
Learn Python The Hard Way Presentation
 
Variables: names, bindings, type, scope
Variables: names, bindings, type, scopeVariables: names, bindings, type, scope
Variables: names, bindings, type, scope
 
Memory Management In Python The Basics
Memory Management In Python The BasicsMemory Management In Python The Basics
Memory Management In Python The Basics
 
Ti1220 Lecture 2: Names, Bindings, and Scopes
Ti1220 Lecture 2: Names, Bindings, and ScopesTi1220 Lecture 2: Names, Bindings, and Scopes
Ti1220 Lecture 2: Names, Bindings, and Scopes
 
A(n abridged) tour of the Rust compiler [PDX-Rust March 2014]
A(n abridged) tour of the Rust compiler [PDX-Rust March 2014]A(n abridged) tour of the Rust compiler [PDX-Rust March 2014]
A(n abridged) tour of the Rust compiler [PDX-Rust March 2014]
 
Mixing Source and Bytecode: A Case for Compilation By Normalization (OOPSLA 2...
Mixing Source and Bytecode: A Case for Compilation By Normalization (OOPSLA 2...Mixing Source and Bytecode: A Case for Compilation By Normalization (OOPSLA 2...
Mixing Source and Bytecode: A Case for Compilation By Normalization (OOPSLA 2...
 
Perl intro
Perl introPerl intro
Perl intro
 
WordPress Plugin Localization
WordPress Plugin LocalizationWordPress Plugin Localization
WordPress Plugin Localization
 
Python Compiler Internals Presentation Slides
Python Compiler Internals Presentation SlidesPython Compiler Internals Presentation Slides
Python Compiler Internals Presentation Slides
 

Similar a Your Own Metric System

Stop wasting-time-by-applying-clean-code-principles
Stop wasting-time-by-applying-clean-code-principlesStop wasting-time-by-applying-clean-code-principles
Stop wasting-time-by-applying-clean-code-principlesEdorian
 
C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#Hawkman Academy
 
Measuring Your Code
Measuring Your CodeMeasuring Your Code
Measuring Your CodeNate Abele
 
Measuring Your Code 2.0
Measuring Your Code 2.0Measuring Your Code 2.0
Measuring Your Code 2.0Nate Abele
 
Debugging Complex Systems - Erlang Factory SF 2015
Debugging Complex Systems - Erlang Factory SF 2015Debugging Complex Systems - Erlang Factory SF 2015
Debugging Complex Systems - Erlang Factory SF 2015lpgauth
 
Tools for the Toolmakers
Tools for the ToolmakersTools for the Toolmakers
Tools for the ToolmakersCaleb Callaway
 
Metrics ekon 14_2_kleiner
Metrics ekon 14_2_kleinerMetrics ekon 14_2_kleiner
Metrics ekon 14_2_kleinerMax Kleiner
 
Static Code Analysis PHP[tek] 2023
Static Code Analysis PHP[tek] 2023Static Code Analysis PHP[tek] 2023
Static Code Analysis PHP[tek] 2023Scott Keck-Warren
 
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
 
Code quality par Simone Civetta
Code quality par Simone CivettaCode quality par Simone Civetta
Code quality par Simone CivettaCocoaHeads France
 
Developing a Culture of Quality Code (Midwest PHP 2020)
Developing a Culture of Quality Code (Midwest PHP 2020)Developing a Culture of Quality Code (Midwest PHP 2020)
Developing a Culture of Quality Code (Midwest PHP 2020)Scott Keck-Warren
 
Head in the Clouds: Testing Infra as Code - Config Management 2020
Head in the Clouds: Testing Infra as Code - Config Management 2020Head in the Clouds: Testing Infra as Code - Config Management 2020
Head in the Clouds: Testing Infra as Code - Config Management 2020Peter Souter
 
A Replay Approach to Software Validation
A Replay Approach to Software ValidationA Replay Approach to Software Validation
A Replay Approach to Software ValidationJames Pascoe
 
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
 
Howto Test A Patch And Make A Difference!
Howto Test A Patch And Make A Difference!Howto Test A Patch And Make A Difference!
Howto Test A Patch And Make A Difference!Joel Farris
 

Similar a Your Own Metric System (20)

Clean Code 2
Clean Code 2Clean Code 2
Clean Code 2
 
Wtf per lineofcode
Wtf per lineofcodeWtf per lineofcode
Wtf per lineofcode
 
Stop wasting-time-by-applying-clean-code-principles
Stop wasting-time-by-applying-clean-code-principlesStop wasting-time-by-applying-clean-code-principles
Stop wasting-time-by-applying-clean-code-principles
 
Dutch PHP Conference 2013: Distilled
Dutch PHP Conference 2013: DistilledDutch PHP Conference 2013: Distilled
Dutch PHP Conference 2013: Distilled
 
C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#
 
Measuring Your Code
Measuring Your CodeMeasuring Your Code
Measuring Your Code
 
Measuring Your Code 2.0
Measuring Your Code 2.0Measuring Your Code 2.0
Measuring Your Code 2.0
 
Debugging Complex Systems - Erlang Factory SF 2015
Debugging Complex Systems - Erlang Factory SF 2015Debugging Complex Systems - Erlang Factory SF 2015
Debugging Complex Systems - Erlang Factory SF 2015
 
Code metrics in PHP
Code metrics in PHPCode metrics in PHP
Code metrics in PHP
 
Tools for the Toolmakers
Tools for the ToolmakersTools for the Toolmakers
Tools for the Toolmakers
 
Metrics ekon 14_2_kleiner
Metrics ekon 14_2_kleinerMetrics ekon 14_2_kleiner
Metrics ekon 14_2_kleiner
 
Static Code Analysis PHP[tek] 2023
Static Code Analysis PHP[tek] 2023Static Code Analysis PHP[tek] 2023
Static Code Analysis PHP[tek] 2023
 
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
 
Code quality par Simone Civetta
Code quality par Simone CivettaCode quality par Simone Civetta
Code quality par Simone Civetta
 
Developing a Culture of Quality Code (Midwest PHP 2020)
Developing a Culture of Quality Code (Midwest PHP 2020)Developing a Culture of Quality Code (Midwest PHP 2020)
Developing a Culture of Quality Code (Midwest PHP 2020)
 
Head in the Clouds: Testing Infra as Code - Config Management 2020
Head in the Clouds: Testing Infra as Code - Config Management 2020Head in the Clouds: Testing Infra as Code - Config Management 2020
Head in the Clouds: Testing Infra as Code - Config Management 2020
 
Introduction to C ++.pptx
Introduction to C ++.pptxIntroduction to C ++.pptx
Introduction to C ++.pptx
 
A Replay Approach to Software Validation
A Replay Approach to Software ValidationA Replay Approach to Software Validation
A Replay Approach to Software Validation
 
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
 
Howto Test A Patch And Make A Difference!
Howto Test A Patch And Make A Difference!Howto Test A Patch And Make A Difference!
Howto Test A Patch And Make A Difference!
 

Más de Erin Dees

Logic Lessons That Last Generations
Logic Lessons That Last GenerationsLogic Lessons That Last Generations
Logic Lessons That Last GenerationsErin Dees
 
How 5 people with 4 day jobs in 3 time zones enjoyed 2 years writing 1 book
How 5 people with 4 day jobs in 3 time zones enjoyed 2 years writing 1 bookHow 5 people with 4 day jobs in 3 time zones enjoyed 2 years writing 1 book
How 5 people with 4 day jobs in 3 time zones enjoyed 2 years writing 1 bookErin Dees
 
How 5 people with 4 day jobs in 3 time zones enjoyed 2 years writing 1 book
How 5 people with 4 day jobs in 3 time zones enjoyed 2 years writing 1 bookHow 5 people with 4 day jobs in 3 time zones enjoyed 2 years writing 1 book
How 5 people with 4 day jobs in 3 time zones enjoyed 2 years writing 1 bookErin Dees
 
A jar-nORM-ous Task
A jar-nORM-ous TaskA jar-nORM-ous Task
A jar-nORM-ous TaskErin Dees
 
Cucumber meets iPhone
Cucumber meets iPhoneCucumber meets iPhone
Cucumber meets iPhoneErin Dees
 

Más de Erin Dees (6)

Logic Lessons That Last Generations
Logic Lessons That Last GenerationsLogic Lessons That Last Generations
Logic Lessons That Last Generations
 
How 5 people with 4 day jobs in 3 time zones enjoyed 2 years writing 1 book
How 5 people with 4 day jobs in 3 time zones enjoyed 2 years writing 1 bookHow 5 people with 4 day jobs in 3 time zones enjoyed 2 years writing 1 book
How 5 people with 4 day jobs in 3 time zones enjoyed 2 years writing 1 book
 
How 5 people with 4 day jobs in 3 time zones enjoyed 2 years writing 1 book
How 5 people with 4 day jobs in 3 time zones enjoyed 2 years writing 1 bookHow 5 people with 4 day jobs in 3 time zones enjoyed 2 years writing 1 book
How 5 people with 4 day jobs in 3 time zones enjoyed 2 years writing 1 book
 
A jar-nORM-ous Task
A jar-nORM-ous TaskA jar-nORM-ous Task
A jar-nORM-ous Task
 
Cucumber meets iPhone
Cucumber meets iPhoneCucumber meets iPhone
Cucumber meets iPhone
 
Yes, But
Yes, ButYes, But
Yes, But
 

Último

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfhans926745
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 

Último (20)

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 

Your Own Metric System

Notas del editor

  1. Hello, and welcome. I&amp;#x2019;m Ian.\n
  2. By day, I make oscilloscopes. By night, I play guitar irresponsibly.\n
  3. I also write books, mostly about Ruby topics. A group of us&amp;#x2014;me, plus two major contributors to the Cucumber test framework&amp;#x2014;are working on a new book of specific testing techniques. Ruby and its various test frameworks were my gateway drug to code metrics, though for this talk we&amp;#x2019;ll be concentrating on other languages.\n
  4. Oscilloscopes have been available commercially since the 1940s. Their architecture changes slowly. Software needs to last, and it tends to last whether we wish for a rewrite or not. Our team&amp;#x2019;s exploration of this mix of old and new code led to our interest in code metrics.\n
  5. And even if you&amp;#x2019;re not working on a large legacy code base, there are likely issues that we face in common.\n
  6. There are a lot of forces that push on us and our teams. Today, I want to talk about two very different forces that have surprisingly similar effects: the entropy that drags our code down over time, and the apathy that drags us down personally over time.\n
  7. How do we fight these forces? How do we keep our interest after our tenth straight hour wading into the weeds of an incomprehensible legacy routine? How do we prevent the code we write today from being someone&amp;#x2019;s nightmare tomorrow?\n
  8. We have many tools in our chest; one is a good set of metrics&amp;#x2014;information about our code base. My hope is that you&amp;#x2019;ll consider code metrics at least as an intriguing, low-cost possibility for making the day go by a little better.\n
  9. The risk with doing this&amp;#x2014;and there&amp;#x2019;s always a risk&amp;#x2014;is that we might waste our time making changes we don&amp;#x2019;t need, or worse, end up trashing our code in the name of blindly satisfying some target number.\n
  10. How do we address that risk? By letting our project needs dictate our metric choices, not the other way around. It sounds simple. But as we&amp;#x2019;ll see, it&amp;#x2019;s possible to misapply a metric and make a big mess.\n
  11. Since getting the reasons right is so important, let&amp;#x2019;s talk about why we&amp;#x2019;re gathering this data.\n
  12. The purpose of any metric should be to help you answer a question. Since we&amp;#x2019;re developers who maybe also do a little testing, let&amp;#x2019;s ask a few example questions now.\n
  13. For example, if several files need some love, where should I concentrate my efforts?\n
  14. Something else may be giving us guidance on what part of the code to work in&amp;#x2014;like the product backlog. But you may be in a situation where you&amp;#x2019;ve got a little more leeway, like an explicit charter to pay down technical debt.\n
  15. That said, when you do wander off the map, you do risk creating a bug. With legacy code, you may also uncover an existing bug and get the blame nonetheless. One way to address this risk is to improve your test coverage, and make small changes at a time. Another is to choose the right metrics; fixing static analysis warnings has anecdotally been one of the lowest-risk change activities I&amp;#x2019;ve ever seen.\n
  16. Here&amp;#x2019;s another question we might ask. Where are the bugs? Where are the old bugs we haven&amp;#x2019;t found yet? Where are the new ones we might have created recently?\n
  17. We can also turn to our code for ideas of what questions to ask. Has anyone seen something like this comment in production code? The number of these red flags in your code is a kind of code metric you can measure and reduce.\n
  18. That quantitative measurement&amp;#x2014;number of bad comments in the code&amp;#x2014;is helping us make a qualitative determination.\n
  19. The questions we&amp;#x2019;ve heard so far are things we might ask,...\n
  20. ...not things someone else might ask.\n
  21. Not that other people&amp;#x2019;s questions aren&amp;#x2019;t legitimately interesting, or that they might not apply metrics of their own.\n
  22. For example, the SQA team might be looking for red flags that could hold up the release.\n
  23. So they might look at aggregate errors per thousand lines of code. Not something I necessarily use to make decisions as a developer, but it doesn&amp;#x2019;t scare me if this metric is in use somewhere.\n
  24. On a more sinister note, tracking rates of code production or error creation/resolution are outright destructive of teams.\n
  25. There was apparently a brief, dark time at Apple when employees were tracked by lines of code produced, until Bill Atkinson showed that you can improve and shorten the code at the same time.\n
  26. Another, more subtle trap is setting absolute thresholds for various metrics.\n
  27. Doing so is like blindly obeying a GPS device: sooner or later, you&amp;#x2019;ll drive off a cliff.\n
  28. Metrics are supposed to be here for our benefit.\n
  29. And indeed, in addition to answering specific questions about our projects, they can make coding seem a little bit like a game where the side effect is to produce better code...\n
  30. ...as long as we still get around to writing the code eventually.\n
  31. We have to be careful not to spend all day writing fancier shell scripts and slapping our stats onto elaborate dashboards (though there are quick-and-cheap dashboards I like; see the Tranquil project).\n
  32. Now that we have a few questions in mind about our code base, let&amp;#x2019;s look at some metrics commonly used by many projects. (Later, we&amp;#x2019;ll look at writing our own.) The nice thing about prefab metrics is that we can find open source implementations and supporting research.\n
  33. Rather than present you with a laundry list, I&amp;#x2019;m going to stick to a few targeted examples in C and Perl. But similar tools likely exist for your language; catch me in the hall afterwards if you&amp;#x2019;d like to explore that together.\n
  34. The code samples you&amp;#x2019;re about to see are on GitHub; feel free to send a pull request if you&amp;#x2019;d like your favorite language to be included.\n
  35. The granddaddy of modern code metrics is McCabe Cyclomatic Complexity. It&amp;#x2019;s meant to be a loose measure of how many different paths there are through a piece of code.\n
  36. The fancy explanation is that you draw a graph of control flow through your function, then calculate a score from the number of edges, nodes, and return points.\n
  37. The simpler explanation is that we walk through the code and add a point for each decision the code has to make.\n
  38. So we&amp;#x2019;d start with a value of 1 for this code sample...\n
  39. ...add 1 point for the if statement...\n
  40. ...and add 1 final point for the boolean operator. Depending on the implementation, we might add a point for the multiple returns.\n
  41. One easy-to-use implementation of this metric for C code is pmccabe.\n
  42. When we run it, it prints the complexity, size, and location of each function in our project.\n
  43. CPAN has several metrics modules for Perl; Perl::Metrics::Simple is an easy one to get started with.\n
  44. Here&amp;#x2019;s a Perl subroutine similar to the one we saw.\n
  45. Similar to pmccabe, Perl::Metrics::Simple gives us the size and complexity of each method.\n
  46. Speaking of size and complexity, this paper reexamined several previous studies and found that several popular code metrics were effectively just expensive ways...\n
  47. ...of counting lines. The paper didn&amp;#x2019;t consider cyclomatic complexity alone (and there were other issues dealt with in subsequent papers by other authors), but we should always be skeptical of our own metrics. Fortunately, most tools give us both a line count and a complexity metric; we can decide for ourselves.\n
  48. Some teams set complexity targets. In the degenerate case, they turn their code into a bunch of tiny functions that do nothing&amp;#x2014;making the overall code base more complex and prone to bugs.\n
  49. Another widely used metric is the percentage of your code that gets executed by your tests.\n
  50. Measuring this typically involves instrumenting your code, so that you can watch it as it runs your tests.\n
  51. Knowing our test coverage helps address the &amp;#x201C;epic confidence&amp;#x201D; problem that Laura Thomson described in her Open Source Bridge talk, &amp;#x201C;How Not To Release Software.&amp;#x201D; Teams afflicted by this bug assert without evidence that their tests are great.\n
  52. In addition to combating hubris, measuring coverage helps us make our code more testable. Testability is not an end in itself, but a property with beneficial side effects.\n
  53. For C projects, it&amp;#x2019;s easy to measure coverage. GCC comes with the gcov coverage tool.\n
  54. Here&amp;#x2019;s a test that exercises just one branch of our code from earlier.\n
  55. First, we&amp;#x2019;d compile and link our program with a couple of gcov&amp;#x2019;s required flags.\n
  56. Then, we&amp;#x2019;d run our tests and point gcov at the logfiles.\n
  57. The result is a list of what lines did and didn&amp;#x2019;t get executed. In this case, we never ran the &amp;#x201C;else&amp;#x201D; clause.\n
  58. Not to be outdone, Perl provides Devel::Cover.\n
  59. You just point Devel::Cover at your tests, and it produces an HTML report for you.\n
  60. Devel::Cover gives us more information than gcov did. We executed line 26 once, but didn&amp;#x2019;t exercise both sides of the &amp;#x201C;&amp;&amp;&amp;#x201D;.\n
  61. Which brings us to another thing to keep in mind. Hitting each line of code once isn&amp;#x2019;t the same as hitting each combination of branches. Code coverage is meant to help you look for holes, not to lull you into false security.\n
  62. The advantage of applying commonly used measurements is good support. The downside is lack of context; the creators of those metrics have nowhere near the knowledge of your project that you do. So you may want to supplement common metrics with a few of your own. I can&amp;#x2019;t tell you what those metrics are, but I can tell you a couple of the ones I&amp;#x2019;ve seen used.\n
  63. First, let&amp;#x2019;s look at what I&amp;#x2019;ll call X-rated-ness.\n
  64. Just as George Carlin gave us his famous list of words you can&amp;#x2019;t say on television,...\n
  65. ...software teams have their own lists of bad words.\n
  66. (Sorry, I should have blurred those out. ;-)\n
  67. This is dead simple to do with ack, the modern-day replacement for grep. Just count string occurrences across your files, and optionally do a little sorting.\n
  68. Grepping works on nearly every language, of course. But Perl has its own specific implementation of this metric.\n
  69. All you have to do is throw a couple of lines into a &amp;#x201C;.t&amp;#x201D; file...\n
  70. ...and Perl won&amp;#x2019;t even let your tests pass if you&amp;#x2019;ve got a naughty word in your code.\n
  71. Another metric that&amp;#x2019;s not universally used, but can still come in handy, is code churn: how often does a given piece of code change?\n
  72. Churn can tell us what parts have changed recently; those parts may have new bugs.\n
  73. Churn can also tell us what parts change often; those parts can become trouble spots.\n
  74. You can get as crazy as you want with churn: examining which lines have changed the most, which functions have had the most people working on them, and so on. Git can tell you a lot more than a simple metric can, but if you&amp;#x2019;re on a centralized system you may want to just grab the data yourself and pick it apart with UNIX tools.\n
  75. If you&amp;#x2019;re writing code that&amp;#x2019;s going to get used by developers outside of your team, you might use a metric like documentation coverage to identify the parts of the code that most badly need docs.\n
  76. Most of the metrics we&amp;#x2019;ve seen so far have been one-shot numbers. But it&amp;#x2019;s also possible to track things over time, like occurrences of compiler errors or test failures.\n
  77. Zed Shaw does a great demo of this in his Play by Play screencast with PeepCode.\n
  78. We&amp;#x2019;ve talked about the kinds of questions we want to ask about our code, and the metrics that can help us answer those questions. Now for the bigger question: what&amp;#x2019;s the effect on our software? Well, here are some of the things that happened with my team.\n
  79. One, I found a surprisingly high complexity number in what was supposed to be a simple math routine. Somebody had snuck in an unwanted dependency on an unrelated system.\n
  80. While looking for untested code, we found some code that didn&amp;#x2019;t need any tests&amp;#x2014;because it was never called anyway!\n
  81. I personally like to look at what features have changed when it&amp;#x2019;s time to do manual testing.\n
  82. Some designs come at a time when our understanding of the domain is imperfect. As our understanding improves, we refactor the code. Complexity metrics can be handy for prioritizing.\n
  83. One of the common themes woven through much of this discussion is that absolute limits for code metrics are not as helpful as relative measures within a project.\n
  84. My hope is that you come away from this session with a couple of ideas for metrics you&amp;#x2019;d like to try, and with the well-founded belief that you can get started with very little time investment.\n
  85. I hope you find the answers you need for your project, and that you have fun getting them.\n
  86. Thank you, and have a fantastic OSCON.\n
  87. The images in this presentation were used by permission under the terms of a Creative Commons license.\n