I
I
Insolent Muzzle2021-07-07 20:29:38
C++ / C#
Insolent Muzzle, 2021-07-07 20:29:38

Which code is correct?

There is a structure

struct Book
{
  std::string name;
  std::string author;
};

Which declaration of its object is correct?
Book cpp {
    "The C++ Programming Language",
    "Бьёрн Страуструп"
};

Or
auto cpp = Book {
    "The C++ Programming Language",
    "Бьёрн Страуструп"
};

Or is it all heresy, and you need to write something differently?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Shatunov, 2021-07-07
@pluffie

Any code written by a person should always be fully understandable by another person when reading. It is important to pay attention to the fact that the code should be clear to the reader simply when reading, and not when running, and, moreover, not when tracing. The reader should be able not to ask questions about the reasons for the existence of the written code.
There are no questions for the first option. Here you can immediately and clearly see the aggregate initialization, because type Bookis aggregate.
There are questions about the second option. What is the purpose of presence autoinstead of explicitly specifying the variable's type? Why did the writer need to specify the type twice, replacing the first indication with auto? What is the purpose of copy-initialization for a given variable? Why did the writer write so hard?
The answers to each question should provide strong evidence that such a code exists.
Clean code does not raise questions from the reader. Clean code does not beg to be erased or urgently refactored. It's nice to work with clean code. Clean code is nice to write. And most importantly, the author is not ashamed of clean code.
But for dirty code, like the second option, the writer should be ashamed, because. the writer steals the time of his employees and from himself in the future with such a code by making him spend this time on reading and understanding what is written.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question