Clean code: Difference between revisions

From A Technological Wiki
Jump to navigation Jump to search
No edit summary
No edit summary
 
Line 17: Line 17:
}</syntaxhighlight>
}</syntaxhighlight>


== '''Reusability''' ==
== Reusability ==
It is another hallmark of clean code. Code that is modular and decoupled is like a set of versatile Lego blocks. Such blocks can be assembled in myriad ways to build diverse structures. Similarly, functions and modules written with a single, clear responsibility can be combined and recombined to achieve varied functionalities without reinventing the wheel. This not only speeds up the development process but also reduces the chances of introducing errors.
It is another hallmark of clean code. Code that is modular and decoupled is like a set of versatile Lego blocks. Such blocks can be assembled in myriad ways to build diverse structures. Similarly, functions and modules written with a single, clear responsibility can be combined and recombined to achieve varied functionalities without reinventing the wheel. This not only speeds up the development process but also reduces the chances of introducing errors.


Line 42: Line 42:
}</syntaxhighlight>
}</syntaxhighlight>


== '''Refactorability''' ==
== Refactorability ==
It pertains to the ease with which code can be changed or improved. In an ever-evolving tech landscape, software needs are constantly changing. Whether it's due to changing user requirements, new technologies, or unforeseen challenges, the ability to alter code without upheaval is a tremendous asset. Clean code, by its inherent organized and modular nature, can be refactored with minimal friction.
It pertains to the ease with which code can be changed or improved. In an ever-evolving tech landscape, software needs are constantly changing. Whether it's due to changing user requirements, new technologies, or unforeseen challenges, the ability to alter code without upheaval is a tremendous asset. Clean code, by its inherent organized and modular nature, can be refactored with minimal friction.



Latest revision as of 08:45, 20 October 2025

Clean Code: The Art of Writing Readable and Maintainable Software In the realm of software development, the final product is often evaluated by its functionality, efficiency, and user experience. While these aspects are undeniably crucial, the process and craftsmanship behind the scenes, the code, plays an equally vital role in ensuring the software's longevity and adaptability. Clean code stands at the heart of this craftsmanship. But what exactly is clean code, and why is it so pivotal?

Clean code is a concept that goes beyond the mere functionality of code. At its essence, clean code is readable, reusable, and refactorable. It is written by a developer who anticipates the needs of others, be it fellow developers, reviewers, or even their future self, who will interact with, modify, or build upon that code.

Readability

It is paramount. Just as a well-written novel flows seamlessly from one chapter to the next, guiding the reader through its narrative, clean code guides its reader through its logic. It uses meaningful variable and function names, adheres to a consistent style, and is organized in a logical manner. Comments, when used, provide valuable context or explain complex decisions, rather than stating the obvious. The importance of readability cannot be overstated; code is read far more times than it is written. By ensuring clarity, we save countless hours of deciphering, debugging, and deducing.

PHP Example:

# Not Readable:
function p($a, $b){
  return $a + $b;
}
# Readable:
function addTwoNumbers($firstNumber, $secondNumber){
  return $firstNumber + $secondNumber;
}

Reusability

It is another hallmark of clean code. Code that is modular and decoupled is like a set of versatile Lego blocks. Such blocks can be assembled in myriad ways to build diverse structures. Similarly, functions and modules written with a single, clear responsibility can be combined and recombined to achieve varied functionalities without reinventing the wheel. This not only speeds up the development process but also reduces the chances of introducing errors.

PHP Example:

# Not Reusable
function calculateInvoice($price){
  $tax = 0.1 * $price;
  $shipping = 5;
  return $price + $tax + $shipping;
}

# Reusable
function calculateTax($amount){
  return 0.1 * $amount;
}

function calculateShipping(){
  return 5;
}

function calculateInvoice($price){
  return $price + calculateTax($price) + calculateShipping();
}

Refactorability

It pertains to the ease with which code can be changed or improved. In an ever-evolving tech landscape, software needs are constantly changing. Whether it's due to changing user requirements, new technologies, or unforeseen challenges, the ability to alter code without upheaval is a tremendous asset. Clean code, by its inherent organized and modular nature, can be refactored with minimal friction.

PHP Example

# Hard to Refactor
function userRegistration($data){
  // Validation
  if(!isset($data['email']) || !filter_var($data['email'], FILTER_VALIDATE_EMAIL)){
    return &quot;Invalid email.&quot;;
  }

  // Database connection
  $conn = new mysqli('localhost', 'user', 'pass', 'test');
  if ($conn-&gt;connect_error) {
    die(&quot;Connection failed: &quot; . $conn-&gt;connect_error);
  }

  // Inserting user data
  $sql = &quot;INSERT INTO users (email) VALUES ('&quot;.$data['email'].&quot;')&quot;;
  if ($conn-&gt;query($sql) !== TRUE) {
    return &quot;Error: &quot; . $sql . &quot;&lt;br&gt;&quot; . $conn-&gt;error;
  }
  return &quot;User registered successfully.&quot;;
}

# Easier to Refactor
function validateEmail($email){
  return isset($email) &amp;&amp; filter_var($email, FILTER_VALIDATE_EMAIL);
}

function createDatabaseConnection(){
  $conn = new mysqli('localhost', 'user', 'pass', 'test');
  if ($conn-&gt;connect_error) {
    die(&quot;Connection failed: &quot; . $conn-&gt;connect_error);
  }
  return $conn;
}

function insertUser($conn, $email){
  $sql = &quot;INSERT INTO users (email) VALUES ('&quot;.$email.&quot;')&quot;;
  if ($conn-&gt;query($sql) !== TRUE) {
    return false;
  }
  return true;
}

function userRegistration($data){
  if(!validateEmail($data['email'])){
    return &quot;Invalid email.&quot;;
  }

  $conn = createDatabaseConnection();
  if(!insertUser($conn, $data['email'])){
    return &quot;Error while registering user.&quot;;
  }
  return &quot;User registered successfully.&quot;;
}