Coding patterns

Version 1

Modify code to make it more readable

Coding patterns contains examples of how to refine your code to be more readable and usable.

Good aim is to write code without comments: If you have to write a comment about what is happening, something smells!!!

Good practice

Good practice is always good: You can aply these in every situation.

Don't abbreviate variable names

$cT = time();

Use descriptive variable names.

$currentTime = time();

Split Temporary Variable

$temp = 100;
print $temp;
$temp = 100 * 200;
print $temp;

Use temp variable for only one purpose:

$length = 100;
print $length;
$area  = 100 * 200;
print $area;

Remove assignments to Arguments

function ($val){
    $val = $val * 2;
}

Don't modify function arguments. If you need to locally modify them, set them to new temp variable.

function ($val){
    $tempVal = $val * 2;
}

Refactorings

Refactorigns are patterns to redefine your code. Most of the patters are reversable: What to use depends on the situation.

Extract Method

// Do something: Comment here to understand what is going on
$my = 'code';
$is = 'here';

Extract a block code of block to its own method. Use method name as 'Comment':

doSomething(){
  $my = 'code';
  $is = 'here';
}

Inline Temp

$var = 100*100*100;
return $var * $otherVar;

Replace Temp with function:

return myTempValue() * $otherVar;

Introduce Explaining Variable

if ( $value > $maxLimit || $value < $minLimit ){ ... }

Replace statements with more readable Temp variable.

$isTooHigh = $value > $maxLimit;
$isTooLow  = $value < $minLimit;
if ( $isTooLow || $isTooHigh ){ ... }