As you start reading more and more about software development, you often come across the phrase «clean code». In its purest form, it is code that other people can easily read. He is expressive and handsome, and you can easily understand his intentions, just looking at him .

Writing clean code is easier said than done.

tinkerer or you are building a Raspberry Pi applications with Python, or you are even a web developer. There are some useful tips to make your code easier for others to read. Here’s what you need to know .

Be consistent

Perhaps the first and most obvious advice is to be consistent in what you do. A good example of this is using the same patterns when naming functions and variables . You must choose a naming convention and stick to it.

So what naming convention should you use?

Well, if you’re writing Python for the Raspberry Pi, the answer is clear. The PEP-8 standard (the barometer for good, clean Python code) says that variable names must be in lower case, with each word separated by an underscore. For example: gpio_input and humidity_sensor_reading .

cleancode, Arduino

The Arduino style guide implicitly says that you should write your variables in the so-called camel case. Here, the words are not separated by anything, but the first letter of each word is capitalized, except for the first word. For example: button pressed and temperature reading .

There are, of course, other styles for naming variables. The above is simply recommended by the official style guides. But whatever you choose, make sure you stick to it and use the same naming convention throughout your program.

Write meaningful comments

Comments are a great way to explain what your program does. You can specify what each function does and each variable represents in its own words. This makes it easy for a third party to read your code, but it also makes your code easier to maintain as you end up understanding it better.

But if you don’t write your comments in such an obvious and expressive way, you don’t have to worry.

When writing comments, you should try to explain why the code, in addition to how. Try to make the goals very clear and say something about the code that he can’t say himself. So instead of:

  // обновить чтение 

Consider writing:

  // Обновляем количество раз, когда лазерный луч был сломан, прежде чем твитнуть его 

Make sure you write complete, grammatically correct sentences. Also, the PEP-8 standard for Python states that you should always write your comments and variables in English. This makes it easier to collaborate with others if you decide to release your code as open source, as English is pretty much the language of software development.

The Arduino Style Guide goes even further and says that you must comment out every block of code, every for loop, and every variable declaration.

Personally, I think it’s a bit extreme. If you write long, expressive variable names, then your code is already self-documenting. However, feel free to add comments where you think they are needed. Use your own sound judgment.

Simplify your code

When you first learn to design you are often overwhelmed with a huge burst of enthusiasm. You read everything you can about your chosen language, framework, or platform. You start encountering concepts you never knew before and you are too eager to use them in your own code.

Things like ternary operators, which allow you to condense the logic of an «if statement» like this one:

int x = 5; if ( x < 10) { y = 1; { else { y = 0; } 

In one line, like this:

 int x = 5; int y = (x < 10) ? 1 : 0; printf("%i\n", y); 

Ternary operators are cool, of course, and I encourage you to read them. But when you write code that is easy for others to read, they are best avoided. This is just one example.

The Arduino Style Guide also recommends avoiding pointers, #define statements, and non-standard data types: boolean, char, byte, int, unsigned int, long, unsigned long, float, double, string, array, and void. You should avoid data types such as uint8_t as they are less common, not documented, and not very concise.

Indent and take advantage of the space

When it comes to writing clean code, Python users have an advantage, as the standard Python interpreter requires all code to be reasonably structured and indented. If you don't indent every function and class declaration and conditional statement, your program simply won't work.

cleancode-python

On the Arduino, nothing stops you from writing unstructured, concise code. It is ultimately hard to read and hard to maintain.

But nothing prevents you from better structuring your code.

First, set how much you are going to indent. You must use the Tab key wisely, as each text editor handles ASCII code for tabs differently, and if you share your code with someone else, there's a chance they might inadvertently introduce inconsistencies in your indentation. These inconsistencies can break your program, especially if you're using a whitespace-sensitive language like CoffeeScript or Python. This article from OpenSourceHacker explains in more detail why the tab key should be avoided.

cleancode-tab

I usually use four spaces for each indent, but the total is up to you. As long as you are consistent.

However, you can set the IDE and text editor to treat each tab as a certain number of spaces, which allows you to use the tab key without the risk of problems. If you are using Sublime Text 2, check out their official documentation. If you are using Vim just edit your file .vimrc with these lines. The Arduino editor will automatically do this for you and insert two spaces each time you press the Tab key.

Then you just need to know where to indent your code. As a good rule of thumb, you should always indent after every function declaration and after every if , else , for while , switch and case .

Many editors have the ability to insert entire blocks of code at once. If you are using Sublime Text 2, you can set up a combination of hotkeys or keystrokes. Otherwise, you can use the default combination, which (on OS X) is cmd + [ . В редакторе Arduino вы можете автоматически исправить отступы вашего файла, нажав Ctrl + T в Windows и Linux и Cmd + T в OS X.

Это полностью зависит от вашего редактора, так что читайте руководство !

Не повторяй себя

Одна из важнейших мантр хорошей разработки программного обеспечения — не повторять себя , что часто сокращается до СУХОЙ.

Написание DRY-кода невероятно важно, так как оно обеспечивает согласованность логики вашей программы, позволяет вносить изменения в одном месте и отражать их глобально, и вы тратите меньше времени на написание одной и той же вещи снова и снова.

Лучший способ сохранить СУХОЙ заключается в свободном и щедром использовании функций — заключении повторяющейся задачи в блок кода, который вы можете вызывать снова и снова, — и обеспечении того, чтобы каждая из них была четкой и хорошо написанной.

cleancode сухой

Хорошая функция коротка; Руководство PEP-8 мало говорит о длине функций, но « Чистый код: Справочник по гибкому программному мастерству» Боба Мартина (настоятельно рекомендуется) гласит, что «функции вряд ли когда-либо будут иметь длину 20 строк». Желательно, чтобы они были еще короче этого .

Функции также должны делать только одно. Нужна функция, которая делает две вещи? Напишите две функции.

Эти советы позволяют легко следить за ходом программы и, в случае необходимости, отлаживать ее. Есть также дополнительное преимущество для пользователей Arduino, которые жестко ограничены ограничениями хранилища, так как избыточность устранена. Это приводит к меньшим программам.

Быть явным

Другая важная мантра разработки программного обеспечения — «явное лучше, чем неявное» . Это означает, что ваш код должен на первый взгляд кричать о том, что он делает. Руководство по стилю Arduino говорит, что подобной вещи следует избегать:

 if(buttonPressed){ doSomething(); } 

Скорее, вы должны сделать очевидным, что происходит. Вместо этого напишите что-то вроде этого:

 if (buttonPressed == True){ doSomething(); } 

Выйти и код (хорошо)

Написание чистого кода на удивление просто. Вам просто нужно быть последовательным во всем, что вы делаете, избегать избыточностей и быть явным. Помните, что чистый код — это просто код, который можно прочитать.

На эту тему есть много отличных материалов для чтения. Хорошей отправной точкой являются учебник по Arduino и руководства по стилю API , а также стандарт PEP-8, если вы создаете приложения Python для Raspberry Pi. Если вы используете другой язык (например, Javascript на доске Tessel. ), обратитесь к Google за официальным руководством по стилю.

Если вы ищете более академическое прочтение по этому вопросу, ознакомьтесь с « Чистым кодом: справочник Agile Software Craftsmanship» Боба Мартина . Я упоминал об этом ранее в этой статье, и это очень рекомендуется. Хотя он использует Java для иллюстрации концепций, многие идеи могут быть переданы на другие языки, такие как Python и C для Arduino.

Есть также несколько блестящих постов в Интернете, которые иллюстрируют, как написать хороший, описательный, чистый код. Я рекомендую вам прочитать «Чистый высококачественный код: руководство о том, как стать лучшим программистом», написанное Арашом Араби для butterfly.com.au , и «Основы написания чистого кода» Криса Рейнольдса, написанное для webdevstudios. ком .

Хотя это явно не связано с чистым кодом, полезно также узнать, каких функций и библиотек лучше избегать на выбранном вами языке. Например, если вы изучаете PHP, вам следует избегать библиотек «mysql» , а если вы создаете физические продукты с помощью Arduino, вам никогда не следует использовать функцию

Помните, что код, который легче читать, легче поддерживать. Кроме того, если вы когда-нибудь что-то застряли, кому-то будет легче прочитать это и помочь вам.

Есть ли у вас какие-либо советы по написанию чистого кода? Я что-то пропустил? Скажите мне! Оставьте мне комментарий ниже, и дайте мне знать.

Фото: Сухая кровать (Premasagar) , Little TAB Key (Кай Хендри) , 2015 (Wikilogia)

Похожие записи