In the fast-paced world of software development, clarity is key. Whether you're a seasoned developer or just starting your coding journey, you've likely encountered the frustration of trying to decipher someone else's code or even your own after a few months away from a project. This is where self-documenting code comes in. In this article we will dive into different ways we can write meaningful, clear and expressive code, that will reduce the reliance on external documentation, and will not only make life easier for your fellow team-mates but also yourself.
What is Self-Documenting Code ?
Self-documenting code is a practice that emphasizes writing code that's so clear and intuitive that it doesn't require additional comments to explain its functionality. By using meaningful variable names, well-structured functions, and straightforward logic, you can create code that essentially "documents itself." This not only makes your code easier to read and maintain but also enhances collaboration, reduces bugs, and accelerates the onboarding process for new team members. While comments are a good method and a norm in the industry as means of explaining code, a well written piece of code is always going to be superior. Comments can sometime be up for interpretation depending on the complication involved, while code is the ultimate source of truth. The bottom-line being, Code never lies, comments sometimes do.
Why should I write Self-Documenting Code ?
- Enhanced Readability: Code that clearly expresses its purpose is easier to read and understand. This reduces the cognitive load on developers, allowing them to quickly grasp the functionality without needing extensive comments or external documentation.
- Improved Maintenance: As projects grow and evolve, maintaining code can become a daunting task. Self-documenting code simplifies this process by making it easier to identify and fix bugs, implement new features, and refactor existing code.
- Reduced Dependency on Documentation: While documentation is still important, self-documenting code minimizes the reliance on it. This is especially useful when documentation becomes outdated or incomplete, ensuring the codebase remains the primary source of truth.
- Faster Onboarding: New team members can get up to speed more quickly with a codebase that is easy to read and understand. This accelerates the onboarding process and allows new developers to contribute meaningfully in a shorter amount of time.
How to write Self-Documenting Code ?
Creating self-documenting code involves adopting practices that enhance clarity and readability. Here are some key strategies:
Use descriptive variable names:
One of the most important, effective and basic strategy of writing a well self-documented code is paying attention to your variable naming conventions. A variable name that defines the data it is going to store goes a long way in improving readability.
//Bad Practice
$a = 15;
$b = 3;
$c = $a * $b;
//Good Practice
$item_price = 15;
$quantity = 3;
$subtotal = $item_price * $quantity;
Define datatypes:
It is important that your define your datatypes while writing your code this not only makes your code more strict but also helps in understanding what type of data is needed in a scenario.
// Bad Practice
function calculateSubtotal($item_price, $quantity) {
// ....
return $subtotal;
}
// Good Practice
function calculateSubtotal(float $item_price, int $quantity): float {
// ....
return $subtotal;
}
Make focused functions:
Rather than writing one function that contains lines upon lines of heavy logic, break down your code into small bite-sized functions, which are focused on a single part of the process, this will not only increase the readability of your code but will also increase reusability of code.
//Bad Practice
function checkout() {
// .....
// Code with lots of logic
// .....
return $data;
}
//Good Practice
function getCart(int $customer_id): array {
// Code that retrieves cart details
return $cart;
}
function generateBill(array $cart): array {
// Code that generates bill
return $bill;
}
function processPayment(array $bill, array $customer_details): array {
// Code that processes payments
return $result;
}
function sendConfirmationEmail(array $customer_details): boolean {
// Code that sends confirmation email to the customer
return $result;
}
Use descriptive function names:
Along with having focused functions it is important that you name your functions in such a way that it describes exactly what the function is responsible for, this would make it so that you will know what the function is doing even before you read the logic that resides in it.
//Bad Practice
function getData() {
// ....
return $data;
}
//Good Practice
function getCustomerDeatils(): array {
// ....
return $customer_details;
}
Better error messages:
Writing better error messages be it while creating logs or while returning a simple string of error message is very vital to a project and makes it clear to the reader what kind of error would occur for a specific error message to show up.
//Bad Practice
function getCustomerDetails(int $user_id) {
try{
// ....
} catch () {
return "Something went wrong";
}
}
//Good Practice
function processPayment(int $customer_id) {
try{
// ....
} catch () {
return [
'code' => '404',
'message' => 'Error: Customer not found'
];
}
}
Establish consistency:
When working on a codebase that is being worked on by multiple developers its is very important to define coding standards, things like naming conventions for functions, classes and variables. For example:
//PascalCase for Class Name
class PaymentProcessor
{
//camelCase for Function Name
function getCart() {
//snake_case for variables
return $cart_details;
}
}
Similarly it is a good idea to define function naming conventions for example
get: Start your functions with "get" when you are retrieving data (getCart)create: Start your functions with "create" when you are storing data (createBlog)patch: Start your functions with "patch" when you are updating data (patchUser)destroy: Start your functions with "destroy" when you are deleting data (destroyArticle)
Use comments in complex scenarios:
While the idea behind writing Self-Documenting code is to reduce to reliance on comments and documentation, they still are a part of good practice and can not be eliminated, in certain more complex scenarios having comments might be beneficial for a more in depth understanding of what is happening with the code. Tools like PHPDocs, JSDocs and TSDocs can be very useful in such scenarios.
/**
* Concatenate two strings and return them as an array.
*
* @param string $str1 The first string.
* @param string $str2 The second string.
* @return string containing the concatenated strings.
*/
function concatenate_strings($str1, $str2): string {
return $str1 . $str2;
}
Conclusion
In the ever-evolving landscape of software development, the importance of self-documenting code cannot be overstated. By prioritizing clarity, consistency, and conciseness in your codebase, you empower yourself and your team to build projects that are easier to understand, maintain, and extend. Remember, self-documenting code is not just about writing code, it's about fostering a mindset of clarity and communication within your development process. By following the principles outlined in this guide using descriptive names, organizing code logically, and leveraging language features you can create code that speaks for itself. Here's to writing code that not only works but also tells a clear and compelling story. Happy coding!