[Ненормальное программирование, Программирование, Совершенный код] Dark code-style academy: line breaks, spacing, and indentation
Автор
Сообщение
news_bot ®
Стаж: 6 лет 9 месяцев
Сообщений: 27286
Hey guys! Let me walk you through the next part of our dark-style code academy. In this post, we will discover some other ways how to slow down the reading speed of your code. The next approaches will help you to decrease maintenance and increase a chance to get a bug in your code. Ready? Let's get started.Line breaks, spacing, and indentation may killHow do people read books? From up to bottom, from left to right (at least majority). The same happens when developers read code. One line should give only one thought, therefore every line should match only one command. If you want to confuse other developers you'd better violate those principles. And I will show you how. Case #1Look at this piece of code. One idea per line. It is so clean so it makes me sick.
return elements
.Where(element => !element.Disabled)
.OrderBy(element => element.UpdatedAt)
.GroupBy(element => element.Type)
.Select(@group => @group.First());
We can join all statements into one line, but it's going to be too easy. In this way, the developer's brain will understand that something is wrong and will parse your statements from left to right. Easy-peasy! The better way is to leave a couple of statements per one line and some on own separate one. The best scenario is when a developer might not even notice some statements which will lead to misunderstanding and to a bug eventually. In another way, we will just slow down his understanding of this code due to the parsing and "WTF" screaming.
return elements.Where(e => !e.Disabled)
.OrderBy(e => e.UpdatedAt).GroupBy(e => e.Type)
.Select(g => g.First());
How cool is that? You can add some indentation so other developers will be aligning your code for decades if they need to rename elements variable.
return elements.Where(e => !e.Disabled)
.OrderBy(e => e.UpdatedAt).GroupBy(e => e.Type)
.Select(g => g.First());
Send me a postcard if this approach passed code review in your team.
Lesson: Leave a couple of statements per one line and someplace on their own lines.
Case #2Absolutely the same idea here. But this code you can see more often.
var result =
(condition1 && condition2) ||
condition3 ||
(condition4 && condition5);
Action items are the same as well. Split lines to confuse as much as you can. Play a little with line breaks to choose the best option.
var result = (condition1 && condition2) || condition3 ||
(condition4 && condition5);
And plus some indentation to make it like normal code.
var result = (condition1 && condition2) || condition3 ||
(condition4 && condition5);
Remember, you have to keep a balance between the unreadability of your code and the believability of your excuse.
Lesson: Play with line breaks to choose the best option.
Case #3What about this one?
if (isValid)
{
_unitOfWork.Save();
return true;
}
else
{
return false;
}
Same problem but in another shade. Here is the best way to join all statements into one line and, of course, leave curly braces.
if (isValid) { _unitOfWork.Save(); return true; } else { return false; }
This approach will work only in case you don't have many statements in then and else blocks. Otherwise, your code may be rejected on the code-review stage.
Lesson: Join small if/for/foreach statements into one line.
Case #480 characters per line is a standard which is preferable even today. This allows you to keep a developer concentrated while reading your code. Moreover, you can open two documents simultaneously per one screen when you need and there is a place left for your solution explorer.
bool IsProductValid(
ComplexProduct complexProduct,
bool hasAllRequiredElements,
ValidationSettings validationSettings)
{
// code
}
The easiest way to slow down reading your code is to let other developers scrolling your code horizontally. Just ignore the rule of 80 characters.
bool IsProductValid(ComplexProduct complexProduct, bool hasAllRequiredElements, ValidationSettings validationSettings)
{
// code
}
It is super easy to forget what was before you start scrolling or miss the line where you have started. Nice trick.
Lesson: Ignore the rule of 80 characters on purpose.
Case #5An empty line in the right place is a powerful instrument to group your code up and increase reading speed.
ValidateAndThrow(product);
product.UpdatedBy = _currentUser;
product.UpdatedAt = DateTime.UtcNow;
product.DisplayStatus = DisplayStatus.New;
_unitOfWork.Products.Add(product);
_unitOfWork.Save();
return product.Key;
An empty line in the wrong place along with other tips from these lessons may help you to save your job. Which empty line do you prefer?
ValidateAndThrow(product);
product.UpdatedBy = _currentUser;
product.UpdatedAt = DateTime.UtcNow;
product.DisplayStatus = DisplayStatus.New;
_unitOfWork.Products.Add(product);
_unitOfWork.Save();
return product.Key;
Lesson: Place empty lines randomly.
Case #6When you commit your code to a repository, there is a teeny-tiny possibility that you can take a look at what you are committing. DONT DO THIS! It is ok if you added an extra empty line like this.
private Product Get(string key)
{
// code
}
private void Save(Product product)
{
// code
}
Or, which is better, some extra spaces on the empty line here (just select line 5).
private Product Get(string key)
{
// code
}
private void Save(Product product)
{
// code
}
Why do you need it? The code is still working (but that's not for sure). You still understand your code. Another developer will understand your code less. You can' just add some extra spaces overall methods at once in your project (code review is our enemy), but using this practice you will get some mess in a couple of weeks of active development. One additional benefit from using extra spaces per line is that when other developers will commit some related functionality, their IDE may automatically fix file formatting. On code review, they will see thousands of same red and green lines. If you know what I mean ;)For this reason, you can set up tabs on your IDE if you have spaces on your project and vice versa.
Lesson: Do not look at the code before commit.
Case #7Bypass those developers who can see extra space in this code. They are dangerous for your career.
product.Name = model.Name;
product.Price = model.Price;
product.Count = model.Count;
Lesson: Know your enemy.
Hard work will make your code unmaintainable. When you gather lots of small issues then they will be growing without your input. Junior developers will be writing their code by your template. Once, on a wonderful day, during your code review, you will hear "WFT?" from your team lead and you will get an opportunity to use the famous phrase: "What? We always do like this." And then you can point him to a thousand places like this one. Enjoy.
===========
Источник:
habr.com
===========
Похожие новости:
- [Разработка веб-сайтов, JavaScript, Программирование] Рецепты по приготовлению оффлайн-приложений (перевод)
- [Программирование, Проектирование и рефакторинг, Профессиональная литература, Читальный зал] Заметки по книге «Философия разработки ПО»
- [Программирование микроконтроллеров] Еще немного RISC-V
- [JavaScript, ReactJS, Карьера в IT-индустрии, Программирование] Вопросы, которые мне задавали на фронтенд-собеседованиях (перевод)
- [Python, Программирование] Напишем и поймем Decision Tree на Python с нуля! Часть 1. Краткий обзор (перевод)
- [TypeScript, ООП, Проектирование и рефакторинг, Совершенный код] Главное — в деталях. Что на самом деле даёт ООП?
- [Программирование, Системы сборки] Make на мыло, redo сила
- [Совершенный код, Проектирование и рефакторинг, UML Design, ООП] Как построить четкие модели классов и получить реальные преимущества от UML (перевод)
- [Анализ и проектирование систем, Программирование] Мама, кажется я архитектор
- [Алгоритмы, Высокая производительность, Математика, Программирование] Динамическая балансировка нагрузки в pull-схеме
Теги для поиска: #_nenormalnoe_programmirovanie (Ненормальное программирование), #_programmirovanie (Программирование), #_sovershennyj_kod (Совершенный код), #_code_style, #_clean_code, #_dark_code_academy, #_fun, #_nenormalnoe_programmirovanie (
Ненормальное программирование
), #_programmirovanie (
Программирование
), #_sovershennyj_kod (
Совершенный код
)
Вы не можете начинать темы
Вы не можете отвечать на сообщения
Вы не можете редактировать свои сообщения
Вы не можете удалять свои сообщения
Вы не можете голосовать в опросах
Вы не можете прикреплять файлы к сообщениям
Вы не можете скачивать файлы
Текущее время: 23-Ноя 00:29
Часовой пояс: UTC + 5
Автор | Сообщение |
---|---|
news_bot ®
Стаж: 6 лет 9 месяцев |
|
Hey guys! Let me walk you through the next part of our dark-style code academy. In this post, we will discover some other ways how to slow down the reading speed of your code. The next approaches will help you to decrease maintenance and increase a chance to get a bug in your code. Ready? Let's get started.Line breaks, spacing, and indentation may killHow do people read books? From up to bottom, from left to right (at least majority). The same happens when developers read code. One line should give only one thought, therefore every line should match only one command. If you want to confuse other developers you'd better violate those principles. And I will show you how. Case #1Look at this piece of code. One idea per line. It is so clean so it makes me sick. return elements
.Where(element => !element.Disabled) .OrderBy(element => element.UpdatedAt) .GroupBy(element => element.Type) .Select(@group => @group.First()); return elements.Where(e => !e.Disabled)
.OrderBy(e => e.UpdatedAt).GroupBy(e => e.Type) .Select(g => g.First()); return elements.Where(e => !e.Disabled)
.OrderBy(e => e.UpdatedAt).GroupBy(e => e.Type) .Select(g => g.First()); Lesson: Leave a couple of statements per one line and someplace on their own lines.
var result =
(condition1 && condition2) || condition3 || (condition4 && condition5); var result = (condition1 && condition2) || condition3 ||
(condition4 && condition5); var result = (condition1 && condition2) || condition3 ||
(condition4 && condition5); Lesson: Play with line breaks to choose the best option.
if (isValid)
{ _unitOfWork.Save(); return true; } else { return false; } if (isValid) { _unitOfWork.Save(); return true; } else { return false; }
Lesson: Join small if/for/foreach statements into one line.
bool IsProductValid(
ComplexProduct complexProduct, bool hasAllRequiredElements, ValidationSettings validationSettings) { // code } bool IsProductValid(ComplexProduct complexProduct, bool hasAllRequiredElements, ValidationSettings validationSettings)
{ // code } Lesson: Ignore the rule of 80 characters on purpose.
ValidateAndThrow(product);
product.UpdatedBy = _currentUser; product.UpdatedAt = DateTime.UtcNow; product.DisplayStatus = DisplayStatus.New; _unitOfWork.Products.Add(product); _unitOfWork.Save(); return product.Key; ValidateAndThrow(product);
product.UpdatedBy = _currentUser; product.UpdatedAt = DateTime.UtcNow; product.DisplayStatus = DisplayStatus.New; _unitOfWork.Products.Add(product); _unitOfWork.Save(); return product.Key; Lesson: Place empty lines randomly.
private Product Get(string key)
{ // code } private void Save(Product product) { // code } private Product Get(string key)
{ // code } private void Save(Product product) { // code } Lesson: Do not look at the code before commit.
product.Name = model.Name;
product.Price = model.Price; product.Count = model.Count; Lesson: Know your enemy.
=========== Источник: habr.com =========== Похожие новости:
Ненормальное программирование ), #_programmirovanie ( Программирование ), #_sovershennyj_kod ( Совершенный код ) |
|
Вы не можете начинать темы
Вы не можете отвечать на сообщения
Вы не можете редактировать свои сообщения
Вы не можете удалять свои сообщения
Вы не можете голосовать в опросах
Вы не можете прикреплять файлы к сообщениям
Вы не можете скачивать файлы
Вы не можете отвечать на сообщения
Вы не можете редактировать свои сообщения
Вы не можете удалять свои сообщения
Вы не можете голосовать в опросах
Вы не можете прикреплять файлы к сообщениям
Вы не можете скачивать файлы
Текущее время: 23-Ноя 00:29
Часовой пояс: UTC + 5