Tuesday, July 29, 2008

PHP Coding Ethic

Everyone can be programmer...
But we need to ensure that our coding is easy to be follow up by others...
Okay, maybe you don't care about others, but what if YOU are the one following up other peoples code?
Any nice feeling? i bet ya ;)

Okay, this might be not the only standard way of making things looks nice,
but it is our way of doing things in the company.

---------------------
Bad Coding:
$var1 = 123;
$var2 = "xxxx";
$var3 = true;
Why?
  • Bad Naming:
    - Who would have known the purpose of the variable "var1"?
    - Variable type is difficult to know... especially long piece of codes...
Better Coding:
$iCounter = 123;
$sMsg = "xxxx";
$bCheck = true;
Why?
  • Good naming:
    - $i... indicate variable type of number
    - $iCounter indicate what it is used for..

Its best to have proper naming. We include the starting 1st charactor in our variable naming as the variable type. List of naming:
  • $i... - number
  • $f... - float
  • $s... - string
  • $b... - boolean
  • $m... - mixed type
  • $o... - object
-----------------

Bad Coding:
if($bCheck == true) { $xxx = 1;
echo $xxx; }

foreach($xx as $yy ){
echo $yy; }

echo (($bXx == true) ? (($xxx==1)? "1": (($bYy==$xxx-1)? "true": "false")) : "ok" );
Why?:
  • Bad spacing if($bCheck <-- look too compact
  • Bad curly bracket positining and indent...
  • Too compact formula, look cool!, but it is definitely not easy to debug if problem risest! Even for the developer him/herself!
Better Coding:
if ($bCheck == true)
{
$xxx = 1;
echo $xxx;
}

foreach ($xx as $yy)
{
echo $yy;
}


if ($bXx == true)
{
if ($xxx == 1)
{
echo "1";
}
else
{
if ($bYy==$xx-1)
{
echo "true";
}
else
{
echo "false";
}
}
}
else
{
echo "ok";
}


Why?
  • Easier for reading and debugging
  • More spacing and proper curly bracket positioning


Disclaimer:
Logos and photos used in this tutorial are copyright of their respective owner. The content published above is solely for education purpose. Feel free to close this website if you are not happy here.. :)


No comments: