📜 ⬆️ ⬇️

Parable about programmers and coders

Long ago, in a distant galaxy far away, intelligent mammals lived on the same provincial planet, which recently began the age of information technology. In that century, many had to write programs in different languages ​​for different software platforms. And any descendant of a monkey from this planet who wrote at least a couple of lines of code that made a stupid computing machine do some reasonable (from the point of view of the author) actions, already considered himself an enlightened sage who befell DAO information technology and was called Jedi programmer.

image

Today, dear lovers of the history of the universe, we will try to figure out what the fundamental error of these descendants of human apes is, and what is the difference between programmers and non-programmers, for simplicity, we will call them coders.

The absolute majority of people believe that it does not matter how the result was achieved, if the task seems to be solved. Starting to solve any software development task (and not only), many do not think about the fundamental principles of design, but simply copy the working blocks of their predecessors. The coders, armed with a reference book on the syntax of the language and an Internet search engine, create their own “programming mega-masterpieces”. Quickly forcing the program using the debugger to perform more or less similar to the logical behavior of the actions, the developers give the order. The client is happy, the coder is at the money - everyone is happy at first glance.
')
Further, as a rule, the following happens: quite a bit of time passes and the client wants to change something in his program, and, as a rule, much. The customer addresses either the author of the program or another coder and orders the changes. The contractor looks at the code, and does not understand how this jumble of search engine results works, and begins to painfully rewrite the code, disrupting the deadlines even for "elementary changes". On the second or slightly later revision, the application code becomes so difficult to understand, not manageable and buggy, that it actually becomes easier to rewrite it from scratch, having requested the full budget for the new development from the customer. And here the client finally feels his epic blunder with the choice of performers, since he has to pay for the second development of the application, or hire geniuses for mega money for the simplest changes in the program, although the life of the application has just begun.

Together with the awareness of this situation, we are closer to understanding the fundamental differences between a specialist and a non-specialist in the field of software development. Programmers, unlike coders, understand the fundamental principles of their craft, which allows them to write simple and understandable code that appropriately uses technology as applied to the current task. This simple and clear application code allows the customer to save money, since such code is easy to read and change, both to another programmer and to any coder. An application with a successful architecture and high-quality code can be successfully used and evolved over a considerable period of time, with minimal customer costs for changes and support.

And here the indignant coders complained: “We know all these fundamental principles! They are all useless and stupid! ” And the universe answered them: "Perhaps this is true, but perhaps you do not understand them, and therefore you do not know how to apply."

Take simple code examples using the mega language of PHP web developers that is popular on this provincial planet. The language itself is quite good for its use for its intended purpose, although opinions on this issue usually differ.

Part 1: Simplicity Code


Example 1:

if ($u->g) $u->reg($u->email, $u->nm); 

Just a line of code written by a coder, but what it does is not at all obvious and requires at least comments.
Now the same line of code written by the programmer:

 $user->email = $email; $user->name = $name; if ($user->isGuest) $user->register(); 

I think all questions have disappeared, and comments are no longer needed. And just correctly and unambiguously given the names of variables and functions.

Example 2:

 //… $sql = 'SELECT * FROM usr LIMIT 10'; //… /** view */ if ($n<10) echo ...; 

It seems that the code is more or less clear, although magic constants like 10 are alarming, in addition, the code is found in different files and is often repeated.
How would a programmer write it? Yes something like that:

 class User { const MAX_VIEW_USERS_ON_PAGE = 10; ... ... ... $sqlQuery = 'SELECT * FROM `User` LIMIT '.User::MAX_VIEW_USERS_ON_PAGE; … /** view */ if (count($users) < User::MAX_VIEW_USERS_ON_PAGE) echo ...; 

It became much more convenient to read the code, and the number of users displayed on all pages (10) is now easy to change, since it is used through a named constant, a similar situation with the name of the table in the database.

Example 3:

 if ((isset($user->online) || (time() - $user->lastVisit < User::LOGOUT_TIMEOUT)) && Post::getNumOfPostsForUser($user->id) > Post::ACTIVE_USER_MIN_POSTS) $Raiting::addBonus($user->id, Rating::BONUS_RATING_POINTS); 

It seems that the variables with methods and constants are well-named, but still somehow too difficult to read.

 $userOnline = (isset($user->online) || (time() - $user->lastVisit < User::LOGOUT_TIMEOUT)); $userIsActivePoster = Post::getNumOfPostsForUser($user->id) > Post::ACTIVE_USER_MIN_POSTS; if ($userOnline && $userIsActivePoster) $Raiting::addBonus($user->id, Rating::BONUS_RATING_POINTS); 

Well, now the condition has become simple and clear as day, but only additional logical variables are introduced to simplify the code.

Example 4:

The code is repeated in several places:

 $hdr = explode(' ',trim($header)); $hdr[0] = '<span class="hdr-decor">'.$hdr[0].'</span>'; $header = implode(' ',$hdr); 

How to make the situation better?

 class StringHelper { /** * Return text header with CSS * @param string $header * @return string */ static public function getCSSDecoratedHeader($header) { $hdr = explode(' ',trim($header)); $hdr[0] = '<span class="hdr-decor">'.$hdr[0].'</span>'; return implode(' ',$hdr); } ... $header = StringHelper::getCSSDecoratedHeader($header); 

Now it is enough for us to call our function assistant to get the same result in all places of the application, and, of course, the code has become easier and its number has decreased.

Part 2: Objects and Classes


Coders are perplexed: “Why do we need OOP, if everything can be written with functions or even just with operators?”.
The universe responded: “Yes, everything is the same - to make large or complex code more simple, understandable and well structured.”
Encapsulation is the most important property in managing the complexity of the code, logically hiding our data and algorithms inside the private class methods, we significantly simplify the entire logic of working with a class, and also simplify all future operations to change the behavior of a class.
Inheritance is a great way to not write duplicate code in similar classes and simplify all descendant classes.
Polymorphism - we easily change the logic of the descendant class behavior by changing only one method.

Example 5:

The coder learned how to extract data from database tables and now spells in all files:

 $sqlQuery = "SELECT * FROM User WHERE id=:id"; $connection = $this->getDbConnection(); $command = $connection->createCommand($sqlQuery); $user = $command->execute(array(':id'=>$id)); echo $user['name']; 

But thanks to OOP and the specially prepared User class, you can write much shorter and clearer:

 $user = User::model()->findByPk($id); echo $user->name; 


Example 6:

The coder has written several classes for the payment systems supported by his site, each of which has several completely identical methods and fields.

The programmer would create a base payment system class that would contain common fields and methods for all systems, and concrete classes for each payment system would inherit from the base one, which would greatly reduce the amount of code in these classes and the project as a whole.

Part 3: Modularity


Coders are perplexed: “Why should a program make a bunch of files, and even in different folders? You can make one or two files and there will be all the constants, classes and functions of our project, and the variables will all be global. ”

The Universe responded: “Yes ... but then you yourself can sort your kilometer-sized files”.

Example 7:

The coder has learned to write in the MVC framework, but has not become acquainted with the modular structure and writes all the code in the model:

 class Article extends CModel { ... ... public static function getDecoratedHeader($header) { $words = explode(' ', $header); $words[0] = '<span class="decorator">' . $words[0] . '</span>'; return implode(' ', $words); } ... ... } 

The programmer knows that the model should only have code to work with the data of this model and this method will put StringHelper :: getDecoratedHeader () in the helper. Accordingly, each application function has its specific purpose, which is determined by the module in which its implementation is located (model, controller, component, widget, etc.) and programmers will understand a lot about the essence of the methods written by other programmers, just seeing which module he belongs

Part 4: Patterns


Koder heard the word pattern and immediately ranked him into the category of abusive ones, although the universe hinted to him that the patterns are extremely successful solutions, typical software development tasks and this knowledge would significantly simplify the coder’s work, as well as communication with programmers who know the patterns.

Example 8:

The encoder uses in its application the external component Mailer and writes in the modules of the system calls to its send () method.
Mailer :: send ($ subject, $ message);
But the trouble is that in the new version of this component, which corrects a bunch of bugs and improves performance, the send () method has been removed and replaced with the post () method with other required parameters. The coder will have to shovel all the application code, correcting all calls to the component, and if he used one of the simplest patterns, the access method:

 class MailerWrap { public function send($params) { return Mailer::send($params); } } 

It would be enough for the programmer to change only one method with a call in the class-wrapper of the Mailer component to take full advantage of the new version.

Part 5: Framework


The coder is too lazy to learn the framework, he himself can perfectly write all the necessary modules and components, which, moreover, will work faster.

Example 9:

The project is developed without the use of any well-known frameworks and agreements on the design and writing of code. A new developer has come to the project, they are trying to bring him up to date, weeks and months go by, but he is still poorly oriented in the heterogeneous application code whose documentation nobody has ever written, spends a lot of time picking the source code in order to understand what is happening. A new developer is dismissed due to “insufficient competence”, a new one is hired, and the situation is repeated exactly. Programmers would use the framework for a large project and adhere to the code generation framework of this framework. This would allow them to easily hire new developers with knowledge of this framework, while the adaptation period of a new team member would be minimal, since all application code in any module is standardized, uniform, and described in the framework documentation with which the new specialist is already familiar.

Part 6: Optimization


Koder heard about optimization, and even used a couple of tips from a search engine in his programs, in any case, he says so to others.

Example 10:

Koder wrote a forum, but the trouble is that after a couple of months of active chatter, the site’s pages began to open very slowly. He dug into the code and with great difficulty found out that the query to the MySQL database was executed for a very long time. The coder has been reading tips from a search engine and decided to rewrite the entire forum using the noSQL database, since it only takes a month. In this case, the programmer would analyze the query plan and add a couple of indexes to the tables in 3 minutes.

Example 11:

The coder started optimizing the performance of his code consisting of 8 functions, optimizing each of them in order. He spent the week refactoring 5 functions, but the performance gain was only 10%. Koder was disappointed in optimization and threw this business, having reconciled with application brakes. The programmer would analyze the execution time of each of the 8 functions, after which he would take up the optimization of the longest running function. Other functions, the execution time of which is significantly (an order of magnitude) less than the main one, did not optimize at all.

Part 7: Security


Coder never really thought about code security. What for? No one will ever hack his programs ...

Example 12:

The encoder has many requests in the application, where it simply substitutes the data transmitted from the user (GET, POST, COOKIES, JSON, XML) directly into the request:
 $sqlQuery = 'SELECT `name`, `surname` FROM `User` WHERE `id`='.$_GET['id']; $command->create($sqlQuery); $result = $command->execute(); print_r($result); 

And what will happen if the “user” sends the following string in the id parameter: “0 UNION SELECT` email`, `password` FROM` User` LIMIT 10 ”? Probably be full ah-ah-ah!
Programmers write these queries like this:
 $sqlQuery = 'SELECT * FROM `User` WHERE `id`=:id'; $command->create($sqlQuery); $result = $command->execute(array(':id'=>$_GET['id'])); print_r($result); 

Programmers never forget about the substitution of values ​​in functions of type eval (), as well as the cool word “validation”.

Conclusion


The principles of building a universe are extremely simple, like the whole universe, which is why it is so great. As in any business, in the development of software for long-term sustainable development, it is important, first of all, to understand the basic, basic principles, and not to know a specific toolkit, which provides only a superficial level of skills in the short term. All the above basic principles are simple in nature and the majority of coders know about them, at least, but not everyone really understands them and uses them in their practice.

May this great knowledge be with you, young Padawan!

Source: https://habr.com/ru/post/236863/


All Articles