What is the difference between a class and an object? - uml

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();

Related

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.

How to modelize smart contracts in UML?

I am looking for a way to modelize ethereum smart contracts interaction using a modeling language like UML.
I have the following serivce Contract:
contract ServiceContract {
constructor (address _storeC, address _quizC, address _signC) {
StorageContract storeC = StoreContract(_storeC);
QuizContract quizC = QuizContract(_quizC);
SignatureContract signC = SignatureContract(_signC);
}
function storeData (bytes32 data) public {
storeC.save(data);
}
function getAnswer( bytes32 question) public constant returns (bytes32) {
return quizC.get(question);
}
function sign (bytes32 data) public returns (bytes32) {
return signC.sign(data);
}
}
I modelized it with this class diagram, is it correct?
[Edited for extra clarification]
Modelling a system is describing it in a formal way using a modelling language, and in some cases following some common guidelines. In this case you suggest the use of UML (See UML Specification).
UML diagrams can be divided into three categories:
Structural: The common structure, the values, the classifiers and the packages are in this category
Behavioral: The common behavior, the actions, state machines, the activities and the interactions are in this category.
Suplemental: The use cases, the deployments and the information flows are in this category.
As a modeler you decide which diagrams do you you need for what target you want to apply.
In your question you say that you are looking for a way to modelize an interaction. That is within the behavioral category. However you provide a sample code and a proposed class diagram, which is within the structural category.
That being said, is it your proposed diagram correct? I would say that it is inaccurate and incomplete (but not necessarily incorrect). Let me explain this a bit further.
In your proposed diagram you have four classes: ServiceContract, StorageContract, QuizContract and SignatureContract. You have drawn a relationship between the classes that is known as a dependency. And this dependency is of a specific type: usage (represented by the «use» keyword). What does this mean in UML?
A dependency in UML is defined as a relation where "the semantics of the clients are not complete without the suppliers" (Section 7.7.3.1 of the UML specification). Moreover, a usage dependency is defined as a relation where "one NamedElement requires another NamedElement (or set of NamedElements) for its full implementation or operation" (Section 7.7.3.2).
Hence, if we apply those defintions to your proposed diagram, you may read the relation between the ServiceContract and the StorageContract as "ServiceContract uses StorageContract". But nothing else. With this diagram you don't know how ServiceContract uses StorageContract, if it uses more than one instance of StorageContract, and so on.
Since you know how those classes are related, you should use a more accurate and complete diagram.
The first step is to use an association instead of a dependency. In UML an association is defined as "a semantic relationship that can occur between typed instances". And you know the semantic relationship between the classes that you are modelling in your class diagram. Therefore it makes more sense to use an association.
An association is represented with a solid line (indeed the UML specification says that it may be drawn as a diamond, but for binary associations it says that normally it is drawn just with a solid line). So let's start changing your diagram to the new one. In the next figure you can see the four classes with the association relationship (still incomplete):
Now that we have the association, we need to define it further. Has the association a name? Can the association be read in both ways? Do we know the multiplicity values for each end of the association? Do the ends of the associations have contraints?
In this example we don't need a name for the association, it seems that it can be read in both ways, and also that the multiplicity values are exactly 1 for all the ends. Then we do not to add anything to the diagram related to these questions. But what about the constraints?
Let's take a look at the source code. When you put this:
contract ServiceContract {
constructor (address _storeC, address _quizC, address _signC) {
StorageContract storeC = StoreContract(_storeC);
QuizContract quizC = QuizContract(_quizC);
SignatureContract signC = SignatureContract(_signC);
}
}
you can express it as "the ServiceContract has (owns) a property named storeC that is of a type of StoreContract", and so on. An ownership in an association is represented by a small filled circle (called a dot), at the point where the line meets the Classifer that is owned. Also you can add the name of the property that holds the ownership (Section 11.5.4). At this point the diagram is like this:
(See the answer from Thomas Kilian)
Since we cannot infer the visibility of the properties from the source, we can just let it as undefined (otherwise we can use a + sign before the name of the property for a public property, a - sign for a private property, a # for a protected property, and a ~ for a package).
Also we can show the properties within the Classifier for ServiceContract instead of at the end of the owned Classifier in the association. This will look like this:
Both styles are allowed by the UML specification (Section 9.5.3), and it also does not enforce any convention. However it mentions the convention for general modelling scenarios "that a Property whose type is a kind of Class is an Association end, while a property whose type is a kind of DataType is not".
This diagram is correct in the sense that it complies with the UML specification, and that it describes a system in which you have:
A Classifier named ServiceContract that owns three properties:
A Property named storeC whose type is a Classifier named StorageContract.
A Property named quizC whose type is a Classifier named QuizContract.
A Property named signC whose type is a Classifier named SignatureContract.
And remember, it is your choice, as a modeler, if this is enough for your target or not.
From the source I can say that the previous diagram is still incomplete and inaccurate. Why?
Because the source includes three Operations (the functions) that are not represented in the diagram. This can be improved in terms of completeness.
Because you cannot say from the diagram if the Classifiers that are owned by the ServiceContract are owned to group together a set of instances of the owned Classifiers or not. And given the case, if the owned Classifiers share the same scope or not. This can be improved in terms of accuracy.
First we are going to add the operations (the functions) to the diagram:
[NOTE: You may also add the _constructor_ to the operations.]
I guess that the functions are public, so I have included the + modifier at the beginning of each operation name.
Now for the accuracy, it seems to me that the ServiceContract groups together the StorageContract, the QuizContract and the SignatureContract in order to provide a common Classifier to access to certain operations (functions). If that is the case, then we are talking about aggregation. In UML aggregation is defined as an association where "one instance is used to group together a set of instances" (Section 9.5.3).
An aggregation can be of two types: shared (or just commonly known as aggregation from previous versions of the specification), and composite (or just commonly known as composition from previous versions of the specification).
The UML specification provides a more or less specific semantics for what it means for an aggregation to be of the type composite: "the composite object has responsibility for the existence and storage of the composed objects".
Let's say that in your case the existence and storage of the StorageContract, the QuizContract and the SignatureContract is responsability of the ServiceContract. Then in that case you have a composite aggregation, that is represented by a black diamond:
And it is read as "ServiceContract is composed by an owned property of classifier type StorageContract called storeC", and so on.
Keep in mind that using a composite type of aggregation you are saying that the ServiceContract object is responsible for the existence and storage. That means that whenever an instance of the ServiceContract is removed/destroyed, the associated StorageContract, QuizContract and SignatureContract must be destroyed also.
If that is not the case, and given that still the assocation matches the aggregation definition, then the only other option available is that the aggregation must be shared. The UML specification explictly does not provide a precise semantics of what a shared aggregation is, leaving the application area and the modeler with the responsability of giving those semantics.
So, if the StorageContract, the QuizContract, and the SignatureContract exist independently of the ServiceContract, and if you agree that the ServiceContract aggregates those objects according to definition given in the UML specification, you must use a shared aggregation.
A shared aggregation is represented by a hollow diamond at the end of the association of the Classifier that aggregates other Classifiers. And this it's how it looks:
And this diagram can be read as:
There are four Classifiers: ServiceContract, StorageContract, QuizContract and SignatureContract.
ServiceContract aggregates three owned properties:
storeC, of type StorageContract.
quizC, of type QuizContract.
signC, of type SignatureContract.
ServiceContract has one constructor that requires three arguments:
_storeC of type address.
_quizC of type address.
_signC of type address.
ServiceContract has three public functions:
storeData, that requires one argument of type bytes32 called data and returns nothing.
getAnswer, that requires one argument of type bytes32 called question and returns a bytes32 data type.
sign, that requires one argument of type bytes32 called data and returns a bytes32 data type.
Keep in mind that maybe for your desired target this final diagram is too detailed. It is your responsability as modeler to decide wether to include some details or not into the diagram.
You simply have associations to these three classes:
(I just drew a single relation)
The role name to the right tells in conjunction with the dot that it's a owned property of the class to the left. Not sure about the visibility (if that's private per default replace the + with a -).
While it may be goodness to spend some time to learn what exact arrow should used for particular Solidity relationship in UML (inheritance, composition etc), general trend is to let standard tool to care about this.
There is sol2uml UML generator https://github.com/naddison36/sol2uml
that is already used on https://etherscan.io
e.g. for USDT
https://etherscan.io/viewsvg?t=1&a=0xdAC17F958D2ee523a2206206994597C13D831ec7
(See image below)
So don't spend time manually drawing lines, use wiser tools to do it quicker for you.

How to model associative arrays in 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.

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).

UML Questions about 'abstract' and stereotypes

hi every body i'm trying to understand UML but there are some questions about it
In UML what is the significance of tagging a class with the stereotype <<abstract>>?
and how to express this constraint as an invariant,
A stereotype "abstract" does not exist - an abstract class should be depicted using italic font. Abstract means that a class cannot be instantiated. It needs a subclass to do so. So as a pseudo-code constraint this would mean
for all instances i of MyAbstractClass holds: i.actualClass != MyAbstractClass
or in ocl for MyAbstractClass holds
self.allInstances()->forAll(i: MyAbstractClass | i.classifier <> self)
As the word 'abstract' was not displayed in your first question version, I expanded on stereotypes in general:
First of all: When learning UML, stereotypes should not be the first things you look into. They are rather complex.
Stereotypes or keywords (both denoted with <<MyStereotype>>) do not have a general meaning. It is defined by the specific stereotype. Commonly you cannot express a stereotype as an invariant instead.
But some other aspects of UML can be shown the same way: A class from the UML Metalevel is marked with <<metaclass>> even though it does not have a stereotype or even is of different actual type. The Stereotypes themselves are shown with a <<stereotype>> marker (even if they are instances of a special class).
An example for a custom stereotype could be "Service". You could mark classes with it which represent a Service. There could be a constraint which tells you that a "Service" must implement a special Interface. In this case you could express this constraint as a (boring) invariant. But probably it is even just a marker. In the latter case you can use a keyword as replacement.
I realize this thread is a couple of years old, but I came to it when it was referenced by someone else, as supporting the assertion that the «abstract» stereotype isn't supported by the UML spec. That assertion isn't quite accurate, and I'd like to explain why. I'll start by clarifying what abstract classes are.
Abstract classes are definitions of classes that don't include complete implementation. Therefore, abstract classes can't be directly instantiated; they have to be specialized (inherited). Abstract classes are notated by italicizing the class name and the methods that are abstract, and additionally by optionally adding an {abstract} property to the class name and/or to the operations (methods, we usually say, but methods are actually the "method" by which the operation is implemented) that are abstract.
Interfaces are actually a specific type of abstract class: a class with zero implementation. Their notation is different from other types of abstract classes (don't italicize, use the «interface» keyword, and notate all the specialization arrows with dotted lines). So, as Christian says here, there is standard notation for abstract classes--at least, there is in class diagrams.
Now, while it is true, as Christian also says, that the «abstract» stereotype doesn't exist, it is also true that you can create it if you want to, and that doing so is supported by the UML spec. It's unlikely that you'll have a reason to (at least in class diagrams), but you still can.
A stereotype is an "extensibility mechanism" for UML (there are three: stereotypes, tagged values, and constraints). It allows you to more specifically define some sort of element. Stereotypes are applied to classes (metaclasses actually, metaclasses are classes whose instances are also classes). A number of stereotypes are pre-defined "Standard Stereotypes" (in UML 1.4 they were called "Standard Elements"). Examples of these are «metaclass» (again, a class whose instances are also classes) and «file» (a physical file in the context of the system developed).
Stereotypes are a type of keyword. The spec (Superstructure 2.0, Annex B, p. 663) has this to say about keywords:
UML keywords are reserved words that are an integral part of the UML
notation and normally appear as text annotations attached to a UML
graphic element or as part of a text line in a UML diagram. These
words...cannot be used to name user-defined model elements where such naming would result in ambiguous interpretation of
the model. For example, the keyword “trace” is a system-defined
stereotype of Abstraction (see Annex C, “Standard Stereotypes”) and,
therefore, cannot be used to define any user-defined stereotype.
In UML, keywords are used for four different purposes:
To distinguish a particular UML concept (metaclass) from others sharing the same general graphical form...
To distinguish a particular kind of relationship between UML concepts (meta-association) from other relationships sharing the same general graphical form...
To specify the value of some modifier attached to a UML concept (meta-attribute value)...
To indicate a Standard Stereotype (see Annex C, “Standard Stereotypes”)...
Keywords are always enclosed in guillemets («keyword»), which serve as visual cues to more readily distinguish when a keyword is being used...In addition to identifying keywords, guillemets are also used to distinguish the usage of stereotypes defined in user profiles. This means that:
Not all words appearing between guillemets are necessarily keywords (i.e., reserved words), and
words appearing in guillemets do not necessarily represent stereotypes.
In other words, you can create any stereotype that you want, so long as it isn't a keyword. Since "abstract" is not a keyword, it follows that you can create an «abstract» stereotype.
In order to do so, however, you would have to go to some trouble, more trouble in UML 2.0 and above than in UML 1.4. UML 1.4 simply stated that a stereotype was an extension mechanism for the UML spec. One could simply define the stereotype, apply it to whichever part of the UML metamodel one wanted, and document the change. UML 2.0 wanted to formalize the relationship of a stereotype to a UML metaclass (any item on a UML diagram is a metaclass, and part of the UML metamodel). So, they came up with Profiles. This sample diagram shows how profiles work:
Now, that black arrow may look a bit strange, since you don't see it in any context but this one. UML 2.0 introduced the concept of an Extension, which it defines as "used to indicate that the properties of a metaclass are extended through a stereotype." This black arrow indicates an extension.
I'll quote Tom Pender (The UML Bible, Wiley Publishing, 2004) for an explanation of this diagram, since he does a better job than the spec (and I certainly can't improve on it):
It shows that a Component is extended by a Bean stereotype, which is required. The Bean stereotype is an abstract type, with two subtypes - Entity and Session. Each instance of Component, therefore, must be extended by an instance of either the Entity stereotype or the Session stereotype. Remember that a stereotype is a kind of class that can have properties - in this case, a Session stereotype has an attribute named state. This corresponds to a tagged definition whose value specifies the state of the Session. The tagged value is an enumeration, StateKind, which has either a stateless or stateful value.
The Component has a constraint on it, displayed in the note attached to the Component symbol, which states that a Component cannot be generalized or
specialized.
The diagram also shows that an Interface metaclass is extended by the Remote and Home stereotypes. The EJB package has a constraint, displayed in the note that sits in the package, that states a Bean must realize exactly one Home interface.
So, you can indeed use an «abstract» stereotype if you have reason to go to the trouble of creating it. The main reason that anyone might want to is to represent an abstract class in some place other than a class diagram.

Resources