How are OO interfaces treated in component diagrams? - interface

My component diagram is mostly components, ports, and interfaces. The interfaces have operations and attributes. They do not capture any class based OO at the moment. What's the right way of doing that?
My options as I see them is either:
Add the class constructors to the component interfaces, and let the type carry remaining details like class operations.
Duplicate class interfaces into the component interfaces, e.g. having the class object as first parameter.
From the two the former is least work obviously. But perhaps there is a better way I've overlooked.

Notation
The easiest way to do this is to capture the interfaces in a separate class diagram, with only «interface» classifiers. The advantage is that these classifiers give a (hopefully short) name to an interface, and describe the attributes and operations that are needed, with all required details, including constructors (keep in mind that in UML constructors should be preceded with «Create»)
You can then show for the components in your component diagram the interfaces provided (lollipop) and required (socket) just referring to the named interfaces, without cluttering the diagram with lots of redundant interface specifications.
Design
When you refer to duplicating class interfaces at the component level, I understand that you mean to add attributes (parts?) and operations to the component.
Of course, components implementing the same implicit interface could in principle be interchangeable. However, this approach does not allow to have a clear understanding of the dependencies, and in particular use dependencies, that are practical to decouple components. In other words, your components would be hard-wired.
Adding class constructors at the component level seems cleaner in this regard, since your class constructor would reuse classes that are defined somewhere else. But if you're going into that direction, you could go one step further and consider using a factory class:
The factory class constructs objects of a given class or a given interface
Your component would be initialized or configured with such factory provided from outside. The factories could be interchanged to construct different kind of objects that meet the requirements.
*. If you go that way, I come back to the notational topic: the lolipo/socket notation would then allow to highlight better the decoupling that this design would offer.

I didn't understand the options you describe. Maybe a diagram would help. Here is how I would do it:
The specification component has two ports and is indirectly instantiated. For the realization component I select two classes that are realizing the component. Class1 has an operation that uses the service defined by interface I1. Class2 implements the service promised by I2. Since port p2 has a multiplicity of 16, the part typed by Class2 also has at least this multiplicity. The constructors (with the «create» stereotype), don't have parameters, so that the component can be constructed without any additional logic.
If you need additional logic, you can use directly instantiated components. They have constructors that could call the parametrized constructors of realizing classes and also create the wiring.

Related

Object-languages misdescribed by UML?

I've read that UML assumes by default that :
a class can inherit several others
an object is an instance of only one class
an object of a given class cannot change to another class
This leads me to the question : as there are 3 hypothesis, there are 2^3 possible combinations. Could you give me languages which would be examples of each of them ?
I mean for me Java is "false-true-true" and C++ is "true-true-true". What about the 6 others ? Or did I misinterpret the assumptions ?
Let's look at the UML 2.5 standard of the OMG, to have a definitive answer:
1.Class inheritance
The UML 2.5 standard clearly defines that a class can have none or several superclasses and, that conversely, a class can be superclass of none or several classes (see section 11.4.2 and 11.8.3.6).
So UML definitively allows multiple inheritance (as in C++ or Python). But you may as well restrict yourself and use only single inheritance and several interface implementations, like in Java and C#. You'd use a realization relationship to show the "inheritance" from an abstract interface (the inheritance arrow is then dotted).
2. Objects and classes
9.8.1: InstanceSpecifications represent instances of Classifiers in a modeled
system. They are often used to model example configurations of
instances.
FYI: the terms used in the standard are a little more general, but an object is an instance, and a class a classifier. This definition is then further refined in the semantcs in chapter 9.8.3 :
The InstanceSpecification may represent: • Classification of the
instance by one or more Classifiers, any of which may be abstract.
So UML allows objects to be an instantiation of several classes. I don't know languages that allow this, but if you do don't hesitate to comment ;-).
3. Changing class of object
I must admit that I can't answer this answer 100%. I don't think so, because, becoming an instance of another class would mean to re-insantiate a class, so it's not corresponding anymore to the definition of an instantiation.
Furthermore (see 9.8.3):
An InstanceSpecification may represent an instance at a point in time
(a snapshot). Changes to the instance may be modeled using multiple
InstanceSpecification, one for each snapshot.
This is somewhat ambiguous: a given object in a given diagram can't change classes. However, you can represent several times the object in different diagrams (snapshot) to show a change.
Conclusions
So your assumption 1 is true, 2 is false, and 3 true or false depending if you're reasoning at diagram or model level.

required interface vs interface realization vs <<use>> dependency

As the title suggest what is the difference between the three and when should one use one of the three instead of the other two?
The internet is filled with their definition but i couldn't find any text or explanation on when and where to use required interface or the <<use>> dependency.
There are only two cases in fact: realize/use on the one hand, and provided/required on the other. They essentially describe the same thing, but with different emphasis.
With realize/use you draw visible relationships from the class (or component, as in my examples below) to the interface, and thus show the interface and its operations in the diagram.
You could, of course, split that into two different diagrams.
With provided/required, on the other hand, the interface is only shown as lollipops so you can't see the operations. But you can draw visible relationships (usually "assembly") between the lollipops.
I'd say that realize/use is more appropriate if you want to show who implements what. Provided/required is more appropriate if you want to focus more on interactions between parts.
A required interface is usually shown as socket. It means that in order to have the class working it needs at runtime a counterpart with a lollipop. This counterpart in turn offers the interface via a lollipop. To decouple class and interface definition you put the interface in a stereotyped class and draw a realization from the providing class to the interface. Vice versa you draw a dependency from the requiring class to the interface. Whether you stereotype the dependency with <<use>> is more a matter of taste.
as described above and as alternate representation:

Interface in a dynamic language?

Interface (or an abstract class with all the methods abstract) is a powerful weapon in a static-typed language such as C#, JAVA. It allows different derived types to be used in a uniformed way. Design patterns encourage us to use interface as much as possible.
However, in a dynamic-typed language, all objects are not checked for their type at compile time. They don't have to implement an interface to be used in a specific way. You just need to make sure that they have some methods (attributes) defined. This makes interface not necessary, or at least not as useful as it is in a static language.
Does a typical dynamic language (e.g. ruby) have interface? If it does, then what are the benefits of having it? If it doesn't, then are we losing many of the beautiful design patterns that require an interface?
Thanks.
I guess there is no single answer for all dynamic languages. In Python, for instance, there are no interfaces, but there is multiple inheritance. Using interface-like classes is still useful:
Interface-like classes can provide default implementation of methods;
Duck-typing is good, but to an extent; sometimes it is useful to be able to write isinstance(x, SomeType), especially when SomeType contains many methods.
Interfaces in dynamic languages are useful as documentation of APIs that can be checked automatically, e.g. by development tools or asserts at runtime.
As an example, zope.interface is the de-facto standard for interfaces in Python. Projects such as Zope and Twisted that expose huge APIs for consumption find it useful, but as far as I know it's not used much outside this type of projects.
In Ruby, which is a dynamically-typed language and only allows single inheritance, you can mimic an "interface" via mixins, rather than polluting the class with the methods of the "interface".
Mixins partially mimic multiple inheritance, allowing an object to "inherit" from multiple sources, but without the ambiguity and complexity of actually having multiple parents. There is only one true parent.
To implement an interface (in the abstract sense, not an actual interface type as in statically-typed languages) You define a module as if it were an interface in a static language. You then include it in the class. Voila! You've gathered the duck type into what is essentially an interface.
Very simplified example:
module Equippable
def weapon
"broadsword"
end
end
class Hero
include Equippable
def hero_method_1
end
def hero_method_2
end
end
class Mount
include Equippable
def mount_method_1
end
end
h = Hero.new
h.weapon # outputs "broadsword"
m = Mount.new
m.weapon # outputs "broadsword"
Equippable is the interface for Hero, Mount, and any other class or model that includes it.
(Obviously, the weapon will most likely be dynamically set by an initializer, which has been simplified away in this example.)

What exactly is a Class Factory?

I see the word thrown around often, and I may have used it myself in code and libraries over time, but I never really got it. In most write-ups I came across, they just went on expecting you to figure it out.
What is a Class Factory? Can someone explain the concept?
Here's some supplemental information that may help better understand several of the other shorter, although technically correct, answers.
In the strictest sense a Class Factory is a function or method that creates or selects a class and returns it, based on some condition determined from input parameters or global context. This is required when the type of object needed can't be determined until runtime. Implementation can be done directly when classes are themselves objects in the language being used, such as Python.
Since the primary use of any class is to create instances of itself, in languages such as C++ where classes are not objects that can be passed around and manipulated, a similar result can often be achieved by simulating "virtual constructors", where you call a base-class constructor but get back an instance of some derived class. This must be simulated because constructors can't really be virtual✶ in C++, which is why such object—not class—factories are usually implemented as standalone functions or static methods.
Although using object-factories is a simple and straight-forward scheme, they require the manual maintenance of a list of all supported types in the base class' make_object() function, which can be error-prone and labor-intensive (if not over-looked). It also violates encapsulation✶✶ since a member of base class must know about all of the base's concrete descendant classes (now and in the future).
✶ Virtual functions are normally resolved "late" by the actual type of object referenced, but in the case of constructors, the object doesn't exist yet, so the type must be determined by some other means.
✶✶ Encapsulation is a property of the design of a set of classes and functions where the knowledge of the implementation details of a particular class or function are hidden within it—and is one of the hallmarks of object-oriented programming.
Therefore the best/ideal implementations are those that can handle new candidate classes automatically when they're added, rather than having only a certain finite set currently hardcoded into the factory (although the trade-off is often deemed acceptable since the factory is the only place requiring modification).
James Coplien's 1991 book Advanced C++: Programming Styles and Idioms has details on one way to implement such virtual generic constructors in C++. There are even better ways to do this using C++ templates, but that's not covered in the book which predates their addition to the standard language definition. In fact, C++ templates are themselves class factories since they instantiate a new class whenever they're invoked with different actual type arguments.
Update: I located a 1998 paper Coplien wrote for EuroPLoP titled C++ Idioms where, among other things, he revises and regroups the idioms in his book into design-pattern form à la the 1994 Design Patterns: Elements of Re-Usable Object-Oriented Software book. Note especially the Virtual Constructor section (which uses his Envelope/Letter pattern structure).
Also see the related answers here to the question Class factory in Python as well as the 2001 Dr. Dobb's article about implementing them with C++ Templates titled Abstract Factory, Template Style.
A class factory constructs instances of other classes. Typically, the classes they create share a common base class or interface, but derived classes are returned.
For example, you could have a class factory that took a database connection string and returned a class implementing IDbConnection such as SqlConnection (class and interface from .Net)
A class factory is a method which (according to some parameters for example) returns you a customised class (not instantiated!).
The Wikipedia article gives a pretty good definition: http://en.wikipedia.org/wiki/Factory_pattern
But probably the most authoritative definition would be found in the Design Patterns book by Gamma et al. (commonly called the Gang of Four Book).
I felt that this explains it pretty well (for me, anyway). Class factories are used in the factory design pattern, I think.
Like other creational patterns, it [the factory design pattern]
deals with the problem of creating
objects (products) without specifying
the exact class of object that will be
created. The factory method design
pattern handles this problem by
defining a separate method for
creating the objects, which subclasses
can then override to specify the
derived type of product that will be
created. More generally, the term
factory method is often used to refer
to any method whose main purpose is
creation of objects.
http://en.wikipedia.org/wiki/Factory_method_pattern
Apologies if you've already read this and found it to be insufficient.

Interesting Applications of Interfaces [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Why are interfaces useful?
Actually, I have a [small] idea of why interfaces are useful/necessary but...
What are [interesting or realistic] applications of interfaces?
Interfaces are interesting because you can allow 2 classes to implement the same methods. Lets look at an example.
Say I have a base class called Animal. All animals breathe, and communicate. Now lets say I have 3 classes, called Dolphin, Human, and Tiger. All of theses animals breathe and communicate. But I want to implement a walking method for the Human and Tiger. Dolphins cant walk. So I inherit the IWalk method for the latter two, and when I compile the class, I HAVE to implement the methods specified in the interface, or it won't compile. It's a contract saying, "If I want to implement this class, I have to implement these methods."
One use that I have for interfaces is to help with unit testing framework classes that are hard to mock. I will create an interface that works basically the same as the framework class and a wrapper class that implements the interface. The constructor of the wrapper class takes an instance of the framework class as an argument. The wrapper delegates the interface functionality it supports to the framework class, but I implement to my interface instead of the framework. Using the interface makes it easy for me to mock out the wrapper class's functionality in my unit tests -- either using a mocking framework or by providing a fake class that also implements the interface and supplying it via dependency injection to any classes that would normally rely on the framework class.
They allow polymorphism without some of the bad sides of inheritance.
What do I mean by bad sides of inheritance?
Code and Data inherited down a long chain (making it less obvious).
Inherited members that are over-ridden somewhere in the inheritance tree.
How can you use polymorphism?
To avoid repeating yourself. Create functions, switches, or conditionals which use the interface instead of the objects that implement the interface.
Java Specific
In Java, it often makes sense to use interfaces as a way to get multiple-inheritance.
This makes sense if something naturally fits into two categories and you have separate behavior expected for both of them.
Some Java Examples from the Web
http://home.cogeco.ca/~ve3ll/jatutor5.htm
http://java.freehep.org/lib/freehep/doc/root/index.html
http://www.codeguru.com/java/tij/tij0080.shtml
An interface (or an abstract class) is a contract you pass with the compiler. This contract says :
-- Well, compiler, make sure that all the classes that will implement this will provide at least everything that is defined in this interface !
With this insurance, you can then write methods that manipulate objects of any class implementing this interface :
void myGenericMethod( IAnInterface genericObject )
myGenericMethod method can use any member of the interface IAnInterface. It will never throw a runtime error (any missing member will have been caught by the compiler).
Utility : to give some common behavior to different objects. You may want for example to be able to call a method named GetID on any of your objects, being it a BankAccount, a ComputerCluster or an AirplaneTrip.
You will find a lot of useful interface usages in most design patterns. MSDN provides some hints about when you should use an interface here : http://msdn.microsoft.com/en-us/library/27db6csx.aspx
As tvanfosson mentioned, there very useful for mocking, also if you writing a library that depends on outside configuration you can make an IFooProvider and have the calling program implement it.
I assume you mean "interface" in the programming language sense rather than in the other senses, e.g. "User Interface".
An interface in languages like Java or C# serves two purposes. The first is to provide a contract for a type to implement; a suite of method names and signatures that the type provides to other types that use it. The second is to provide polymorphism upon that interface for the type. For example, if I have a type that implements the IFoo interface, I can pass an instance of that type to another class where the other class needs only know about the IFoo interface rather than every detail of my class that implements IFoo.
Interfaces are useful when you want to allow interoperability between two classes that do not share a common class hierarchy.
A good example of this is java.lang.CharSequence. Lots of other things can be abstractly treated as strings, but it wouldn't be correct to subclass String to do so. In fact String is final so it couldn't be done anyway.
Some time around JDK 1.4 (I beleive?) the CharSequence interface was introduced. Now String, StringBuffer, CharBuffer and lots of other existing classes in the JDK implement it. With that, new methods could be added to other APIs which accept CharSequence, allowing them to abstractly handle all of these in a unified way.
You can also implement this interface yourself and use it the same way. It's far more flexible to implement a common interface than try and force things to extend from a specific base class (or sometimes it's impossible).
I prefer to regard an interface as a description of a role to be fulfilled by each instance of an implementing class, independent of any implementation inheritance hierarchy.
By way of analogy, you can describe a "screen pass" football play in terms of how certain positions on the team interact. That description, in terms of position (or role or interface) is independent of which player happens to be playing the position at a given time. It's also independent of whether the team happens to have some talented players who can play more than one position.
The advantage of interface-oriented thinking is that it puts the focus on the role that an object fulfills in a given interaction with other objects, without concern for any other roles the object may play in other kinds of interactions. It also allows testing to focus on scenarios that are relevant to a role (and to mock or fake roles in a test scenario).