SlideShare a Scribd company logo
1 of 52
Abbas Ali
Web Developer
“Readable code is code that
clearly communicates its intent to the reader”
Source: https://fellow.app/blog/engineering/the-complete-guide-to-readable-code/
What is good code?
What is good code?
Appearance
Formatting
Coding
Standards
Formatting
Coding
Standards
CS Fixer
Spacing
function handle_form_submission() {
$error = new WP_Error();
if ( empty( $_POST['first_name'] ) ) {
$error->add( 'empty', 'First name is required' );
}
if ( empty( $_POST['last_name'] ) ) {
$error->add( 'empty', 'Last name is required' );
}
// ...
}
Spacing
function handle_form_submission() {
$error = new WP_Error();
if ( empty( $_POST['first_name'] ) ) {
$error->add( 'empty', 'First name is required' );
}
if ( empty( $_POST['last_name'] ) ) {
$error->add( 'empty', 'Last name is required' );
}
// ...
}
Spacing before return
function get_user( $id ) {
$data = WP_User::get_data_by( 'ID', $id );
$user = new WP_User;
$user->init( $data );
return $user;
}
Spacing before return
function get_user( $id ) {
$data = WP_User::get_data_by( 'ID', $id );
$user = new WP_User;
$user->init( $data );
return $user;
}
Return early
function make_editor( $id ) {
$userdata = WP_User::get_data_by( 'ID', $id );
if ( $userdata ) {
$user = new WP_User;
$user->init( $userdata );
$user->add_role( 'editor' );
return $user;
} else {
return false;
}
}
Return early
function make_editor( $id ) {
$userdata = WP_User::get_data_by( 'ID', $id );
if ( !$userdata ) {
return false;
}
$user = new WP_User;
$user->init( $userdata );
$user->add_role( 'editor' );
return $user;
}
Arrange variables
$start_day = 2;
$start_year = 2022;
$end_day = 3;
$start_month = 4;
$end_year = 2023;
$end_month = 6;
Arrange variables
$start_day = 2;
$start_month = 4;
$start_year = 2022;
$end_day = 3;
$end_month = 6;
$end_year = 2023;
Nomenclature
only two hard things in Computer Science: cache invalidation and nam
— Phil Karlton
Why naming matters?
• Naming is communication and bad naming prevents code from
communicating clearly.
• Code with obfuscated names is hard to read and understand.
• Other people should be able to read and understand the code.
Use proper language
Source: https://www.learningexplorer.org
Use proper language
Source: https://unsplash.com/
Use proper language
Avoid abbreviations
function calculate_salary() {
$b = 10000;
$hra = 5000;
$ta = 3000;
$inc = 5000;
$tds = 2000;
$sal = ($b + $hra + $ta + $inc) - $tds;
return $sal;
}
Avoid abbreviations
function calculate_salary() {
$basic = 10000;
$hra = 5000;
$travel_allowance = 3000;
$incentive = 5000;
$tds = 2000;
$salary = ($basic + $hra + $travel_allowance + $incentive) - $tds;
return $salary;
}
Prefix variables and methods
function handle( $id ) {
$todo = get_todo( $id );
$completed = $todo->completed();
if ( $completed ) {
// do something
}
}
Prefix variables and methods
function handle( $id ) {
$todo = get_todo( $id );
$is_completed = $todo->is_completed();
if ( $is_completed ) {
// do something
}
}
Function prefixes
$user = find_user( $id );
$remote_user = find_remote_user( $id );
Function prefixes
$user = get_user( $id );
$remote_user = fetch_user( $id );
Consistency in naming
function handle()
{
$first_name = 'John';
$lastName = 'Doe';
$EmailAddress = 'john@doe.com';
}
Consistency in naming
function handle()
{
$first_name = 'John';
$last_name = 'Doe';
$email_address = 'john@doe.com';
}
Use timestamps instead of booleans
$todo = get_todo( $id );
if ( $todo['completed'] === true ) {
// When was it completed?
}
Use timestamps instead of booleans
$todo = get_todo( $id );
if ( $todo[‘completed_at'] !== null ) {
// We now know when it was completed
}
Code Format and Refactor
Only if there was no else!
function send_email() {
if ( $user->is_active() ) {
if ( $user->has_subscribed() ) {
return send_subscription_email( $user );
} else {
return send_marketing_email( $user );
}
} else {
return send_activation_email( $user );
}
}
Only if there was no else!
function send_email() {
if ( !$user->is_active() ) {
return send_activation_email( $user );
}
if ( $user->hasSubscribed() ) {
return send_subscription_email( $user );
}
return send_marketing_email( $user );
}
Methods ordering
class My_Class {
public function update();
public function destroy();
public function create();
}
Methods ordering
class My_Class {
public function create();
public function update();
public function destroy();
}
Refactor your code
function subscribe() {
if (
( $user->is_active === true && $user->deleted_at !== null )
|| $user->is_admin === true
) {
$user->start_subscription();
}
}
Refactor your code
function subscribe() {
if ( $user->can_subscribe() ) {
$user->start_subscription();
}
}
Modular code
function save() {
global $wpdb;
// get and save invoices
$response = wp_remote_get( 'https://dummyjson.com/products' );
if( is_wp_error( $response ) ) {
return false;
}
$body = wp_remote_retrieve_body( $response );
$products = json_decode( $body, true );
foreach ( $products as $product ) {
$wpdb->insert( 'wp_products', ['name' => $product['title'], 'price' => $product['price']] );
$product_id = $wpdb->insert_id;
foreach ( $product['images'] as $image ) {
$upload_dir = wp_upload_dir();
$path = $upload_dir . '/products/' . md5( $image ) . '.jpg';
$wpdb->insert( 'wp_product_images', ['product_id' => $product_id, 'path' => $path] );
file_put_contents( $path, file_get_contents($image) );
}
}
}
Modular code
function fetch_products() {
// get and save invoices
$response = wp_remote_get( 'https://dummyjson.com/products' );
if( is_wp_error( $response ) ) {
return false;
}
$body = wp_remote_retrieve_body( $response );
return json_decode( $body, true );
}
Modular code
function save_products( $products ) {
global $wpdb;
foreach ( $products as $product ) {
$fields = ['name' => $product['title'], 'price' => $product['price']];
$wpdb->insert( 'wp_products', $fields );
save_product_images( $wpdb->insert_id, $product['images'] );
}
}
Modular code
function save_product_images( $product_id, $images ) {
global $wpdb;
foreach ( $images as $image ) {
$upload_dir = wp_upload_dir();
$path = $upload_dir . '/products/' . md5( $image ) . '.jpg';
$wpdb->insert( 'wp_product_images', ['product_id' => $product_id, 'pat
file_put_contents( $path, file_get_contents($image) );
}
}
Modular code
function save() {
if ( !$products = fetch_products() ) {
return false;
}
save_products( $products );
}
Smart variable assignment
function my_function() {
$user = get_user( $id );
if ( !$user ) {
return false;
}
$user->some_method();
}
Smart variable assignment
function my_function() {
if ( !$user = get_user( $id ) ) {
return false;
}
$user->some_method();
}
Thank You!
Abbas Ali
Ranium Systems
@_abbas
abbasali
Caption
Caption
Caption
https://laravelnagpur.com
Questions?
Getty Images

More Related Content

Similar to Tidy Up Your Code

Your code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnConYour code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnConRafael Dohms
 
Dutch PHP Conference - PHPSpec 2 - The only Design Tool you need
Dutch PHP Conference - PHPSpec 2 - The only Design Tool you needDutch PHP Conference - PHPSpec 2 - The only Design Tool you need
Dutch PHP Conference - PHPSpec 2 - The only Design Tool you needKacper Gunia
 
PHPSpec - the only Design Tool you need - 4Developers
PHPSpec - the only Design Tool you need - 4DevelopersPHPSpec - the only Design Tool you need - 4Developers
PHPSpec - the only Design Tool you need - 4DevelopersKacper Gunia
 
Modern Web Development with Perl
Modern Web Development with PerlModern Web Development with Perl
Modern Web Development with PerlDave Cross
 
PHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolvePHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolveXSolve
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologyDaniel Knell
 
PHP and Rich Internet Applications
PHP and Rich Internet ApplicationsPHP and Rich Internet Applications
PHP and Rich Internet Applicationselliando dias
 
Crafting beautiful software
Crafting beautiful softwareCrafting beautiful software
Crafting beautiful softwareJorn Oomen
 
WordPress REST API hacking
WordPress REST API hackingWordPress REST API hacking
WordPress REST API hackingJeroen van Dijk
 
You code sucks, let's fix it
You code sucks, let's fix itYou code sucks, let's fix it
You code sucks, let's fix itRafael Dohms
 
Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5Leonardo Proietti
 
Introduction to Zend Framework web services
Introduction to Zend Framework web servicesIntroduction to Zend Framework web services
Introduction to Zend Framework web servicesMichelangelo van Dam
 
SULTHAN's - PHP MySQL programs
SULTHAN's - PHP MySQL programsSULTHAN's - PHP MySQL programs
SULTHAN's - PHP MySQL programsSULTHAN BASHA
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ EtsyNishan Subedi
 
How to write code you won't hate tomorrow
How to write code you won't hate tomorrowHow to write code you won't hate tomorrow
How to write code you won't hate tomorrowPete McFarlane
 
PHP and Rich Internet Applications
PHP and Rich Internet ApplicationsPHP and Rich Internet Applications
PHP and Rich Internet Applicationselliando dias
 

Similar to Tidy Up Your Code (20)

Your code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnConYour code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnCon
 
Dutch PHP Conference - PHPSpec 2 - The only Design Tool you need
Dutch PHP Conference - PHPSpec 2 - The only Design Tool you needDutch PHP Conference - PHPSpec 2 - The only Design Tool you need
Dutch PHP Conference - PHPSpec 2 - The only Design Tool you need
 
PHPSpec - the only Design Tool you need - 4Developers
PHPSpec - the only Design Tool you need - 4DevelopersPHPSpec - the only Design Tool you need - 4Developers
PHPSpec - the only Design Tool you need - 4Developers
 
Modern Web Development with Perl
Modern Web Development with PerlModern Web Development with Perl
Modern Web Development with Perl
 
PHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolvePHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolve
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technology
 
Min-Maxing Software Costs
Min-Maxing Software CostsMin-Maxing Software Costs
Min-Maxing Software Costs
 
PHP and Rich Internet Applications
PHP and Rich Internet ApplicationsPHP and Rich Internet Applications
PHP and Rich Internet Applications
 
Crafting beautiful software
Crafting beautiful softwareCrafting beautiful software
Crafting beautiful software
 
WordPress REST API hacking
WordPress REST API hackingWordPress REST API hacking
WordPress REST API hacking
 
You code sucks, let's fix it
You code sucks, let's fix itYou code sucks, let's fix it
You code sucks, let's fix it
 
Daily notes
Daily notesDaily notes
Daily notes
 
Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5
 
Introduction to Zend Framework web services
Introduction to Zend Framework web servicesIntroduction to Zend Framework web services
Introduction to Zend Framework web services
 
Framework
FrameworkFramework
Framework
 
SULTHAN's - PHP MySQL programs
SULTHAN's - PHP MySQL programsSULTHAN's - PHP MySQL programs
SULTHAN's - PHP MySQL programs
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ Etsy
 
How to write code you won't hate tomorrow
How to write code you won't hate tomorrowHow to write code you won't hate tomorrow
How to write code you won't hate tomorrow
 
Smarty
SmartySmarty
Smarty
 
PHP and Rich Internet Applications
PHP and Rich Internet ApplicationsPHP and Rich Internet Applications
PHP and Rich Internet Applications
 

Recently uploaded

SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfIdiosysTechnologies1
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 

Recently uploaded (20)

SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdf
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 

Tidy Up Your Code

  • 1.
  • 3. “Readable code is code that clearly communicates its intent to the reader” Source: https://fellow.app/blog/engineering/the-complete-guide-to-readable-code/
  • 4. What is good code?
  • 5. What is good code?
  • 9. Spacing function handle_form_submission() { $error = new WP_Error(); if ( empty( $_POST['first_name'] ) ) { $error->add( 'empty', 'First name is required' ); } if ( empty( $_POST['last_name'] ) ) { $error->add( 'empty', 'Last name is required' ); } // ... }
  • 10. Spacing function handle_form_submission() { $error = new WP_Error(); if ( empty( $_POST['first_name'] ) ) { $error->add( 'empty', 'First name is required' ); } if ( empty( $_POST['last_name'] ) ) { $error->add( 'empty', 'Last name is required' ); } // ... }
  • 11. Spacing before return function get_user( $id ) { $data = WP_User::get_data_by( 'ID', $id ); $user = new WP_User; $user->init( $data ); return $user; }
  • 12. Spacing before return function get_user( $id ) { $data = WP_User::get_data_by( 'ID', $id ); $user = new WP_User; $user->init( $data ); return $user; }
  • 13. Return early function make_editor( $id ) { $userdata = WP_User::get_data_by( 'ID', $id ); if ( $userdata ) { $user = new WP_User; $user->init( $userdata ); $user->add_role( 'editor' ); return $user; } else { return false; } }
  • 14. Return early function make_editor( $id ) { $userdata = WP_User::get_data_by( 'ID', $id ); if ( !$userdata ) { return false; } $user = new WP_User; $user->init( $userdata ); $user->add_role( 'editor' ); return $user; }
  • 15. Arrange variables $start_day = 2; $start_year = 2022; $end_day = 3; $start_month = 4; $end_year = 2023; $end_month = 6;
  • 16. Arrange variables $start_day = 2; $start_month = 4; $start_year = 2022; $end_day = 3; $end_month = 6; $end_year = 2023;
  • 18. only two hard things in Computer Science: cache invalidation and nam — Phil Karlton
  • 19. Why naming matters? • Naming is communication and bad naming prevents code from communicating clearly. • Code with obfuscated names is hard to read and understand. • Other people should be able to read and understand the code.
  • 20.
  • 21. Use proper language Source: https://www.learningexplorer.org
  • 22. Use proper language Source: https://unsplash.com/
  • 24. Avoid abbreviations function calculate_salary() { $b = 10000; $hra = 5000; $ta = 3000; $inc = 5000; $tds = 2000; $sal = ($b + $hra + $ta + $inc) - $tds; return $sal; }
  • 25. Avoid abbreviations function calculate_salary() { $basic = 10000; $hra = 5000; $travel_allowance = 3000; $incentive = 5000; $tds = 2000; $salary = ($basic + $hra + $travel_allowance + $incentive) - $tds; return $salary; }
  • 26. Prefix variables and methods function handle( $id ) { $todo = get_todo( $id ); $completed = $todo->completed(); if ( $completed ) { // do something } }
  • 27. Prefix variables and methods function handle( $id ) { $todo = get_todo( $id ); $is_completed = $todo->is_completed(); if ( $is_completed ) { // do something } }
  • 28. Function prefixes $user = find_user( $id ); $remote_user = find_remote_user( $id );
  • 29. Function prefixes $user = get_user( $id ); $remote_user = fetch_user( $id );
  • 30. Consistency in naming function handle() { $first_name = 'John'; $lastName = 'Doe'; $EmailAddress = 'john@doe.com'; }
  • 31. Consistency in naming function handle() { $first_name = 'John'; $last_name = 'Doe'; $email_address = 'john@doe.com'; }
  • 32. Use timestamps instead of booleans $todo = get_todo( $id ); if ( $todo['completed'] === true ) { // When was it completed? }
  • 33. Use timestamps instead of booleans $todo = get_todo( $id ); if ( $todo[‘completed_at'] !== null ) { // We now know when it was completed }
  • 34. Code Format and Refactor
  • 35. Only if there was no else! function send_email() { if ( $user->is_active() ) { if ( $user->has_subscribed() ) { return send_subscription_email( $user ); } else { return send_marketing_email( $user ); } } else { return send_activation_email( $user ); } }
  • 36. Only if there was no else! function send_email() { if ( !$user->is_active() ) { return send_activation_email( $user ); } if ( $user->hasSubscribed() ) { return send_subscription_email( $user ); } return send_marketing_email( $user ); }
  • 37. Methods ordering class My_Class { public function update(); public function destroy(); public function create(); }
  • 38. Methods ordering class My_Class { public function create(); public function update(); public function destroy(); }
  • 39. Refactor your code function subscribe() { if ( ( $user->is_active === true && $user->deleted_at !== null ) || $user->is_admin === true ) { $user->start_subscription(); } }
  • 40. Refactor your code function subscribe() { if ( $user->can_subscribe() ) { $user->start_subscription(); } }
  • 41. Modular code function save() { global $wpdb; // get and save invoices $response = wp_remote_get( 'https://dummyjson.com/products' ); if( is_wp_error( $response ) ) { return false; } $body = wp_remote_retrieve_body( $response ); $products = json_decode( $body, true ); foreach ( $products as $product ) { $wpdb->insert( 'wp_products', ['name' => $product['title'], 'price' => $product['price']] ); $product_id = $wpdb->insert_id; foreach ( $product['images'] as $image ) { $upload_dir = wp_upload_dir(); $path = $upload_dir . '/products/' . md5( $image ) . '.jpg'; $wpdb->insert( 'wp_product_images', ['product_id' => $product_id, 'path' => $path] ); file_put_contents( $path, file_get_contents($image) ); } } }
  • 42. Modular code function fetch_products() { // get and save invoices $response = wp_remote_get( 'https://dummyjson.com/products' ); if( is_wp_error( $response ) ) { return false; } $body = wp_remote_retrieve_body( $response ); return json_decode( $body, true ); }
  • 43. Modular code function save_products( $products ) { global $wpdb; foreach ( $products as $product ) { $fields = ['name' => $product['title'], 'price' => $product['price']]; $wpdb->insert( 'wp_products', $fields ); save_product_images( $wpdb->insert_id, $product['images'] ); } }
  • 44. Modular code function save_product_images( $product_id, $images ) { global $wpdb; foreach ( $images as $image ) { $upload_dir = wp_upload_dir(); $path = $upload_dir . '/products/' . md5( $image ) . '.jpg'; $wpdb->insert( 'wp_product_images', ['product_id' => $product_id, 'pat file_put_contents( $path, file_get_contents($image) ); } }
  • 45. Modular code function save() { if ( !$products = fetch_products() ) { return false; } save_products( $products ); }
  • 46. Smart variable assignment function my_function() { $user = get_user( $id ); if ( !$user ) { return false; } $user->some_method(); }
  • 47. Smart variable assignment function my_function() { if ( !$user = get_user( $id ) ) { return false; } $user->some_method(); }
  • 48. Thank You! Abbas Ali Ranium Systems @_abbas abbasali

Editor's Notes

  1. While it’s easier said than done and often a challenge for new developers, creating readable code is as important as solving any software problem—this is why this should be one of the first techniques a developer learns on the job.
  2. It must be correct i.e it must produce a result that is expected when executed. The code must be easily readable and understandable by ourselves and other developers. Since our software code can be shared with other developers, we’ll want to make it easier to work with this shared code. To do this, we’ll have to make sure that everyone involved, including ourselves, understands the same thing easily and quickly. Code that is readable for one person is not necessarily readable for another. Code that is not readable takes more time to understand and can make us lose a lot of time on what should be a simple task. The worst-case scenario is that it could even take several iterations to fix some problems. In some cases, we might spend so much time trying to understand code that we might want to rewrite it completely.
  3. It must be correct i.e it must produce a result that is expected when executed. The code must be easily readable and understandable by ourselves and other developers. Since our software code can be shared with other developers, we’ll want to make it easier to work with this shared code. To do this, we’ll have to make sure that everyone involved, including ourselves, understands the same thing easily and quickly. Code that is readable for one person is not necessarily readable for another. Code that is not readable takes more time to understand and can make us lose a lot of time on what should be a simple task. The worst-case scenario is that it could even take several iterations to fix some problems. In some cases, we might spend so much time trying to understand code that we might want to rewrite it completely.
  4. Appearance is everything. As a human, you always want to appear best so that others like you. Not just others, but you should also like your own appearance in mirror. The same is the case with code. It should be written in a way that it appears best to others and when you read your own code after a few months, it should still appear best to you as well.
  5. Use Wordpress Coding Standards. If using some other CMS or framework then start with that community standard Follow PSR (PHP Standards Recommendation) - Makes code well formatted - Consistent - Robust Use PHP_CodeSniffer WordPress Coding Standards for PHP_CodeSniffer PHP Coding Standards Fixer aka php-cs-fixer VS Code and other editor plugins
  6. Use Wordpress Coding Standards. If using some other CMS or framework then start with that community standard Follow PSR (PHP Standards Recommendation) - Makes code well formatted - Consistent - Robust Use PHP_CodeSniffer WordPress Coding Standards for PHP_CodeSniffer PHP Coding Standards Fixer aka php-cs-fixer VS Code and other editor plugins
  7. Hard to read Can’t figure out the code blocks
  8. Clear distinguishes blocks of code and logic Gives a much needed breathing room to your code
  9. Return value getting lost Can’t determine just by glance if function is returning something or not
  10. If the first block is large then hard to see what is happening in else condition Code is first processing positive scenario and then negative. You should arrange the code such that it first tackles all the negative scenarios Unnecessary else
  11. Nomenclature is naming things
  12. The hardest thing for new parents is to name their baby. Same is the case with the code. Your code is your baby and it is really difficult to give proper and meaningful names to variables, functions, classes and files.
  13. TODO: ALL BULLETS AT THE SAME TIME Naming is communication and bad naming prevents code from communicating clearly. For example, if we name a boy as Preeti and a girl as Rahul - do you think this is a good naming? Code with obfuscated names is hard to read and understand. Other people should be able to read and understand the code.
  14. What is this guy doing? He is either thinking about the best way to bust the cache or thinking how to name a class. Do you want to get in this situation? Let’s see how to come out of this situation.
  15. TODO: Make it shorter English is the standard language to use in programming. Code can be managed by programmers from other regions and countries and everyone understands English. Avoid using emojis and local language for variables, functions etc.
  16. Meaningful names like $days instead of $d. Have seen many using $a, $b etc.Never do that. Can use commonly accepted single letter variables for loops like $i. Synonyms - Head_of_School -> Principal $loginAsOtherUser -> $impersonate, photos_and_videos -> media
  17. create_new_user should be create_user new_group_created_send_notification() -> send_group_created_notification() update_old_data() -> update_data()
  18. TODO: Make it shorter Meaningful names like $days instead of $d. Have seen many using $a, $b etc.Never do that. Can use commonly accepted single letter variables for loops like $i. Synonyms - $loginAsOtherUser -> $impersonate, photos_and_videos -> media new_group_created_send_notification() -> send_group_created_notification() update_old_data() -> update_data()
  19. After this discuss Adding metrics name to variables $expiryTime = 60; $expiryTimeInMinutes = 60; Adding prefix to method names $user->subscribed(); // returns true or false $user->hasSubscribed();
  20. Boolean database fields are used for storing true or false. Example - todos.completed This only tells us whether a todo is completed or not. Replace that field with a timestamp nullable field completed_at Now we can determine if the todo has been completed or not as well as the time it was completed at.
  21. Boolean database fields are used for storing true or false. Example - todos.completed This only tells us whether a todo is completed or not. Replace that field with a timestamp nullable field completed_at Now we can determine if the todo has been completed or not as well as the time it was completed at.
  22. Avoid else. It makes your code a lot cleaner Else has a wide scope. Reduce cyclomatic complexity