Главное не результат, главное процесс

BPM-блог Анатолия Белайчука

Моделируем подпроцессы в BPMN

Если вы взялись за достаточно сложный бизнес-процесс, то скорее рано, чем поздно вы столкнетесь с тем, что схема процесса разрослась и стала нечитаемой. Это значит, что пришла пора выполнить иерархическую декомпозицию - проще говоря, разбить процесс на подпроцессы. На BPMN распространяется старое правило: на одном уровне декомпозиции желательно иметь от 5 до 9 активностей.

Рассмотрим в качестве примера процесс заключения договора, состоящий из трех фаз:

  1. согласование содержательных условий договора
  2. согласование текста договора
  3. подписание договора

Зачастую приходится встречать наивные процессные диаграммы типа следующей:

Рис.1 Наивная диаграмма

Я назвал ее наивной потому, что в ней не предусмотрено досрочное завершение процесса, например, из-за того, что не договорились о существенных условиях. Как правило, после каждого подпроцесса проверяется чем он завершился:

Рис.2 Диаграмма с проверкой промежуточных результатов

Уместен вопрос: зачем делать проверку после последнего подпроцесса, если процесс так и так завершается. Ответ: затем, что это разные завершения - успешное и неуспешное. Нам полезно видеть это на схеме, а если схема исполняемая, то мы сможем получить статистику по проценту успешных и неуспешных завершений.

Надо понимать, что события на BPMN диаграмме, даже если они не влекут за собой никаких явных действий, протоколируются процессным движком: по каждому экземпляру процесса в журнале остается аудиторский след о том, что такое-то событие произошло в такое-то время. Поэтому если мы хотим расставить в процессе вехи (milestone) и контролировать сроки прохождения процесса от старта до вехи или от одной вехи до другой, то нам надо просто добавить в схему “пустые” промежуточные события (intermediate none event):

Рис.3 Диаграмма с вехами

Кстати, мы только что ответили на часто задаваемый вопрос “как в BPMN моделируются вехи?”. Ответ: “пустыми” промежуточными событиями, как показано на рис.3.

Все бы хорошо, но если мы заглянем во внутрь подпроцесса, то с большой вероятностью обнаружим там ту же самую проверку, что во внешнем процессе. Например, для подпроцесса согласования текста договора:

Рис.4 Двойная проверка

Как видим, проверка “текст согласован” производится дважды. Люди с программистким складом ума такие вещи не любят, справедливо указывая, что тут имеет место дублирование.

Как избавиться от дублирования проверки? Сделать из подпроцесса два выхода, как на следующей диаграмме, нельзя. Это грубая ошибка: потоки управления в BPMN не имеют права пересекать границы подпроцесса.

Рис.5 Некорректная диаграмма: поток управления пересекает границу подпроцесса

Корректный способ - трактовать один из выходов подпроцесса как основной/желаемый, а остальные - как бизнес-исключения. Для рассматриваемого примера это может выглядеть так:

Рис.6 Выход из подпроцесса через эскалацию

Если текст не согласован, подпроцесс инициирует событие типа “эскалация” (escalation), и управление передается на прикрепленный обработчик (attached event).

Полная диаграмма со свернутыми подпроцессами будет выглядеть так:

Рис.7 Эскалации и вехи

Но помним, что эскалации появились только в BPMN 2.0, поэтому если вы ограничены рамками BPMN 1.x, пользуйтесь вместо них событиями “ошибка” (error):

Рис.8 BPMN 1.x: событие “ошибка” вместо эскалации

Вехи на этой диаграмме опциональны - если от них отказаться, получим более компактную диаграмму:

Рис.9 Компактная версия без вех

Резюме:

  1. Для моделирования подпроцессов используйте паттерны, изображенные на рис.2 или 9; какой именно использовать - дело вкуса.
  2. Диаграммы на рис.3 и 8 - модификации, в которые добавлены промежуточные события, моделирующие вехи процесса.
  3. Если ваш инструментарий поддерживает BPMN 2.0, то вместо ошибок в диаграммах на рис.8 и 9 используйте эскалации, как показано на рис.7.

27.05.11 | Статьи | , , ,    

Комментарии (22)

  1. Keith 28.05.11 19:07

    Excellent! I like the progression, and explaining the steps. I wish, however, that the “normal” routes did not have to be drawn differently than the “branching” routes. There are many cases where a person has a choice, and both choices are “normal” (and not so clearly exception). In that situation one will be forced to arbitrarily pick one route as “normal” and the other as exceptional. The “normal” route should have an event indicator on the edge of the activity as well. I realize this is not BPMN but maybe someday it will be…..

    Here is my 1993 paper on a very related subject: http://kswenson.workcast.org/1993/199309_COOCS/p130-swenson.pdf
    The visual notation was pre-BPMN (obviously) but you can see that finally BPMN is getting to the point where we can start to actually represent subprocesses in this way. This is first published paper of linking subprocesses in this way.

  2. Anatoly Belychook 29.05.11 09:41

    Keith

    Thanks for the input.

    As for the “normal” routes, I’d rather call them “successful” or “desirable”.

    How about these rules of thumb:
    1) Follow patterns depicted at figures 7, 8 and 9 if you want to outline a happy path (e.g. order approved vs. order declined).
    2) Use patterns presented at figures 2 and 3 when branches are equally desirable (e.g. product order vs. services order).

  3. Bruce Silver 01.06.11 04:05

    Keith, Are you kidding? I have been teaching this since 2007 as BPMN Method and Style. Anatoly, I agree with your post, but quibble on just 2 points. First, I think Error is preferred to Escalation, as Escalation is normally non-interrupting. Maybe you are using convention of interrupting Escalation for business exceptions and Error for technical exceptions? In that case, fine, but explain the convention. Second point, you should label the end events and boundary events (matching throw-catch labels) to make the meaning clearer from the diagram alone. But overall I am totally in agreement with your post!
    –Bruce

  4. Anatoly Belychook 01.06.11 07:02

    Bruce

    That’s right: I’m using Error for system abnormalities and Escalation for business exceptions. BTW, there is another difference between Error and Escalation: Error terminates all active threads i.e. behave like Terminate while Escalation affects a current thread only.Taking this into account, maybe it’s better to use Error for both cases.

    Thank you for point out the labelling issue. Technically one may leave a boundary event unlabelled to make it a catcher for any exception but the diagram at fig.6 is invalid: the escalation end event must have a code.

  5. Bruce Silver 06.06.11 18:00

    I am unaware of the different termination behavior of interrupting Escalation vs Error. Is this in the spec? Can you provide reference?

  6. Anatoly Belychook 06.06.11 18:31

    Bruce

    BPMN 2.0, p.255:
    - Error. This type of End indicates that a named Error should be generated. All currently active threads in the particular Sub-Process are terminated as a result.
    - Escalation. This type of End indicates that an Escalation should be triggered. Other active threads are not affected by this and continue to be executed.

  7. Marina 04.07.11 11:55

    Очень интересная и полезная статья. Спасибо.

  8. Илья Логинов 10.04.12 13:26

    Очень доходчиво Брюсу и нам объяснили различие ошибки и эскалации. Теперь полная ясность

  9. Kirill Kurishev 30.08.12 10:55

    Anatoly, everything is right. But only the page is 248 (BPMN 2.0 Jaunary 2011). There is a little question. You’ve wrote, that “All currently active threads in the particular Sub-Process are terminated as a result”. But why Sub-Process? I think that all threads in Pull are terminated, arn’t they? Thanks.

  10. Anatoly Belychook 09.09.12 15:03

    Kirill

    To be precise, all threads in the given context are terminated. The context may be a top-level process (pool) or a subprocess. But if there is a subprocess S2 executed in parallel to the subprocess S1 that initiated an error then S2 won’t be immediately affected by the event. It may be affected though if the error was not catched by the subprocess S1 boundary event or event subprocess - if this is the case than the error will propagate to the upper level of subprocess or top process and hence terminate all child threads including S2.

  11. Самат 15.08.13 07:22

    Здравствуйте Анатолий
    хотелось бы узнать как правильно создавать bpmn схемы , для потдверждения запросов и подобного?
    и еще вопрос возможны ли бесплатные консультации?

  12. Anatoly Belychook 15.08.13 07:30

    Самат

    Основательно научиться можно на моем тренинге http://bpmntraining.ru/

    Бесплатную консультацию можно попросить на форумах http://bpmnforum.ru/ https://www.facebook.com/groups/bpmnforum/

  13. Самат 15.08.13 07:52

    спасибо

  14. Cristian 06.02.14 14:37

    Anatoly,

    Do you know why isn’t Bizagi modeler allowing me to add a catching interrupting boundary event of type Error to a sub-process?

  15. Anatoly Belychook 06.02.14 18:59

    Of course it’s a bug. Interestingly, one may attach a catcher to task then convert the task into subprocess and it will work, more or less.

  16. Cristian 06.02.14 20:34

    Oh, a bug! Thanks for sharing, Anatoly. I will try to use your trick…

  17. Cristian 09.02.14 12:17

    Actually I just discovered that one needs to use Attach Event from menu rather than dragging and dropping an event onto the boundary of subprocess and it works to add error events…thought about sharing back

  18. Cristian 19.02.14 14:05

    Do you know if Bizagi modeler allows non-interrupting event subprocesses? It looks like it does not…

  19. Anatoly Belychook 19.02.14 14:42

    Sure it does, use the context menu (right click).

  20. Cristian 20.02.14 10:16

    Version 2.6.0.4 of modeler only allows interrupting event subprocesses. Maybe you are talking about interrupting event subprocesses, those can be created. The non-interrupting can’t.

  21. Anatoly Belychook 20.02.14 11:53

    Sorry I was wrong, didn’t get you right from the first time.

    Interrupting/non-interrupting mode should be set up by the interrupting/non-interrupting flag on start event of the event subprocess. But there is no start event in the palette. Seems that the damned thing is totally broken.

    I never needed event subprocesses, the attached event can always do the job.

  22. Cristian 20.02.14 12:23

    I also resorted to boundary non-interrupting event instead of event subprocess, I had no choice. But for my needs both approaches work well. Thanks!

Комментирование закрыто

Copyright © 2008-2024 Анатолий Белайчук. Спасибо Wordpress и Yahoo.  Контент  Комментарии