How to model associative arrays in UML? - uml

I know there are some related questions about this question, such as this, this and this, but no one of them really helped me. My array keys are dynamic, so I can't create an additional class holding this attributes (like done in second linked question).
The idea of my concept is to hold instances of classes as follows:
$instances = [
"nameOfClass" => [
//instances of "nameOfClass"
],
"nameOfClass2" => [
//instances of "nameOfClass2"
]
//some more classes
];
But I don't know how to model these concept with UML when the array-key is unanimously with the class-name.
Is there a way to model my concept/in general associative arrays?

The correct way to express this in UML is to use a qualifier, or qualified association. There you have an owner and that has a qualifier, i.e., "key", that associates to a class. Further you can give the qualifier a type, to express that your key is a String, int, or Object of a certain class.
See also p. 206 of UML 2.5.

It sounds like you are wanting to simulate classes in PHP by building an associative array of named classes, where each class name (e.g., Person or ShoppingCart) maps to a collection of instances. If so, you are essentially trying to represent a non-OO simulation of OO in UML. UML is already OO, so you are trying to jump through your own belly button!
Unlike in PHP, in UML, a Property (i.e., a variable) must be owned by a Classifier, which is usually a Class or an Association. Therefore, to express $instances as a Property, it would have to be owned by a Class or Association.
If you are willing to accept that there will be an owning Class (let's call it ClassIndex), you will then need another UML Class, probably called Class, to represent each class (e.g., Person or ShoppingCart) and its attributes (e.g., firstName and lastName). Are you getting confused by the meta-programming yet? We haven't even gotten to the part about how to track the attributes of each class and so on.
While UML has all of the parts you need to re-invent OO programming, you have a fundamental mismatch between UML and PHP. The same would be true for C or assembler. UML allows you to work at a much higher level of abstraction than those languages. Therefore, I recommend you get an OO simulation working, then use UML to model your domain classes (e.g., Person or ShoppingCart) and generate a "configuration" that your OO simulation can run.

Related

What is the difference between a class and an object?

i am learning UML and I need some clarity about class diagrams.
for example I have the class
person with firstname, surname, date of birth as attributes.
what are or is the object? i do understand the class (that is person including the attributes), i do understand the attributes. but they are also talking about objects in my book, what would that be?
thank you in advance.
Where to start? Not that easy. Trying to find the definition of Class in UML 2.5 PDF is like looking for something in the remains of the Twin towers after 9/11 :-( So I took the UML metamodel published by OMG as XMI and imported that into EA. And there were are:
Class
You find the element like this:
and it's comment reads
A Class classifies a set of objects and specifies the features that characterize the structure and behavior of those objects. A Class may have an internal structure and Ports.
So, as it looks, a Class is derived from objects. Pretty much what Carl Linnaeus did in the 18th century. We can leave that for the moment and start looking for those objects.
Object
Trying to look for an Object element in the metamodel revealed: nothing. Probably for good reason since it's going into metaphysics. And Carl from above wasn't the only guy thinking about classification of the world.
Side note: I created an instance of Class in EA and ended up with an element of the metatype Object. A relic from pre UML 2.0 times. I looked into UML 1.5 and actually found a definition of object on p. 3-64:
3.39 Object
3.39.1 Semantics
An object represents a particular instance of a class. It has identity and attribute values. A similar notation also represents a role within a collaboration because roles have instance-like characteristics.
This has settled for a long time and is still in the mindset of most people. The IT guys defined a couple of classes out of the blue (with some requirements in mind) and when you use them you have these objects. Quite the other way around our Carl was approaching things. And now 12 years after UML 1.5 we have UML 2.5 and no trace of Object!
So, per UML 2.5 an Object does not exist. But we have ObjectFlow and ObjectNodes. So there must be something. On p. 12 of UML 2.5 you find
6.3 On the Semantics of UML
6.3.1 Models and What They Model
Classifiers. A classifier describes a set of objects. An object is an individual with a state and relationships to other objects. The state of an object identifies the values for that object of properties of the classifier of the object. (In some cases, a classifier itself may also be considered an individual; for example, see the discussion of static structural features in sub clause 9.4.3.)
and a bit below
UML models do not contain objects, occurrences, or executions, because such individuals are part of the domain being modeled, not the content of the models themselves. UML does have modeling constructs for directly modeling individuals: instance specifications, occurrence specifications, and execution specifications for modeling objects, occurrences, and executions, respectively, within a particular context.
Honestly I was surprised to read that, since I still live in the past where we had object diagrams (UML tools like EA still allow to create them). And that's probably the cause of the confusion. An object is by far too complex (and it has been in discussion since the invention of philosophy) to end up as UML element. Instead, UML allows to bring light to certain aspects of an object by using e.g. SDs to see details of behavior.
Summary
It's a bit of the hen and egg problem. Mapping between real world (the "Objects") and what has been modeled (the "Class") is tough. And it depends on your goals. Are you trying to get your head around somehing that already exists and sketch its behavior or is it that you have invented something new where you want to see how it interacts?
In any case, your question, so simple it is, turns out to be an excellent one!
I like qwerty_so's well documented and comprehensive answer. May I suggest an intuitive alternative?
A class describes features of the objects that belong to the class. For example, the class Person defines firstname, surname, dateOfBirth as properties. It also defines the type of these properties.
Object of the class Person, say John:Person or Jane:Person have specific values for each of the properties. The object John would have firstname="John", lastname="Doe", dateOfBirth=1961-10-01, whereas the object Jane would have firstname="Jane", lastname="Smith",dateOfBirth=1965-02-20.
The same difference can be experimented with in popular programming languages. Example:
// definition of a class, i.e. the general rules
class Person {
private String firstname;
private String lastname;
...
public Person (String first, String last, ...) { ... }
public void doSomething() { ... }
}
// definition of objects, that abide by the classe's rules:
Person Jane = new Person("Jane", "Smith", ...);
Person P2 = new Person("John", "Doe", ...);
// the objects need to have their properties set. But the behaviors of the class can be used without redefining them
Jane.doSomething();

UML dependency or association in class diagram

I have class Controller in my java project, which has method like this:
As you can see, in the first line I am getting Singleton instance of ActualModes class and call method getActualModes().
So the first question is, which relatinship I should use in class diagram.
After that I am creating new instane of ModeContext class and then call method executeStrategy. In this case, which relatiship is better ?
It should be like this:
Access to the singleton (note the stereotype which is just convenient and no obligation or general standard) is anonymous and so you just have a dependency. The ModeContext in contrast uses a private (I don't know the scoping rules of the language you used, so I made it pivate) property called context. Note the dot which is saying exactly that.
Disclaimer: UML does not specify a mapping between Java and UML, so every answer to your question is open for debate.
I think both relationships are dependencies, drawn as dashed arrows from Controller to ActualModes and from Controller to ModeContext. The definition of 'dependency' according to the UML 2.5 specification (§7.8.4.1) is:
A Dependency is a Relationship that signifies that a single model Element or a set of model Elements requires other
model Elements for their specification or implementation.
An example of a type of relationship which is in my opinion less suited, is the association, although its definition (§11.5) is quite broad:
An Association classifies a set of tuples representing links between typed instances. (...) An Association specifies a semantic relationship that can occur between typed instances.
One could argue that there are links between Controller and the other two classes, in the form of variables, but these variables are local method variables, which exist only temporarily during the execution of the method. Associations represent more durable links, e.g. class members - as far as I understand UML and as far as I have seen associations used in practice.

Generalization between UML enumeration and class

Is it correct in accordance with UML specification for UML in version 2.5 to model generalization relationship between UML enumeration and UML class? In page 166 the specification states "As a specification of Classifier, Enumerations can participate in generalization relationships". Is it however correct to put generalization relationship between class and enumeration? If yes, how such a enumeration should than be interpreted?
Yes, you can do so. Both elements are Classifiers as the UML 2.5 metamodel shows.
As such you can use inheritance between both.
Now for your question what that would mean. Well, honestly I don't know. Enumerations are basically meant to be just enumerations. In the old days they were just that list of EnumerationLiterals. More recent languages allow for operations/properties as well. But when you pimp them with a Class, then what is the point? Generalization is a blade with two edges. Defining an amphi-car as inheriting from car and ship feels strange. It's neither of both but something new. So in case of Enumeration it's similar.
I still did not find a formal constraint, but you may use the Generalization definition to find evidence whether a generalization between a Class and an Enumeration makes sense (or find examples which have an interpretation):
A Generalization is a taxonomic relationship between a more general
Classifier and a more specific Classifier. Each instance of the
specific Classifier is also an instance of the general Classifier. (UML 2.5.1, p.138)
With your construction, an instance of the Enumeration would also be an instance of the Class (or vice versa). Now let's look at what that means.
When a Classifier is generalized, certain members of its
generalizations are inherited, that is they behave as though they were
defined in the inheriting Classifier itself. For example, an inherited
member that is an attribute may have a value or collection of values
in any instance of the inheriting Classifier... (UML 2.5.1, p.100)
In fact an Enumeration can have attributes just like any Classifier, thus why shouldn't it inherit those from a Class? Looking further into what it means to be an instance of an Enumeration or an instance of a class, we find this:
DataTypes model Types whose instances are distinguished only by their
value. ... Each value of an Enumeration corresponds to one of its
user-defined EnumerationLiterals. ... EnumerationLiterals may not
change during their existence, so any attributes on an Enumeration
shall be read-only. (UML 2.5.1, p. 209 f.)
Aha, maybe we could enumerate objects with their attribute values (instances of Class) as values of an Enumeration? Would the instances of the Enumeration than also be instances of the Class? Would that be a suitable interpretation?
I am just thinking out loud, not being sure if this makes much sense. I just wouldn't rule out that there is an interpretation just because I never encountered one or cannot imagine one. In fact, look at Enums in Java - they implicitly extend the Class java.lang.Enum and the only reason why they can not extend further user-defined classes or other Enums is that Java does not support multiple inheritance of state (Oracle Java tutorials).

UML class diagrams: how to represent the fulfillment of a role by either 1 of X xor 1..* of Y?

Let's say I have class Foo that has an association to some thing(s) that fulfill(s) a role. This role could be fulfilled by either (strictly) one Bar xor any number of Baz. Similarly, the role might be fulfilled by either any number or Bar xor any number of Baz (but a mixed collection is intolerable). Are there reasonable ways to represent these in a class diagram using only associations, classes, and interfaces? I would (really) like to avoid using OCL or constraint elements.
(The reason I would like to avoid these is because we are generating code from our UML. We have already implemented generation that handles associations, classes, and interfaces. Dealing with OCL would be quite the task. Constraint elements wouldn't be so bad but still quite a lot of work.)
I would start with the picture below and create several different versions before deciding which one generates best code (junior-40).
The yellow blocks represent necessary "glue code" needed to straighten your example against your other requirements
Consider creating an abstract class Thing and derive Bar and Baz from it. It abstract the whole role, can contain some own atts and methods if needed and is quite flexible and extendible.
Now Account has an association only with AccountOwner (role "role", as Jim L. has explained in his comment, a role name must be unique in this context).
Note that this does not eliminate the need of some additional restrictions. For example, all linked "roles" should be of the same type. Sometimes is not easy (or even possible) to remove all restrictions. Otherwise we would make complete systems out of class diagram. I agree though, that as much information as possible should be contained in classes, their taxonomies and features (atts, assocs and methods).
EXAMPLE:
EXAMPLE 2 (after comments):
This version overcomes the need to use OCL ant yet keeps the simplicity and flexibility:
Multiplicities are now also derived and refined for each concrete "role". No OCL needed. :)
You add a constraint on the class in OCL:
(self.role->exists(r|r.oclIsType(Bar)) and self.role->notexists(r|r.oclIsType(Baz)) ) or
(self.role->exists(r|r.oclIsType(Baz)) and self.role->notexists(r|r.oclIsType(Bar)))
You can try this out with MDriven Designer.
The reason for introducing OCL (object constraint language) in the UML specification was just this; ability to add constraint not possible or practical to convey with simple cardinality and type information
Could this image help you ? It is extracted from the norm.
Are you thinking of something like the following:
(source: uml-diagrams.org)
Where Account is your Foo, Person is your Bar, and Corporation is your Baz.
You can then specify multiplicity on each of the two associations: [1] for Bar (Person) and [1..*] for Baz (Corporation).

How to define this class relationship

This my UML class diagram (URL)
In above diagram, ChildParent (or Child1, Child2, and Child3) can only be initialized in MainObject->create_new_object() and store it in class Library through ObjectData->lib->add_object(key, newObject).
So, how to define UML class relationship between ChildParent, Library, and MainObject?
Thank you
Relationships between classes are structural, not behavioral. The MainObject is creating it, but it is not controlling its lifespan nor does it own it in any way. After creating is it handed over to the ObjectData, transported to the Library and stored there. There is a behavioral relationship between the MainObject and the ChildParent object, but there is not a structural relationship between the two of them. I should not depict any relationship between them.
The Library is storing it. This is a typical whole part relationship and structural. What is a library without books? Therefor would I make use of the aggregation type of relation. It is not the composition, because the Library does not control the lifespan of any ChildParent or Child object nor does it imply that the ChildObject will be destroyed when the Library object is destroyed. That might happen, but given the presented data is that not clear to me.
EDIT as a reply to a comment:
Class diagrams show the structural relationships between classes, not their usage. When a class implements an interface, then will you see that relationship in the diagram. In the code (the behaviour) might you not see this relationship, because the implementation is hidden in a factory method or provided by a IoC container or it might even be a relationship that is never used.
What is the relationship between a class (the caller) that is picking a class (the callee) from a library and between the caller and the library?
It is obvious that the caller and the library have a behavioral relationship. If the module changes, can the caller get his callee from some other class. Therefor will the library and the caller have no relationship in the class diagram.
There is a structural relationship between the caller and the callee. The caller needs the callee. Your comment does not specify the exact relationship between them, but there is a relationship. The weakest form is the dependency relationship. An example in connection with a library is that a person is lending a book from a library. When he starts to read the book, is the callee used. It does not belong intrinsically to the person as a whole, but it does belong to a certain method of the person class.
There are a lot of ways to implement a library. It can be for instance a wardrobe. What is the relationship between a person in the military and his uniforms? He needs to wear some uniforms in certain situations, yet in other situations are those uniforms forbidden to wear. Wearing an uniform is a part of the class military. You can not be in the military without wearing an uniform in the time of duty. The moment you are out of the military are you not allowed to wear the uniform anymore. Hence has a military a compositional relationship with that uniform from his wardrobe.
There are more types of relationships possible between the caller and the callee. You can not say it at forehand. You must answer it the same way as any other relationship. The first question is very clear: is this a structural relationship or not? Keywords like 'is a' and 'has a' depict a structural relationship. Keywords like 'uses', 'asks', 'picks from' show a behavioral relationship. Have you concluded that it is a structural relationship, then should you find out what the dependency between the two classes is.

Resources