Difference between alt and opt fragment in sequence diagram?

I want to know in detail about the difference between alt and opt fragment in sequence diagram, they seem similar, I can't distinguish them. Anyone knows about this thing?

129702 次浏览

alt is used to describe alternative scenarios of a workflow. Only one of the options will be executed.

opt is used to describe optional step in workflow.

For example, for online shop purchase sequence diagram you may use opt to describe how user can add gift wrapping if she wishes. alt may be used to describe two variants of payment: using credit card or wire money transfer.

example of alt and opt sections in the sequence diagram

In UML specification the meaning is described in section 17.12.15. opt and alt are two different operator types and here's how specification describes them:

alt:

The InteractionOperatorKind alt designates that the CombinedFragment represents a choice of behavior. At most one of the operands will be chosen. The chosen operand must have an explicit or implicit guard expression that evaluates to true at this point in the interaction. An implicit true guard is implied if the operand has no guard.

opt:

The InteractionOperatorKind opt designates that the CombinedFragment represents a choice of behavior where either the (sole) operand happens or nothing happens. An option is semantically equivalent to an alternative CombinedFragment where there is one operand with non-empty content and the second operand is empty.

They are basically the same.

alt is more used for several choices, like a switch sentence group in C programming language. While opt is more used for only two choices, like a if sentence.

But, don't get surprised, if you see both concepts used interchangeably.

Alt is alternative flow (SWITCH or if. IF with two paths) Opt is IF with one flow. If you use Opt, code will be executed or not !

Alt (alternative) is indeed similar to "if" but neither is limited to 2 options only, both can actually have many "else", many options, as needed. For example: //if (a=b) then a++; else if (a>b) then a--; else b++. In any case, if Alt is part of a code that is being called, Alt will execute.

Whereas Opt (Optional) not necessarily will be executed even if it is contained in the middle of a sequence or code that is being called. Typically, to execute an Opt sequence requires external interaction from user that is making a decision where many options were presented (like choosing an online paying method). In this particular case, as opposed to an Alt sequence, if the paying methods were "credit card", "pay pal" or "prepaid", the code will have 3 Opt sequences - with only one flow each -, but one and only one of the Opt sequences will actually execute.

Hope this helps!!

Best, SD

UML - sequence diagram alt vs opt

alt - if else
opr - single condition

enter image description here