0% found this document useful (0 votes)
35 views

Is The Code Clean and Readable

The document discusses making code clean, readable, and secure. It emphasizes that programmers are authors writing code for other programmers to understand. It provides examples of good and bad practices for variable names, function structure, comments, and conditional statements. Programmers should aim to write code that is intention-revealing, avoids unnecessary complexity, and properly documents functions and classes. The key is writing code that is a pleasure for humans to read, rather than just computers.

Uploaded by

Zulfa VirgoBoy
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views

Is The Code Clean and Readable

The document discusses making code clean, readable, and secure. It emphasizes that programmers are authors writing code for other programmers to understand. It provides examples of good and bad practices for variable names, function structure, comments, and conditional statements. Programmers should aim to write code that is intention-revealing, avoids unnecessary complexity, and properly documents functions and classes. The key is writing code that is a pleasure for humans to read, rather than just computers.

Uploaded by

Zulfa VirgoBoy
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 33

is the Code Clean,

Readable and Secure?


"Some stuff that most programmers always did while coding"

{Arhen Devlops;}

Slides for Komunitas Programmer


Makassar

"Any fool can write code that a computer can understand.


Good programmers write code that humans can
understand."

Martin Fowler

What is clean code and why do


we need it?
Robert Martin in his book Clean Code,
the only valid measurement of code
quality is the number of WTFs per minute.

So, do we care ?!!


Programmers are really authors, and your
target audience is not the computer it is
other programmers (and yourself).

Here we Go!

#Issues1
(Variable and method name)

1.1. Use intention-revealing name


This is bad:
protected $d; // elapsed time in days

This is good:
protected $elapsedTimeInDays;
protected $daysSinceCreation;
protected $daysSinceModification;
protected $fileAgeInDays;

1.2. Use pronounceable name


This is bad:
public $genymdhms;
public $modymdhms;

This is good:
public $generationTimestamp;
public $modificationTimestamp;

1.3. Use namespaces instead of


prefixing names
This is bad:
class Part {
private $m_dsc;
}

This is good:
class Part {
private $description;
}

1.4. Don't be so cute ( -_-')


This is bad:
$program->whack();
This is good:
$program->kill();

1.5. Use verbs for function names and


nouns for classes and attributes
class Product {
private $price;
public function increasePrice($dollarsToAddToPrice)
{
$this->price += $dollarsToAddToPrice;
}
}

#Issues2
(Better Function)

2.1. A function should only do one


thing
function dataProduct{
$method = $_GET['method'];
if($method == 'create'){
Product::create([
"id_product" => $_POST['id'],
"name-product" => $_POST['name'],
"detail_product" => $_POST['detail']
);
}else if($method == 'edit'){
Product::edit([
Blah Blah Blah
);
}

2.2. Less arguments are better


More than three arguments are evil. For example:
function makeCircle($center, $radius);

Is better than
function makeCircle($x, $y, $radius);

2.3. No side effects

Functions must only do what the name suggests and


nothing else.

2.4. Error Handling is one thing


if (Y != 0)
{
result = X/Y;
}
But, If u doing that stuff above in Loop, it will be "Crazy Things" if error occurs.
try
{
result = X/Y;
}
catch (DevideByZeroException zeroEx)
{
//Log Error
}

#Issues3
(Comments)

3.1. Dont comment bad code, rewrite it

3.2. If code is readable you dont need


comments

Ex:
$r = $n / 2;
while ( abs( $r - ($n/$r) ) > $t ) {
$r = 0.5 * ( $r + ($n/$r) );
}
echo

"r = " . $r;

Rewrite it!!
// square root of n with Newton-Raphson approximation
private SquareRootApproximation($n) {
$r = $n / 2;
while ( abs( $r - ($n/$r) ) > $t ) {
$r = 0.5 * ( $r + ($n/$r) );
}
return $r;
}
echo

"r = ". $this->SquareRootApproximation($n);

3.3. Emphasis important points in


comments
For example (1):
// the trim function is very
username // has a trailing space

important,

in

most

cases

the

For example (2):


/* take a look for __autoload() function to learn some stuff with
autoload means */
// This is terrible if we have class in separated folder. Maybe
// take a look for composer autoloader?
spl_autoload_register('autoload');

3.4. Noise comments are bad


For example:
/** The day of the month. */
private $dayOfMonth;

3.5. Always have your PHPDoc


comments
Most IDEs do this automatically, just select the shortcut.
Having doc comments are especially important in PHP because methods dont have argument
and return types. Having doc comments lets us specify argument and return types for
functions.
/**
* Static function for dinamic hashing password
* @param

[string] $algo [the algorithm method (md5, sha1, whirpool, etc)]

* @param

[string] $data [the data to encode]

* @param

[string] $salt [the key]

* @return [string]

[The hashed/salted data]

*/
public static function create($algo, $data, $salt)

#issue4
(Avoid 'shity' code!)

4.1 Avoid unwanted usage of


conditional statements
If ($condition1 == true){
Do Something;
} else {
perform die(); or exit();
}
Same Cases, much better!
if(! $condition){
// display warning message.
die("Invalid statement");
}
Do Something;

4.2 Avoid unwanted html tags in the


PHP code
Compiler, consume much
time!
<?php
echo "<table>";
echo <tr>;
echo <td>;
echo Hai welcome to
php;
echo </td>;
echo </tr>;
echo </table>;
?>

Much Better!
<html>
<body>
<table>
<tr>
<td>
<?php echo
"Hai welcome to php";
?>
</td>
</tr>
</table>
</body>
</html>

4.3 Appropriate use of Looping


codes
For example, instead of:
$res = mysql_query("select * from tbl_products");
for($iC = 0;$iC< mysql_num_rows($res);$iC++){
echo mysql_result($res,$iC);
}

The same can be coded this way, in order to reduce the execution time:
$res = mysql_query("select * from tbl_products");
while($obj = mysql_fetch_object($res)){
echo $obj->column_name1;
}

4.4 Using of case switches


Example of using a series of If
statements:
if($checking_value1==$value){
echo "result1";

The same thing can be expressed in a simpler


way using the switch case, which greatly
reduces the operational time:

switch ($checking_value){
case value1 :

}else if($checking_value2==$value){

echo "result1";

echo "result2";

break;

}else if($checking_value3==$value){
echo "result3";
}else{
echo "result 4";
}

More Suggestion!

OOP vs Sequencial Style!


Use Design Patterns ( MVC is good for starting)
Make your Code Syncronizing with the world. Use Code Style! (Docs it)
Using Any Libraries in the internet.
Build your First Project!!

Programming is an art. Let other programmers


enjoy your code.
{$this->me}

Connect with me!


Rahmat Hidayat Slamet
bitbucket.org/arhen03

[email protected]

www.upanastudio.com

You might also like