How to implement in Kotlin the Composition UML relationship? - kotlin

I have a UML 2.5 class diagram with a lot of composition relationships.
I'm tying to implement them in Kotlin (I am new in Kotlin sorry):
class RuleScenarioState (val description : String){
var action: RuleStateAction? = null
var stateType : ScenarioStateType? = null
var completeCriteria : StateCompleteCriteria? = null
private class ComplexCompleteCriteria private constructor(val customCriteriaImplementation : String): StateCompleteCriteria() {
}
private class ExpressionCompleteCriteria private constructor(val expression : RegulationExpression): StateCompleteCriteria() {
}
private class RegulationNodeCompleteCriteria private constructor(val regulationNodeTreeId : UUID): StateCompleteCriteria() {
}
private class CustomCompleteCriteria private constructor(val customCriteriaImplementation : String): StateCompleteCriteria() {
}
private class CustomRuleStateAction private constructor(val customActionImplementationName : String): RuleStateAction() {
}
private class ClassificationRuleActionState private constructor(val classificationExpression : RegulationExpression): RuleStateAction() {
}
}
Unfortunately I have no idea how this classes will be used, I just have a diagram which need to implement. I think that it is bad idea to create instances with intensive state manipulations as shown above, but how to assure one-to-one instances relationship? How to implement properly UML composition relationship in Kotlin?

What does the UML model require?
I'm new to Kotlin as well. When you read about composition in this language, you must be aware of the difference between object composition, which simply means to have a property that is an object, and composition in the UML meaning, which is also called composite aggregation.
UML composite aggregation is a kind of association that ensures two things:
that a component instance (e.g. RuleStateAction) is exclusively owned by a single composite (e.g. RuleScenarioState);
that the composite (e.g. RuleScenarioState) has the responsibility for the existence and the storage of its components (e.g. RuleStateAction), and in particular that its components are destroyed should the composite be terminated.
How to implement it in Kotlin?
The first requirement means to declare a private property to the class, using private var or private val. You should also make sure not to leak the object to the outside word by returning it in a way or in another. This can be a tricky point in some cases and may require to clone the object.
The second requirement may be achieved by creating the components in the composite. Kotlin is garbage collected, so if only the composite knows about the component, once the composite is no longer used, so is its component (you could also consider making it closeable, but let's not add unnecessary difficulty ;-)
Several unrelated remarks:
According to your design you should use some abstract classes. You seem to have avoided them in your code, but they are essential for this design to work. So you'd have a private var that is initialized with an instance of a concrete class inherited from the abstract class.
your diagram tells nothing about multiplicity of components. If it's only only one there is nothing special to add. But if it is many, you'll have to consider collections.

Related

Extending vs Re-instantiating

I'm wondering which of the following two methods would be more efficient, or if it doesn't actually matter which route you take as the overhead is minuscule.
Essentially, is it better to instantiate a class (for example, 'Db') that you know is going to be used often in a parent class and simply extend the parent class whenever you want to use 'Db', or is it better to instantiate 'Db' separately in the constructor of the classes you want to use it.
Obviously the best route to take in terms of avoiding duplicate code would be to instantiate it in a parent class but just out of curiosity I was wondering if anyone has any insight into how significant/insignificant the effect on the server is for these two routes.
Route 1:
// Parent
class template {
public function __construct() {
$this->db = new Db();
}
}
// Child
class login extends template {
public function __construct() {
// Has access to $this->db
}
}
Route 2:
class login {
public function __construct() {
$this->db = new Db();
}
}
Thanks in advance.
It shouldn't matter performance wise.
If you extend the template class, you still have to instantiate the child class, which in turn will call the constructor of the parent implicitly. This means that in both cases, the DB class will be instantiated. Even worse, the extended class will probably be a little bit slower because it has the added overhead of an extra function call (that of the parent construct method).
That being said I strongly recommend to read up on composition over inheritance. Parent child relations are there to enforce an "is a" relationship. If you start extending the same class simply for performance reasons, chances are you are going to shoot yourself in the foot later on. It is simply unexpected behavior for most programmers to have unrelated classes extend from the same parent.

loose coupling related to composition

After searching different forums related to tight coupling (when a group of classes are highly dependent on one another)
Example1
class CustomerRepository
{
private readonly Database database;
public CustomerRepository(Database database)
{
this.database = database;
}
public void Add(string CustomerName)
{
database.AddRow("Customer", CustomerName);
}
}
class Database
{
public void AddRow(string Table, string Value)
{
}
}
Above class CustomerRepository is dependent on Database class so they are tightly coupled .and i think this class is also an example of Compostion ,then i searched for loose coupling so changing the above class so that tight coupling dependency is removed.
Example2
class CustomerRepository
{
private readonly IDatabase database;
public CustomerRepository(IDatabase database)
{
this.database = database;
}
public void Add(string CustomerName)
{
database.AddRow("Customer", CustomerName);
}
}
interface IDatabase
{
void AddRow(string Table, string Value);
}
class Database : IDatabase
{
public void AddRow(string Table, string Value)
{
}
}
I have searched that composition support loose coupling now my question is how example1 is tightly coupled as it were based on composition? secondly what is the relation between loose coupling and composition?
Any help will be greatly appreciated.
What you have there is not really tight coupling. Tight coupling would be this:
class CustomerRepository {
private readonly Database database;
public CustomerRepository() {
this.database = new Database;
}
}
The class has a hardcoded dependency on a specific Database class which cannot be substituted. That's really tight coupling.
The composition example you're showing is already loosely coupled, since it's entirely possible to substitute the dependency being injected into the constructor by any other Database inheriting class.
Your second example is even more loosely coupled, since it uses an interface instead of a concrete class; but that's something of a minor detail.
#deceze's explains most of your questions. I am just adding my 2 cents to his answer.
Both examples are loosely coupled but to different degrees.
Example -1 You are allowed to inject object of concrete type via its constructor.
Example -2 You are allowed to inject an objecto of abstract type via its constructor.
What makes the example 2 more loosly coupled is the due to Dependency Inversion Principle. It's main idea is - one should “Depend upon Abstractions. Do not depend upon concretions.”
Second example depends on interface and not on a Concrete class like the first one. Now comes the confusion -why interface is special why not a class both of them do the same thing?
Lets assume tomorrow if you want to delete Database Class and replace it with new class FlatFile, you need to change CustomerRepository class in the first example but not the second. In the second example the person who will create an instance of CustomerRepository only should worry replacing Database class with FlatFile Class. This is the meaning of loose copling changing Database class should not force you to change CustomerRepository class.
To answer your last question
what is the relation between loose coupling and composition?
There is no direct relation, you can still use composition and mess up the coupling between class by not implementing the Dependency inversion principle. So the right question you should ask is -
How to make a tightly coupled code to loosely coupled?
Follow Dependency inversion principle.

Multiple Inheritance: What's a good example?

I'm trying to find a good example for the use of multiple inheritance what cannot be done with normal interfaces.
I think it's pretty hard to find such an example which cannot be modeled in another way.
Edit: I mean, can someone name me a good real-world example of when you NEED to use multiple inheritance to implement this example as clean as possible. And it should not make use of multiple interfaces, just the way you can inherit multiple classes in C++.
The following is a classic:
class Animal {
public:
virtual void eat();
};
class Mammal : public Animal {
public:
virtual void breathe();
};
class WingedAnimal : public Animal {
public:
virtual void flap();
};
// A bat is a winged mammal
class Bat : public Mammal, public WingedAnimal {
};
Source: wiki.
One example where multiple class inheritance makes sense is the Observer pattern. This pattern describes two actors, the observer and the observable, and the former wants to be notified when the latter changes its object state.
A simplified version for notifying clients can look like this in C#:
public abstract class Observable
{
private readonly List<IObserver> _observers = new List<IObserver>();
// Objects that want to be notified when something changes in
// the observable can call this method
public void Subscribe(IObserver observer)
{
_observers.Add(observer);
}
// Subclasses can call this method when something changes
// to notify all observers
protected void Notify()
{
foreach (var observer in _observers)
observer.Notify();
}
}
This basically is the core logic you need to notify all the registered observers. You could make any class observable by deriving from this class, but as C# does only support single class inheritance, you are limited to not derive from another class. Something like this wouldn't work:
public class ImportantBaseClass { /* Members */ }
public class MyObservableSubclass : ImportantBaseClass, Observable { /* Members */ }
In these cases you often have to replicate the code that makes subclasses observable in all of them, basically violating the Don't Repeat Yourself and the Single Point of Truth principles (if you did MVVM in C#, think about it: how often did you implement the INotifyPropertyChanged interface?). A solution with multiple class inheritance would be much cleaner in my opinion. In C++, the above example would compile just fine.
Uncle Bob wrote an interesting article about this, that is where I got the example from. But this problem often applies to all interfaces that are *able (e.g. comparable, equatable, enumerable, etc.): a multiple class inheritance version is often cleaner in these cases, as stated by Bertrand Meyer in his book "Object-Oriented Software Construction".

Bridge Pattern - Composition or Aggregation?

I'm reading some books about Design Patterns and while some describe the relation between the abstraction and the implementation as a composition, some describe it as an aggregation. Now I wonder: is this dependant on the implementation? On the language? Or context?
The terms "composition" and "aggregation" mean more or less the same thing and may be used interchangeably. Aggregation may be used more frequently when describing container classes such as lists, dynamic arrays, maps, and queues where the elements are all of the same type; however, both terms may be found to describe classes defined in terms of other classes, regardless of whether those types are homogenous (all of the same type) or heterogenous (objects of different types).
To make this clearer:
class Car {
// ...
private:
Engine engine;
Hood hood;
};
// The car is *composed* of an engine and a hood. Hence, composition. You are
// also bringing together (i.e. *aggregating*) an engine and hood into a car.
The relationship between abstraction and implementation typically implies inheritance, rather than composition/aggregation; typically the abstraction is an interface or virtual base class, and the implementation is a fully concrete class that implements the given interface. But, to make things confusing, composition/aggregation can be a part of the interface (because, for example, you may need to set/get the objects that are used as building blocks), and they are also an approach to implementation (because you might use delegation to provide the definition for methods in your implementation).
To make this clearer:
interface Car {
public Engine getEngine();
public Hood getHood();
public void drive();
}
// In the above, the fact that a car has these building blocks
// is a part of its interface (the abstraction).
class HondaCivic2010 implements Car {
public void drive(){ getEngine().drive(); }
// ...
}
// In the above, composition/delegation is an implementation
// strategy for providing the drive functionality.
Since you have tagged your question "bridge", I should point out that the definition of the bridge pattern is a pattern where you use composition rather than inheritance to allow for variation at multiple different levels. An example that I learned at college... using inheritance you might have something like:
class GoodCharacter;
class BadCharacter;
class Mage;
class Rogue;
class GoodMage : public GoodCharacter, Mage;
class BadMage : public BadCharacter, Mage;
class GoodRogue : public GoodCharacter, Rogue;
class BadRogue : public BadCharacter, Rogue;
As you can see, this kind of thing goes pretty crazy, and you get a ridiculous number of classes. The same thing, with the bridge pattern, would look like:
class Personality;
class GoodPersonality : public Personality;
class BadPersonality : public Personality;
class CharacterClass;
class Mage : public CharacterClass;
class Rogue : public CharacterClass;
class Character {
public:
// ...
private:
CharacterClass character_class;
Personality personality;
};
// A character has both a character class and a personality.
// This is a perfect example of the bridge pattern, and we've
// reduced MxN classes into a mere M+N classes, and we've
// arguably made the system even more flexible than before.
the bridge pattern must use delegation (aggregation/composition and not inheritance). from the gang-of-four book:
Use the Bridge pattern when
* you want to avoid a permanent binding between an abstraction and its implementation. This might be the case, for example, when the implementation must be selected or switched at run-time.
* both the abstractions and their implementations should be extensible by subclassing. In this case, the Bridge pattern lets you combine the different abstractions and implementations and extend them independently.
* changes in the implementation of an abstraction should have no impact on clients; that is, their code should not have to be recompiled.
* (C++) you want to hide the implementation of an abstraction completely from clients. In C++ the representation of a class is visible in the class interface.
* you have a proliferation of classes as shown earlier in the first Motivation diagram. Such a class hierarchy indicates the need for splitting an object into two parts. Rumbaugh uses the term "nested generalizations" [RBP+91] to refer to such class hierarchies.
* you want to share an implementation among multiple objects (perhaps using reference counting), and this fact should be hidden from the client. A simple example is Coplien's String class [Cop92], in which multiple objects can share the same string representation (StringRep).
Standard UML of Bridge pattern clears out all air around the confusion. Below is an explanation with a brief example to clear the air around this.
Apologies for this lengthy code, best way is to copy this code to Visual Studio to easily understand it.
Read through the explanation written at the end of code
interface ISpeak
{
void Speak();
}
class DogSpeak : ISpeak
{
public void Speak()
{
Console.WriteLine("Dog Barks");
}
}
class CatSpeak : ISpeak
{
public void Speak()
{
Console.WriteLine("Cat Meows");
}
}
abstract class AnimalBridge
{
protected ISpeak Speech;
protected AnimalBridge(ISpeak speech)
{
this.Speech = speech;
}
public abstract void Speak();
}
class Dog : AnimalBridge
{
public Dog(ISpeak dogSpeak)
: base(dogSpeak)
{
}
public override void Speak()
{
Speech.Speak();
}
}
class Cat : AnimalBridge
{
public Cat(ISpeak catSpeak)
: base(catSpeak)
{
}
public override void Speak()
{
Speech.Speak();
}
}
-- ISpeak is the abstraction that bot Dog and Cat has to implement
-- Decoupled Dog and Cat classes by introducing a bridge "Animal" that is composed of ISpeak
-- Dog and Cat classes extend Animal class and thus are decoupled from ISpeak.
Hope this clarifies

Ensuring only factory can create instance

class XFactory {
private XFactory() {}
static void getX() {
if(...)
return new A(new XFactory());
else
return new B(new XFactory());
}
}
class A {
private A() {}
public A(XFactory xf) {}
}
class B {
private B() {}
public A(XFactory xf) {}
}
By this way I can ensure only Factory can create instances of it's belonging Classes.
Is this right approach or there is any other alternative/good approach?
The common approach (in C++) is to make the "belonging classes" constructors private, and have them declare the factory class as friend.
I would make classes A and B friends of XFactory, and keep all their constructors private. Therefore, only XFactory has access to their constructors.
That is, in C++. In Java or C#, I don't see any clean way of enforcing that at compile-time. Your example is far from fool-proof and even a bit confusing, since as long as one has an instance of XFactory, he can pass it to the constructor of A or B and instantiate them directly like that.
If you were up for hacks and could not make your constructors private, you could:
Make your factory a global singleton and to create an object:
Create a random key
Add that key to a private list in the factory object of keys in use
Pass the key to the constructor
Have the constructor retrieve the global factory object and call it to validate the key.
If they key validation fails, scuttle your program (call exit, die, ... whatever is appropriate). Or possibly email a stack tract to an admin. This is the kind of thing that should be caught quickly.
(Do I get hack points?)
Jacob
In Java you can make the constructors private and provide the factory in the form of a public nested class, since nested classes have access to the private members of the class in which they are declared.
public class ExampleClass {
private ExampleClass() {
}
public class NestedFactory {
public ExampleClass createExample() {
return new ExampleClass();
}
}
Anyone who wanted to could create an instance of ExampleClass.NestedFactory and through it instantiate ExampleClasses.
I haven't been able to figure out a way to do this that lets you then inherit from ExampleClass since the Java compiler demands that you specify a constructor for the superclass... so that's a disadvantage.