225
votes

I was wondering, how can one represent "if" statement on a sequence diagram?

if (somethingShouldBeDone) {
       // Do it
} else {
       // Do something else
}

Can it be represented at all? The thing is ... in my code, fair amount of conditions are checked to determine a variety of actions. If i am going to show the actions, I'd like to explicitly state that actions are caused by particular events.

If possible create an image representation of a solution.

4
I know this question is old and I haven't done a search yet, but it made me wonder whether showing branching is even a good idea for sequence diagrams. I always thought the conditions for the sequence were explicitly described in the scenario and thus no branching took place during the sequence. Alternative paths were handled by describing a variant of the scenario which had its own sequence diagram. It's somewhat subjective so maybe I should post it on Meta or possibly Software Engineering?Kelly S. French

4 Answers

329
votes

If else condition, also called alternatives in UML terms can indeed be represented in sequence diagrams. Here is a link where you can find some nice resources on the subject http://www.ibm.com/developerworks/rational/library/3101.html

branching with alt

38
votes

If you paste

A.do() {
  if (condition1) {
   X.doSomething
  } else if (condition2) {
   Y.doSomethingElse
  } else {
   donotDoAnything
  }
}

onto https://www.zenuml.com. It will generate a diagram for you.If/else sequence diagram

9
votes

Very simple , using Alt fragment

Lets take an example of sequence diagram for an ATM machine.Let's say here you want

IF card inserted is valid then prompt "Enter Pin"....ELSE prompt "Invalid Pin"

Then here is the sequence diagram for the same

ATM machine sequence diagram

Hope this helps!

2
votes

In Visual Studio UML sequence this can also be described as fragments which is nicely documented here: https://msdn.microsoft.com/en-us/library/dd465153.aspx