In UML what kind of association exists between two classes if one uses a static method of the other? - uml

For example let's say we have a class called "Secretary" and another class called "Utils"
Utils has some functions that do general stuff, for example finding the maximum of 3 integers.
"Secretary" needs to call some of these functions and in this class these functions are called using the following notation:
Utils.function()
now my question is, what kind of association, if there is any, exists between these two classes?

Most likely Dependency. Associations are normally used to capture some relationship that has meaningful semantics in a domain. So, for example, Secretary 'works for' Manager. Your example is different: you're not capturing meaningful relationships among instances. Therefore Dependency is probably most appropriate.
More importantly though: what are you trying to illustrate? Remember to use UML like any other tool - make it work for you. So, for example, it's fine to show a binary association if (a) it helps you and/or (b) it helps you communicate with other team members. The fact that it doesn't comply with the intended UML usage doesn't matter - as long as you find it useful.
hth.

Related

How do I find a UML object if I only know the value of one of its attributes in OCL?

I have a UML class Student that has an attribute id. I want to write a query in OCL to find a particular Student by only knowing its id. Should I use allInstances()? Or derive? I'm not very familiar with OCL.
Usually OCL is used to express some constraints on an UML model, in relation to a given class instance (context or self) and you’ll start navigating from a specific instance.
But OCL was developed as a formal specification language that can be used to specify more than only constraints, and in particular queries as explained in section 7.1. of the OCL specifications.
If you want to express something regarding all the possible instances of a class MyClass, you would then start your clause with:
MyClass.allInstances()
Wich is a set containing all the instances of the given class. Typically, you would then operate on this set to further specify some model features.
For example, to express uniqueness of an id, you would write a Boolean clause on this set (based on example of section 7.5.10 of the OCL specs)
MyClass.allInstances()->forAll(e1, e2 | e1 <> e2 implies e1.id <> e2.id)
One of the operation you can perform on such set is to create a subset by selecting elements that match a certain condition, and this should answer your question:
MyClass.allInstances()->select(c|c.id='...')
Additional thoughts:
OCL is an abstract language. Nothing is said on how this expression will be implemented. It could be a large inefficient iteration over an in-memory collection, or a very effective SQL query. OCL will help you to define what the result should be, but not how to really get it. So performance should not be your concern at this level of abstraction.
Now, you didn’t tell the purpose of your OCL query. If it is to explain how database queries will be performed, you could see some advantages in separation of concerns: identify the relevant classes and reusable queries and enrich your model using the repository pattern: a repository is a (singleton) class MyClassRepository that acts as a container of all objects of a given MyClass in the database. You would then define operation for manipulating and querying the database. Typically, you’ll have a couple of getXxxx() operation like getById() that return one or a set of several instances. First it will make explicit what is to be implemented as a database functionality, second the new operations can be used to simplify some OCL expressions.
Yes. allInstances() is the easy solution, but potentially the least efficient and not necessarily flexible.
If your application and constraints (for one School) are expanded to multiple schools you may realize that actually you wanted the Student at a particular School, so it is often better to go to the logical context and invoke a method on the School to return a given Student. Perhaps this is what you meant by 'derive'. The implementation of School.students->at(id) might well use a Map giving multiple gains, through not searching the whole model for every access and through having a fast access to what you have already got.

How to parameterize a UML sequence diagram and apply it to multiple object instances?

I would like to to create a sequence diagram to show some interaction, and then use that sequence diagram as an interaction occurrence (sub-sequence) on other sequence diagrams. The point is I would like to apply the sub-sequence each time to a different object instance that is involved in the interaction in the sub-sequence. In my case the instances are simply various file artifacts. Is there any legitimate way of doing this prescribed by UML?
EDIT: some more clarification of my context:
I have 2 main sequence diagrams where I want to reuse the sub-sequence as an interaction occurrence
on the 1st main sequence there is one file for which the sub-sequence has to be applied 3 times
on the 2nd main sequence there are 3 different files for which the sub-sequence has to be applied 3 times
the files are read by the same object instance
I model reading from a file by a call arrow stereotyped as <<read>> to a on object instance which represents the file.
I need to reference the file somehow in the sub-sequence, but I haven't found a good and simple way of doing this.
Complicated, but formally (almost) correct solution with Collaborations
Just using InteractionUses is not enough, because this doesn't allow you to assign the actual roles in the main interaction to the generic roles of your used interaction.
Collaborations, CollaborationUses and Role Bindings can be used for this.
See my example here:
This defines a Collaboration with generic roles sender, relay and receiver and shows the interaction between them.
You can now use this collaboration in a concrete situation:
Class S uses the Collaboration two times with different role bindings to its parts (A, B and C are assumed to be able to send and receive Sig1).
With these definitions you can now create your main sequence diagram:
Unfortunately, this is not correct UML, even though there is an example in the specification (I filed an Issue https://issues.omg.org/browse/UMLR-768). You will have to fake this notation until the taskforce comes up with a fix. How to fake it, depends on how strict your tool implements the specification.
Advantage: formally correct and versatile solution, backed by an example in the specification
Disadvantage: complicated and difficult to explain, not completely usable, because of a bug in the specification
Basically there are three different ways to specify such situations.
Using a gate. Whith gates you specify the sequence with messages that start or end at a gate that is defined and in most tools (if usable at all) not shown explicitly. Instead it is modelled with messages starting or ending at the interaction border.
Similar as gates are lost and found messages. These are special messages that pass out the control to another sequence or returns from one. Such as in the case before you can define a set of further diagrams specifying the interaction in more details.
Using abstraction, which is my favorit for most of the cases. This means you extract the common interface from the classes and specify the interaction against the interface instead of the concrete classes.
Use an Interaction with Parameters:
Now we would like to reference the Lifelines of the main Interaction in the arguments of the InteractionUse. Unfortunately, in UML this is not possible, since arguments are ValueSpecifications and they cannot reference another modelelement.
However, NoMagic suggested and implemented an additional ValueSpecification, called ElementValue, that does exactly this. I think this would be a valuable addition to UML and hopefully it will be added some day. Up to then, only MagicDraw users can use this solution (as far as I know).
With this non standard element, we can model this:
The connection between the lifelines is now via the arguments for the parameters of the generic interaction. Technically the lifelines would not need to be explicitely covered by the Interaction Use, but I think that it makes sense to do it (shown in my tool with a non standard circle on the border of the Interaction Use).
Advantage:
compact and versatile solution, almost conformant to the standard
Disadvantage:
uses a non standard model element, currently only available to MagicDraw users.
pragmatic non conformant solution with covered lifelines:
The collaboration and parameter solutions allow to specify it (almost) formally correct. However, in many cases, a simplified model would be sufficient. In your case, for example, you only have two participants and they have different types. So, even though there is no formal connection between the lifelines of the used interaction, and those of the main interaction, there would be no ambiguity. You could use the covered attribute of the InteractionUse to specify, which of the lifelines (files) you are targeting at a specific InteractionUse. Could that be the pragmatic solution, you are looking for?
Advantage:
compact solution
Disadvantage:
not conformant to UML, ambiguous in more complicated situations

UML - association or aggregation (simple code snippets)

I drives me crazy how many books contradicts themselves.
Class A {} class B {void UseA(A a)} //some say this is an association,
no reference is held but communication is possible
Class A {} class B {A a;} //some say this is
aggregration, a reference is held
But many say that holding a reference is still just an association and for aggregation they use a list - IMHO this is the same, it it still a reference.
I am very confused, I would like to understand the problem.
E.g. here: http://aviadezra.blogspot.cz/2009/05/uml-association-aggregation-composition.html - what is the difference between Strong Association and Aggregation, in both cases the author uses a field to store the reference..
Another example:
This is said to be Association:
And this is said to be Aggregration:
public class Professor {
// ...
}
public class Department {
private List<Professor> professorList;
// ..
}
Again, what is the difference? It is a reference in both cases
This question has been, and will be, asked many times in many different variants, because many people, including many high-profile developers, are confused about the meaning of these terms, which have been defined in the UML. Since the question has been asked many times, it has also been answered many times. See, e.g. this answer. I'll try to summarize the UML definitions.
An association between two classes is not established via a method parameter, but rather via reference properties (class attributes), the range/type of which are the associated classes. If the type of a method parameter is a class, this does not establish an association, but a dependency relationship.
It's essential to understand the logical concept of associations first, before looking at how they are coded. An association between object types classifies relationships between objects of those types. For instance, the association Committee-has-ClubMember-as-chair, which is visualized as a connection line in the class diagram shown below, may classify the relationships FinanceCommittee-has-PeterMiller-as-chair, RecruitmentCommittee-has-SusanSmith-as-chair and AdvisoryCommittee-has-SarahAnderson-as-chair, where the objects PeterMiller, SusanSmith and SarahAnderson are of type ClubMember, and the objects FinanceCommittee, RecruitmentCommittee and AdvisoryCommittee are of type Committee.
An association is always encoded by means of reference properties, the range/type of which is the associated class. For instance, like so
class Committee { ClubMember chair; String name;}
In the UML, aggregation and composition are defined as special forms of associations with the intended meaning of classifying part-whole-relationships. In the case of aggregation, as opposed to composition, the parts of a whole can be shared with other wholes. This is illustrated in the following example of an aggregation, where a course can belong to many degree programs.
The defining characteristic of a composition is to have exclusive (or non-shareable) parts. A composition may come with a life-cycle dependency between the whole and its parts implying that when a whole is destroyed, all of its parts are destroyed with it. However, this only applies to some cases of composition, and not to others, and it is therefore not a defining characteristic. An example of a composition where the parts (components) can be detached from the whole (composite) and therefore survive its destruction, is the following:
See Superstructures 2.1.1:
An association may represent a composite aggregation (i.e., a whole/part relationship). Only binary associations can be aggregations. Composite aggregation is a strong form of aggregation that requires a part instance be included in at most one composite at a time. If a composite is deleted, all of its parts are normally deleted with it. Note that a part can (where allowed) be removed from a composite before the composite is deleted, and thus not be deleted as part of the composite. Compositions may be linked in a directed acyclic graph with transitive deletion characteristics; that is, deleting an element in one part of the graph will also result in the deletion of all elements of the subgraph below that element. Composition is represented by the isComposite attribute on the part end of the association being set to true.
Navigability means instances participating in links at runtime (instances of an association) can be accessed efficiently from instances participating in links at the other ends of the association. The precise mechanism by which such access is achieved is implementation specific. If an end is not navigable, access from the other ends may or may not be possible, and if it is, it might not be efficient. Note that tools operating on UML models are not prevented from navigating associations from non-navigable ends.
Your above examples are on different abstraction levels. Department/Course are concrete coding classes while Department/Professor are at some abstract business level. Though there is no good source (I know) explaining this fact, composition and aggregation are concepts you will use only on business level and almost never at coding level (exception below). When you are at code level you live much better with Association having role names on both sides. Roles themselves are a different(/redundant!) rendering of properties of a class that refer to the opposite class.
Aggregation as a strong binding between classes is used e.g. in database modeling. Here you can delete a master only if the aggregates have all been deleted previously (or vice vera: deleting the master will force deletion of the aggregates). The aggregate can not live on its own. The composition as in your example is (from my POV) a silly construct as it pretends to be some week aggregation. But that's simply nonsense. Then use an association. Only on a business level you can try to model (e.g.) machine parts as composite. On a concrete level a composition is a useless concept.
tl;dr;
If there is a relation between classes show it as simple association. Adding details like roles will aid when discussing domain details. Use of composition/aggregation is encouraged only when modeling on business level and dis-encouraged on code level.
I've written an article about the differences between UML Association vs Aggregation vs Composition based on the actual UML specification rather then interpretations of book authors.
The primary conclusion being that
In short, the Composition is a type of Association with real constraints and impact on development, whereas the Aggregation is purely a functional indication of the nature of the Association with no technical impact.
Navigability is a completely different property and independent of the AggregationKind.
For one thing, UML is a rich language, meaning there is more than one way to describe the same thing. That's one reason you find different ways described in different books (and conflicting answers on SO).
But a key issue is the huge disconnect between UML and source code. How a specific source code construct is represented in UML, and vice versa, is not part of the UML specification at all. To my knowledge, only one language (Java) has an official UML profile, and that's out of date.
So the representation of specific source-language constructs are left to the tool vendors, and therefore differ. If you intend to generate code from your model, you must follow the vendor's conventions. If, conversely, you wish to generate a model from existing source code, you get a model based on those same conventions. But if you transfer that model to a different tool (which is difficult at the best of times) and generate code out of that, you won't end up with the same code.
In language-and-tool-agnostic mode, my take on which relationships to use in which situations can be found here. One point there worth repeating is that I don't use undirected associations in source-code models, precisely because they have no obvious counterpart in actual code. If in the code class A has a reference to class B, and B also has one to A, then I draw two relationships instead.

Graphically Modeling Metaprogramming

Are there any tools out there that let you model how a class (or a class hierarchy) can change at runtime? For example, if I have a given number of mixin classes that will be combined at runtime and I don't know which ones will be combined until the program runs, how do you go about diagramming that type of runtime behavior?
Here's a better example. Let's say that I have a base class called IceCream, and I have over 100 possible flavors that all derive from that one IceCream class. Let's also suppose that any instance of the IceCream class can be combined with another instance of the IceCream class to create a completely unique IceCream type altogether. Given this domain, how do you use a graphical model to actually say that any one of these types can be combined at runtime?
It would be inefficient to model all the possible combinations of IceCream types, given that there can be a virtually infinite number of permuations for these 100 IceCream types. So again, here's the question: Are there any graphical modeling languages that let you specify this sort of behavior?
Your design sounds a little disturbing. If two different ice creams have different behavior, then why is it wrong to model all the possibilities? Where are you loading the behaviors from? It very well could be the case, but if so I'd guess that you want to contain the behavior instead...
If they don't have different behaviors, then all you are talking is a class "IceCream" with a "Flavor" member. Never create a second class when the only difference is data--the code must actually differ in the two cases to warrant different classes.
If I totally missed something I apologize.
Edit: Let me be more specific about "Containing behavior". If each of your ice-cream flavors had a "Taste" (which is code) and the taste is different between Vanilla, Strawberry and Chocolate--then you have 3 "Taste" ice-cream classes that are contained in one "Cone" class.
The Cone class would be what I think you are trying to model as "IceCream". Since the cone contains all three, a "Lick" method can combine those three in any way possible. Either you can lick(bottom), lick(middle) or lick(top), or you can just lick() and allow the lick method to combine all three into a single call (to be more real-code, you might pass a single variable to lick() that would be forwarded to all contained flavors).
I wonder if the personal db approach of Bento or DabbleDB could be relevant for the actual modelling part. Then maybe the Django admin's model introspection for the logic part. Sounds like you want to create an interface to a scripting language. A kind of vpl library. So, a beefed up and more reflective Django admin might be a starting point.
In general, if you want to create UML class diagrams you can exploit Generic Types in UML. Also, there is the concept of Template Parameters in UML.
Have a look at this site: Defining Generics with UML Templates
They use the Eclipse Modeling Framework as a tool.

What's the best approach to naming classes?

Coming up with good, precise names for classes is notoriously difficult. Done right, it makes code more self-documenting and provides a vocabulary for reasoning about code at a higher level of abstraction.
Classes which implement a particular design pattern might be given a name based on the well known pattern name (e.g. FooFactory, FooFacade), and classes which directly model domain concepts can take their names from the problem domain, but what about other classes? Is there anything like a programmer's thesaurus that I can turn to when I'm lacking inspiration, and want to avoid using generic class names (like FooHandler, FooProcessor, FooUtils, and FooManager)?
I'll cite some passages from Implementation Patterns by Kent Beck:
Simple Superclass Name
"[...] The names should be short and punchy.
However, to make the names precise
sometimes seems to require several
words. A way out of this dilemma is
picking a strong metaphor for the
computation. With a metaphor in mind,
even single words bring with them a
rich web of associations, connections,
and implications. For example, in the
HotDraw drawing framework, my first
name for an object in a drawing was
DrawingObject. Ward Cunningham came
along with the typography metaphor: a
drawing is like a printed, laid-out
page. Graphical items on a page are
figures, so the class became Figure.
In the context of the metaphor, Figure
is simultaneously shorter, richer, and
more precise than DrawingObject."
Qualified Subclass Name
"The names of subclasses have two jobs.
They need to communicate what class
they are like and how they are
different. [...] Unlike the names at
the roots of hierarchies, subclass
names aren’t used nearly as often in
conversation, so they can be
expressive at the cost of being
concise. [...]
Give subclasses that serve as the
roots of hierarchies their own simple
names. For example, HotDraw has a
class Handle which presents figure-
editing operations when a figure is
selected. It is called, simply, Handle
in spite of extending Figure. There is
a whole family of handles and they
most appropriately have names like
StretchyHandle and TransparencyHandle.
Because Handle is the root of its own
hierarchy, it deserves a simple
superclass name more than a qualified
subclass name.
Another wrinkle in
subclass naming is multiple-level
hierarchies. [...] Rather than blindly
prepend the modifiers to the immediate
superclass, think about the name from
the reader’s perspective. What class
does he need to know this class is
like? Use that superclass as the basis
for the subclass name."
Interface
Two styles of naming interfaces depend on how you are thinking of the interfaces.
Interfaces as classes without implementations should be named as if they were classes
(Simple Superclass Name, Qualified Subclass Name). One problem with this style of
naming is that the good names are used up before you get to naming classes. An
interface called File needs an implementation class called something like
ActualFile, ConcreteFile, or (yuck!) FileImpl (both a suffix and an
abbreviation). In general, communicating whether one is dealing with a concrete or
abstract object is important, whether the abstract object is implemented as an
interface or a superclass is less important. Deferring the distinction between
interfaces and superclasses is well >supported by this style of naming, leaving you
free to change your mind later if that >becomes necessary.
Sometimes, naming concrete classes simply is more important to communication than
hiding the use of interfaces. In this case, prefix interface names with “I”. If the
interface is called IFile, the class can be simply called File.
For more detailed discussion, buy the book! It's worth it! :)
Always go for MyClassA, MyClassB - It allows for a nice alpha sort..
I'm kidding!
This is a good question, and something I experienced not too long ago. I was reorganising my codebase at work and was having problems of where to put what, and what to call it..
The real problem?
I had classes doing too much. If you try to adhere to the single responsibility principle it will make everything all come together much nicer.. Rather than one monolithic PrintHandler class, you could break it down into PageHandler , PageFormatter (and so on) and then have a master Printer class which brings it all together.
In my re-org, it took me time, but I ended up binning a lot of duplicate code, got my codebase much more logical and learned a hell of a lot when it comes to thinking before throwing an extra method in a class :D
I would not however recommend putting things like pattern names into the class name. The classes interface should make that obvious (like hiding the constructor for a singleton). There is nothing wrong with the generic name, if the class is serving a generic purpose.
Good luck!
Josh Bloch's excellent talk about good API design has a few good bits of advice:
Classes should do one thing and do it well.
If a class is hard to name or explain then it's probably not following the advice in the previous bullet point.
A class name should instantly communicate what the class is.
Good names drive good designs.
If your problem is what to name exposed internal classes, maybe you should consolidate them into a larger class.
If your problem is naming a class that is doing a lot of different stuff, you should consider breaking it into multiple classes.
If that's good advice for a public API then it can't hurt for any other class.
If you're stuck with a name, sometimes just giving it any half-sensible name with commitment to revising it later is a good strategy.
Don't get naming paralysis. Yes, names are very important but they're not important enough to waste huge amounts of time on. If you can't think up a good name in 10 minutes, move on.
If a good name doesn't spring to mind, I would probably question whether there is a deeper problem - is the class serving a good purpose? If it is, naming it should be pretty straightforward.
If your "FooProcessor" really does process foos, then don't be reluctant to give it that name just because you already have a BarProcessor, BazProcessor, etc. When in doubt, obvious is best. The other developers who have to read your code may not be using the same thesaurus you are.
That said, more specificity wouldn't hurt for this particular example. "Process" is a pretty broad word. Is it really a "FooUpdateProcessor" (which might become "FooUpdater"), for example? You don't have to get too "creative" about the naming, but if you wrote the code you probably have a fairly good idea of what it does and doesn't do.
Finally, remember that the bare class name isn't all that you and the readers of your code have to go on - there are usually namespaces in play as well. Those can often give readers enough context to see clearly what your class if really for, even if its bare name is fairly generic.

Resources