SlideShare a Scribd company logo
1 of 45
SAVE TIME BY APPLYING
CLEAN CODE PRINCIPLES
ABOUT ME
Software Engineer
PHP since 11 years
CI
CleanCode
DevOps
TDD
Shipping
Bullet points
WORKING FOR
ResearchGate gives science back to the people who make it happen.
We help researchers build reputation and accelerate scientific
progress.
On their terms.
GET IN TOUCH
stackoverflow:
Twitter: @_ _edorian
G+ / Xing: Volker Dusch
IRC (freenode): edorian
Mail: php@wallbash.com
AGENDA
Motivation
Big picture
Concrete examples
WE'RE DEVELOPERS
Let's start with us!
We get paid to do what we love
Most of us started because we where fascinated by programming
But what is our job?
OUR JOB IS TO DELIVER
Get things done
Give good estimates
Ask the right questions
Keep doing that
Don't slow down
Keep our promises
THE COST OF HAVING USFOLKSAROUND
German numbers, YMMV €, Approximations
Salary: ~50k a year 50.000€ / Year
adding non-wage labor cost 80.000€ / Year
and office space, water, hardware,
coffee, plants, cleaning, travels, training 100.000€ / Year
Weekends, holidays, vacation, etc:
We work 220 days a year. 455€ / day
"Classic" 8 hour work day 55 Bucks per Hour!
We are expected to contribute over 100.000 Bucks in business value
per year!
WHAT DO WE SPEND TIME ON?
Planning a change
Reading the code
Acting on that plan
Evaluating the outcome
GOTO 10
OUR CODE LIKE OUR DATA STORAGE
It has a read:write ratio of 10:1
...and our brains are really bad caches!
GOALS
Cheap writes
The ability to adapt our software to new requirements.
Cheap reads
The ability to understand and reason about our software quickly.
Writes require reads
There is no UPDATE. All we have is GET and PUT.
CHEAP READS
Your coworkers will read your code again and again and again
Does it take them 2 hours or 5 minutes to understand a module?
SO HOW DO WE KEEP IT EASY?
CHEAP WRITES!
Fear to break something leads to not cleaning up
Not cleaning up leads to expensive reads
Expensive reads lead to expensive writes
So how do we reduce fear of breaking things?
TESTING
TDD is a pragmatic approach to maintainable code.
It's not going to get easier than that ;)
It doesn't even have to take longer
SHORT TDD INTERMISSION
Write unit tests! TDD is just the fastest way, eventually.
Tools? You don't need tools to get started!
watch –n1 'phpunit'and ¼ of a screen is ALL you need!
Aim for 100% test coverage but don't obsess. Test what breaks a lot.
Have a fast test suite. Or use --filterif you can't.
Writing tests can feel like extra work if you are rethinking an already
solved problem.
TDD offers a way to first think about the problem, the interface and
the interactions and then filling in the details step by step until you are
done with the bigger picture.
TESTING ISN'T HARD
Writing proper code is hard
The harder it is to use the code in question, the harder is writing tests
for it
Complex tests mean that the code is to complex. Break it down.
If anything: Mocking is hard(-ish).
Phake is your friend:
http://phake.digitalsandwich.com/docs/html/
FBMock: Mocking for grown ups:
https://github.com/facebook/FBMock
The PHPUnit mocking API is still good enough.
CODING GUIDELINES
A collection for formatting and structure rules so that everyone can
easily find their way around and produce uniform code.
Just create the rule set fitting your practices
Adapt when there is pain
Don't over analyze. Just do it
PHP CodeSniffer:
http://pear.php.net/package/PHP_CodeSniffer
http://pear.php.net/manual/en/package.php.php-
codesniffer.annotated-ruleset.php
http://edorian.github.io/php-coding-standard-generator/#phpcs
COMPLEXITYGUIDELINES
Similar to a coding standard but focusing on hunting down potential
problems within your source code
Possible bugs
Suboptimal code
Overcomplicated expressions
Unused parameters, methods, properties
PHP MessDetector
http://phpmd.org/
http://phpmd.org/rules/
http://edorian.github.io/php-coding-standard-generator/#phpmd
CODE
Rules for structuring our source code that have proven to help with
sustainability.
THE MOST BASIC THING:
Separate the web-glue from the business logic.
Keep templates stupid
Have services owning the logic for manipulation of business entities
Hide the data access behind a layer that you can maintain
individually
SOLID
Single responsibility
Open-closed
Liskov substitution
Interface segregation
Dependency inversion
http://en.wikipedia.org/wiki/SOLID design)
COMPOSITION OVER INHERITANCE
Don't inherit from things if you can just use them.
http://c2.com/cgi/wiki?CompositionInsteadOfInheritance
http://en.wikipedia.org/wiki/Composition_over_inheritance
DEPENDENCYINJECTION
This goes for you code base as well as for your whole Company.
Allows for quick and easy reuse of small components
If wiring is to hard people will copy/paste instead
Can be achieved in many ways. Pick one that works for you
http://pimple.sensiolabs.org/
http://symfony.com/doc/current/components/dependency_injection/index.h
https://github.com/researchgate/injektor
REUSING CODE
The dependency manager for PHP
As easy as committing everything to your SCM.
But with care free autoloading and updates!
CODE EXAMPLES!
What to focus on?
—Phil Karlton
NAMING
A good name tells you everything you need to know!
class User {
public function getId() {…}
public function getName() {…}
/**
* Calculate Body-Mass-Index
* @link ...wikipedia...
* @return float
*/
public function getBMI() {…}
/**
* @param float $kg Weight in kilogramms
*/
public function setWeight($kg) {…}
}
YOU SHOULDN'T NEED COMMENTS
Names are documentation
class User {
public function getUserId() {…}
public function getFirst/Last/Full/DisplayName() {…}
/**
* @return float
*/
public function getBodyMassIndex() {…}
/**
* @param float $kilogramm
*/
public function setWeight($kilogramms) {…}
}
ANOTHER ONE
class Calendar {
public function getMonth($shortened = false) {…}
}
class Calendar {
public function getMonthNames() {…}
public function getShortendMonthNames {…}
}
NAMES ARE GUIDES
Descriptive names communicate intent
They enable us to understand what's up
Misleading names can make it nearly impossible to navigate in a code
base
It is easy to write code that a machine understands.
Writing code that another human can understand is A LOT harder.
CLASSY CLASS NAMES
A class name is the single most important definition of what behavior
fits into that class
Using generic names throws that away!
ApplicationManager, FrameworkDataInformationProvider,
UtilityDataProcessor
ONE CLASS, ONE PURPOSE
Name it after its purpose
There should be only one reason to change a class
A good class names makes inappropriate methods stand out
Do we ask your customers how much they owe us or do we keep track
of that?
$customer->getStoreDiscount(); // ?
$customerManager->getStoreDiscount(); // ?
$discountService->calculateDiscountForCustomer($customer); // ?
SMALLER MORE FOCUSED CLASSES
Should we let our Email class figure out attachment mime types?
By always asking if stuff fits we can "discover" new classes in our
applications
EmailAttachment, EmailImageAttachment?
WHY DO WE CARE AGAIN
Big inflexible classes rob us of all the OOP benefits
Lots of dependencies
Harder to maintain
Harder to reuse
Swapping out a piece of the behavior gets way more complex
INTERFACES ARE FOR THE CONSUMER
interface Logger {
public function log($logMessage);
public function setOutputFormat($format);
public function activate();
public function deactivate();
public function flush();
public function setIncludeTimestamp($format);
public function addLogger(Logger $logger);
}
ONLY PUT IN THERE WHAT USERS NEED
interface Logger {
public function log($message);
}
FUNCTION NAMING
Centralize implementation but exposing questions, not state
$status = $user->getStatus();
if ($status == $user::STATUS_BANNED) {
}
if ($user->isBanned()) {
}
DON'T USE BOOLEANS AS PARAMETERS EITHER
$user->setAdminStatus(false);
$user->setAdminStatus(true);
$user->revokeAdminRights();
$user->grantAdminRights();
FUNCTION LENGTH
Do you like reading functions that are:
100 lines?
20 lines?
7 lines?
Functions tend to get big quickly because it's very easy to write for that
one current specialized use case.
LONG FUNCTIONS
Local variables and code that operates on them? :)
public function log($message) {
$log = '';
$errors = array();
$log .= PHP_EOL . date('Y-m-d H:i:s') . ': ';
if (!$message) {
$errrors[] = 'No Message';
} else {
$log .= $message;
}
if ($fp = !fopen(ERROR_LOG, 'w')) {
$errors[] = 'Error log issue'
}
if (!$fp || !fwrite($this->log)) {
$errors[] = 'Write Error';
}
return $errros;
}
ARRAYS
Arrays are great ad-hoc data structures but hard to read and maintain
$monthlyUsers = array(124334, 123234141, // ...
$monthlyUsers = array(1 => 124334, 2 => 123234141, // ...
$monthlyUsers = array('jan' => 124334, 'feb' => 123234141, // ...
VALUE OBJECTS
class MonthlyValues implements IteratorAggregate {
protected $values = array();
public function __construct(array $values) {
if(count($values) != 12) {
thrown new InvalidArgumentException('...');
}
$this->values = $values;
}
/**
* @param monthNumber See: Month::JANUARY ...
*/
public function getValueFor($monthNumber) {
// error handling...
return $this->values[$monthNumber];
}
public function getIterator() {
return $this->values;
}
}
THANK YOU!
QUESTIONS?
GET IN TOUCH
stackoverflow:
Twitter: @_ _edorian
G+ / Xing: Volker Dusch
IRC (freenode): edorian
Mail: php@wallbash.com
Save time by applying clean code principles

More Related Content

What's hot

C# coding standards, good programming principles & refactoring
C# coding standards, good programming principles & refactoringC# coding standards, good programming principles & refactoring
C# coding standards, good programming principles & refactoringEyob Lube
 
Clean code & design patterns
Clean code & design patternsClean code & design patterns
Clean code & design patternsPascal Larocque
 
Coding Standards & Best Practices for iOS/C#
Coding Standards & Best Practices for iOS/C#Coding Standards & Best Practices for iOS/C#
Coding Standards & Best Practices for iOS/C#Asim Rais Siddiqui
 
10 Ways To Improve Your Code( Neal Ford)
10  Ways To  Improve  Your  Code( Neal  Ford)10  Ways To  Improve  Your  Code( Neal  Ford)
10 Ways To Improve Your Code( Neal Ford)guestebde
 
Coding Best Practices
Coding Best PracticesCoding Best Practices
Coding Best Practicesmh_azad
 
Seven Ineffective Coding Habits of Many Programmers
Seven Ineffective Coding Habits of Many ProgrammersSeven Ineffective Coding Habits of Many Programmers
Seven Ineffective Coding Habits of Many ProgrammersKevlin Henney
 
Writing clean code in C# and .NET
Writing clean code in C# and .NETWriting clean code in C# and .NET
Writing clean code in C# and .NETDror Helper
 
Coding standards for java
Coding standards for javaCoding standards for java
Coding standards for javamaheshm1206
 
Driving Design with PhpSpec
Driving Design with PhpSpecDriving Design with PhpSpec
Driving Design with PhpSpecCiaranMcNulty
 
New Ideas for Old Code - Greach
New Ideas for Old Code - GreachNew Ideas for Old Code - Greach
New Ideas for Old Code - GreachHamletDRC
 
Agile 2012 Simple Design Applied
Agile 2012 Simple Design AppliedAgile 2012 Simple Design Applied
Agile 2012 Simple Design AppliedDeclan Whelan
 
The Art of Clean code
The Art of Clean codeThe Art of Clean code
The Art of Clean codeVictor Rentea
 
Dependency Injection for PHP
Dependency Injection for PHPDependency Injection for PHP
Dependency Injection for PHPmtoppa
 
Douglas Crockford Presentation Goodparts
Douglas Crockford Presentation GoodpartsDouglas Crockford Presentation Goodparts
Douglas Crockford Presentation GoodpartsAjax Experience 2009
 
Commenting Best Practices
Commenting Best PracticesCommenting Best Practices
Commenting Best Practicesmh_azad
 

What's hot (20)

C# coding standards, good programming principles & refactoring
C# coding standards, good programming principles & refactoringC# coding standards, good programming principles & refactoring
C# coding standards, good programming principles & refactoring
 
Clean code & design patterns
Clean code & design patternsClean code & design patterns
Clean code & design patterns
 
Coding Standards & Best Practices for iOS/C#
Coding Standards & Best Practices for iOS/C#Coding Standards & Best Practices for iOS/C#
Coding Standards & Best Practices for iOS/C#
 
10 Ways To Improve Your Code( Neal Ford)
10  Ways To  Improve  Your  Code( Neal  Ford)10  Ways To  Improve  Your  Code( Neal  Ford)
10 Ways To Improve Your Code( Neal Ford)
 
Clean Code 2
Clean Code 2Clean Code 2
Clean Code 2
 
Code Smells
Code SmellsCode Smells
Code Smells
 
Coding Best Practices
Coding Best PracticesCoding Best Practices
Coding Best Practices
 
Seven Ineffective Coding Habits of Many Programmers
Seven Ineffective Coding Habits of Many ProgrammersSeven Ineffective Coding Habits of Many Programmers
Seven Ineffective Coding Habits of Many Programmers
 
Writing clean code in C# and .NET
Writing clean code in C# and .NETWriting clean code in C# and .NET
Writing clean code in C# and .NET
 
Coding standards for java
Coding standards for javaCoding standards for java
Coding standards for java
 
Driving Design with PhpSpec
Driving Design with PhpSpecDriving Design with PhpSpec
Driving Design with PhpSpec
 
New Ideas for Old Code - Greach
New Ideas for Old Code - GreachNew Ideas for Old Code - Greach
New Ideas for Old Code - Greach
 
Agile 2012 Simple Design Applied
Agile 2012 Simple Design AppliedAgile 2012 Simple Design Applied
Agile 2012 Simple Design Applied
 
Exceptional Naming
Exceptional NamingExceptional Naming
Exceptional Naming
 
The Art of Clean code
The Art of Clean codeThe Art of Clean code
The Art of Clean code
 
Simple Design
Simple DesignSimple Design
Simple Design
 
Dependency Injection for PHP
Dependency Injection for PHPDependency Injection for PHP
Dependency Injection for PHP
 
What's in a name
What's in a nameWhat's in a name
What's in a name
 
Douglas Crockford Presentation Goodparts
Douglas Crockford Presentation GoodpartsDouglas Crockford Presentation Goodparts
Douglas Crockford Presentation Goodparts
 
Commenting Best Practices
Commenting Best PracticesCommenting Best Practices
Commenting Best Practices
 

Viewers also liked

компьютерная мышь
компьютерная мышькомпьютерная мышь
компьютерная мышьyolkina548
 
Implementing and using employee self-service software
Implementing and using employee self-service softwareImplementing and using employee self-service software
Implementing and using employee self-service softwareSoftworld
 
What to look for in a hosted supplier
What to look for in a hosted supplierWhat to look for in a hosted supplier
What to look for in a hosted supplierSoftworld
 
One Liberty Plaza Av Trng
One Liberty Plaza Av TrngOne Liberty Plaza Av Trng
One Liberty Plaza Av TrngChris_Moore
 
компьютерная мышь
компьютерная мышькомпьютерная мышь
компьютерная мышьyolkina548
 
презентация1
презентация1презентация1
презентация1yolkina548
 
2118 F I N A L With Bg 2
2118  F I N A L With Bg 22118  F I N A L With Bg 2
2118 F I N A L With Bg 22118tibet
 
Save time, reduce risk and improve quality: How online accounting adds value
Save time, reduce risk and improve quality: How online accounting adds valueSave time, reduce risk and improve quality: How online accounting adds value
Save time, reduce risk and improve quality: How online accounting adds valueSoftworld
 
танцевальная студия
танцевальная студиятанцевальная студия
танцевальная студияokorkus
 

Viewers also liked (20)

Wordpress install setup
Wordpress install setupWordpress install setup
Wordpress install setup
 
компьютерная мышь
компьютерная мышькомпьютерная мышь
компьютерная мышь
 
Naomi bills
Naomi billsNaomi bills
Naomi bills
 
Implementing and using employee self-service software
Implementing and using employee self-service softwareImplementing and using employee self-service software
Implementing and using employee self-service software
 
Online distance PG Diploma courses from MIT Pune
Online distance PG Diploma courses from MIT PuneOnline distance PG Diploma courses from MIT Pune
Online distance PG Diploma courses from MIT Pune
 
What to look for in a hosted supplier
What to look for in a hosted supplierWhat to look for in a hosted supplier
What to look for in a hosted supplier
 
One Liberty Plaza Av Trng
One Liberty Plaza Av TrngOne Liberty Plaza Av Trng
One Liberty Plaza Av Trng
 
компьютерная мышь
компьютерная мышькомпьютерная мышь
компьютерная мышь
 
Audrey rose
Audrey roseAudrey rose
Audrey rose
 
презентация1
презентация1презентация1
презентация1
 
Katie. c
Katie. cKatie. c
Katie. c
 
2118 F I N A L With Bg 2
2118  F I N A L With Bg 22118  F I N A L With Bg 2
2118 F I N A L With Bg 2
 
Save time, reduce risk and improve quality: How online accounting adds value
Save time, reduce risk and improve quality: How online accounting adds valueSave time, reduce risk and improve quality: How online accounting adds value
Save time, reduce risk and improve quality: How online accounting adds value
 
Triptico
TripticoTriptico
Triptico
 
Enfermedad de chagas
Enfermedad de chagasEnfermedad de chagas
Enfermedad de chagas
 
Comic
ComicComic
Comic
 
танцевальная студия
танцевальная студиятанцевальная студия
танцевальная студия
 
Mit pune e prospectus
Mit pune e prospectusMit pune e prospectus
Mit pune e prospectus
 
Distance Learning P G D B A From M I T Pune
Distance Learning  P G D B A From  M I T  PuneDistance Learning  P G D B A From  M I T  Pune
Distance Learning P G D B A From M I T Pune
 
Sydney h
Sydney hSydney h
Sydney h
 

Similar to Save time by applying clean code principles

Joomla! Day Chicago 2011 Presentation - Steven Pignataro
Joomla! Day Chicago 2011 Presentation - Steven PignataroJoomla! Day Chicago 2011 Presentation - Steven Pignataro
Joomla! Day Chicago 2011 Presentation - Steven PignataroSteven Pignataro
 
Building Large Scale PHP Web Applications with Laravel 4
Building Large Scale PHP Web Applications with Laravel 4Building Large Scale PHP Web Applications with Laravel 4
Building Large Scale PHP Web Applications with Laravel 4Darwin Biler
 
Catalyst - refactor large apps with it and have fun!
Catalyst - refactor large apps with it and have fun!Catalyst - refactor large apps with it and have fun!
Catalyst - refactor large apps with it and have fun!mold
 
Product! - The road to production deployment
Product! - The road to production deploymentProduct! - The road to production deployment
Product! - The road to production deploymentFilippo Zanella
 
Best Practices For Drupal Developers By Mir Nazim @ Drupal Camp India 2008
Best Practices For Drupal Developers By Mir Nazim @ Drupal Camp India 2008Best Practices For Drupal Developers By Mir Nazim @ Drupal Camp India 2008
Best Practices For Drupal Developers By Mir Nazim @ Drupal Camp India 2008Mir Nazim
 
Starting with PHP and Web devepolment
Starting with PHP and Web devepolmentStarting with PHP and Web devepolment
Starting with PHP and Web devepolmentRajib Ahmed
 
Become Jythonic in FDMEE (KSCOPE15)
Become Jythonic in FDMEE (KSCOPE15)Become Jythonic in FDMEE (KSCOPE15)
Become Jythonic in FDMEE (KSCOPE15)Francisco Amores
 
Introduction to Using PHP & MVC Frameworks
Introduction to Using PHP & MVC FrameworksIntroduction to Using PHP & MVC Frameworks
Introduction to Using PHP & MVC FrameworksGerald Krishnan
 
Code Quality Practice and Tools
Code Quality Practice and ToolsCode Quality Practice and Tools
Code Quality Practice and ToolsBob Paulin
 
Agile development with Ruby
Agile development with RubyAgile development with Ruby
Agile development with Rubykhelll
 
Drupal Best Practices
Drupal Best PracticesDrupal Best Practices
Drupal Best Practicesmanugoel2003
 
CICONF 2012 - Don't Make Me Read Your Mind
CICONF 2012 - Don't Make Me Read Your MindCICONF 2012 - Don't Make Me Read Your Mind
CICONF 2012 - Don't Make Me Read Your Mindciconf
 
Behavior & Specification Driven Development in PHP - #OpenWest
Behavior & Specification Driven Development in PHP - #OpenWestBehavior & Specification Driven Development in PHP - #OpenWest
Behavior & Specification Driven Development in PHP - #OpenWestJoshua Warren
 
Develop High Performance Windows 8 Application with HTML5 and JavaScriptHigh ...
Develop High Performance Windows 8 Application with HTML5 and JavaScriptHigh ...Develop High Performance Windows 8 Application with HTML5 and JavaScriptHigh ...
Develop High Performance Windows 8 Application with HTML5 and JavaScriptHigh ...Doris Chen
 
MWLUG 2014: ATLUG Comes To You
MWLUG 2014: ATLUG Comes To YouMWLUG 2014: ATLUG Comes To You
MWLUG 2014: ATLUG Comes To YouPeter Presnell
 
SoTWLG Intro to Code Bootcamps 2016 (Roger Nesbitt)
SoTWLG Intro to Code Bootcamps 2016 (Roger Nesbitt)SoTWLG Intro to Code Bootcamps 2016 (Roger Nesbitt)
SoTWLG Intro to Code Bootcamps 2016 (Roger Nesbitt)ruthmcdavitt
 

Similar to Save time by applying clean code principles (20)

Joomla! Day Chicago 2011 Presentation - Steven Pignataro
Joomla! Day Chicago 2011 Presentation - Steven PignataroJoomla! Day Chicago 2011 Presentation - Steven Pignataro
Joomla! Day Chicago 2011 Presentation - Steven Pignataro
 
Building Large Scale PHP Web Applications with Laravel 4
Building Large Scale PHP Web Applications with Laravel 4Building Large Scale PHP Web Applications with Laravel 4
Building Large Scale PHP Web Applications with Laravel 4
 
Dutch PHP Conference 2013: Distilled
Dutch PHP Conference 2013: DistilledDutch PHP Conference 2013: Distilled
Dutch PHP Conference 2013: Distilled
 
Tdd is not about testing
Tdd is not about testingTdd is not about testing
Tdd is not about testing
 
Catalyst - refactor large apps with it and have fun!
Catalyst - refactor large apps with it and have fun!Catalyst - refactor large apps with it and have fun!
Catalyst - refactor large apps with it and have fun!
 
Product! - The road to production deployment
Product! - The road to production deploymentProduct! - The road to production deployment
Product! - The road to production deployment
 
Best Practices For Drupal Developers By Mir Nazim @ Drupal Camp India 2008
Best Practices For Drupal Developers By Mir Nazim @ Drupal Camp India 2008Best Practices For Drupal Developers By Mir Nazim @ Drupal Camp India 2008
Best Practices For Drupal Developers By Mir Nazim @ Drupal Camp India 2008
 
Starting with PHP and Web devepolment
Starting with PHP and Web devepolmentStarting with PHP and Web devepolment
Starting with PHP and Web devepolment
 
Become Jythonic in FDMEE (KSCOPE15)
Become Jythonic in FDMEE (KSCOPE15)Become Jythonic in FDMEE (KSCOPE15)
Become Jythonic in FDMEE (KSCOPE15)
 
Introduction to Using PHP & MVC Frameworks
Introduction to Using PHP & MVC FrameworksIntroduction to Using PHP & MVC Frameworks
Introduction to Using PHP & MVC Frameworks
 
Code Quality Practice and Tools
Code Quality Practice and ToolsCode Quality Practice and Tools
Code Quality Practice and Tools
 
Agile development with Ruby
Agile development with RubyAgile development with Ruby
Agile development with Ruby
 
Ruby For Startups
Ruby For StartupsRuby For Startups
Ruby For Startups
 
Drupal Best Practices
Drupal Best PracticesDrupal Best Practices
Drupal Best Practices
 
CICONF 2012 - Don't Make Me Read Your Mind
CICONF 2012 - Don't Make Me Read Your MindCICONF 2012 - Don't Make Me Read Your Mind
CICONF 2012 - Don't Make Me Read Your Mind
 
Behavior & Specification Driven Development in PHP - #OpenWest
Behavior & Specification Driven Development in PHP - #OpenWestBehavior & Specification Driven Development in PHP - #OpenWest
Behavior & Specification Driven Development in PHP - #OpenWest
 
Best practices tekx
Best practices tekxBest practices tekx
Best practices tekx
 
Develop High Performance Windows 8 Application with HTML5 and JavaScriptHigh ...
Develop High Performance Windows 8 Application with HTML5 and JavaScriptHigh ...Develop High Performance Windows 8 Application with HTML5 and JavaScriptHigh ...
Develop High Performance Windows 8 Application with HTML5 and JavaScriptHigh ...
 
MWLUG 2014: ATLUG Comes To You
MWLUG 2014: ATLUG Comes To YouMWLUG 2014: ATLUG Comes To You
MWLUG 2014: ATLUG Comes To You
 
SoTWLG Intro to Code Bootcamps 2016 (Roger Nesbitt)
SoTWLG Intro to Code Bootcamps 2016 (Roger Nesbitt)SoTWLG Intro to Code Bootcamps 2016 (Roger Nesbitt)
SoTWLG Intro to Code Bootcamps 2016 (Roger Nesbitt)
 

More from Edorian

Your (coding) standards matter
Your (coding) standards matterYour (coding) standards matter
Your (coding) standards matterEdorian
 
Nginx - The webserver you might actually like
Nginx - The webserver you might actually likeNginx - The webserver you might actually like
Nginx - The webserver you might actually likeEdorian
 
From dev to ops and beyond - getting it done
From dev to ops and beyond - getting it doneFrom dev to ops and beyond - getting it done
From dev to ops and beyond - getting it doneEdorian
 
Code review in practice
Code review in practiceCode review in practice
Code review in practiceEdorian
 
PhpUnit Best Practices
PhpUnit Best PracticesPhpUnit Best Practices
PhpUnit Best PracticesEdorian
 
Nginx & php fpm - the webserver you might actually like - php usergroup berlin
Nginx & php fpm - the webserver you might actually like - php usergroup berlinNginx & php fpm - the webserver you might actually like - php usergroup berlin
Nginx & php fpm - the webserver you might actually like - php usergroup berlinEdorian
 
Clean code is not the goal - working software is
Clean code is not the goal - working software isClean code is not the goal - working software is
Clean code is not the goal - working software isEdorian
 
The state of PHPUnit
The state of PHPUnitThe state of PHPUnit
The state of PHPUnitEdorian
 
The State of PHPUnit
The State of PHPUnitThe State of PHPUnit
The State of PHPUnitEdorian
 
Nginx The webserver you might actually like
Nginx   The webserver you might actually likeNginx   The webserver you might actually like
Nginx The webserver you might actually likeEdorian
 
The State of PHPUnit
The State of PHPUnitThe State of PHPUnit
The State of PHPUnitEdorian
 
php unconference Europa: Clean code - Stop wasting my time
php unconference Europa: Clean code - Stop wasting my timephp unconference Europa: Clean code - Stop wasting my time
php unconference Europa: Clean code - Stop wasting my timeEdorian
 
Clean Code: Stop wasting my time
Clean Code: Stop wasting my timeClean Code: Stop wasting my time
Clean Code: Stop wasting my timeEdorian
 

More from Edorian (13)

Your (coding) standards matter
Your (coding) standards matterYour (coding) standards matter
Your (coding) standards matter
 
Nginx - The webserver you might actually like
Nginx - The webserver you might actually likeNginx - The webserver you might actually like
Nginx - The webserver you might actually like
 
From dev to ops and beyond - getting it done
From dev to ops and beyond - getting it doneFrom dev to ops and beyond - getting it done
From dev to ops and beyond - getting it done
 
Code review in practice
Code review in practiceCode review in practice
Code review in practice
 
PhpUnit Best Practices
PhpUnit Best PracticesPhpUnit Best Practices
PhpUnit Best Practices
 
Nginx & php fpm - the webserver you might actually like - php usergroup berlin
Nginx & php fpm - the webserver you might actually like - php usergroup berlinNginx & php fpm - the webserver you might actually like - php usergroup berlin
Nginx & php fpm - the webserver you might actually like - php usergroup berlin
 
Clean code is not the goal - working software is
Clean code is not the goal - working software isClean code is not the goal - working software is
Clean code is not the goal - working software is
 
The state of PHPUnit
The state of PHPUnitThe state of PHPUnit
The state of PHPUnit
 
The State of PHPUnit
The State of PHPUnitThe State of PHPUnit
The State of PHPUnit
 
Nginx The webserver you might actually like
Nginx   The webserver you might actually likeNginx   The webserver you might actually like
Nginx The webserver you might actually like
 
The State of PHPUnit
The State of PHPUnitThe State of PHPUnit
The State of PHPUnit
 
php unconference Europa: Clean code - Stop wasting my time
php unconference Europa: Clean code - Stop wasting my timephp unconference Europa: Clean code - Stop wasting my time
php unconference Europa: Clean code - Stop wasting my time
 
Clean Code: Stop wasting my time
Clean Code: Stop wasting my timeClean Code: Stop wasting my time
Clean Code: Stop wasting my time
 

Recently uploaded

The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 

Recently uploaded (20)

The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 

Save time by applying clean code principles

  • 1. SAVE TIME BY APPLYING CLEAN CODE PRINCIPLES
  • 2. ABOUT ME Software Engineer PHP since 11 years CI CleanCode DevOps TDD Shipping Bullet points
  • 3.
  • 4. WORKING FOR ResearchGate gives science back to the people who make it happen. We help researchers build reputation and accelerate scientific progress. On their terms.
  • 5. GET IN TOUCH stackoverflow: Twitter: @_ _edorian G+ / Xing: Volker Dusch IRC (freenode): edorian Mail: php@wallbash.com
  • 7. WE'RE DEVELOPERS Let's start with us! We get paid to do what we love Most of us started because we where fascinated by programming But what is our job?
  • 8. OUR JOB IS TO DELIVER Get things done Give good estimates Ask the right questions Keep doing that Don't slow down Keep our promises
  • 9. THE COST OF HAVING USFOLKSAROUND German numbers, YMMV €, Approximations Salary: ~50k a year 50.000€ / Year adding non-wage labor cost 80.000€ / Year and office space, water, hardware, coffee, plants, cleaning, travels, training 100.000€ / Year Weekends, holidays, vacation, etc: We work 220 days a year. 455€ / day "Classic" 8 hour work day 55 Bucks per Hour! We are expected to contribute over 100.000 Bucks in business value per year!
  • 10. WHAT DO WE SPEND TIME ON? Planning a change Reading the code Acting on that plan Evaluating the outcome GOTO 10
  • 11. OUR CODE LIKE OUR DATA STORAGE It has a read:write ratio of 10:1 ...and our brains are really bad caches!
  • 12. GOALS Cheap writes The ability to adapt our software to new requirements. Cheap reads The ability to understand and reason about our software quickly. Writes require reads There is no UPDATE. All we have is GET and PUT.
  • 13. CHEAP READS Your coworkers will read your code again and again and again Does it take them 2 hours or 5 minutes to understand a module?
  • 14. SO HOW DO WE KEEP IT EASY? CHEAP WRITES! Fear to break something leads to not cleaning up Not cleaning up leads to expensive reads Expensive reads lead to expensive writes So how do we reduce fear of breaking things?
  • 15. TESTING TDD is a pragmatic approach to maintainable code. It's not going to get easier than that ;) It doesn't even have to take longer
  • 16. SHORT TDD INTERMISSION Write unit tests! TDD is just the fastest way, eventually. Tools? You don't need tools to get started! watch –n1 'phpunit'and ¼ of a screen is ALL you need! Aim for 100% test coverage but don't obsess. Test what breaks a lot. Have a fast test suite. Or use --filterif you can't. Writing tests can feel like extra work if you are rethinking an already solved problem. TDD offers a way to first think about the problem, the interface and the interactions and then filling in the details step by step until you are done with the bigger picture.
  • 17. TESTING ISN'T HARD Writing proper code is hard The harder it is to use the code in question, the harder is writing tests for it Complex tests mean that the code is to complex. Break it down. If anything: Mocking is hard(-ish). Phake is your friend: http://phake.digitalsandwich.com/docs/html/ FBMock: Mocking for grown ups: https://github.com/facebook/FBMock The PHPUnit mocking API is still good enough.
  • 18. CODING GUIDELINES A collection for formatting and structure rules so that everyone can easily find their way around and produce uniform code. Just create the rule set fitting your practices Adapt when there is pain Don't over analyze. Just do it PHP CodeSniffer: http://pear.php.net/package/PHP_CodeSniffer http://pear.php.net/manual/en/package.php.php- codesniffer.annotated-ruleset.php http://edorian.github.io/php-coding-standard-generator/#phpcs
  • 19. COMPLEXITYGUIDELINES Similar to a coding standard but focusing on hunting down potential problems within your source code Possible bugs Suboptimal code Overcomplicated expressions Unused parameters, methods, properties PHP MessDetector http://phpmd.org/ http://phpmd.org/rules/ http://edorian.github.io/php-coding-standard-generator/#phpmd
  • 20. CODE Rules for structuring our source code that have proven to help with sustainability.
  • 21. THE MOST BASIC THING: Separate the web-glue from the business logic. Keep templates stupid Have services owning the logic for manipulation of business entities Hide the data access behind a layer that you can maintain individually
  • 22. SOLID Single responsibility Open-closed Liskov substitution Interface segregation Dependency inversion http://en.wikipedia.org/wiki/SOLID design)
  • 23. COMPOSITION OVER INHERITANCE Don't inherit from things if you can just use them. http://c2.com/cgi/wiki?CompositionInsteadOfInheritance http://en.wikipedia.org/wiki/Composition_over_inheritance
  • 24. DEPENDENCYINJECTION This goes for you code base as well as for your whole Company. Allows for quick and easy reuse of small components If wiring is to hard people will copy/paste instead Can be achieved in many ways. Pick one that works for you http://pimple.sensiolabs.org/ http://symfony.com/doc/current/components/dependency_injection/index.h https://github.com/researchgate/injektor
  • 25. REUSING CODE The dependency manager for PHP As easy as committing everything to your SCM. But with care free autoloading and updates!
  • 26. CODE EXAMPLES! What to focus on? —Phil Karlton
  • 27. NAMING A good name tells you everything you need to know! class User { public function getId() {…} public function getName() {…} /** * Calculate Body-Mass-Index * @link ...wikipedia... * @return float */ public function getBMI() {…} /** * @param float $kg Weight in kilogramms */ public function setWeight($kg) {…} }
  • 28. YOU SHOULDN'T NEED COMMENTS Names are documentation class User { public function getUserId() {…} public function getFirst/Last/Full/DisplayName() {…} /** * @return float */ public function getBodyMassIndex() {…} /** * @param float $kilogramm */ public function setWeight($kilogramms) {…} }
  • 29. ANOTHER ONE class Calendar { public function getMonth($shortened = false) {…} } class Calendar { public function getMonthNames() {…} public function getShortendMonthNames {…} }
  • 30. NAMES ARE GUIDES Descriptive names communicate intent They enable us to understand what's up Misleading names can make it nearly impossible to navigate in a code base It is easy to write code that a machine understands. Writing code that another human can understand is A LOT harder.
  • 31. CLASSY CLASS NAMES A class name is the single most important definition of what behavior fits into that class Using generic names throws that away! ApplicationManager, FrameworkDataInformationProvider, UtilityDataProcessor
  • 32. ONE CLASS, ONE PURPOSE Name it after its purpose There should be only one reason to change a class A good class names makes inappropriate methods stand out Do we ask your customers how much they owe us or do we keep track of that? $customer->getStoreDiscount(); // ? $customerManager->getStoreDiscount(); // ? $discountService->calculateDiscountForCustomer($customer); // ?
  • 33. SMALLER MORE FOCUSED CLASSES Should we let our Email class figure out attachment mime types? By always asking if stuff fits we can "discover" new classes in our applications EmailAttachment, EmailImageAttachment?
  • 34. WHY DO WE CARE AGAIN Big inflexible classes rob us of all the OOP benefits Lots of dependencies Harder to maintain Harder to reuse Swapping out a piece of the behavior gets way more complex
  • 35. INTERFACES ARE FOR THE CONSUMER interface Logger { public function log($logMessage); public function setOutputFormat($format); public function activate(); public function deactivate(); public function flush(); public function setIncludeTimestamp($format); public function addLogger(Logger $logger); }
  • 36. ONLY PUT IN THERE WHAT USERS NEED interface Logger { public function log($message); }
  • 37. FUNCTION NAMING Centralize implementation but exposing questions, not state $status = $user->getStatus(); if ($status == $user::STATUS_BANNED) { } if ($user->isBanned()) { }
  • 38. DON'T USE BOOLEANS AS PARAMETERS EITHER $user->setAdminStatus(false); $user->setAdminStatus(true); $user->revokeAdminRights(); $user->grantAdminRights();
  • 39. FUNCTION LENGTH Do you like reading functions that are: 100 lines? 20 lines? 7 lines? Functions tend to get big quickly because it's very easy to write for that one current specialized use case.
  • 40. LONG FUNCTIONS Local variables and code that operates on them? :) public function log($message) { $log = ''; $errors = array(); $log .= PHP_EOL . date('Y-m-d H:i:s') . ': '; if (!$message) { $errrors[] = 'No Message'; } else { $log .= $message; } if ($fp = !fopen(ERROR_LOG, 'w')) { $errors[] = 'Error log issue' } if (!$fp || !fwrite($this->log)) { $errors[] = 'Write Error'; } return $errros; }
  • 41. ARRAYS Arrays are great ad-hoc data structures but hard to read and maintain $monthlyUsers = array(124334, 123234141, // ... $monthlyUsers = array(1 => 124334, 2 => 123234141, // ... $monthlyUsers = array('jan' => 124334, 'feb' => 123234141, // ...
  • 42. VALUE OBJECTS class MonthlyValues implements IteratorAggregate { protected $values = array(); public function __construct(array $values) { if(count($values) != 12) { thrown new InvalidArgumentException('...'); } $this->values = $values; } /** * @param monthNumber See: Month::JANUARY ... */ public function getValueFor($monthNumber) { // error handling... return $this->values[$monthNumber]; } public function getIterator() { return $this->values; } }
  • 44. QUESTIONS? GET IN TOUCH stackoverflow: Twitter: @_ _edorian G+ / Xing: Volker Dusch IRC (freenode): edorian Mail: php@wallbash.com