How to implement design in OOP - oop

I have following structure
One organization can have many environments.
One environment can have many Applications.
One application can have many Policis.
I created class of each entities i.e.
class Organization,
class Environment,
class Application,
class Policy
Now I want to apply policies to Application.
One policy should have one Policy class object. All instances of Policy are different. Every policy have unique name and ID.
Inheritance will not work, Consider following hierarchy -
Organization
Environment(Organization)
API(Environment)
Policy(API)
because every policy, required to procide all details of API, Environment, Organization.
Can we do aggregation here? Need help on this

All instances of Policy are different.
Every policy have unique name and ID
You can indicate that with the constraint :
Policy.allInstances() -> forAll(p1, p2 |
p1 <> p2 implies (p1.name <> p2.name and p1.ID <> p2.ID))
A class diagram from the information you give can be :
I do not use bidirectional relations supposing Policy does not know the associated Application(s) whose does not know associated Environment(s) whose does not know associated Organization(s).
I use multiplicities * equivalent to 0..* because nothing in your question says the minimum multiplicity is 1 each time. I do not indicate the multiplicity in the opposite direction of the relations because your question does not indicate something about them.
Inheritance will not work
A inherits B implies A is a B, among the classes your give none of them satisfy that, so there is no possible inheritance between them.
Can we do aggregation here
may be between Environment and Application because we can say an environment is composed by applications, but else where no.

Related

Complex Django model relationships

I'm trying to build an SQL database for use in Django. I understand the model from an abstract perspective, but I don't know enough about how to build databases to know if I'm relating these objects correctly. I want to keep this abstract so I can implement the code myself.
Say I have three types of objects: A, B, and C. An A may hold one or more B. A B can hold multiple Bs or Cs in any combination, but it must have at least one (B or C) inside of it. A C merely holds some data and is a simple construct.
Currently I have:
from django.db import models
class A(models.Model):
# A attributes
class B(models.Model):
a = models.ForeignKey(A, on_delete=models.CASCADE)
# B attributes
class C(models.Model):
b = models.ForeignKey(B, on_delete=models.CASCADE)
# C attributes
I know that this just allows a Many-To-One relationship between C→B and B→A, but I don't know how to allow a B to refer to another B.
I would also like to be able to easily write a form where you start with an A with a requirement of at least one B inside of it, and you can add or remove Bs at will. Is this possible?
I think there's probably just a better way of setting up this data, but I don't see it since I'm very new to database organization.
If it helps, I'm designing a form to allow easy writing of workouts for swimming. The A is a workout, which has a title and an author. Each B is a set. Sets are composed of things like "2x50yards freestyle" or "8x100 IM on 2:00" — the Cs. But sometimes a set has sort of a sub-set, which is like a loop.
I highly recommend checking out the Django documentation on models which can be found here: Django Models
Moreover, to make a symmetrical Many to Many relationship, use:
class B(models.Model):
bs = models.ManyToManyField("self")
Additionally, I recommend making the relationship between A and B a many to many relationship instead of a foreign key. This will allow you to assign the B to many A's while still allowing 1 A to have many B's. The same logic should potentially be taken for B and C.
To answer your question about making B's required for A, I do not think this is possible. Check out this question for more information: Django 1.7: how to make ManyToManyField required?

difference between association and aggregation

I understand the difference between aggregation and composition but I am struggling a bit with association. My current understanding is that an association exists between classes when ‘they use each other’, for example, one object is passed to the other during a method call. See also:
http://www.codeproject.com/Articles/330447/Understanding-Association-Aggregation-and-Composit
Both objects exist independently and, in contrast to aggregation, no object is a container class of the other. Does this mean that both objects MUST have a copy of the other(s) (e.g. 1:m relationship) or how else is the association ‘stored’. Any feedback would be very much appreciated.
From the UML Superstructure 2.4.1:
An association declares that there can be links between instances of the associated types. A link is a tuple with one value for each end of the association, where each value is an instance of the type of the end. (UML Superstructure, Page 37)
Nothing more, nothing less. and very vague. Because of this, it is also very hard to understand. What I defined (In a course I teach) is a hierarchy of links from dependency to composition where:
Dependency from A to B means that A uses B but indirectly (say by receiving instances of it and forwarding them to other objects).
Association from A to B means that A uses B directly, (for example by calling methods)
Aggregation from A to B means that B is part of A (semantically) but B can be shared and if A is deleted, B is not deleted. Note that this says nothing about how the "is part" is implemented.
Composition from A to B is like Aggregation, where B cannot be shared and if A is deleted, all of its aggregates (Bs) are deleted also.
Aggregation is an Association relationship where the Association can be considered the containing class 'Owning' the contained class, and the lifetime of that relationship is not defined.
Association is an 'Has-A' relationship.
Example:-
public class Person
{
private final Name name;
private Address currentAddress;
//...
}
In this case, the Person Has-A name and Has-A Address, so there is an Association between Person and Name, and Person and Address.
An association describes a relationship between instances of one or more classes. In the words of the UML Reference Manual, "Associations are the glue that holds together a system."
Aggregation is a form of association in which there is a "whole-part" relationship. You may say that if a class Airplane has a class Engine then this forms a "whole-part" relationship.
Aggregation
Let's set the terms. The Aggregation is a metaterm in the UML standard, and means BOTH composition and shared aggregation, simply named shared. Too often it is named incorrectly "aggregation". It is BAD, for composition is an aggregation, too. As I understand, you meant you understand "shared aggregation and composition".
From UML standard:
Precise semantics of shared aggregation varies by application area and
modeler.
I haven't found a word about that aggregation supposed multiplicity, for example.
Association.
A definition from UML 3.4.1 standard:
An association describes a set of tuples whose values refer to typed
instances. An instance of an association is called a link. A link is a
tuple with one value for each end of the association, where each value
is an instance of the type of the end.
Aggregated relationship is a subclass of Association.
Association is based on relationship. IT is the glue for models.
But your feelings didn't lie - as the shared aggregation is not strictly defined, there is also NO any strictly defined boundary between Association and Aggregated association. Authors of tools and modellers have to set it themselves.
Association
It represents a relationship between two or more objects where all objects have their own lifecycle and there is no owner. The name of an association specifies the nature of relationship between objects. This is represented by a solid line.
Let’s take an example of relationship between Teacher and Student. Multiple students can associate with a single teacher and a single student can associate with multiple teachers. But there is no ownership between the objects and both have their own lifecycle. Both can be created and deleted independently.
Aggregation
It is a specialized form of Association where all object have their own lifecycle but there is ownership. This represents “whole-part or a-part-of” relationship. This is represented by a hollow diamond followed by a line.
Let’s take an example of relationship between Department and Teacher. A Teacher may belongs to multiple departments. Hence Teacher is a part of multiple departments. But if we delete a Department, Teacher Object will not destroy.
It depends on the context.
Association: A man drives a car, focus on the caller and callee relationship.
Aggregation: A man has a car, focus on the owner and member relationship.
Composition: A man has a mouth, focus on the owner & member but the owner consists of members, it means that they shared the same life cycle.
Feels like I'm speaking Chinglish.
Association
Association is a relationship where all objects have their own life-cycle and there is no owner. Let’s take the example of Teacher and Student. Multiple students can associate with a single teacher and a single student can associate with multiple teachers but there is no ownership between the objects and both have their own life-cycle. Both can create and delete independently.
Aggregation
the objects in Aggregation have their own life-cycle but there is ownership. Child object can not belong to another parent object. Let’s take an example of Department and teacher. A single teacher can not belongs to multiple departments, but if we delete the department teacher object will not destroy. We can think about the “has-a” relationship.
Composition
It is a strong type of Aggregation. Child object does not have their life-cycle and if parent object deletes all child object will also be deleted. Let’s take again an example of the relationship between House and rooms. House can contain multiple rooms there is no independent life of room and any room can not belongs to two different houses if we delete the house room will automatically delete.
An association between object types classifies relationships between objects of those types. For instance, the association Committee-has-ClubMember-as-chair, which is visualized as a connection line in the class diagram shown below, may classify the relationships FinanceCommittee-has-PeterMiller-as-chair, RecruitmentCommittee-has-SusanSmith-as-chair and AdvisoryCommittee-has-SarahAnderson-as-chair, where the objects PeterMiller, SusanSmith and SarahAnderson are of type ClubMember, and the objects FinanceCommittee, RecruitmentCommittee and AdvisoryCommittee are of type Committee.
See also my alternative CodeProject article.

Is it acceptable to have multiple aggregation that can theoretically be inconsistent?

I have a question about the modelling of classes and the underlying database design.
Simply put, the situation is as follows: at the moment we have Positions and Accounts objects and tables and the relationship between them is that a Position 'has an' Account (an Account can have multiple Positions). This is simple aggregation and is handled in the DB by the Position table holding an Account ID as a foreign key.
We now need to extend this 'downwards' with Trades and Portfolios. One or more Trades make up a Position (but a Trade is not a Position in itself) and one or more Portfolios make up an Account (but a Portfolio is not an Account in itself). Trades are associated with Portfolios just like Positions are associated with Accounts ('has a'). Note that it is still possible to have a Position without Trades and an Account without Portfolios (i.e. it is not mandatory to have all the existing objects broken down in subcomponents).
My first idea was to go simply for the following (the first two classes already exist):
class Account;
class Position {
Account account;
}
class Portfolio {
Account account;
}
class Trade {
Position position;
Portfolio portfolio;
}
I think the (potential) problem is clear: starting from Trade, you might end up in different Accounts depending if you take the Position route or the Portfolio route. Of course this is never supposed to happen and the code that creates and stores the objects should never be able create such an inconsistency. I wonder though whether the fact that it is theoretically possible to have an inconsistent database implies a flawed design?
Looking forward to your feedback.
The design is not flawed just because there are two ways to get from class A to class D, one way over B and one over C. Such "squares" will appear often in OOP class models, sometimes not so obvious, especially if more classes lie in the paths. But as Dan mentioned, always the business semantics determine if such a square must commute or not (in the mathematic sense).
Personally I draw a = sign inside such a square in the UML diagram to indicate that it must commute. Also I note the precise formula in an UML comment, in my example it would be
For every object a of class A: a.B.D = a.C.D
If such a predicate holds, then you have basically two options:
Trust all programmers to not break the rule in any code, since it is very well documented
Implement some error handling (like Dan and algirdas mentioned) or, if you don't want to have such code in your model, create a Checker controller, which checks all conditions in a given model instance.

Many to many with implied and explicit relationships

I have a standard many-to-many relationship in my database between Person and Widget. A Person in an administrative role has access to ALL Widgets. In my application, I want to see which Widgets a Person has access to.
I have two high level options:
Explicitly manage the relationships. When a Person becomes an administrator, relate that Person to all existing Widgets. When a Widget is created, relate that Widget to all existing administrators.
At run-time, if the Person is an administrator, assume they have access to ALL widgets and bypass the relationship table when loading Widgets.
Is one option better than the other? Is there a name for this scenario?
I have been trying to apply option 2 using NHibernate and I can't seem to figure out how to get it to bypass the relationship table when loading all Widgets for an entity (and even if I could, this would unnecessarily load alot of information unless I load Widgets separately from the Person entity and apply paging).
I would map this by means of Roles.
Roles : Person = 1 : Many
So when you create a person, you also create a new Role, unless they are an Administrator in which case they use the existing Admin Role.
Then the problem is easy: You need a WidgetRole table.
When a new Widget is created, and entry is automatically added to the WidgetRole table for NewWidget, AdminRole
When a Person changes to an Admin Role, simply change their current Role.
imo this setup is logically simpler, than having a special Admin case.
I had to share the final solution - should help anyone trying to force NH to load up a relationship that is not explicit in the DB.
I was already creating sub classes of person and NHibernate is smart enough to recognize Administrator : Person and instantiate that Person as an Administrator (where Administrator has a table with a PK/FK PersonId)
I just added a new mapping override for Administrator...
mapping.HasManyToMany(x => x.Widgets)
.Table("AdministratorWidgetAccess")
.Cascade.None();
And I added a view called AdministratorWidgetAccess...
SELECT a.PersonId as [AdministratorId], w.WidgetId as
FROM dbo.Administrator AS a LEFT OUTER JOIN
dbo.Widget AS w ON 1 = 1
When running, if the Person is an Administrator it loads up all Widgets based on the relationship in the view, otherwise it loads up Widgets based on the join table.

Larman's System Operation Contracts - CRUD example

I have some confusion with applying Larman's system operation contracts (OO Analysis from book Applying UML and Patterns) on CRUD-like operations. More precisely, I'm confused with postcondition part.
For example, if I have CRUD system operations looking as follows:
createEmployee(employee:Employee),
readEmployee(employeeId:int),
updateEmployee(employee:Employee),
deleteEmployee(employeeId:int)
what would be postcondition on, for example, readEmployee system operation, or some other operation like searchEmployees etc?
For example: for read operation, system needs to read record from database, instantiate domain object, set attribute values on domain object (set relations also) and that's it. Does it means that postconditions are above mentioned - instance creation, changes on attributes, etc. Or, read operation does not have any postcondition. None of this does sound logical to me.
My confusion is about relation between domain model (state) and database (state). I just don't get implications which above operations will have on domain model. I always think in way that the database is a place that preserves the state of the system. After I create employee, its object's state will be persisted in database... But what happens with domain model state?
The post-condition defines what the state of your application (or object, depending on the level of abstraction) should be after the operation for it to be considered as successful. For the readEmployee operation, for example, the post-condition would be that:
a new Employee instance is created.
the Employee instance contains attributes matching the database values.
the database connection is closed.
I like to think of "pre-condition" and "post-condition" as the "state of mind" of your application before and after an operation has executed, respectively. As you can imagine, it's more a thought process than a coding exercise when you do DbC.
(If you do unit-testing, states make it clear what needs to be covered by your tests. Basically, you end up testing the "state of mind" of your application.)
Interestingly, if you consider the reverse of DbC, you realise that to identify what operations your application (or object) should expose, it is simply a matter of listing what states it can have and how it transitions between these states. The actions that you need to take to make these transitions then become your operations, and you do not have to bother with implementing operations that do not lead to any desired states. So, for example, you probably want the following states for your application.
Employee details added (S1)
Employee details loaded (S2)
Employee details updated (S3)
Employee details deleted (S4)
The following state transitions are possible.
S1 -> S3 (add new employee, update the details)
S1 -> S4 (add new employee, delete the employee)
S2 -> S3 (load employee details, update employee details)
S2 -> S4 (load employee details, delete employee)
S4 -> S1 (delete employee, add new employee)
S2 -> S1 (load employee details, add new employee)
S3 -> S1 (update employee details, add new employee)
S3 -> S2 (update employee details, load employee details)
Based on the above, you can write your operations in such a way that only valid transitions are allowed, with anything else giving rise to errors.
Impossible state transitions:
S4 -> S2 (cannot delete an employee, then load their details)
S4 -> S3 (cannot delete an employee, then update their details)
State modeling is probably the most important part of designing objects, so you're asking the right questions. If you want a good resource on state modeling, get Object Lifecycles Modeling the World in States from Sally Shlaer / Stephen Mellor. It is quite an old book and costs almost nothing on Amazon, but the principles it introduces form the basis of modern UML -- incidentally, the notation used in the book looks nothing like UML.
I realise I did not touch on database state, but at the conceptual level, the database layer is just another system of states and the same principles apply.
I hope this was useful.
My interpretation of Larman's contracts is always with respect to the domain model. Larman clearly states there are only 5 types of post conditions:
Instance creation
Instance deletion
Attribute change of value.
Associations formed.
Associations broken.
Therefore, a Read (or search) operation would have no post conditions, at least not on the elements that are being read or searched. For example, if 10,000 users performed reads/searches in one day, but never did any of the other operations (C, U, D), there would be no change to the objects in the domain.
There is an exception to this, however, in domains where searches/reads are remembered. For example, Google surely keeps track of searches. In this case, doing a search has the postcondition of creating a new object in their domain model, e.g., A Search instance s was created (instance creation).
The confusing comes form mentioning data model relation within the contract template that Larman provided as in :
Contract CO2: enterItem
Operation: enterItem(itemID : ItemID, quantity : integer)
...
sli was associated with a ProductSpecification, based on itemID match (association formed).
The detail referential properties of the database should not be mentioned in the operation contract. It is better to leave it as: "sli was associated with a ProductSpecification".
In fact, it is one of the things that Larman's operation contracts does not talk about in much detail. Think about a contract for an operation that calculates a total number of items and return the total ! seems that it cannot be written as an operation contract.