[转]Clean Code Principles: Be a Better Programmer

原文:https://www.webcodegeeks.com/web-development/clean-code-principles-better-programmer/

-----------------------------------------------------------------

“My code is working well, the website I built is looking great, and my client is happy. So why would I still care about writing clean code?”

If this sounds like you, then read on.

A little while ago, I was having a discussion with one of my friends, Kabir. Kabir is an experienced programmer. He was working on a complex project, and he was discussing a problem with me. When I asked to see the code for that problem, he said, sounding proud, “I built this project so we are the only ones who can understand the code.”

I was pretty horrified. I asked him if he deliberately wrote dirty code.

“The client didn’t give me enough time,” my friend told me. “He is always in a hurry and pushing for deliveries, so I did not have time to think about cleaning it up.”

This is almost always the excuse I hear when I ask about dirty code.

Some programmers write dirty code because they plan to release the first working version and then work to make it clean. But it does not work; no client gives you time to clean code. Once the first version is released, they will push you for the second. So, make it a habit to write code as clean as you can from the first line of code.

I’ve always learned that using clean code principles has many benefits down the line, and this post will show you why.

It is the job of the project manager, sales head, or client to get the project done in minimum time so they can control the cost of the project. But producing quality, clean code is your duty as the programmer.

Writing clean code is not a big or time-consuming task, but making it your routine, and committing to it, will go a long way toward advancing your career and improving your own time management.

Clean code always looks like it was written by someone who cares.

“Any fool can write code that a computer can understand. Good programmers write code that humans can understand.”—Martin Fowler

You’ve probably read this far for two reasons: First, you are a programmer. Second, you want to be a better programmer. Good. We need better programmers.

Keep reading to learn why clean code matters, and you’ll become a better programmer.

Why Should We Strive for Clean Code?

Clean code is readable and easy to understand by everyone whether the reader is the author of the code or a new programmer.

Writing clean code is a necessary mindset. It takes practice to write clean and structured code, and you will learn to do it over time. But you need to start with the mindset of writing this way. And you’ll get used to reviewing and revising your code so it’s the cleanest it can be.

No one is perfect, and so you are not either. You always will find some opportunity to improve or refactor the code when you come back to review your code after a few days or weeks. So, start writing the code as clean as you can from the first line of code so later you can work more on performance and logic improvement.

Benefits of Clean Code

“Why should I care about writing clean code?” you may still be asking yourself.

There are many reasons to get into the clean code mindset I described above. Some of the most important reasons are:

Better Use of Your Time

The first beneficiary of clean code is the programmer themselves. If you are working on a project for months, it’s easy to forget things you did in the code, especially when your client comes back with changes. Clean lines of code make it easier to make changes.

Easier Onboarding for New Team Members

Using clean code principles helps to get a new programmer onboard. There is no need for documentation to understand the code; the new programmer can directly jump into it. This also saves time for both training the new programmer as well as the time it takes for the new programmer to adjust to the project.

Easier Debugging

Whether you write dirty or clean code, bugs are inevitable. But clean code will help you to debug faster, regardless of how much experience or expertise you have.

And it’s not uncommon for your colleagues or managers to help you solve the problem. If you’ve written clean code, no problem: They can jump in and help you out. But if your manager has to work through your dirty code, well, you might end up like my friend Kabir.

More Efficient Maintenance

“Of course bad code can be cleaned up. But it’s very expensive.”
―Robert C. Martin

Maintenance does not refer to bug fixing. As any project grows, it will need new features, or changes to existing features.

Do you know that the major cost of any software project is in maintenance? The company will always release the first version, or minimum viable product (MVP), as early as possible. Additional or new features are always an afterthought as the software gets more use. Clean code makes maintenance relatively fast and easy.

These first three points explain how clean code can save a programmer’s time. And, saving a little time every day will have a compound effect on the delivery time and cost of the software. That’s good for your company.

You’ll Feel Good


Does it help you feel confident to share your work with others, too? Or with your client?
If you’re writing quality, clean code, you should feel super confident. You should not have a fear of breakdown; you can fix defects faster.

And that means you’re also probably enjoying the programming.

Now, how do you write clean code?

How To Write Clean Code

“You should name a variable using the same care with which you name a first-born child.”
―Robert C. Martin, Clean Code: A Handbook of Agile Software Craftsmanship

A programmer is an author, but they might make the mistake in identifying the audience. The audience of a programmer is other programmers, not computers. If computers were the audience, then you might be writing the code in machine language.

So, to make it easy to understand for your audience, you should use meaningful nomenclature for variables, functions, and classes. And make it more readable by using indentation, short method, and short statement, where appropriate:

  • Use easily pronounceable names for variables and methods. Do not use abbreviations in the variable and method names. Use the variable name in full form so it can be easily pronounced and everyone can understand it.
Dirty code examples Clean code examples
public $notiSms;
public $addCmt;
public $notifySms
public $addComment;
foreach ($people as $x) {
echo $x->name;
}
foreach ($people as $person) {
echo $person->name;
}
$user->createUser();
createUser method does not make sense as it is written in user class.
$user->create();
Remove redundancy
  • Use the name to show intention. The purpose of the variable should be understandable to someone reading the name of the variable. Write the name as you would speak it.
Dirty code examples Clean code examples
protected $d; // elapsed time in days protected $elapsedTimeInDays;
protected $daysSinceCreation;
protected $daysSinceModification;
protected $fileAgeInDays;
if (‘paid’ === $application->status) {
//process paid application
}
if ($application->isPaid()) {
//process paid application
}
  • Don’t be innovative; be simple. Show the innovation in logic, not in naming variables or methods. Having a simple name makes it understandable for everyone.
Dirty code example Clean code example
$order->letItGo(); $order->delete();
  • Be consistent. Use one word for similar functions. Don’t use “get” in one class and “fetch” in another.
  • Don’t hesitate to use technical terms in names. Go ahead, use the technical term. Your fellow programmer will understand it. For example, “jobQueue” is better than “jobs.”
  • Use a verb as the first word in method and use a noun for class. Use camelCase for variable and function name. The class should start from the capital.
Dirty code examples Clean code examples
public function priceIncrement() public function increasePrice()
Public
$lengthValidateSubDomain
Public $validateLengthOfSubdomain;
class calculationIncentive class Incentive
  • Use consistent naming conventions. Always use uppercase, and separate words with underscores.
Dirty code example Clean code example
define(‘APIKEY’, ‘123456’); define(‘API_KEY’, ‘123456’);
  • Make functions apparent. Keep a function as short as possible. My ideal length of a method is up to 15 lines. Sometimes it can go longer, but the code should be conceptually clean to understand.
  • Keep arguments to fewer than or equal to three. (If arguments are greater than three, then you must think to refactor the function into a class.)

You should also limit a function or method to a single task. (Avoid using “and” in a method name, like “validateAndSave.” Instead, create two methods, one for validation and another for save).

Indentation is also important. Your clean code must use four spaces for indents, not the tab key. If you’re already in the habit of using the tab key, change your IDE setting to make the tab key denote four spaces as opposed to its usual five.

If your method has more than three indentations, then it’s time to refactor in new methods.

  • Behavior of class and object. One class should do one thing. If it is for the user, then all methods must be written entirely for the user experience.
  • Don’t comment on bad code. If you have to add comments to explain your code, it means you need to refactor your code and create new methods. Comment only if it is legally required or if you need to keep notes on the program’s future or history.
Dirty code example Clean code example
// Check to see if the employee is eligible for full benefits
if ($employee->flags && self::HOURLY_FLAG && $employee->age > 65)
if ($employee->isEligibleForFullBenefits())
  • Use Git for version history. Sometimes, features change and methods need to be rewritten. Usually, we comment out the old code for fear that clients will make a U-turn and request the older version. But if you use the Git version control system, it will keep all versions stored, so there’s no need to keep dead code. Remove it and make your code clean.
  • Avoid working with a large array. Avoid making an array for a large data set; instead, use a class. That make it more readable, not to mention that it creates an additional safety for your application.
  • Do not repeat the code. Every time you write a method, ask yourself if something similar has already been built. Check the code library or other documentation.
  • Don’t hardcode. Define constant or use variables instead of hardcoding the values. Using the variable will not only make it readable but will also make it easy to change if it is being used at multiple places.
Dirty code example Clean code example
if (7 == $today) {
return ‘It is holiday’;
}
const SATURDAY = 7;
if (self::SATURDAY == $today) {
return ‘It is holiday’;
}
  • Make the statement readable. To make the statement readable, keep the line short so you don’t need to scroll horizontally to read the complete line.

Some Other Tips for Cleaner Code


Review your code yourself. Review your code once in a while. I’m sure you’ll find something new to improve on every time you revisit it.

Review your code with your colleagues. Review your colleagues’ codes, and ask them to review yours. Don’t hesitate to consider suggestions.

Every language has its own naming convention. If you are writing for PHP, use PSR-2’s coding style guide.

To increase the quality of the code, you should use the TDD approach and write unit tests. Test-driven development makes code changes easy; you do not need to fear breakdown of the code. If you made any mistakes, the unit test will fail, and you will know what test case failed and what block of code was responsible for that.

Use the Git version control system to collaborate on development. Git becomes an essential tool when multiple programmers are working on a project. Code review becomes easy if you are using a version control system.

For future reading, check out Clean Code, by Robert C. Martin.

Moving Forward to Cleaner Code

Writing clean code has many benefits, and it’s easy to see why.

With these tips, you can be well on your way to writing code that everyone can understand—and that will make life easier for you in the long run.

It will help your colleagues, your team, and your employer as well.

Published on Web Code Geeks with permission by Rakesh Shekhawat, partner at our WCG program. See the original article here: Clean Code Principles: Be a Better Programmer

Opinions expressed by Web Code Geeks contributors are their own.

原文地址:https://www.cnblogs.com/oxspirt/p/9597661.html

时间: 2024-12-18 21:32:29

[转]Clean Code Principles: Be a Better Programmer的相关文章

Writing Clean Code 读后感

最近花了一些时间看了这本书,书名是 <Writing Clean Code ── Microsoft Techniques for Developing Bug-free C Programs> 这里主要总结了一些里面的编程思想. 为空语句加上NULL 当需要使用空语句的时候,最好写上NULL, 比如: if (music_on()) NULL; else turn_it_on(); 参数类型相同的问题 如果函数中两个参数的类型相同,如果用户调用这个函数时错误替换了参数的顺序,就会出现问题.

说说怎么写clean code

前两天参加了公司组织的一个培训,主题是“如何写出好的代码” ,刚看到这个主题,第一反应是又不知道是哪个培训机构来忽悠钱的!老大安排了,就去听听呗. 说实在的,课程内容没有什么新鲜的东西,就是讲讲如何发现代码的坏味道,如何重构函数,如何修改遗留系统的代码.这些东西从本科到研究生到实习到正式工作,也不知道看过多少听过多少了,话说本科的课程设计也和代码重构相关,私底下重构和设计模式方面的书也没少看,感觉应该没啥好培训的,不过两天的课程听完,打心眼里觉得来对了,意犹未尽! 课程结束了,感觉需要把这两天课

Clean Code 读书笔记三

clean code 之方法(函数) - 短小 ,再短小,更短小 20行最佳 只做一件事 准确说来每个方法应该是只做抽象概念上的的一件事 只做一件事的方法是无法把逻辑分段的 自顶向下的代码 To say this differently, we want to be able to read the program as though it were a set of TO paragraphs, each of which is describing the current level of

Building Maintainable Software-java篇之 Write Clean Code

Building Maintainable Software-java篇之 Write Clean Code Writing clean code is what you must do in order to call yourself a professional. -Robert C. Martin Guideline: ? Write clean code. ? Do this by not leaving code smells behind after development wor

clean code 读书笔记一

什么是 clean code ? 大神对优雅代码的定义: I like my code to be elegant and efficient. The logic should be straightforward to make it hard for bugs to hide, the dependencies minimal to ease maintenance, error handling complete according to an articulated strategy,

《Clean Code》一书回顾

<Clean Code>一书从翻开至今,已经差不多两个月的时间了,尽管刨去其中的假期,算下来实在是读得有点慢.阅读期间,断断续续的做了不少笔记.之前,每每在读完了一本技术书籍之后,其中的诸多细节会很快的淡忘,最终留下的往往是在阅读时候与自己之前的印象产生极大共鸣的部分,或者在之后实践当中碰巧运用到的一些知识点.所以,根据已往的经验来说,对于一本技术书籍的学习,个人更愿意依照如下两个基本原则来学习: 撷取个人当前认同最深的少数几个知识点,反复进行实践,并在理解之后再扩张到其他的知识点 择期再次阅

《Clean Code》读书笔记——第二周

本周我阅读了<Clean Code>. "神在细节中!",建筑家范德罗如是说.他当然专注于基于宏伟构架之上的永恒建筑形式,他也同样为自己设计的建筑挑选门把手.同样软件开发也是这样,小处见大.在宏伟的建筑作品中,我们也要关注细节的回响.重点便是整理,从而达成Clean.一个很好的例子是对于变量命名,认真对待每个变量名.书中作者说,我们就像一群代码猴子,无视混乱无序,失去代码的真谛.整洁的代码正是迈向编程之美的基础,重要性毋庸置疑. 作者断言,我们永远需要代码.我们可以创造各种

《clean code》讲述代码中的道,而不是术

Clean code 看<clean code>一书,学习高手写出的代码,简单高效的代 1.目标 Bjarne Stroustrup:优雅且高效:直截了当:减少依赖:只做好一件事 Grady booch:简单直接 Dave thomas:可读,可维护,单元测试 Ron Jeffries:不要重复.单一职责,表达力(Expressiveness) 代码的书写,一定程度上体现了编程的思想,编码者的功力,标识出红色的部分我觉得体现了函数式编程,面向对象的思想,需要细细体会 2 命名 2.1 前期统一

-----------------Clean Code《代码整洁之道》--------------------

-----------------------Chapter1:整洁代码---------------------- 1.<C++>程序设计语言作者——C++之父Bjarne Stroustrup 对于整洁代码的定义: 我喜欢优雅和高效的代码.代码逻辑应当直截了当,叫缺陷难以隐藏:经量减少依赖关系,使之便于维护:移居某种分层战略完善错误处理代码:性能调至最优,省的引诱别人做没规矩的优化,搞出一堆混乱来.整洁的代码只做好一件事. 2.Grady Booch,Object Oriented Ana