SlideShare a Scribd company logo
I empower WordPress developers.
@hellofromtonya
@KnowTheCodePro
Makes Our Jobs Easier
Tonya Mork
This session will cover…
➡ Identify why the practice of “code quality” exists.
What problem is it trying to solve?

➡ Frame the session around you.

➡ Open your mind to how building to maximize quality
makes your job easier.

➡ Give you easy-to-go-implement-right-now strategies.
Code quality is a big topic
My approach is to give you strategies that
immediately increase the quality of your code.
?Why does the
practice of “code quality”
exist?
What problem does it seek to solve?
Why is it problematic?Huh?
↑Risk of misunderstanding
?Slows you down which ↑costs
• break something
• waste time going in wrong direction
• scrap it
• …
Standards
Linters
Design Patterns
Better Practices
Mess Detectors
Sniffers
Measure
compliance
Define how
to build
Code quality is all about…
Building code
to maximize
human understanding.
The programming languages and computers
don’t care if your code is human readable.
Did you know? ?
function f471(){$a=f982(); return !empty($a) ? $a->p1 : false;}
function get_the_ID() {
$post = get_post();
return ! empty( $post ) ? $post->ID : false;
}
Uglified code is hard for a human to
read and understand.
But….it’ll run.
!function(t){"use strict";t.component("alert",{defaults:{fade:!0,duration:
200,trigger:".uk-alert-close"},boot:function(){t.$html.on("click.alert.uikit","[data-
uk-alert]",function(i){var o=t.$(this);if(!o.data("alert")){var
e=t.alert(o,t.Utils.options(o.attr("data-uk-alert")));t.$
(i.target).is(e.options.trigger)&&(i.preventDefault(),e.close())}})},init:function()
{var t=this;this.on("click",this.options.trigger,function(i)
{i.preventDefault(),t.close()})},close:function(){var
t=this.trigger("close.uk.alert"),i=function()
{this.trigger("closed.uk.alert").remove()}.bind(this);this.options.fade?
t.css("overflow","hidden").css("max-height",t.height()).animate({height:0,opacity:
0,"padding-top":0,"padding-bottom":0,"margin-top":0,"margin-bottom":
0},this.options.duration,i):i()}})}(UIkit);
Programming is the art of
telling another human
what one wants
the computer to do.
~ Donald Knuth
Computing Pioneer
“
Code Quality
Quality Code
Clean Code
<human code>
Code

tells
humans
of building code that minimizes misunderstandings is:
anyone (including you)
can jump into the project,
quickly figure out what’s going on…and why,
and then get to work.
The Result
Makes your job easier.
The Benefits
How does it make your job easier?
• Easier to sniff out problems

• Easier to reuse on the next project

• Easier to avoid propagating bugs or structural issues

• Easier to extend, remove, reconfigure, and change

• Easier to support and fix without the fear of breaking something else
Code Quality Makes Your Job Easier
Benefits for the business of code
• Easier to onboard new contributors or teammates

• Reduce costs

• Reduce risks
How do you build code
to tell humans?
?
HEY, ________
should happen here.
What
makes code easier for
humans?
?
Consider…
Code is readable.
#1
Code is understandable.
#2
What
makes code easier to
read and understand?
?
Keys to reading
✓ Presentation
✓ Structure
Imagine trying to read a 300+ page book with no paragraphs.
You are reading this book for two reasons.First, you are a programmer.Second, you want to be a better programmer.Good.We need better
programmers.This is a book about good programming.It is filled with code.We are going to look at code from every different direction.
We’ll look down at it from the top, up at it from the bottom, and through it from the inside out.By the time we are done, we’re going to
know a lot about code.What’s more, we’ll be able to tell the difference between good code and bad code.We’ll know how to write good
code.And we’ll know how to transform bad code into good code.There Will Be CodeOne might argue that a book about code is somehow behind
the times—that code is no longer the issue; that we should be concerned about models and requirements instead. Indeed some have
suggested that we are close to the end of code.That soon as code will be generated instead of written.That programmers simply won’t be
needed because business people will generate programs from specifications.Nonsense!We will never be rid of code,because code represents
the details of the requirements.At some level those details cannot be ignored or abstracted; they have to be specified. And specifying
requirements in such detail that a machine can execute them in programming.Such a specification is code.I expect that the level of
abstraction of our languages will continue to increate.I also expect that the number of domain-specific languages will continue to
grow.This will be a good thing.But it will not eliminate code.Indeed,all the specifications written in these higher level and domain-
specific language will be code!It will still need to be rigorous, accurate, and so formal and detailed that a machine can understand and
execute it.The folks who think that code will one day disappear are like mathematicians who hope one day to discover a mathematics that
does not have to be formal.They are hoping that one day we will discover a way to create machines that can do what we want rather than
what we say.These machines will have to be able to understand us so well that they can translate vaguely specified needs into perfectly
executing programs that precisely meet those needs.This will never happen.Not even humans,with all their intuition and creativity,have
been able to create successful systems from the vague feelings of their customers.Indeed, if the discipline of requirements
specification has taught us anything,it is that well-specified requirements are as formal as code and can act as executable tests of
that code!Remember that code is really the language in which we ultimately express the requirements.We may create languages that are
closer to the requirements.We may create tools that help us parse and assemble those requirements into formal structures.But we will
never eliminate necessary precision—so there will always be code.Bad CodeI was recently reading the preface of Kent Beck’s book Imple…
Clean Code: A Handbook of Agile Software Craftsmanship
by Robert C. Martin
Keys to reading
✓ Presentation
✓ Structure
✓ Format and code style
✓ Naming conventions
✓ Organization
✓ Consistency
Keys to understanding
✓ Clear communication
✓ Tell what’s going on and why
✓ Small building blocks…think LEGOs
Code Quality Makes Your Job Easier
Keys to understanding
✓ Clear communication
✓ Tell what’s going on and why
✓ Small building blocks…think LEGOs
✓ Singular….one thing
✓ Code does what it says it will do…every single time
✓ Relatable for us to comprehend…experiences and skill level
Strategies to build

<human code>
Define the way you build.
Becomes your standard, process, and best
practices.
Consistently follow it.
Validate code to it.
<human code> Strategy
Use community coding standards and best practices.
My Advice
✓ Makes it easier to onboard

✓ Makes it easier for you to reuse community
components, snippets, processes, tooling, practices, etc.

✓ Increases quality in the community and our ecosystem
Define the way you build.
Where can you learn more?
WordPress Coding Standards

https://make.wordpress.org/core/handbook/best-practices/coding-standards/
WordPress at Scale

https://scalewp.io/
XWP Engineering Best Practices

https://xwp.github.io/engineering-best-practices/
10up Engineering Best Practices

https://10up.github.io/Engineering-Best-Practices/
Code Style
<human code> Strategy
Driver of human readable code.
function get_the_ID() {
$post = get_post();
return ! empty( $post ) ? $post->ID : false;
}
function get_the_ID() {
$post = get_post();
return ! empty( $post )
? $post->ID
: false;
}
function get_the_ID() {
$post = get_post();
return !empty($post)
? $post->ID
: false;
}
function get_the_ID()
{
$post = get_post();
return !empty($post)
? $post->ID
: false;
}
Following WPCS:
Your own:
function get_the_ID() {
$post = get_post();
return ! empty( $post )
? $post->ID
: false;
}
One expected behavior

for a given set of conditions.
<human code> Strategy
Name to tell.
<human code> Strategy
Code

tells
humans
Driver of human readable code.
Name to tell.

๏Drives your design

๏Forces you to define what each element
does

๏Forces you to think about the human side
<human code> Strategy
I often hear:

Hey Tonya, naming is hard.
• Expected behavior is not well defined or known.

• Not sure of the set of conditions.

• Not sure what the value is.

• It’s doing too much.
If you’re having a difficult time naming,

that’s a clue….
Functions and methods.
“Name to Tell” Guide
✓ Do work

✓ Start with a verb

✓ Be an action phrase

✓ Name it to: TELL you what it will do when you call it
Expected
behavior
Functions and methods.
“Name to Tell” Guide
Starting verbs:

• State checker: is, does, has, did, doing
• Get: get, fetch, open

• Write: set, update, put

• Others: count, enroll, render, parse,
enqueue, process, add, remove
Functions and methods.
“Name to Tell” Guide
verb + the expected behavior
Variable.
“Name to Tell” Guide
✓ Symbol to represent a piece of data

✓ Represents a value

✓ That “value” could be a state, collection of data,
object, binding to a closure, etc.

✓ Name it to: TELL you what value it represents
Class.
“Name to Tell” Guide
✓ Represents an object

✓ It’s a noun.

✓ Name to TELL you what that “thing” is.
The more clear the name, 

the greater the understanding.
<human code> Strategy
The less risk of misunderstandings.
Done processing? Bail out.
<human code> Strategy
When the conditions
are not right, stop.
Bail Out Strategy Dos and Don’ts
Don’t wrap your processing code inside a conditional's
code block when nothing else will happen.

Do - invert it into a guard clause.
function strip_fragment_from_url( $url ) {
$parsed_url = @parse_url( $url );
if ( ! empty( $parsed_url['host'] ) ) {
$url = $parsed_url['scheme'] . '://' . $parsed_url['host'];
if ( ! empty( $parsed_url['port'] ) ) {
$url .= ':' . $parsed_url['port'];
}
if ( ! empty( $parsed_url['path'] ) ) {
$url .= $parsed_url['path'];
}
if ( ! empty( $parsed_url['query'] ) ) {
$url .= '?' . $parsed_url['query'];
}
}
return $url;
}
The business logic
Bail Out Strategy Examplefunction strip_fragment_from_url( $url ) {
$parsed_url = @parse_url( $url );
if ( empty( $parsed_url['host'] ) ) {
return $url;
}
$url = $parsed_url['scheme'] . '://' . $parsed_url['host'];
if ( ! empty( $parsed_url['port'] ) ) {
$url .= ':' . $parsed_url['port'];
}
if ( ! empty( $parsed_url['path'] ) ) {
$url .= $parsed_url['path'];
}
if ( ! empty( $parsed_url['query'] ) ) {
$url .= '?' . $parsed_url['query'];
}
return $url;
}
Guard clause
Simplify decision making.
<human code> Strategy
Tell us what the decision is.
Focus us on the details of the decision
Focus on the functionality.
Simplify decision making example
public function show_notices() {
..
if ( ( prefix_get_option( 'purchase_page', ‘' ) == '' || 'trash' ==
get_post_status( prefix_get_option( ‘purchase_page', ‘' ) ) ) &&
current_user_can( ‘edit_pages' ) && ! get_user_meta( get_current_user_id(),
‘_prefix_set_checkout_dismissed' )) {
..
}
..
}
Simplify decision making example
function show_notices() {
..
if (
( prefix_get_option( 'purchase_page', '' ) == '' ||
'trash' == get_post_status( prefix_get_option( 'purchase_page', '' ) ) ) &&
current_user_can( 'edit_pages' ) &&
! get_user_meta( get_current_user_id(), '_prefix_set_checkout_dismissed' )
) {
..
}
..
}
The decisions:

1. Does the purchase page exist?

2. Is it in trash?

3. Does the current user have the right to edit the page?

4. Did the current user dismissed the checkout?
Simplify decision making example
function get_the_content( $more_link_text = null, $strip_teaser = false ) {
..
if ( false !== strpos( $post->post_content, '<!--noteaser-->' ) && ( ! $multipage || $page == 1 ) )
..
Is <!—noteaser—>
in the content?
Is this the 1st or
single page?
function get_the_content( $more_link_text = null, $strip_teaser = false ) {
..
if ( false !== strpos( $post->post_content, '<!--noteaser-->' ) && ( ! $multipage || $page == 1 ) )
..
// Checks if the <!--noteaser--> exists in the content on the first page.
{
}
Strategy 1: Add an inline comment
Don’t forget the curly braces!
function get_the_content( $more_link_text = null, $strip_teaser = false ) {
..
if ( false !== strpos( $post->post_content, '<!--noteaser-->' ) && ( ! $multipage || $page == 1 ) )
..
{
}
function _has_noteaser_in_content( $post ) {
global $multipage, $page;
if ( $multipage && $page > 1 ) {
return false;
}
return false !== strpos( $post->post_content, '<!--noteaser-->' );
}
( _has_noteaser_in_content( $post ) ) {
Strategy 2: Abstract
Focuses you on the
decision. Why? To keep
you focused on
get_the_content().
A lot more strategies
<human code> Strategy
Let’s Review the Key
Take Aways
Code quality is all about…
Building code
to maximize
human understanding.
Keys to reading
✓ Presentation
✓ Structure
✓ Format and code style
✓ Naming conventions
✓ Organization
✓ Consistency
Keys to understanding
✓ Clear communication
✓ Tell what’s going on and why
✓ Small building blocks…think LEGOs
✓ Singular….one thing
✓ Code does what it says it will do…every single time
✓ Relatable for us to comprehend…experiences and skill level
Code

tells
humans
human
readable
Easy-to-go-implement-right-now Strategies
• Define the way you build.

• I recommend using the WordPress Coding Standards along with community best
practices such as XWP and 10up.

• Validate your code’s compliance to those standards.

• Be strict with your code style.

• One expected behavior for a given set of conditions.

• Name to tell.

• Bail out when done.

• Simplify decision making.
Clues
• If you’re having trouble:

• Identifying the expected behavior or the given set of
conditions

• Naming

• Inline comments
Building <human code>, makes your
code more human readable, lowering
the risk of misunderstandings.
It makes your job easier.
Want more?
Get my Refactoring Tweaks book and workbook bundle 

for free on Leanpub.

https://leanpub.com/b/refactoring-tweaks-bundle.
@hellofromtonya
https://KnowTheCode.io

More Related Content

PDF
WordCamp Nashville 2015: Agile Contracts for WordPress Consultants
mtoppa
 
PDF
Pixel Perfect Guide
Geoffrey Dorne
 
PDF
Naming Things (with notes)
Pete Nicholls
 
PDF
Transactions redefined
Alberto Brandolini
 
PDF
Gui 设计&amp;评审原则 完整
Johnson Yu
 
PDF
Backend roadmap
wassimbenfatma1
 
PDF
Writing code for people
Alexey Ivanov
 
PDF
Clean Code. An Agile Guide to Software Craft Kameron H.
komvjzfjj621
 
WordCamp Nashville 2015: Agile Contracts for WordPress Consultants
mtoppa
 
Pixel Perfect Guide
Geoffrey Dorne
 
Naming Things (with notes)
Pete Nicholls
 
Transactions redefined
Alberto Brandolini
 
Gui 设计&amp;评审原则 完整
Johnson Yu
 
Backend roadmap
wassimbenfatma1
 
Writing code for people
Alexey Ivanov
 
Clean Code. An Agile Guide to Software Craft Kameron H.
komvjzfjj621
 

Similar to Code Quality Makes Your Job Easier (20)

PDF
Clean Code. An Agile Guide to Software Craft Kameron H.
krantzloigu
 
PDF
Clean Code. An Agile Guide to Software Craft Kameron H.
sagolbencib
 
PPTX
Clean code - DSC DYPCOE
Patil Shreyas
 
PDF
Meaningful code - BeCode Brussels - August 2018
Yannick Lemin
 
PPTX
2015.01.09 - Writing Modern Applications for Mobile and Web
Marco Parenzan
 
PPTX
30% faster coder on-boarding when you have a code cookbook
Gabriel Paunescu 🤖
 
PPTX
Improving Code Quality Through Effective Review Process
Dr. Syed Hassan Amin
 
PDF
高品質軟體的基本動作 101 for NTHU
Su Jan
 
PDF
Write code and find a job
Yung-Yu Chen
 
PPTX
Best-Practices-for-Writing-Clean-Code.Presentation
Ozias Rondon
 
PDF
Writing Readable Code
eddiehaber
 
PDF
Patterns, Code Smells, and The Pragmattic Programmer
Jason McCreary
 
PDF
Linux Commands, C, C++, Java and Python Exercises For Beginners
Manjunath.R -
 
PDF
Learning to code in 2020
Nicholas Sterling
 
PPTX
An Introduction To Software Development - Implementation
Blue Elephant Consulting
 
PPT
Writing Quality Code
indikaMaligaspe
 
PDF
Basics of Computer Coding: Understanding Coding Languages
Brian Pichman
 
ODP
Documenting code yapceu2016
Søren Lund
 
PDF
高品質軟體的基本動作 101 + 102 for NUU
Su Jan
 
PDF
8 programming concepts_you_should_know_in_2017
Rajesh Shirsagar
 
Clean Code. An Agile Guide to Software Craft Kameron H.
krantzloigu
 
Clean Code. An Agile Guide to Software Craft Kameron H.
sagolbencib
 
Clean code - DSC DYPCOE
Patil Shreyas
 
Meaningful code - BeCode Brussels - August 2018
Yannick Lemin
 
2015.01.09 - Writing Modern Applications for Mobile and Web
Marco Parenzan
 
30% faster coder on-boarding when you have a code cookbook
Gabriel Paunescu 🤖
 
Improving Code Quality Through Effective Review Process
Dr. Syed Hassan Amin
 
高品質軟體的基本動作 101 for NTHU
Su Jan
 
Write code and find a job
Yung-Yu Chen
 
Best-Practices-for-Writing-Clean-Code.Presentation
Ozias Rondon
 
Writing Readable Code
eddiehaber
 
Patterns, Code Smells, and The Pragmattic Programmer
Jason McCreary
 
Linux Commands, C, C++, Java and Python Exercises For Beginners
Manjunath.R -
 
Learning to code in 2020
Nicholas Sterling
 
An Introduction To Software Development - Implementation
Blue Elephant Consulting
 
Writing Quality Code
indikaMaligaspe
 
Basics of Computer Coding: Understanding Coding Languages
Brian Pichman
 
Documenting code yapceu2016
Søren Lund
 
高品質軟體的基本動作 101 + 102 for NUU
Su Jan
 
8 programming concepts_you_should_know_in_2017
Rajesh Shirsagar
 
Ad

Recently uploaded (20)

PDF
Data Protection & Resilience in Focus.pdf
AmyPoblete3
 
PDF
Slides: PDF Eco Economic Epochs for World Game (s) pdf
Steven McGee
 
PPTX
How tech helps people in the modern era.
upadhyayaryan154
 
PPTX
Parallel & Concurrent ...
yashpavasiya892
 
PPTX
Different Generation Of Computers .pptx
divcoder9507
 
PPTX
Microsoft PowerPoint Student PPT slides.pptx
Garleys Putin
 
PDF
PDF document: World Game (s) Great Redesign.pdf
Steven McGee
 
PPTX
ppt lighfrsefsefesfesfsefsefsefsefserrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrt.pptx
atharvawafgaonkar
 
PDF
Project English Paja Jara Alejandro.jpdf
AlejandroAlonsoPajaJ
 
PPT
Transformaciones de las funciones elementales.ppt
rirosel211
 
PPTX
AI ad its imp i military life read it ag
ShwetaBharti31
 
PDF
Cybersecurity Awareness Presentation ppt.
banodhaharshita
 
PPTX
Perkembangan Perangkat jaringan komputer dan telekomunikasi 3.pptx
Prayudha3
 
PPTX
nagasai stick diagrams in very large scale integratiom.pptx
manunagapaul
 
PPTX
办理方法西班牙假毕业证蒙德拉贡大学成绩单MULetter文凭样本
xxxihn4u
 
PDF
Latest Scam Shocking the USA in 2025.pdf
onlinescamreport4
 
PPTX
B2B_Ecommerce_Internship_Simranpreet.pptx
LipakshiJindal
 
PPTX
Artificial-Intelligence-in-Daily-Life (2).pptx
nidhigoswami335
 
PDF
BGP Security Best Practices that Matter, presented at PHNOG 2025
APNIC
 
PPTX
谢尔丹学院毕业证购买|Sheridan文凭不见了怎么办谢尔丹学院成绩单
mookxk3
 
Data Protection & Resilience in Focus.pdf
AmyPoblete3
 
Slides: PDF Eco Economic Epochs for World Game (s) pdf
Steven McGee
 
How tech helps people in the modern era.
upadhyayaryan154
 
Parallel & Concurrent ...
yashpavasiya892
 
Different Generation Of Computers .pptx
divcoder9507
 
Microsoft PowerPoint Student PPT slides.pptx
Garleys Putin
 
PDF document: World Game (s) Great Redesign.pdf
Steven McGee
 
ppt lighfrsefsefesfesfsefsefsefsefserrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrt.pptx
atharvawafgaonkar
 
Project English Paja Jara Alejandro.jpdf
AlejandroAlonsoPajaJ
 
Transformaciones de las funciones elementales.ppt
rirosel211
 
AI ad its imp i military life read it ag
ShwetaBharti31
 
Cybersecurity Awareness Presentation ppt.
banodhaharshita
 
Perkembangan Perangkat jaringan komputer dan telekomunikasi 3.pptx
Prayudha3
 
nagasai stick diagrams in very large scale integratiom.pptx
manunagapaul
 
办理方法西班牙假毕业证蒙德拉贡大学成绩单MULetter文凭样本
xxxihn4u
 
Latest Scam Shocking the USA in 2025.pdf
onlinescamreport4
 
B2B_Ecommerce_Internship_Simranpreet.pptx
LipakshiJindal
 
Artificial-Intelligence-in-Daily-Life (2).pptx
nidhigoswami335
 
BGP Security Best Practices that Matter, presented at PHNOG 2025
APNIC
 
谢尔丹学院毕业证购买|Sheridan文凭不见了怎么办谢尔丹学院成绩单
mookxk3
 
Ad

Code Quality Makes Your Job Easier

  • 1. I empower WordPress developers. @hellofromtonya @KnowTheCodePro Makes Our Jobs Easier Tonya Mork
  • 2. This session will cover… ➡ Identify why the practice of “code quality” exists. What problem is it trying to solve? ➡ Frame the session around you. ➡ Open your mind to how building to maximize quality makes your job easier. ➡ Give you easy-to-go-implement-right-now strategies.
  • 3. Code quality is a big topic My approach is to give you strategies that immediately increase the quality of your code.
  • 4. ?Why does the practice of “code quality” exist? What problem does it seek to solve?
  • 5. Why is it problematic?Huh? ↑Risk of misunderstanding ?Slows you down which ↑costs • break something • waste time going in wrong direction • scrap it • …
  • 6. Standards Linters Design Patterns Better Practices Mess Detectors Sniffers Measure compliance Define how to build
  • 7. Code quality is all about… Building code to maximize human understanding.
  • 8. The programming languages and computers don’t care if your code is human readable. Did you know? ? function f471(){$a=f982(); return !empty($a) ? $a->p1 : false;} function get_the_ID() { $post = get_post(); return ! empty( $post ) ? $post->ID : false; }
  • 9. Uglified code is hard for a human to read and understand. But….it’ll run. !function(t){"use strict";t.component("alert",{defaults:{fade:!0,duration: 200,trigger:".uk-alert-close"},boot:function(){t.$html.on("click.alert.uikit","[data- uk-alert]",function(i){var o=t.$(this);if(!o.data("alert")){var e=t.alert(o,t.Utils.options(o.attr("data-uk-alert")));t.$ (i.target).is(e.options.trigger)&&(i.preventDefault(),e.close())}})},init:function() {var t=this;this.on("click",this.options.trigger,function(i) {i.preventDefault(),t.close()})},close:function(){var t=this.trigger("close.uk.alert"),i=function() {this.trigger("closed.uk.alert").remove()}.bind(this);this.options.fade? t.css("overflow","hidden").css("max-height",t.height()).animate({height:0,opacity: 0,"padding-top":0,"padding-bottom":0,"margin-top":0,"margin-bottom": 0},this.options.duration,i):i()}})}(UIkit);
  • 10. Programming is the art of telling another human what one wants the computer to do. ~ Donald Knuth Computing Pioneer “
  • 11. Code Quality Quality Code Clean Code <human code> Code tells humans
  • 12. of building code that minimizes misunderstandings is: anyone (including you) can jump into the project, quickly figure out what’s going on…and why, and then get to work. The Result
  • 13. Makes your job easier. The Benefits
  • 14. How does it make your job easier? • Easier to sniff out problems • Easier to reuse on the next project • Easier to avoid propagating bugs or structural issues • Easier to extend, remove, reconfigure, and change • Easier to support and fix without the fear of breaking something else
  • 16. Benefits for the business of code • Easier to onboard new contributors or teammates • Reduce costs • Reduce risks
  • 17. How do you build code to tell humans? ? HEY, ________ should happen here.
  • 18. What makes code easier for humans? ? Consider…
  • 21. What makes code easier to read and understand? ?
  • 22. Keys to reading ✓ Presentation ✓ Structure
  • 23. Imagine trying to read a 300+ page book with no paragraphs. You are reading this book for two reasons.First, you are a programmer.Second, you want to be a better programmer.Good.We need better programmers.This is a book about good programming.It is filled with code.We are going to look at code from every different direction. We’ll look down at it from the top, up at it from the bottom, and through it from the inside out.By the time we are done, we’re going to know a lot about code.What’s more, we’ll be able to tell the difference between good code and bad code.We’ll know how to write good code.And we’ll know how to transform bad code into good code.There Will Be CodeOne might argue that a book about code is somehow behind the times—that code is no longer the issue; that we should be concerned about models and requirements instead. Indeed some have suggested that we are close to the end of code.That soon as code will be generated instead of written.That programmers simply won’t be needed because business people will generate programs from specifications.Nonsense!We will never be rid of code,because code represents the details of the requirements.At some level those details cannot be ignored or abstracted; they have to be specified. And specifying requirements in such detail that a machine can execute them in programming.Such a specification is code.I expect that the level of abstraction of our languages will continue to increate.I also expect that the number of domain-specific languages will continue to grow.This will be a good thing.But it will not eliminate code.Indeed,all the specifications written in these higher level and domain- specific language will be code!It will still need to be rigorous, accurate, and so formal and detailed that a machine can understand and execute it.The folks who think that code will one day disappear are like mathematicians who hope one day to discover a mathematics that does not have to be formal.They are hoping that one day we will discover a way to create machines that can do what we want rather than what we say.These machines will have to be able to understand us so well that they can translate vaguely specified needs into perfectly executing programs that precisely meet those needs.This will never happen.Not even humans,with all their intuition and creativity,have been able to create successful systems from the vague feelings of their customers.Indeed, if the discipline of requirements specification has taught us anything,it is that well-specified requirements are as formal as code and can act as executable tests of that code!Remember that code is really the language in which we ultimately express the requirements.We may create languages that are closer to the requirements.We may create tools that help us parse and assemble those requirements into formal structures.But we will never eliminate necessary precision—so there will always be code.Bad CodeI was recently reading the preface of Kent Beck’s book Imple… Clean Code: A Handbook of Agile Software Craftsmanship by Robert C. Martin
  • 24. Keys to reading ✓ Presentation ✓ Structure ✓ Format and code style ✓ Naming conventions ✓ Organization ✓ Consistency
  • 25. Keys to understanding ✓ Clear communication ✓ Tell what’s going on and why ✓ Small building blocks…think LEGOs
  • 27. Keys to understanding ✓ Clear communication ✓ Tell what’s going on and why ✓ Small building blocks…think LEGOs ✓ Singular….one thing ✓ Code does what it says it will do…every single time ✓ Relatable for us to comprehend…experiences and skill level
  • 29. Define the way you build. Becomes your standard, process, and best practices. Consistently follow it. Validate code to it. <human code> Strategy
  • 30. Use community coding standards and best practices. My Advice ✓ Makes it easier to onboard ✓ Makes it easier for you to reuse community components, snippets, processes, tooling, practices, etc. ✓ Increases quality in the community and our ecosystem
  • 31. Define the way you build. Where can you learn more? WordPress Coding Standards https://make.wordpress.org/core/handbook/best-practices/coding-standards/ WordPress at Scale https://scalewp.io/ XWP Engineering Best Practices https://xwp.github.io/engineering-best-practices/ 10up Engineering Best Practices https://10up.github.io/Engineering-Best-Practices/
  • 32. Code Style <human code> Strategy Driver of human readable code.
  • 33. function get_the_ID() { $post = get_post(); return ! empty( $post ) ? $post->ID : false; } function get_the_ID() { $post = get_post(); return ! empty( $post ) ? $post->ID : false; } function get_the_ID() { $post = get_post(); return !empty($post) ? $post->ID : false; } function get_the_ID() { $post = get_post(); return !empty($post) ? $post->ID : false; } Following WPCS: Your own: function get_the_ID() { $post = get_post(); return ! empty( $post ) ? $post->ID : false; }
  • 34. One expected behavior for a given set of conditions. <human code> Strategy
  • 35. Name to tell. <human code> Strategy Code tells humans Driver of human readable code.
  • 36. Name to tell. ๏Drives your design ๏Forces you to define what each element does ๏Forces you to think about the human side <human code> Strategy
  • 37. I often hear: Hey Tonya, naming is hard. • Expected behavior is not well defined or known. • Not sure of the set of conditions. • Not sure what the value is. • It’s doing too much. If you’re having a difficult time naming, that’s a clue….
  • 38. Functions and methods. “Name to Tell” Guide ✓ Do work ✓ Start with a verb ✓ Be an action phrase ✓ Name it to: TELL you what it will do when you call it Expected behavior
  • 39. Functions and methods. “Name to Tell” Guide Starting verbs: • State checker: is, does, has, did, doing • Get: get, fetch, open • Write: set, update, put • Others: count, enroll, render, parse, enqueue, process, add, remove
  • 40. Functions and methods. “Name to Tell” Guide verb + the expected behavior
  • 41. Variable. “Name to Tell” Guide ✓ Symbol to represent a piece of data ✓ Represents a value ✓ That “value” could be a state, collection of data, object, binding to a closure, etc. ✓ Name it to: TELL you what value it represents
  • 42. Class. “Name to Tell” Guide ✓ Represents an object ✓ It’s a noun. ✓ Name to TELL you what that “thing” is.
  • 43. The more clear the name, the greater the understanding. <human code> Strategy The less risk of misunderstandings.
  • 44. Done processing? Bail out. <human code> Strategy When the conditions are not right, stop.
  • 45. Bail Out Strategy Dos and Don’ts Don’t wrap your processing code inside a conditional's code block when nothing else will happen. Do - invert it into a guard clause.
  • 46. function strip_fragment_from_url( $url ) { $parsed_url = @parse_url( $url ); if ( ! empty( $parsed_url['host'] ) ) { $url = $parsed_url['scheme'] . '://' . $parsed_url['host']; if ( ! empty( $parsed_url['port'] ) ) { $url .= ':' . $parsed_url['port']; } if ( ! empty( $parsed_url['path'] ) ) { $url .= $parsed_url['path']; } if ( ! empty( $parsed_url['query'] ) ) { $url .= '?' . $parsed_url['query']; } } return $url; } The business logic
  • 47. Bail Out Strategy Examplefunction strip_fragment_from_url( $url ) { $parsed_url = @parse_url( $url ); if ( empty( $parsed_url['host'] ) ) { return $url; } $url = $parsed_url['scheme'] . '://' . $parsed_url['host']; if ( ! empty( $parsed_url['port'] ) ) { $url .= ':' . $parsed_url['port']; } if ( ! empty( $parsed_url['path'] ) ) { $url .= $parsed_url['path']; } if ( ! empty( $parsed_url['query'] ) ) { $url .= '?' . $parsed_url['query']; } return $url; } Guard clause
  • 48. Simplify decision making. <human code> Strategy Tell us what the decision is. Focus us on the details of the decision Focus on the functionality.
  • 49. Simplify decision making example public function show_notices() { .. if ( ( prefix_get_option( 'purchase_page', ‘' ) == '' || 'trash' == get_post_status( prefix_get_option( ‘purchase_page', ‘' ) ) ) && current_user_can( ‘edit_pages' ) && ! get_user_meta( get_current_user_id(), ‘_prefix_set_checkout_dismissed' )) { .. } .. }
  • 50. Simplify decision making example function show_notices() { .. if ( ( prefix_get_option( 'purchase_page', '' ) == '' || 'trash' == get_post_status( prefix_get_option( 'purchase_page', '' ) ) ) && current_user_can( 'edit_pages' ) && ! get_user_meta( get_current_user_id(), '_prefix_set_checkout_dismissed' ) ) { .. } .. } The decisions: 1. Does the purchase page exist? 2. Is it in trash? 3. Does the current user have the right to edit the page? 4. Did the current user dismissed the checkout?
  • 51. Simplify decision making example function get_the_content( $more_link_text = null, $strip_teaser = false ) { .. if ( false !== strpos( $post->post_content, '<!--noteaser-->' ) && ( ! $multipage || $page == 1 ) ) .. Is <!—noteaser—> in the content? Is this the 1st or single page?
  • 52. function get_the_content( $more_link_text = null, $strip_teaser = false ) { .. if ( false !== strpos( $post->post_content, '<!--noteaser-->' ) && ( ! $multipage || $page == 1 ) ) .. // Checks if the <!--noteaser--> exists in the content on the first page. { } Strategy 1: Add an inline comment Don’t forget the curly braces!
  • 53. function get_the_content( $more_link_text = null, $strip_teaser = false ) { .. if ( false !== strpos( $post->post_content, '<!--noteaser-->' ) && ( ! $multipage || $page == 1 ) ) .. { } function _has_noteaser_in_content( $post ) { global $multipage, $page; if ( $multipage && $page > 1 ) { return false; } return false !== strpos( $post->post_content, '<!--noteaser-->' ); } ( _has_noteaser_in_content( $post ) ) { Strategy 2: Abstract Focuses you on the decision. Why? To keep you focused on get_the_content().
  • 54. A lot more strategies <human code> Strategy
  • 55. Let’s Review the Key Take Aways
  • 56. Code quality is all about… Building code to maximize human understanding.
  • 57. Keys to reading ✓ Presentation ✓ Structure ✓ Format and code style ✓ Naming conventions ✓ Organization ✓ Consistency
  • 58. Keys to understanding ✓ Clear communication ✓ Tell what’s going on and why ✓ Small building blocks…think LEGOs ✓ Singular….one thing ✓ Code does what it says it will do…every single time ✓ Relatable for us to comprehend…experiences and skill level
  • 60. Easy-to-go-implement-right-now Strategies • Define the way you build. • I recommend using the WordPress Coding Standards along with community best practices such as XWP and 10up. • Validate your code’s compliance to those standards. • Be strict with your code style. • One expected behavior for a given set of conditions. • Name to tell. • Bail out when done. • Simplify decision making.
  • 61. Clues • If you’re having trouble: • Identifying the expected behavior or the given set of conditions • Naming • Inline comments
  • 62. Building <human code>, makes your code more human readable, lowering the risk of misunderstandings. It makes your job easier.
  • 63. Want more? Get my Refactoring Tweaks book and workbook bundle for free on Leanpub. https://leanpub.com/b/refactoring-tweaks-bundle. @hellofromtonya https://KnowTheCode.io