Parable about programmers and coders

A long time ago, in a distant faraway galaxy, intelligent mammals lived on one provincial planet, which recently began the age of information technology. In that century, many had to write programs in different languages ​​for various 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 computer do some reasonable (from the author’s point of view) actions, already considered himself an enlightened sage who comprehended DAO of information technologies and was called nothing more than a Jedi programmer.

image

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

The vast majority of people believe that it does not matter how the result was achieved if the task, apparently, is solved. Starting to solve any task of software development (and not only), many do not think about the fundamental principles of design, but simply copy the working blocks from their predecessors. The coders, armed with a guide to the syntax of the language and the Internet search engine, create their own “mega-masterpieces of programming”. By quickly forcing the program using the debugger to perform more or less similar to logical behavior actions, the developers submit an order. The client is satisfied, the money coder - everyone is happy at first glance.

Then, as a rule, the following happens: very little time passes and the client wants to change something in his program, and, as a rule, a lot. The customer contacts 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 pile of results from the search engine results in, and begins painfully rewriting the code, breaking deadlines even for “elementary changes”. At the second or a little later revision, the application code becomes so difficult to understand, unmanageable and buggy that it really becomes easier to rewrite it from scratch, having requested from the customer a full budget for a new development. And here the client finally feels his epic blunder with the choice of performers, since he has to pay for the second application development,

Together with the awareness of this situation, we came 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 makes appropriate use of technology in relation to the current task. This simple and understandable application code allows the customer to save money, since such a code is easy to read and change, both to another programmer and to any encoder. An application with a good architecture and high-quality code can be successfully operated and evolved over a considerable time, with minimal customer costs for changes and support.

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

Let's take simple code examples using the mega popular PHP web developer language on this provincial planet. The language itself is quite good for its intended use, although opinions on this issue usually differ.

Part 1: Code Simplicity


Example 1:

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

Just a line of code written by an encoder, 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 names are given to 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 ...;

Reading the code has become much more convenient, 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 it’s somehow somehow too hard 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 a day, and just introduced additional logical variables to simplify the code.

Example 4:

The code is repeated in several places:

$hdr = explode(' ',trim($header));
$hdr[0] = ''.$hdr[0].'';
$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] = ''.$hdr[0].'';
		return implode(' ',$hdr);
	}
...
$header = StringHelper::getCSSDecoratedHeader($header);

Now we just need to call our helper function to get the same result in all places of the application, and, of course, the code has become simpler 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 operators?"
The universe responded: “Yes, then everything is to make a large or complex code simpler, understandable, and well-structured.”
Encapsulation is the most important property in managing code complexity, logically hiding our data and algorithms inside private class methods, we greatly simplify the whole logic of working with a class, and also simplify all future operations to change the behavior of a class.
Inheritance is a great way not to 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 encoder has learned to extract data from database tables and now writes a spell 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 a specially prepared User class, you can write much shorter and more understandable:

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


Example 6:

The coder has written several classes for the payment systems supported by its website; each has several completely identical methods and fields.

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

Part 3: Modularity


Coders are perplexed: “Why in the program do 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 all the variables will be global. ”

The universe in response: "Yes ... but then you yourself and parse your kilometer files."

Example 7:

The coder learned to write in the MVC framework, but did not become familiar 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] = '' . $words[0] . '';
		return implode(' ', $words);
	}
	... ...
}

The programmer knows that the model must have exclusively code for working with the data of this model, and such a method will put StringHelper :: getDecoratedHeader () in the helper. Accordingly, each function of the application has its own 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


The coder heard the word pattern and immediately ranked it as abusive, although the universe hinted to him that the patterns are extremely successful solutions, typical tasks of software development and this knowledge would greatly simplify the work of the coder, as well as communication with programmers who know the patterns.

Example 8:

The encoder uses an external Mailer component in its application and writes calls to its send () method in the system modules.
Mailer :: send ($ subject, $ message);
But the trouble is, in the new version of this component, which fixes a bunch of bugs and improves performance, the send () method was removed and replaced with the post () method with other required parameters. The encoder will have to shovel the entire application code, correcting all the component calls, 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 to the Mailer component in the wrapper class to take full advantage of the new version.

Part 5: frameworks


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 into the project, they are trying to get things up to date, weeks and months go by, but he is still poorly oriented in the heterogeneous application code, no one has written documentation for it, he spends a lot of time picking source codes to understand what is going on. A new developer is fired because of “lack of 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 conventions of this framework. This would allow them to easily hire new developers with knowledge of this framework, while the adaptation period for a new team member would be minimal.

Part 6: Optimization


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

Example 10:

The coder wrote a forum, but the trouble is - after a couple of months of active chatter, the pages of the site began to open very slowly. He buried himself in the code and with great difficulty found out that a query to the MySQL database took a very long time. The coder read tips from the 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 encoder is engaged in optimizing the performance of its code, which consists of 8 functions, optimizing each of them in order. He spent a week refactoring 5 functions, but the performance gain was only 10%. The coder was disappointed in the optimization and threw this thing, resigned to the brakes of the application. 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) shorter than the main one, did not optimize at all.

Part 7: Security


An encoder never really thought about code security. What for? Nobody will ever crack 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” passes the following line “0 UNION SELECT` email`, `password` FROM` User` LIMIT 10 ”in the id parameter? Probably there will be a complete ah-ah-ah!
Programmers write such requests something like this:
$sqlQuery = 'SELECT * FROM `User` WHERE `id`=:id';
$command->create($sqlQuery);
$result = $command->execute(array(':id'=>$_GET['id']));
print_r($result);

And programmers never forget about the substitution of values ​​in functions like eval (), as well as about the cool word "validation".

Conclusion


The principles of building the 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 the specific tools that provide only a superficial level of skills in the short term. All of the above basic principles are simple in nature and the bulk of the coders know about them, at least, but not everyone really understands and uses them in their practice.

May this great knowledge be with you, young Padawan!

Also popular now: