AXForum  
Вернуться   AXForum > Microsoft Dynamics AX > DAX Blogs
DAX
Забыли пароль?
Зарегистрироваться Правила Справка Пользователи Сообщения за день Поиск

 
 
Опции темы Поиск в этой теме Опции просмотра
Старый 25.06.2013, 12:11   #1  
Blog bot is offline
Blog bot
Участник
 
25,497 / 847 (79) +++++++
Регистрация: 28.10.2006
mfp: Debug::Assert in X++
Источник: http://blogs.msdn.com/b/mfp/archive/...sert-in-x.aspx
==============
  “In computer programming, an assertion is a predicate (a true–false statement) placed in a program to indicate that the developer thinks that the predicate is always true at that place.”    



What would you rather have: A piece of source code with or without assertions? I’d definitely prefer source code with assertions – it makes the code easier to read, debug and troubleshoot.

My recommendation is to use assertions in X++ when all of the following are true:
  1. The condition can never be false if the code is correct, and
  2. The condition is not so trivial it obviously be always true, and
  3. The condition is in some sense internal to the component, and
  4. The condition can be verified without any method calls.
 

1. The condition can never be false if the code is correct

Assertions and error handling are two different things.

  • Assertions should be used to document logically impossible situations in a correctly implemented program. If the impossible occur, then something is wrong – a programming error has been discovered.
  • Error handling – as the name implies – is the implementation of what should happen when an error occurs. Error handling are valid code paths that determines how the software reacts to various erroneous conditions, like incorrect data entered by the user, to system error conditions like out-of-memory.
In a nutshell, it should be possible to write unit test for error handling – but not for assertions.

2. The condition is not so trivial it obviously be always true

Assert statements takes time to write and read – and if the condition they are asserting is obviously always true, then the assertion is pure clutter – and we are better off without it.

3. The condition is in some sense internal to the component

A failing assertion is an indication of a problem with the implementation. Something within the component – regardless of input from the outside world – is broken and needs fixing. Typically, I’d use assertions for input validation in private methods, and exceptions in public methods. Conversely, you don’t want consumers of your component to be hit by assertions – regardless of how they use your component.

4. The condition can be verified without any method calls.

Assert statements in X++ are a little special, as the X++ compiler always includes assert statements. In other languages (like C#) you can have multiple compiler targets – and typically the release build would not include the assert statements.

Given assert statements in X++ are always evaluated, and thus degrades performance, they should be used with a bit of caution. If the condition can be verified with minimal overhead – for example that a variable has a certain value – then there is no problem. However; if the assertion requires execution of complex logic, RPC or SQL calls then it should be avoided, due to the performance impact. In cases where the performance impact is significant, but you don’t want to compromise on assertions, the assertions can be wrapped inside a call to Debug::debugMode().

“without any method calls” is just a guiding principles. Sometimes it makes sense to factor the condition into a Boolean method – for reuse or for clarity – here I would not object.

Examples

Here is an example of good use of assertion in X++:

private void markDetailRecordAsEdited(
RecId _journalControlDetailId,
RecId _draftConstraintTreeId){ Debug::assert(_journalControlDetailId != 0); Debug::assert(_draftConstraintTreeId != 0); if (! modifiedDetailRecords.exists(_journalControlDetailId)) { modifiedDetailRecords.insert(
_journalControlDetailId,
_draftConstraintTreeId); }}

Here is another example where Debug::debugMode() is used:

private void render(){ ... if (Debug::debugMode()) { Debug::assert(this.hierarchyCount() > 0); Debug::assert(segments != null); Debug::assert(totalSegmentCount > 0); } ...}Closing remarks

I once saw a t-shirt with this print on the front: “If debugging is the process of removing bugs, then programming must be the process of putting them in”.  I wish the back had read: “Programming with assertions is one way to keep bugs out.”




==============
Источник: http://blogs.msdn.com/b/mfp/archive/...sert-in-x.aspx
__________________
Расскажите о новых и интересных блогах по Microsoft Dynamics, напишите личное сообщение администратору.
Старый 27.06.2013, 11:46   #2  
Stitch_MS is offline
Stitch_MS
Участник
Аватар для Stitch_MS
Соотечественники
 
396 / 478 (16) +++++++
Регистрация: 27.02.2006
Адрес: Дания
Радует, что товарищ снова стал делиться опытом. О разных конференциях и релизах и так все пишут.
Старый 02.07.2014, 22:21   #3  
Maxim Gorbunov is offline
Maxim Gorbunov
Administrator
Соотечественники
Лучший по профессии 2009
 
2,483 / 645 (26) +++++++
Регистрация: 27.11.2001
Адрес: Dubai, UAE
Уважаемый mfp умалчивает об одном важном отличии Debug::assert() от throw error(). В случае, если условие в Debug::assert() не выполняется, программа продолжает работать дальше. То есть, пользователи видят ошибку, если есть дебаггер, то он запускается, но при этом выполнение кода продолжается как ни в чём не бывало.

Не самая приятная особенность, если честно. Ведь в большинстве случаев assert() появляется не просто так, а для обозначения того, что нижеследующий код при невыполнении некоторых условий может работать некорректно. Логично было бы в такой ситуации код не выполнять, по-моему.
__________________
Not registered yet? Register here!
Have comments, questions, suggestions or anything else regarding our web site? Don't hesitate, send them to me
Старый 03.07.2014, 07:48   #4  
Alex_KD is offline
Alex_KD
Участник
AxAssist
MCBMSS
Соотечественники
 
522 / 362 (14) ++++++
Регистрация: 06.07.2006
Адрес: Melbourne, Down Under
Цитата:
Сообщение от Maxim Gorbunov Посмотреть сообщение
Уважаемый mfp умалчивает об одном важном отличии Debug::assert() от throw error(). В случае, если условие в Debug::assert() не выполняется, программа продолжает работать дальше.
Надо добавить, что если код вызван из веб-сервиса, то Debug::assert(false) останавливает выполненение кода так же как throw error() если включено "Enable global breakpoints" на сервере. Я так понимаю если вызвать код в CIL то эффект будет такой же.

Ловить тикие ошибки - удовольствие то еще....
__________________
AxAssist 2012 - Productivity Tool for Dynamics AX 2012/2009/4.0/3.0

Последний раз редактировалось Alex_KD; 03.07.2014 в 07:59.
Старый 03.07.2014, 10:13   #5  
trud is offline
trud
Участник
Лучший по профессии 2017
 
1,038 / 1629 (57) ++++++++
Регистрация: 07.06.2003
Записей в блоге: 1
кстати поддержка MBS вообще вызов Debug::assert() за ошибку не считает. рекомендация от них собственно заключается в отключении отладчика у пользователя в таких случаях. вообще конечно непонятная конструкция в нынешнем исполнении
Старый 03.07.2014, 10:50   #6  
Maxim Gorbunov is offline
Maxim Gorbunov
Administrator
Соотечественники
Лучший по профессии 2009
 
2,483 / 645 (26) +++++++
Регистрация: 27.11.2001
Адрес: Dubai, UAE
Цитата:
Сообщение от Alex_KD Посмотреть сообщение
Я так понимаю если вызвать код в CIL то эффект будет такой же.
Если Debug::assert() вызвать в CIL, то выполнение не останавливается (хотя Enable global breakpoints у меня не активировано; возможно, дело в этом). В Infolog вываливается ошибка, но выполнение продолжается со следующей строчки.
__________________
Not registered yet? Register here!
Have comments, questions, suggestions or anything else regarding our web site? Don't hesitate, send them to me
 

Похожие темы
Тема Автор Раздел Ответов Посл. сообщение
ax-erp: Debug BP errors in Dynamics AX 2012 Blog bot DAX Blogs 0 14.12.2012 23:11
ax-erp: Debug::assert() method calls in SYS layer triggering Dynamics AX 2012 debugger Blog bot DAX Blogs 0 10.12.2012 21:11
mfp: Dynamics AX EMEA Technical Conference 2011 Blog bot DAX Blogs 0 21.09.2011 18:11
kamalblogs: Debug::assert statements found in Sys layer in Dynamics Ax 2009 Blog bot DAX Blogs 3 19.07.2010 12:52
mfp: Articles on X++ development Blog bot DAX Blogs 0 23.08.2007 23:40

Ваши права в разделе
Вы не можете создавать новые темы
Вы не можете отвечать в темах
Вы не можете прикреплять вложения
Вы не можете редактировать свои сообщения

BB коды Вкл.
Смайлы Вкл.
[IMG] код Вкл.
HTML код Выкл.
Быстрый переход

Рейтинг@Mail.ru
Часовой пояс GMT +3, время: 16:19.
Powered by vBulletin® v3.8.5. Перевод: zCarot
Контактная информация, Реклама.