Self-learning the MQL5 language from scratch - page 46

 
By the way, I know an example that would give me checkmate in my own challenge. But I won't write about it, for obvious reasons.
 
Vasiliy Sokolov:
By the way, I know an example that would give me checkmate in my own challenge. But I won't write about it, for obvious reasons.
Here we go....))))
 
Реter Konow:
Sailed....))))
No, we haven't sailed. That example is from a veiled PLO. And what we are discussing here is a subset of it. I.e. the example shows that there are some things that can be normally solved only in OOP. The functions alone will not be enough. So it's not a contradiction in itself, but a two-star problem.
But that's school leaver level, and for now we're in first grade.
 

On the evil of global variables, and by the same token, public class fields.

Here's a look.

  1. There is a project with couple hundreds of include files, total size 200k lines (small, actually).
  2. We have a bug.
  3. We have localized it. It is caused by invalid data in a global variable.
  4. The global variable is changed by code in 600 places in 150 include files, in 200 places it is changed in a nontrivial way - via passing by reference into a function. Well, that's the kind of g...architect who cooked this up, and a group of underdogs who wrote it.
  5. The aforementioned crowd searched for a bug for a month, didn't find it, and the boss sacked them all and called seniora.
  6. He took a look at this mess and said: 250k. salary to me and 75k each to my two djuns, and we'll rewrite this shit in six months or throw it away.

Now the right solution: change a global variable, if you can't get away from a crutch) only through a function.

  1. There is a project with a couple hundred files with a total size of 200k lines (so small, actually).
  2. We have a bug.
  3. We have localized it. It is related to invalid data in a global variable.
  4. The function of assigning a variable's value is called by code in 600 places in 150 include files. Well, that's the d...r...ing architect who cooked it up, and a group of underdogs who wrote it, because it's d...r...o anyway.
  5. June inserted a conditional breakpoint into the function and saw the state of the call stack at the time of assigning invalid values (2 min.).
  6. Then Jun's unprintable remarks about the lamer (most likely he is) who wrote it, another half an hour to 2 hours, depending on Jun's hinduship, to fix and debug it.


 
Vladimir Simakov:

On the evil of global variables, and by the same token, public class fields.

Here's a look.

  1. There is a project with couple hundreds of include files, total size 200k lines (small, actually).
  2. We have a bug.
  3. We have localized it. It is caused by invalid data in a global variable.
  4. The global variable is changed by code in 600 places in 150 include files, in 200 places it is changed in a nontrivial way - via passing by reference into a function. Well, that's the kind of g...architect who cooked this up, and a group of underdogs who wrote it.
  5. The aforementioned crowd searched for a bug for a month, didn't find it, and the boss sacked them all and called seniora.
  6. He looked at this mess and said: 250k. salary to me and 75k each to my two djuns, and we'll rewrite this shit in six months or throw it away.

Now the right solution: change a global variable, if you can't get away from a crutch) only through a function.

  1. There is a project with a couple hundred files with a total size of 200k lines (so small, actually).
  2. We have a bug.
  3. We have localized it. It is related to invalid data in a global variable.
  4. The function of assigning a variable's value is called by code in 600 places in 150 include files. Well, that's the d...r...ing architect who cooked it up, and a group of underdogs who wrote it, because it's d...r...o anyway.
  5. June inserted a conditional breakpoint into the function and saw the state of the call stack at the time of assigning invalid values (2 min.).
  6. Then Jun's unprintable remarks about the lamer (most likely he is) who wrote it, another half hour to 2 hours, depending on Jun's Hindustanity, to fix and debug it.


Got it. Global variables are evil. As the saying goes... "What's good for the Russian..." ))))
 
Vasiliy Sokolov:
No, we're not. This example is from a veiled PLO. And what we are discussing here is a subset of it. I.e. the example shows that there are some things that can be normally solved only in OOP. The functions alone will not be enough. So it is not a contradiction in itself, but a two-star task.
But that's the level of a school leaver, and for now we're in the first grade.
Right. As long as we write programs up to ~3000 lines, we can safely use global variables. Then, if Vladimir wants to switch to OOP, he will abandon them). Right?
 
Реter Konow:
Right. As long as we write programs up to ~3000 lines, we can safely use global variables. Then, if Vladimir wants to switch to OOP, he will abandon them). Right?

No, it's not. You have to learn right from the beginning) Every declaration of a global variable (not to be confused with input parameters, although they should be smaller too) should be clearly justified and made using the most unflattering statements (like underjunct vulgaris b...)

 
Vladimir Simakov:

No, it's not. You have to learn right away) If you say evil, you mean evil) Every declaration of a global variable (not to be confused with input parameters, although they should be smaller too) should be clearly justified and made using the most unflattering statements (like underdog vulgaris b...)

I read all messages about global variables and understood, what all participants of this discussion wanted to say to me. I will learn how to write program code, while trying not to use global variables. Thank you all for this constructive advice!

Regards, Vladimir.

 
Реter Konow:
Got it. Global variables are evil. As the saying goes... "What's good for the Russian..." ))))
It's actually not the right proverb. By the way, in terms of drinking they are not weaker than us. It is not about Germans, but about Anglo-Saxons in general. I've been around, you know. I'll never forget those German-speaking old men in Turkey. They drank from 9:00 to 19:00 with a break for lunch, then just the pool bar would close and they continued on to others. Anyway, I looked at the doses they were drinking (Zadornov f...l.) and realised that despite my student background, which I know how to do, I wouldn't have remembered lunch at that rate the next day).
 

I continue studying the MQL5 programming language. I am pasting the revised code of the script again, taking into account the tips from the participants of this thread. I have tested the script in all modes. No problems detected. To begin with I have applied the minimum number of input parameters. The script code is written in English, comments to the code are in Russian, so that it is easier to digest. As I promised earlier, I tried to describe the script in a way understandable for a 1st class student of the programming school.

I hope I did exactly as I was told by the participants of this thread, but I could be wrong.

Regards, Vladimir.

//+------------------------------------------------------------------+
//|                                                Learning_MQL5.mq5 |
//|                        Copyright 2020, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright   "Copyright 2020, MetaQuotes Software Corp."
#property link        "https://www.mql5.com"
#property description "Скрипт подводит итог обучения языку программирования MQL5. В зависимости от"
#property description "входных параметров печатает во вкладке \"Эксперт\" торгового терминала два"
#property description "сообщения на русском языке: \"Я выучу язык MQL5!\" или \"Я не выучу язык MQL5!\""
#property description "Код скрипта написан на основе примера, приведенного Valeriy Yastremskiy на сайте"
#property description "MQL5, в теме \"Самообучение языку MQL5 с полного нуля\"."
#property description "======================================================"
#property description "Ссылка на пример https://www.mql5.com/ru/forum/352460/page30#comment_18646826"
//---
#property version     "1.00"              //версия скрипта 1.00
//---
#property script_show_inputs              //выводить окно со свойствами перед запуском скрипта 
//--- Зададим входные параметры скрипта:
input ushort Period_learning=500;         //Полный период обучения (в днях)
input ushort Days_passed=10;              //Сколько дней прошло с начала обучения (в днях)
input bool   Patience=true;               //Терпение (true - достаточно; false - не достаточно)
//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()                        //старт работы скрипта
  {
   /* Зададим условие для работы скрипта. Если:
      1. значение функции "имею время" будет равно значению истина (true)
      2. и значение функции "имею терпение" будет равно значению истина (true)
   */
   if(have_time()==true && have_patience()==true)
     {
      Print("Я выучу язык MQL5!");    //выводим сообщение "Я выучу язык MQL5!"
     }
   else //в противном случае
     {
      Print("Я не выучу язык MQL5!"); //выводим сообщение "Я не выучу язык MQL5!"
     }
  }
//+------------------------------------------------------------------+
//| have_time function (функция "имею_время")                        |
//+------------------------------------------------------------------+
bool have_time()          //создаём функцию "имею_время" и присвоим тип данных bool
  {
   /* создаём переменную enough_time (достаточно времени), где bool - логическое значение:
      истина (true) или ложь (false) и предопределяем её значение равное false
   */
   bool enough_time=false;
   /* Если:
      1. значение входного параметра Period_learning больше нуля
      2. и значение входного параметра Days_passed больше или равно значения входного параметра Period_learning
   */
   if(Period_learning>0 && Days_passed>=Period_learning)
     {
      enough_time=true;   //то значение enough_time (достаточно времени) будет равно истине (true)
     }
   else                   //в противном случае
     {
      enough_time=false;  //значение enough_time (достаточно времени) будет равно ложь (false)
     }
   return(enough_time);   //возвращаем значение "достаточно времени" в функцию "имею время"
  }
//+------------------------------------------------------------------+
//| have_patience function (функция "имею_терпение")                 |
//+------------------------------------------------------------------+
bool have_patience()           //создаём функцию "имею_терпение" и присвоим тип данных bool
  {
   /* создаём переменную enough_patience (достаточно терпения), где bool - логическое значение:
      истина (true) или ложь (false) и предопределяем её значение равное false
   */
   bool enough_patience=false;
   enough_patience=Patience;   //задаём для переменной enough_patience (достаточно терпения) значение равное
                               //входному параметру "Терпение" (Patience): истина или ложь
   return(enough_patience);    //возвращаем значение "достаточно терпения" в функцию "имею терпение"
  }
//+------------------------------------------------------------------+
Reason: