Build Solutions,
Not Puzzles
Writing Sensible Code
Anis Uddin Ahmad
Head of Software Development
Devnet Limited
http://ajaxray.com/ @ajaxray
/ajaxray
https://gitstat.tophackr.com/ajaxray
Code is communication between People
Code is communication between People
Time spent by programmers at work
20%
80%
Reading Code
Writing Code
Have you ever worked on
other people's code
How did you feel?
Cost of Bad Code
The opportunity cost
of bad code comes
to $85 billion
annually.

— dev.to
Cost of Bad Code
$motivation!--;

$maintainability!--;

$easeOfChange!--;

$debuggingTime!++;

$costOfChange!++;

$costOfNewFeature!++;
Decrease what you
want to have
Increase what you
want to avoid
– Martin Fowler
“Any fool can write code that a
computer can understand.
Good programmers write code that
humans can understand.”
We Will Not Discuss Today
• KISS - Keep It Simple Stupid

• DRY - Don’t Repeat Yourself

• YAGNI - You Aren’t Gonna Need It

• Composition Over Inheritance
• SOLID Principles

• Code Smells

• UNIX Philosophy

• Law of Demeter
But you should ^ study them anyway…
MUST
Never assume…
• I am the ONLY man working on it

• Nothing is going to be added here

• It’s simple, no change will require 

• I’ll do the changes if required

• I know how it works, so (whatever)

• I’ll guide the next guy
ONE
MAN
ARMY
Rather Presume…
• Someone else is going to work on it

• I may not be there to explain things

• *My boss is going to review it in next performance evolution*
“Working” !== “Complete”
Make it work,
Make it right,
Make it fast.
— Kent Beck
Make it work,
Make it right,
Make it fast.
— Kent Beck
Presentable & Accurate
• Can it be simpler?

• Are the names intention-revealing?

• Is there any magic/hard coded things?

• Are the functions small enough?

• Is it clear enough for understanding
without my help?
“Working” !== “Complete”
class Newsletter {

!// Define properties, constructors etc.

public function circulate(array $connParams, array $apiUrl, DateTime $dt)

{

!// Few lines for collecting news [+12 lines]

$pdo= new PDO($connParams['dsn'], $connParams['user'], $connParams['pass']);

$conditions = ['!!/** a few lines for calculating conditions *!//'];

$newsList = $pdo"->query("!--Multiline Query for getting News!--")"->fetchAll();

!// Collect subscribers from API call to $apiBaseUrl using curl [+7 lines]

!// $result=curl_exec($ch);

$subscribers = json_decode($result, true);

foreach ($newsList as $news) {

!// Check if the news is eligible for newsletter circulation

if ((new DateTime('2020-03-01')) < (new DateTime($news['publishDate']))

"&& $news['print_only'] "!= 1

"&& 'some_other_condition' "== 'whatever') {

$this"->add($news);

}

}

foreach ($subscribers as $user) {

!// Initiate Mailer library as $mailer [+5 lines]

$mailer"->send($user['email'], $this"->getContent());

}

}

!// Other methods…

}
class Newsletter {

!// Define properties, constructors etc.

public function circulate(array $connParams, array $apiUrl, DateTime $dt)

{

!// Few lines for collecting news [+12 lines]

$pdo= new PDO($connParams['dsn'], $connParams['user'], $connParams['pass']);

$conditions = ['!!/** a few lines for calculating conditions *!//'];

$newsList = $pdo"->query("!--Multiline Query for getting News!--")"->fetchAll();

!// Collect subscribers from API call to $apiBaseUrl using curl [+7 lines]

!// $result=curl_exec($ch);

$subscribers = json_decode($result, true);

foreach ($newsList as $news) {

!// Check if the new is eligible for newsletter circulation

if ((new DateTime('2020-03-01')) > (new DateTime($news['publishDate']))

"&& $news['print_only'] "!= 1

"&& 'some_other_condition' "== 'whatever') {

$this"->add($news);

}

}

foreach ($subscribers as $user) {

!// Initiate Mailer library as $mailer [+5 lines]

$mailer"->send($user['email'], $this"->getContent());

}

}

!// Other methods…

}

Collecting news from Database - 12 lines
Getting Subscribers from API - 7 lines
Sending Email Newsletter to user - 5 lines
Selecting eligible news for newsletter - 5 lines
class Newsletter {

private $newsRepository;

private $subscription;

public function "__construct(NewsRepository $newsRepo, SubscriptionService $subscription)

{

$this"->newsRepository = $newsRepo;

$this"->subscription = $subscription;

}

public function circulate(DateTime $dt)

{

$newsList = $this"->newsRepository"->findForMonth($dt);

$subscribers = $this"->subscription"->getUsers();

foreach ($newsList as $news) {

!// Check if the news is eligible for newsletter circulation

if((new DateTime('2020-03-01')) < (new DateTime($news['publishDate']))

"&& $news['print_only'] "!= 1

"&& 'some_other_condition' "== 'whatever') {

$this"->add($news);

}

}

foreach ($subscribers as $user) {

$this"->sendToUser($user, $this"->getContent());

}

}

private function sendToUser($user, $content){!/* Define sending to User!!... !*/}

!// Other methods…

}
class Newsletter {

private $newsRepository;

private $subscription;

public function "__construct(NewsRepository $newsRepo, SubscriptionService $subscription)

{

$this"->newsRepository = $newsRepo;

$this"->subscription = $subscription;

}

public function circulate(DateTime $dt)

{

$newsList = $this"->newsRepository"->findForMonth($dt);

$subscribers = $this"->subscription"->getUsers();

foreach ($newsList as $news) {

!// Check if the news is eligible for newsletter circulation

if((new DateTime('2020-03-01')) < (new DateTime($news['publishDate']))

"&& $news['print_only'] "!= 1

"&& 'some_other_condition' "== 'whatever') {

$this"->add($news);

}

}

foreach ($subscribers as $user) {

$this"->sendToUser($user, $this"->getContent());

}

}

private function sendToUser($user, $content){!/* Define sending to User!!... !*/}

!// Other methods…

}
Collecting news from Database - 12 lines
Getting Subscribers from API - 7 lines
Sending Email Newsletter to user - 5 lines
Dependencies are injected
No Mental Mapping
• No “This” means “That” 

• Use Domain Terminology
Keep no explanation in YOUR memory, 

make it explicit in code
• Self-explanatory names 

• Consistent naming - pick one
word per concept
public function circulate(DateTime $dt)

{

$newsList = $this"->newsRepository"->findForMonth($dt);

$subscribers = $this"->subscription"->getUsers();

foreach ($newsList as $news) {

!// Check if the new is eligible for newsletter circulation

if((new DateTime('2020-03-01')) < (new DateTime($news['publishDate']))

"&& $news['print_only'] "!= 1

"&& 'some_other_condition' "== 'whatever') {

$this"->add($news);

}

}

!// ....

}
How this $dt is used?
What’s very special abut this day?
public function circulate(DateTime $dt)

{

$newsList = $this"->newsRepository"->findForMonth($dt);

$subscribers = $this"->subscription"->getUsers();

foreach ($newsList as $news) {

!// Check if the new is eligible for newsletter circulation

if((new DateTime('2020-03-01')) < (new DateTime($news['publishDate']))

"&& $news['print_only'] "!= 1

"&& 'some_other_condition' "== 'whatever') {

$this"->add($news);

}

}

!// ....

}
public function circulate(DateTime $circulationMonthYear)

{

$newsList = $this"->newsRepository"->findForMonth($circulationMonthYear);

$subscribers = $this"->subscription"->getUsers();

foreach ($newsList as $news) {

!// Check if the news is eligible for newsletter circulation

$moduleStartedDate = new DateTime('2020-03-01');

if(($moduleStartedDate < (new DateTime($news['publishDate']))

"&& $news['print_only'] "!= 1

"&& 'some_other_condition' "== 'whatever') {

$this"->add($news);

}

}

!// ....

}
Beware of Copy-Paste Snippets
• Understand every word you’ve
pasted

• Cleanup - keep exactly what
you need 

• Change the names for your
context

• Format as per your* coding
style
Beware of comments
Beware of comments
The best comment is a good name for a method or class.
Purpose of Comment Replace with
Explain a complex expression
Understandable subexpressions
using Extract Variable
Explains a section of code
Extract method with self-explanatory
names
Predefined values (Number/Date/..)
Introduce Constants with purpose-
revealing name
foreach ($newsList as $news) {

!// Check if the news is eligible for newsletter circulation

$moduleStartedDate = new DateTime('2020-03-01');

if(($moduleStartedDate < (new DateTime($news['publishDate']))

"&& $news['print_only'] "!= 1

"&& 'some_other_condition' "== 'whatever') {

$this"->add($news);

}

}

1
2
3
foreach ($newsList as $news) {

!// Check if the news is eligible for newsletter circulation

$moduleStartedDate = new DateTime('2020-03-01');

if(($moduleStartedDate < (new DateTime($news['publishDate']))

"&& $news['print_only'] "!= 1

"&& 'some_other_condition' "== 'whatever') {

$this"->add($news);

}

}

public function circulate(DateTime $circulationMonth)

{

!// ....

foreach ($newsList as $news) {

if($this"->isEligibleToCirculate($news)) {

$this"->add($news);

}

}

!// ....

}

private function isEligibleToCirculate($news)

{

$moduleStartedDate = new DateTime(self"::MODULE_LAUNCHED_ON);

$newsPublishDate = new DateTime($news['publishDate']);

return $moduleStartedDate < $newsPublishDate

"&& $news['print_only'] "!= 1

"&& 'some_other_condition' "== 'whatever';

}

1
2
3
Try Unattended code review
Sign of successful communication
Refactoring
Guru
https://refactoring.guru/refactoring
Let’s take time to write
sensible code
Be happy by making others happy
Questions?

Writing Sensible Code

  • 1.
  • 2.
    Anis Uddin Ahmad Headof Software Development Devnet Limited http://ajaxray.com/ @ajaxray /ajaxray https://gitstat.tophackr.com/ajaxray
  • 3.
    Code is communicationbetween People
  • 4.
    Code is communicationbetween People Time spent by programmers at work 20% 80% Reading Code Writing Code
  • 5.
    Have you everworked on other people's code
  • 6.
  • 7.
    Cost of BadCode The opportunity cost of bad code comes to $85 billion annually. — dev.to
  • 8.
    Cost of BadCode $motivation!--; $maintainability!--; $easeOfChange!--; $debuggingTime!++; $costOfChange!++; $costOfNewFeature!++; Decrease what you want to have Increase what you want to avoid
  • 9.
    – Martin Fowler “Anyfool can write code that a computer can understand. Good programmers write code that humans can understand.”
  • 10.
    We Will NotDiscuss Today • KISS - Keep It Simple Stupid • DRY - Don’t Repeat Yourself • YAGNI - You Aren’t Gonna Need It • Composition Over Inheritance • SOLID Principles • Code Smells • UNIX Philosophy • Law of Demeter But you should ^ study them anyway… MUST
  • 11.
    Never assume… • Iam the ONLY man working on it • Nothing is going to be added here • It’s simple, no change will require • I’ll do the changes if required • I know how it works, so (whatever) • I’ll guide the next guy ONE MAN ARMY
  • 12.
    Rather Presume… • Someoneelse is going to work on it • I may not be there to explain things • *My boss is going to review it in next performance evolution*
  • 13.
    “Working” !== “Complete” Makeit work, Make it right, Make it fast. — Kent Beck
  • 14.
    Make it work, Makeit right, Make it fast. — Kent Beck Presentable & Accurate • Can it be simpler? • Are the names intention-revealing? • Is there any magic/hard coded things? • Are the functions small enough? • Is it clear enough for understanding without my help? “Working” !== “Complete”
  • 15.
    class Newsletter { !//Define properties, constructors etc. public function circulate(array $connParams, array $apiUrl, DateTime $dt) { !// Few lines for collecting news [+12 lines] $pdo= new PDO($connParams['dsn'], $connParams['user'], $connParams['pass']); $conditions = ['!!/** a few lines for calculating conditions *!//']; $newsList = $pdo"->query("!--Multiline Query for getting News!--")"->fetchAll(); !// Collect subscribers from API call to $apiBaseUrl using curl [+7 lines] !// $result=curl_exec($ch); $subscribers = json_decode($result, true); foreach ($newsList as $news) { !// Check if the news is eligible for newsletter circulation if ((new DateTime('2020-03-01')) < (new DateTime($news['publishDate'])) "&& $news['print_only'] "!= 1 "&& 'some_other_condition' "== 'whatever') { $this"->add($news); } } foreach ($subscribers as $user) { !// Initiate Mailer library as $mailer [+5 lines] $mailer"->send($user['email'], $this"->getContent()); } } !// Other methods… }
  • 16.
    class Newsletter { !//Define properties, constructors etc. public function circulate(array $connParams, array $apiUrl, DateTime $dt) { !// Few lines for collecting news [+12 lines] $pdo= new PDO($connParams['dsn'], $connParams['user'], $connParams['pass']); $conditions = ['!!/** a few lines for calculating conditions *!//']; $newsList = $pdo"->query("!--Multiline Query for getting News!--")"->fetchAll(); !// Collect subscribers from API call to $apiBaseUrl using curl [+7 lines] !// $result=curl_exec($ch); $subscribers = json_decode($result, true); foreach ($newsList as $news) { !// Check if the new is eligible for newsletter circulation if ((new DateTime('2020-03-01')) > (new DateTime($news['publishDate'])) "&& $news['print_only'] "!= 1 "&& 'some_other_condition' "== 'whatever') { $this"->add($news); } } foreach ($subscribers as $user) { !// Initiate Mailer library as $mailer [+5 lines] $mailer"->send($user['email'], $this"->getContent()); } } !// Other methods… } Collecting news from Database - 12 lines Getting Subscribers from API - 7 lines Sending Email Newsletter to user - 5 lines Selecting eligible news for newsletter - 5 lines
  • 17.
    class Newsletter { private$newsRepository; private $subscription; public function "__construct(NewsRepository $newsRepo, SubscriptionService $subscription) { $this"->newsRepository = $newsRepo; $this"->subscription = $subscription; } public function circulate(DateTime $dt) { $newsList = $this"->newsRepository"->findForMonth($dt); $subscribers = $this"->subscription"->getUsers(); foreach ($newsList as $news) { !// Check if the news is eligible for newsletter circulation if((new DateTime('2020-03-01')) < (new DateTime($news['publishDate'])) "&& $news['print_only'] "!= 1 "&& 'some_other_condition' "== 'whatever') { $this"->add($news); } } foreach ($subscribers as $user) { $this"->sendToUser($user, $this"->getContent()); } } private function sendToUser($user, $content){!/* Define sending to User!!... !*/} !// Other methods… }
  • 18.
    class Newsletter { private$newsRepository; private $subscription; public function "__construct(NewsRepository $newsRepo, SubscriptionService $subscription) { $this"->newsRepository = $newsRepo; $this"->subscription = $subscription; } public function circulate(DateTime $dt) { $newsList = $this"->newsRepository"->findForMonth($dt); $subscribers = $this"->subscription"->getUsers(); foreach ($newsList as $news) { !// Check if the news is eligible for newsletter circulation if((new DateTime('2020-03-01')) < (new DateTime($news['publishDate'])) "&& $news['print_only'] "!= 1 "&& 'some_other_condition' "== 'whatever') { $this"->add($news); } } foreach ($subscribers as $user) { $this"->sendToUser($user, $this"->getContent()); } } private function sendToUser($user, $content){!/* Define sending to User!!... !*/} !// Other methods… } Collecting news from Database - 12 lines Getting Subscribers from API - 7 lines Sending Email Newsletter to user - 5 lines Dependencies are injected
  • 19.
    No Mental Mapping •No “This” means “That” • Use Domain Terminology Keep no explanation in YOUR memory, make it explicit in code • Self-explanatory names • Consistent naming - pick one word per concept
  • 20.
    public function circulate(DateTime$dt) { $newsList = $this"->newsRepository"->findForMonth($dt); $subscribers = $this"->subscription"->getUsers(); foreach ($newsList as $news) { !// Check if the new is eligible for newsletter circulation if((new DateTime('2020-03-01')) < (new DateTime($news['publishDate'])) "&& $news['print_only'] "!= 1 "&& 'some_other_condition' "== 'whatever') { $this"->add($news); } } !// .... } How this $dt is used? What’s very special abut this day?
  • 21.
    public function circulate(DateTime$dt) { $newsList = $this"->newsRepository"->findForMonth($dt); $subscribers = $this"->subscription"->getUsers(); foreach ($newsList as $news) { !// Check if the new is eligible for newsletter circulation if((new DateTime('2020-03-01')) < (new DateTime($news['publishDate'])) "&& $news['print_only'] "!= 1 "&& 'some_other_condition' "== 'whatever') { $this"->add($news); } } !// .... } public function circulate(DateTime $circulationMonthYear) { $newsList = $this"->newsRepository"->findForMonth($circulationMonthYear); $subscribers = $this"->subscription"->getUsers(); foreach ($newsList as $news) { !// Check if the news is eligible for newsletter circulation $moduleStartedDate = new DateTime('2020-03-01'); if(($moduleStartedDate < (new DateTime($news['publishDate'])) "&& $news['print_only'] "!= 1 "&& 'some_other_condition' "== 'whatever') { $this"->add($news); } } !// .... }
  • 22.
    Beware of Copy-PasteSnippets • Understand every word you’ve pasted • Cleanup - keep exactly what you need • Change the names for your context • Format as per your* coding style
  • 23.
  • 24.
    Beware of comments Thebest comment is a good name for a method or class. Purpose of Comment Replace with Explain a complex expression Understandable subexpressions using Extract Variable Explains a section of code Extract method with self-explanatory names Predefined values (Number/Date/..) Introduce Constants with purpose- revealing name
  • 25.
    foreach ($newsList as$news) { !// Check if the news is eligible for newsletter circulation $moduleStartedDate = new DateTime('2020-03-01'); if(($moduleStartedDate < (new DateTime($news['publishDate'])) "&& $news['print_only'] "!= 1 "&& 'some_other_condition' "== 'whatever') { $this"->add($news); } } 1 2 3
  • 26.
    foreach ($newsList as$news) { !// Check if the news is eligible for newsletter circulation $moduleStartedDate = new DateTime('2020-03-01'); if(($moduleStartedDate < (new DateTime($news['publishDate'])) "&& $news['print_only'] "!= 1 "&& 'some_other_condition' "== 'whatever') { $this"->add($news); } } public function circulate(DateTime $circulationMonth) { !// .... foreach ($newsList as $news) { if($this"->isEligibleToCirculate($news)) { $this"->add($news); } } !// .... } private function isEligibleToCirculate($news) { $moduleStartedDate = new DateTime(self"::MODULE_LAUNCHED_ON); $newsPublishDate = new DateTime($news['publishDate']); return $moduleStartedDate < $newsPublishDate "&& $news['print_only'] "!= 1 "&& 'some_other_condition' "== 'whatever'; } 1 2 3
  • 27.
    Try Unattended codereview Sign of successful communication
  • 28.
  • 29.
    Let’s take timeto write sensible code Be happy by making others happy
  • 30.