Writing clean code is all about following conventions and standards that are generally understood by others. Imagine writing a program and sharing the source code with other developers out there, they will often go through your code and start scratching their head wondering what the hell this chunk of code does, trying to fix something they break everything else. Writing clean and tidy code is all about not making them tightly coupled(shouldn't depend on each other so badly that it breaks entire program if something's missing), write clean code that a somewhat experienced program should be easier able to read and undnerstand, and finally follow coding standards. I personally follow PSR 0, 1 and 2 standards.
PSR 0 is about auto loading and class names
PSR 1 is basic coding standards
PSR 2 extend and contrinues talking about standards.
Before you start reading PSR standards it's important you know what you must do, what's just a recommendation etc.. generally most standards use certain words what they mean is defined in RFC 2119 document http://www.ietf.org/rfc/rfc2119.txt
Once that read you should start reading the standards starting from 0. It's upto individual needed but those first 3 are must for anyone.
Example(Code must not product side effects, it should either declare class/functions or produce side effects - change variable value, echo something etc), if you're including a file it shouldn't just run and echo stuff on screen and run methods etc.. it should do one or another.
What you shouldn't do:
// side effect: change ini settings
ini_set('error_reporting', E_ALL);
// side effect: loads a file
include "file.php";
// side effect: generates output
echo "<html>\n";
// declaration function foo() {
// function body
}
Declare function is okay but echoing HTML in same file is not. Should only have function declaration in one file and other stuff in another. Upon including the file, your class shouldn't start executing unrelated logic that affects other code on page.
// declaration
function foo()
{
// function body
}
// conditional declaration is *not* a side effect
if (! function_exists('bar')) {
function bar()
{
// function body
}
}
You can read more about accepted PSR standards
https://github.com/php-fig/fig-standards/tree/master/accepted
No comments:
Post a Comment