I have a UML book and I am reading about nested fragments. It shows an example of a nested fragment. But what I dont get.. why does it say "If the condition "cancelation not sucessful" is true when entering this fragment (i.e. cancelation was unsuccesful) the interaction within this fragment is no longer executed".
What I have learned before is that a condition should be true before the interaction will be executed? But in this case it says the opposite of it.. (because they say it should be false to execute the interaction)
See for the image: https://ibb.co/CmstLcX
I think this is simply a typo in the book. The diagram makes sense, but the text describes nonsense. While the condition is true, the messages in the loop will happen up to three times.
Maybe the author got confused, because the message immediately before the loop is Cancellation. I assume the loop guard is referring to the success of the Order cancellation message, not to this Cancellation.
By the way, reply messages need to have the name of the original message. Most people get this wrong (and some textbooks). I'll grant that the text on the reply message is often meant to be the return value. As such it should be separated with a colon from the name of the message. In your case it is probably not necessary to repeat the message name, even though techically required. However, the colon is mandatory.
If it is the return value, all reply messages in the loops return the value Acceptance. I wonder, how the guard can then evaluate to true after the first time. Maybe it is only showing the scenario for this case. This is perfectly Ok. A sequence diagram almost never shows all possible scenarios. However, then the loop doesn't make sense. I guess the author didn't mean to return a specific value.
Or maybe it is the assignment target. In this case, it should look like this: Acceptance=Order Cancellation. Then the Acceptance attribute of the Dispatcher Workstation would be filled with whatever gets returned by the Order Cancellation message. Of course, then I would expect this attribute to be used in the guard, like this [not Acceptance].
A third possiblity is, that the author didn't mean synchroneous communication and just wanted to send signals. The Acceptance Signal could well contain an attribute Cancellation not successful. Then of course, no filled arrows and no dashed lines.
I can even think of a fourth possibility. Maybe the author wanted to show the name of an out parameter of the called operation. But this would officially look like this: Order Cancellation(Acceptance). Again the name of the message could be omitted, but the round brackets are needed to make the intention clear.
I think the diagram leaves a lot more questions open than you asked.
It only says "If the cancellation was not successful then" (do exception handling). This is pretty straight forward. if not false is the same as if true. Since it is within a Break fragment, this will be performed (with what ever is inside) and as a result will break the fragment where it is contained (usually some loop). Having a break just stand alone seems a bit odd (not to say wrong).
UML 2.5 p. 581:
17.6.3.9 Break
The interactionOperator break designates that the CombinedFragment represents a breaking scenario in the sense that the operand is a scenario that is performed instead of the remainder of the enclosing InteractionFragment. A break operator with a guard is chosen when the guard is true and the rest of the enclosing Interaction Fragment is ignored. When the guard of the break operand is false, the break operand is ignored and the rest of the enclosing InteractionFragment is chosen. The choice between a break operand without a guard and the rest of the enclosing InteractionFragment is done non-deterministically.
A CombinedFragment with interactionOperator break should cover all Lifelines of the enclosing InteractionFragment.
Except for that: you should not take fragments too serious. Graphical programming is nonsense. You make only spare use of any such constructs and only if they help understanding certain behavior. Do not get tempted to re-document existing code this way. Code is much more dense and better to read. YMMV
In UML 2.5.1, the initial pseudostate of a state machine is defined as follows:
An initial Pseudostate represents a starting point for a Region; that
is, it is the point from which execution of its contained behavior
commences when the Region is entered via default activation. It is the
source for at most one Transition, which may have an associated effect
Behavior, but not an associated trigger or guard. There can be at
most one initial Vertex in a Region.
In other words, a UML state machine should almost always contain exactly one initial pseudostate, which should have exactly one outgoing transition.
However, can an initial pseudostate have incoming transitions as well? For example:
I cannot find anything forbidding it in the UML specification, yet I cannot find any example online where this case happen, therefore I was wondering whether or not I overlooked anything.
EDIT: To go into more detail, if we look into the OCL constraints stated in the specification, we can only find the following one that affects outgoing transitions (section 14.5.6.7):
inv: (kind = PseudostateKind::initial) implies (outgoing->size() <= 1)
but I cannot find any constraint regarding incoming transitions
EDIT2: I have just realized that my model is wrong! Considering this sentence of the specification (cited above): "It is the source for at most one Transition, which may have an associated effect Behavior, but not an associated trigger or guard."
Therefore the transition between init and s1 should actually have zero triggers, instead of having e1 as a trigger.
Note that while this does not invalidate the initial question.
I see nothing in the UML 2.5.1 Specification that prohibits a transition whose target is the initial pseudostate.
Such a transition would be meaningless at best and confusing at worst, which is likely why no examples are found.
Edit: see the comments!
On p. 423 UML 2.5:
15.7.18 InitialNode [Class]
15.7.18.4 Constraints
• no_incoming_edges
An InitialNode has no incoming ActivityEdges.
inv: incoming->isEmpty()
N.B. If you intend to have a self-transition for e1 then why not just using that? The Initial can anyway have only on singular outgoing edge, namely to the first state (here s1).
No this is not allowed. And why would one Do that? As you already stated in the cited text,it can only have one outgoing edge without any guard. So what is the added value, as you cannot reuse anything.
I think the text is pretty clear as-is: "[An initial Pseudostate] is the point from which execution of its contained behavior commences when the Region is entered via default activation." If you connect a transition back around to the initial psuedostate, the initial psuedostate is no longer "the point from which execution of its contained behavior commences," it is something else, and is therefore undefined.
I am designing UML Activity diagram in ArgoUML now.
I know that if I want to design condition like:
if(condition) {
doTrueAction();
} else {
doFalseAction();
}
It could be done in UML activity diagram like following:
But what if we have another condition inside the output of the previous decision? Like this:
if(condition) {
if(condition2) {
condition2TrueAction();
} else {
condition2FalseAction();
}
}else{
conditionFalseAction();
}
As you see conditionTrueOutput is being output and condition at the same time here. It seems to me that design is broken.
Edit: Or I should use fork element instead of decision (diamond) element?
I want to know how to design this correctly. Is there any rule?
There's a wrong assumption in your thoughts. A Decision has no output. It just has conditional control flows leaving it. Each can be guarded by a certain condition. This guard is written in square braces:
Note that I did not write the (implicit) [true] guard after the first test (rather by sloppiness when editing, but actually it can be omitted).
Edit My first though that your diagram has another flaw in that the actions have no control flow going out was incorrect. Actually Superstructures state that a missing outgoing control flow is equivalent to an FlowFinal after processing the Action. So your diagram is correct here.
Regarding your edit: as the comment says, this is for parallel continuation. Nested conditions need to be like shown above.
Edit2 As Ister noted in the comments, a Decision can have more than just the if and else control flow going out, but an arbitrary number greater than 1. The UML 2.5 states on p. 388:
If exactly one target of an unblocked outgoing edge accepts the token, then the token traverses the corresponding edge and all other offers are withdrawn. If multiple targets accept the token simultaneously, then the token traverses only one of the edges corresponding to the accepting targets, but which one is not determined by this specification.
In order to avoid non-deterministic behavior, the modeler should arrange that at most one guard evaluate to true for each incoming token. If it can be ensured that only one guard will evaluate to true, a conforming implementation is not required to evaluate the guards on all outgoing edges once one has been found to evaluate to true.
For use only with DecisionNodes, a predefined guard “else” (represented as an Expression with “else” as its operator and no operands) may be used for at most one outgoing edge. This guard evaluates to true only if the token is not accepted by any other outgoing edge from the DecisionNode.
It seems that your design is coherent but it is not a UML diagram. I suppose that you are mixing the activity diagram with the sequence diagram.
Your diagram looks like a sequence diagram but it tries to represent information that are related to the activity diagrams.
I suggest you this web site to investigate on the differences between the two diagrams, I hope it can help you.
Instead, by trying to use your design, what I suggest you is to insert another condition (e.g. SecondConditionAction) before the two condotion2.
I want to create a UML sequence diagram (see below) where I have an alt frame with two conditions (status equals foo or bar). In the foo case I send a synchronous message from A to B, get the return message and then proceed with the rest of the sequence diagram (call spam()). In the bar case I send another synchronous message from A to C to but there will be no return. I'm trying to model a function call in SW which doesn't return (it blocks forever on a semaphore) so in that case I will never proceed to spam(). Can this be expressed in a sequence diagram? I can exclude the return value but that would only tell me that there is no return value, not that there is no return at all. Can this only be expressed by splitting the diagram in two and handle the conditions separately or is there a better diagram to express this?
You can place a duration constraint between the call and the return.
Under normal circumstances, such a constraint would be represented by an integer followed by a time unit, such as "10 seconds" or by a range such as "[1;10) seconds".
Your question is interesting in that you want to model infinity.
I would go about doing it like this:
However I must admit that I am unsure if my formulation violates OMG's UML 2.5 standard. I did not find anything in the standard which explicitly disallows using 'infinity' as a time unit; the standard does mention that the time should be relative.
So, I was just coding a bit today, and I realized that I don't have much consistency when it comes to a coding style when programming functions. One of my main concerns is whether or not its proper to code it so that you check that the input of the user is valid OUTSIDE of the function, or just throw the values passed by the user into the function and check if the values are valid in there. Let me sketch an example:
I have a function that lists hosts based on an environment, and I want to be able to split the environment into chunks of hosts. So an example of the usage is this:
listhosts -e testenv -s 2 1
This will get all the hosts from the "testenv", split it up into two parts, and it is displaying part one.
In my code, I have a function that you pass it in a list, and it returns a list of lists based on you parameters for splitting. BUT, before I pass it a list, I first verify the parameters in my MAIN during the getops process, so in the main I check to make sure there are no negatives passed by the user, I make sure the user didnt request to split into say, 4 parts, but asking to display part 5 (which would not be valid), etc.
tl;dr: Would you check the validity of a users input the flow of you're MAIN class, or would you do a check in your function itself, and either return a valid response in the case of valid input, or return NULL in the case of invalid input?
Obviously both methods work, I'm just interested to hear from experts as to which approach is better :) Thanks for any comments and suggestions you guys have! FYI, my example is coded in Python, but I'm still more interested in a general programming answer as opposed to a language-specific one!
Good question! My main advice is that you approach the problem systematically. If you are designing a function f, here is how I think about its specification:
What are the absolute requirements that a caller of f must meet? Those requirements are f's precondition.
What does f do for its caller? When f returns, what is the return value and what is the state of the machine? Under what circumstances does f throw an exception, and what exception is thrown? The answers to all these questions constitute f's postcondition.
The precondition and postcondition together constitute f's contract with callers.
Only a caller meeting the precondition gets to rely on the postcondition.
Finally, bearing directly on your question, what happens if f's caller doesn't meet the precondition? You have two choices:
You guarantee to halt the program, one hopes with an informative message. This is a checked run-time error.
Anything goes. Maybe there's a segfault, maybe memory is corrupted, maybe f silently returns a wrong answer. This is an unchecked run-time error.
Notice some items not on this list: raising an exception or returning an error code. If these behaviors are to be relied upon, they become part of f's contract.
Now I can rephrase your question:
What should a function do when its caller violates its contract?
In most kinds of applications, the function should halt the program with a checked run-time error. If the program is part of an application that needs to be reliable, either the application should provide an external mechanism for restarting an application that halts with a checked run-time error (common in Erlang code), or if restarting is difficult, all functions' contracts should be made very permissive so that "bad input" still meets the contract but promises always to raise an exception.
In every program, unchecked run-time errors should be rare. An unchecked run-time error is typically justified only on performance grounds, and even then only when code is performance-critical. Another source of unchecked run-time errors is programming in unsafe languages; for example, in C, there's no way to check whether memory pointed to has actually been initialized.
Another aspect of your question is
What kinds of contracts make the best designs?
The answer to this question varies more depending on the problem domain.
Because none of the work I do has to be high-availability or safety-critical, I use restrictive contracts and lots of checked run-time errors (typically assertion failures). When you are designing the interfaces and contracts of a big system, it is much easier if you keep the contracts simple, you keep the preconditions restrictive (tight), and you rely on checked run-time errors when arguments are "bad".
I have a function that you pass it in a list, and it returns a list of lists based on you parameters for splitting. BUT, before I pass it a list, I first verify the parameters in my MAIN during the getops process, so in the main I check to make sure there are no negatives passed by the user, I make sure the user didnt request to split into say, 4 parts, but asking to display part 5.
I think this is exactly the right way to solve this particular problem:
Your contract with the user is that the user can say anything, and if the user utters a nonsensical request, your program won't fall over— it will issue a sensible error message and then continue.
Your internal contract with your request-processing function is that you will pass it only sensible requests.
You therefore have a third function, outside the second, whose job it is to distinguish sense from nonsense and act accordingly—your request-processing function gets "sense", the user is told about "nonsense", and all contracts are met.
One of my main concerns is whether or not its proper to code it so that you check that the input of the user is valid OUTSIDE of the function.
Yes. Almost always this is the best design. In fact, there's probably a design pattern somewhere with a fancy name. But if not, experienced programmers have seen this over and over again. One of two things happens:
parse / validate / reject with error message
parse / validate / process
This kind of design has one data type (request) and four functions. Since I'm writing tons of Haskell code this week, I'll give an example in Haskell:
data Request -- type of a request
parse :: UserInput -> Request -- has a somewhat permissive precondition
validate :: Request -> Maybe ErrorMessage -- has a very permissive precondition
process :: Request -> Result -- has a very restrictive precondition
Of course there are many other ways to do it. Failures could be detected at the parsing stage as well as the validation stage. "Valid request" could actually be represented by a different type than "unvalidated request". And so on.
I'd do the check inside the function itself to make sure that the parameters I was expecting were indeed what I got.
Call it "defensive programming" or "programming by contract" or "assert checking parameters" or "encapsulation", but the idea is that the function should be responsible for checking its own pre- and post-conditions and making sure that no invariants are violated.
If you do it outside the function, you leave yourself open to the possibility that a client won't perform the checks. A method should not rely on others knowing how to use it properly.
If the contract fails you either throw an exception, if your language supports them, or return an error code of some kind.
Checking within the function adds complexity, so my personal policy is to do sanity checking as far up the stack as possible, and catch exceptions as they arise. I also make sure that my functions are documented so that other programmers know what the function expects of them. They may not always follow such expectations, but to be blunt, it is not my job to make their programs work.
It often makes sense to check the input in both places.
In the function you should validate the inputs and throw an exception if they are incorrect. This prevents invalid inputs causing the function to get halfway through and then throw an unexpected exception like "array index out of bounds" or similar. This will make debugging errors much simpler.
However throwing exceptions shouldn't be used as flow control and you wouldn't want to throw the raw exception straight to the user, so I would also add logic in the user interface to make sure I never call the function with invalid inputs. In your case this would be displaying a message on the console, but in other cases it might be showing a validation error in a GUI, possibly as you are typing.
"Code Complete" suggests an isolation strategy where one could draw a line between classes that validate all input and classes that treat their input as already validated. Anything allowed to pass the validation line is considered safe and can be passed to functions that don't do validation (they use asserts instead, so that errors in the external validation code can manifest themselves).
How to handle errors depends on the programming language; however, when writing a commandline application, the commandline really should validate that the input is reasonable. If the input is not reasonable, the appropriate behavior is to print a "Usage" message with an explanation of the requirements as well as to exit with a non-zero status code so that other programs know it failed (by testing the exit code).
Silent failure is the worst kind of failure, and that is what happens if you simply return incorrect results when given invalid arguments. If the failure is ever caught, then it will most likely be discovered very far away from the true point of failure (passing the invalid argument). Therefore, it is best, IMHO to throw an exception (or, where not possible, to return an error status code) when an argument is invalid, since it flags the error as soon as it occurs, making it much easier to identify and correct the true cause of failure.
I should also add that it is very important to be consistent in how you handle invalid inputs; you should either check and throw an exception on invalid input for all functions or do that for none of them, since if users of your interface discover that some functions throw on invalid input, they will begin to rely on this behavior and will be incredibly surprised when other function simply return invalid results rather than complaining.