Изменения

5563 байта добавлено ,  23:01, 14 ноября 2015
Строка 251: Строка 251:       −
===Debugging Code===
+
===Отладка кода===
   −
Bugs happen. Actually that is an understatement in large projects. Bugs happen frequently. This is fortunate, because there is nothing more satisfying than exterminating a bug.
+
Или иначе дебаггинг(debugging).
    +
====Манеры хорошего кодера====
   −
====Good Coding Habits====
+
Ошибка начинающих программистов в том, что они слишком полагаются на компилятор. Опытные баголовы и багоюзеры знают, что если код скомпилирован, то не факт что он работает как написано. Уязвимости бывают везде.
 +
<!--The novice programmer has far too much faith in the compiler. The veteran bug hunter, however, knows that just because the code compiles doesn't mean it works. It could still be infested with potential problems.-->
   −
The novice programmer has far too much faith in the compiler. The veteran bug hunter, however, knows that just because the code compiles doesn't mean it works. It could still be infested with potential problems.
+
Первый вызов для отладчика кода - суметь прочитать код и попробовать скомпилировать его в уме, так как его увидит машина. Возможно где-то не хватает переменных, возможно некоторые процессы ведут к нулевому значению, возможно некоторые условия невозможно выполнить в принципе. Думайте логически.
 +
<!--The first rule for successful debugging is to compile the code yourself. Of course you do not need to generate the byte code by hand; that's what the compiler is for. Compiling the code yourself means reading through the code you have written as though you were the compiler and making sure what the compiler sees matches what you intended.-->
   −
The first rule for successful debugging is to compile the code yourself. Of course you do not need to generate the byte code by hand; that's what the compiler is for. Compiling the code yourself means reading through the code you have written as though you were the compiler and making sure what the compiler sees matches what you intended.
+
Второй шаг - запустить код, так чтобы он заработал. Подставить необходимые переменные и запустить его в приложении. Сервер может выявить простые ошибки и баги, но только вы можете понять что работает не так, как оно должно работать, и почему это не так. А что работает именно так как описано в коде. Поиграйте с переменными и кодом, чтобы лучше понять механизмы компиляции и работы вашего кода.
 +
<!--The second good debugging habit is to run the code yourself. Initialize the necessary variables to some typical values and step through the procedure in your mind. The server can catch simple errors, but only you know what the code is supposed to do, so only you can tell the difference between code which runs and code which actually works. After doing a typical case, also be sure to think through any exceptional cases which may occur. For example, with a loop, you should verify that the first and last iteration will operate as expected.-->
   −
The second good debugging habit is to run the code yourself. Initialize the necessary variables to some typical values and step through the procedure in your mind. The server can catch simple errors, but only you know what the code is supposed to do, so only you can tell the difference between code which runs and code which actually works. After doing a typical case, also be sure to think through any exceptional cases which may occur. For example, with a loop, you should verify that the first and last iteration will operate as expected.
+
Затем проведите нагрузочное тестирование, попробуйте выйти за пределы допустимых параметров, указанных вами при создании объектов и фич для проекта. Как правило на этом этапе всплывают все баги и уязвимости в написанном и вы можете отловить их и пофиксить\оставить для рабочей версии проекта.
 +
<!--After doing these pre-checks, it is, of course, vital to test the code for real. This is known as beating on the code. Don't be gentle. Treat it roughly to expose any unforeseen weaknesses. If it is code which responds to user input, try doing the usual things and then try things you wouldn't normally expect.
   −
After doing these pre-checks, it is, of course, vital to test the code for real. This is known as beating on the code. Don't be gentle. Treat it roughly to expose any unforeseen weaknesses. If it is code which responds to user input, try doing the usual things and then try things you wouldn't normally expect.
+
Code which has passed these three tests will be reasonably sound. By catching bugs early, you save yourself a lot of trouble, because the code is fresh in your mind and therefore easier to decipher. Besides, you will find that deciphering bug reports from other users can be even harder!-->
   −
Code which has passed these three tests will be reasonably sound. By catching bugs early, you save yourself a lot of trouble, because the code is fresh in your mind and therefore easier to decipher. Besides, you will find that deciphering bug reports from other users can be even harder!
+
===="Неуловимые" баги====
 
  −
 
  −
====Elusive Bugs====
      +
Существует два типа багов: Краш-баги которые останавливают процесс целиком (proc crashers) и мелкие баги(silent errors), которые ломают отдельные фичи. : Пример Краш-бага - обращение к переменной объекта, отсутствие ответа от объекта, придание переменной по умолчанию равной нулю, что приводит к завершению оператора.
 +
Когда крашится процедура, как правило сохраняются логи ошибки в world.log . При запуске созданного вами проекта в клиенте Dream Seeker, эта информация будет показана в отдельном окошке. При запуске проекта на сервере Dream Daemon - логи сохраняются в выводе серверной информации, либо в отдельном файле.
 +
<!--
 
Even when you have been careful, some subtle problems may still occasionally slip through. Hunting them down can be a frustrating experience, so it is good to have a few tricks up the sleeve.
 
Even when you have been careful, some subtle problems may still occasionally slip through. Hunting them down can be a frustrating experience, so it is good to have a few tricks up the sleeve.
    
There are two types of bugs: proc crashers and silent errors. Those that crash procs are the result of some exceptional case occurring. For example, the code might be trying to access an object's variable but the object reference is null. Allowing this sort of case to silently slide by (by pretending the variable of the non-existent object is null, for example) might be a convenient thing to do in some cases, but in others it might cover up a genuine error that needs to be corrected by the programmer. Crashing the procedure and reporting the problem therefore makes it much easier for you to discover the problem and find its source.
 
There are two types of bugs: proc crashers and silent errors. Those that crash procs are the result of some exceptional case occurring. For example, the code might be trying to access an object's variable but the object reference is null. Allowing this sort of case to silently slide by (by pretending the variable of the non-existent object is null, for example) might be a convenient thing to do in some cases, but in others it might cover up a genuine error that needs to be corrected by the programmer. Crashing the procedure and reporting the problem therefore makes it much easier for you to discover the problem and find its source.
   −
When the procedure crashes, some diagnostic information is output to world.log. When running the world directly in the client, this information is displayed directly in the terminal window. With a stand-alone server, it is normally in the server's output but may be redirected to a file.
+
When the procedure crashes, some diagnostic information is output to world.log. When running the world directly in the client, this information is displayed directly in the terminal window. With a stand-alone server, it is normally in the server's output but may be redirected to a file.-->
   −
The most important part of the diagnostic information is the name of the procedure that crashed. The value of the src and usr variables are also included. If there are any procedures in the call stack (that is, the procedure which called this one, and the procedure which in turn called it, and so on) these are displayed.
+
Самое главное - найти в логах название процедуры, которая вызвала падение выполнения кода, а также значение переменных src и usr на момент выполнения процедуры. Процедуры могут быть показаны цепочкой вызовов - будут показаны обращающиеся к этой и вызванной этой процедурой процедуры. 
 +
<!--The most important part of the diagnostic information is the name of the procedure that crashed. The value of the src and usr variables are also included. If there are any procedures in the call stack (that is, the procedure which called this one, and the procedure which in turn called it, and so on) these are displayed.
   −
If this is not enough information for you to locate the source of the problem, try compiling the world with the DEBUG macro defined. This will add source file and line number information to the diagnostic output.
+
Также вы можете воспользоваться макросом DEBUG, описанным выше для отлова багов и точным вычислением их месторасположения в коде исполняемого файла.
 +
<!--If this is not enough information for you to locate the source of the problem, try compiling the world with the DEBUG macro defined. This will add source file and line number information to the diagnostic output.
 +
Существует команда, способная показать вам какое именно значение переменной привело к падению кода. Вот она:
 +
<!--One may also need to probe around in the code to see what is going on. This can be accomplished by sending your own diagnostic information to world.log. For example, you might to know the value of a variable at a particular point in the code. This could be done with a line like the following:-->
   −
One may also need to probe around in the code to see what is going on. This can be accomplished by sending your own diagnostic information to world.log. For example, you might to know the value of a variable at a particular point in the code. This could be done with a line like the following:
+
world.log << "[__LINE__]: myvar = [myvar]"
   −
world.log << "[__LINE__]: myvar = [myvar]"
+
Отладка кода проводится как при отдельных случаях падения кода(и тогда удобнее пользоваться примерами приведёнными выше), так и по всем исполняемым строкам и файлам при финальной диагностике. В последнем случае вы можете пользоваться следующими макросами:
Sometimes debugging output such as this is simply removed after fixing the problem, but sometimes you may want diagnostic information to appear whenever you are testing the code. In this case, a macro such as the following may be useful.
+
<!--Sometimes debugging output such as this is simply removed after fixing the problem, but sometimes you may want diagnostic information to appear whenever you are testing the code. In this case, a macro such as the following may be useful.-->
    
: #ifdef DEBUG
 
: #ifdef DEBUG
Строка 291: Строка 300:  
: #define debug null
 
: #define debug null
 
: #endif
 
: #endif
You can then send output to debug and it will be ignored when not in DEBUG mode.
     −
Another tool for hunting bugs is to comment out code. This may be helpful when determining whether a certain piece of code is responsible for an observed problem. By simplifying the procedure and gradually disabling all but the code which causes the glitch, you can save yourself from scrutinizing a lot of irrelevant material.
+
Вывод информации на отладку будет осуществляться, но он будет игнорироваться до тех пор, пока вы не используете макрос #DEBUG.
 +
<!--You can then send output to debug and it will be ignored when not in DEBUG mode.-->
 +
 
 +
Есть полезный приём при поиске багов - вынести код в комментарии. Код, вынесенный в комментарий перестаёт восприниматься компилятором как исполняемые команды, зато виден разработчику. Это полезно для выделения кусков кода, ответственных за совершение ошибок при исполнении, и временном устранении их, вплоть до отладки проблемного места.
 +
<!--Another tool for hunting bugs is to comment out code. This may be helpful when determining whether a certain piece of code is responsible for an observed problem. By simplifying the procedure and gradually disabling all but the code which causes the glitch, you can save yourself from scrutinizing a lot of irrelevant material.
   −
This is also essential when asking others for help. Nobody wants to read through pages and pages of somebody else's code. If you can't see the problem yourself but can isolate it down to a small piece of code, you will find it much easier (and fruitful) when getting help from other programmers. Sometimes just trying to clearly define the problem enables you to suddenly see the solution yourself--avoiding the embarrassment altogether.
+
This is also essential when asking others for help. Nobody wants to read through pages and pages of somebody else's code. If you can't see the problem yourself but can isolate it down to a small piece of code, you will find it much easier (and fruitful) when getting help from other programmers. Sometimes just trying to clearly define the problem enables you to suddenly see the solution yourself--avoiding the embarrassment altogether.-->
470

правок