Composition or aggregation - oop

Please take note of my class diagram. It shows an excerpt from a software for the management of movie showings in a cinema and comes from a study book.
The study book explains that there is a composition between the room and the seat. If a cinema employee deletes a room, the seats must of course also be deleted.
About my problem: I want to extend the example with the classes Showtime, Reservation and Movie. However, a reservation always refers to a concrete seat. I would pass a reference to a seat to the reservation:
In this case, can the composition between Room and Seat still remain or does it becomes an aggregation?
Translated with www.DeepL.com/Translator (free version)

Preliminary side remark: for the sake of simplicity, you could remove all the shared aggregation (white diamonds), because UML doesn’t define their semantic and they do not fundamentaly change the meaning compared to ordinary associations.
Let’s look at the whole scenario and keep the composite aggregaton. The consequence is the following:
If you delete a room, the seat would die. This sounds logic, because the seat does not make any sense without the enclosing room.
If you accept that a room gets deleted if still in use by a showtime, you accept that some showtimes may not be linked anymore to a room.
In a similar manner, this may propagate to the reservation, since some reservations would loose their link to a seat.
Now is this scenario a problem? I routinely have a reservation for a flight without the reservation being linked to a seat. So it is up to you to decide how you want to handle it:
You could constrain the deletion of the room to require that it is not linked to any showtime. You therefore avoid the described situation.
You could accept any room deletion, if you decide to offer some reallocation functions that would allow to deal with showtime and reservations without room and seat (at least temporarily) and reassign a showtime and the reservation to a different room.
You may even go further and opt for a mixed scenario, and accept that deletion of the room is possible if no showtime exist in the future (active showtime) bust simply do not care for for reservations on past showtimes.

Related

representing doors in ER schema

I have something like this in my ERD.
Note that there can be two rooms connected by more than 1 door.
Translating this in tables I get that every couple door-room is repeated twice (One time as entry and another time as exit). So I simplified my ERD schema like
[this]
Where room1 and room2 are foreign keys.
During lecture we never saw an '' ísolated '' (without relationships)
entity but browsing here on Stack Overflow i saw someone saying that was possible and correct.
Is my solution above correct?
Yes, there can be isolated entities in a diagram.
But your corrected diagram is incomplete: it gives the impression that the entities are isolated whereas they are not; doors and rooms are related and the relationship should appear.
If you'd correct this relation, you'd have something similar to the first diagram, but instead of IN and OUT, you'd have BETWEEN 1 and BETWEEN 2.
You would then immediately notice that your design is not fully equivalent to the original one: the original design allows to represent unidirectional doors. This sounds strange, but if you go in large office buildings, you'll see for example that:
some doors are emergency only doors: you can open it to access the emergency exit stairs, but in the stairs, you cannot go back.
some doors have a handle on only one side to allow exit an office, but yopu have to enter via another one.
The original design requires many duplicate doors because of the unidirectional design (this facilitates graph exploration algorithm). You could still achieve the same expressiveness, by adding either two attributes from_1_to_2 and from_2_to_1 or a single attribute direction which could have three values (unidirectional from 1 to 2, unidirectional from 2 to 1, or bidirectional, the encoding is left as an exercise).
This revised design would be superior to the original design, since it would prevent redundancy, and facilitate normalization if other information about doors need to be recorded (e.g. material, type of lock, fire resistance, automatic closing or not, serial number, etc...).

Discriminator field and data modeling

I have the following case.
A reservation, this reservation be canceled, it can be newly created it can be Confirmed it can be rejected.
There might be different reasons for cancelation. Lets say the reservation has expired, or it may have not been processed within certain timelimit or some other reason.
In order for a reservation to be confirmed a multiple sub - transactions should be performed. This mean that there is a flow within the Confirmation itself. The solution my team came with is some sort of work table holding many different statuses. Which is fine. I felt the need to uniquely identify the state of a reservation by declaring a field ReservationStatus that depicts certain variation of statuses that are already defined in the table. In this case the Reservation status would be NEW,CONFIRMED,CANCELED,REJECTED. Each state will depict certain variation of statuses in the work table.
My team was convinced that this is adding additional complexity. I think this is the opposite it simplifyes the flow. It also declares a natural discriminator and polymorphism. We are supposed to use Queues and asynchroneus processes.
How can I actualy jsutify that we should have such column it apears the arguments I already mentioned were not enough and deep down inside I know I am right :)?
Wanted this to be a comment but it came out too long so here it goes.
#AlexandarPetrov I would add the following questions:
Do all the Statuses concretely represent every State a Reservation could have?
Are there clear rules for all Status migration paths? For e.g. Expired -> CONFIRMED and so forth.
Do you need to model the state changes? And is it a finite state machine?
I'd personally expose the status field but only if it is concrete enough by itself to define state. For e.g. I've seen cases where there are 2 layers of statuses - status and sub-status. In a case like that boundaries are lost and state becomes a complex VO rather than a simple field and state transition rules could become blurry.
Additionally:
For me it seems like Event Sourcing and CQRS could be a good fit for all those Reservations. Especially having in mind the complex flows you mention. Then transitions will be events being applied and the statuses - a simple way to expose state. Tracking status changes separately will also be needless as the Event Stream holds all historical data.
Finally:
How can I actualy jsutify that we should have such column it apears the arguments I already mentioned were not enough and deep down inside I know I am right :)?
Well at the end you can always put your foot down and take responsibility. And if it turns out to be a wrong decision in time - bare the responsibility and admit the mistake.

What is the use of single responsibility principle?

I am trying to understand the Single Responsibility principle but I have tough time in grasping the concept. I am reading the book "Design Patterns and Best Practices in Java by Lucian-Paul Torje; Adrian Ianculescu; Kamalmeet Singh ."
In this book I am reading Single responsibility principle chapter ,
where they have a car class as shown below:
They said Car has both Car logic and database operations. In future if we want to change database then we need to change database logic and might need to change also car logic. And vice versa...
The solution would be to create two classes as shown below:
My question is even if we create two classes , let’s consider we are adding a new property called ‘price’ to the class CAR [Or changing the property ‘model’ to ‘carModel’ ] then don’t you think we also need to update CarDAO class like changing the SQL or so on.
So What is the use of SRP here?
Great question.
First, keep in mind that this is a simplistic example in the book. It's up to the reader to expand on this a little and imagine more complex scenarios. In all of these scenarios, further imagine that you are not the only developer on the team; instead, you are working in a large team, and communication between developers often take the form of negotiating class interfaces i.e. APIs, public methods, public attributes, database schemas. In addition, you often will have to worry about rollbacks, backwards compatibility, and synchronizing releases and deploys.
Suppose, for example, that you want to swap out the database, say, from MySQL to PostgreSQL. With SRP, you will reimplement CarDAO, change whatever dialect-specific SQL was used, and leave the Car logic intact. However, you may have to make a small change, possibly in configuration, to tell Car to use the new PostgreSQL DAO. A reasonable DI framework would make this simple.
Suppose, in another example, that you want to delegate CarDAO to another developer to integrate with memcached, so that reads, while eventually consistent, are fast. Again, this developer would not need to know anything about the business logic in Car. Instead, they only need to operate behind the CRUD methods of CarDAO, and possibly declare a few more methods in the CarDAO API with different consistency guarantees.
Suppose, in yet another example, your team hires a database engineer specializing in compliance law. In preparation for the upcoming IPO, the database engineer is tasked with keeping an audit log of all changes across all tables in the company's 35 databases. With SRP, our intrepid DBA would not have to worry about any of the business logic using any of our tables; instead, their mutation tracking magic can be deftly injected into DAOs all over, using decorators or other aspect programming techniques. (This could also be done of the other side of the SQL interface, by the way.)
Alright one last one - suppose now that a systems engineer is brought onto the team, and is tasked with sharding this data across multiple regions (data centers) in AWS. This engineer could take SRP even further and add a component whose only role is to tell us, for each ID, the home region of each entity. Each time we do a cross-region read, the new component bumps a counter; each week, an automated tool migrates data frequently read across regions into a new home region to reduce latency.
Now, let's take our imagination even further, and assume that business is booming - suddenly, you are working for a Fortune 500 company with multiple departments spanning multiple countries. Business Analysts from the Finance Department want to use your table to plot quarterly growth in auto sales in their post-IPO investor reports. Instead of giving them access to Car (because the logic used for reporting might be different from the logic used to prepare data for rendering on a web UI), you could, potentially, create a read-only interface for CarDAO with a short list of carefully curated public attributes that you now have to maintain across department boundaries. God forbid you have to rename one of these attributes: be prepared for a 3-month sunset plan and many many sad dashboards and late-night escalations. (And please don't give them direct access to the actual SQL table, because the implicit assumption will be that the entire table is the public interface.) Oops, my scars may be showing.
A corollary is that, if you need to change the business logic in Car (say, add a method that computes the lower sale price of each Tesla after an embarrassing recall), you wouldn't touch the CarDAO, since if car.brand == 'Tesla; price = price * 0.6 has nothing to do with data access.
Additional Reading: CQRS
For adding new property you need to change both classes only if that property should be saved to database. If it is a property used in business logic then you do not need to change DAO. Also if you change your database from one vendor to another or from SQL to NoSQL you will have to make changes only in DAO class. And if you need to change some business logic then you need to change only Car class.
Single responsibility principle as stated by Robert C. Martin means that
A class should have only one reason to change.
Keeping this principle in mind will generally lead to smaller and highly cohesive classes, which in turn means that less people need to work on these classes simultaneously, and the code becomes more robust.
In your example, keeping data access and business logic (price calculation) logic separate means that you are less likely to break the other when making changes.

Is this Library Management System ER diagram correct?

Quick question about an ER/EER Diagram.
I have made this Entity Relationship Diagram, but I have been told, that there is something wrong with it by a friend. Is there something wrong with it?
The ER diagram is a design of a Library Management System, where a member can borrow 5 books at a time. The rest of the functionality of the system is how a normal library functions.
Library Management System EER
i don't understand the utility of the relationship between the librarian and the card and i don't understand why the books are splitted in two entities.
I would do 3 entities:
-member
-card
-book
every member has one card, every card is of one member;
every member can take many books, every book can be taken by many members,
the relation between member and book create another table in the logic schema: loans. before inserting a new loan you can check if the member has alredy 5 active loans (by checking the attribute active in the loans table).
Your given context is incomplete for me. I do not see the whole description of your problem/situation, so I will answer based on assumptions, and the experience I had during my life. So let's see...
The tino user questioned the existence of two entities, title and volume, which is something important. Let me explain this for a moment, which will eliminate this as an error. Previously (a time ago) we had video rental stores (I don't know if this the right name where you live, english is not my native language). Remember? We used to go there to rent VHS tapes to watch at home.
What we rented were not films, but more copies/midia of them. A film will always have the same actor, director, title, etc., but a copy could have different attributes/properties, like the year that the media was manufactured, the available languages, the expiration year, among other things. So we had distinctly two different things.
But despite this, we have to consider whether there is a need to create two entities for persistence. We have to remember if we need to persist this information. If a copy/midia has no attributes, then it's entity should not exist, and what a user would rent really would be the movies titles.
In your case, the relationship between volume and title, I belive, is really expressing this discrepancy.
Let's talk about the relationship between librarian and title. What a librarian manages? Does It manages the titles that never change and are abstract things, or the physical objects present in the library? :)
Finally, let's talk about the borrows relationship. When we break down 1-N (or N-1) relationships, we always pass the primary key from the 1 side to the N side, solving the relationship to the formation of the Physical Model in a Entity-Relationship Diagram.
Despite this relationship here is a 0-5, to decompose it, we will not have exactly a 0-5 relationship. We would have in anyway to pass the primary key from the two sides to the table formed by this relationship. Therefore, here we have initially a N-N relationship between member and volume.
N-N relationships allow optional relations between entities. This means we can have the zero side cardinality here. To limit the number of books that can be rented, you need to implement a restriction/constraint with SQL, or with any procedural language in your database. In this case, you can implement a before insert trigger. This trigger has a duty to verify this restriction to allow or denny the completion of the operation as a whole.
Let it be clear that I'm not saying you should remove this notation. Your Conceptual Model should express it. But when you are decomposing, you have to remember that. I think you should just correct it.
Remember one important rule: Relations that have attributes/properties (the attributes/properties) can only exist in N-N relationships. If you have to put attributes/properties in a 1-N (or a N-1) relation, they (the attributes/properties) will always be on the N side. In summary, there are no N-1 (or 1-N) relationships with attributes in the relation. Only N-N relations can have attributes/properties. So be careful with this.
Any questions or clarification, please comment and I will answer.
I see no reason to distinguish member and card. Volume and Librarian don't have primary keys. Are they supposed to be weak entities? That doesn't make sense for Librarian and Volume needs an identifier to distinguish different copies.

DDD: Modeling M:N relation between two roots where the relation itself carries semantic meaning

Update Edited to reflect clarifications requested by Chris Holmes below. Originally I was referring to a Terminal as a Site but changed it to better reflect my actual domain.
At heart, I think this is a question about modeling a many to many relationship between two root entities where the relationship itself carries some semantic meaning.
In my domain
You can think of a Terminal as a branch location of our company
A Terminal can have a relationship with any number of customers
A customer can have a relationship with any number of terminals (standard many to many)
A customer\terminal relationship means that a customer can potentially store products at the Terminal
This relationship can be enabled\disabled. To be disabled merely means you are temporarily not allowed to store product, so a disabled relationship is different from no relationship at all.
A customer can have many Offices
A Terminal that has a relationship with a customer (enabled or not) must have a default office for that customer that they communicate with
There are some default settings that are applied to all transactions between a Customer and a Terminal, these are set up on a Terminal-Customer Relationship level
I think my objects here are pretty clear, Terminal, Customer, Office, and TerminalCustomerRelationship (since there is information being stored specifically about the relationship such as whether it is enabled, default office, ad default settings). Through multiple refactorings I have determined that both Terminal and Customer should probably be aggregate roots. This leaves me with the question of how to design my TerminalCustomerRelationship object to relate the two.
I suppose I could make the traversal from Terminal to TerminalCustomerRelationship unidirectional toward the relationship but I don't know how to break the relation from the relationship to the customer, especially since it needs to contain a reference to an Office which has a relationship to a Customer.
I'm new to this stuff and while most of DDD makes perfect sense I'm getting confused and need a fresh outlook. Can someone give me their opinion on how to deal with this situation?
Please note that I say Relationship not relation. In my current view it deserves to be an object in the same way that a Marriage would be an object in an application for a wedding chapel. Its most visible purpose is that it relates two objects, but it has other properties that rightfully belong to it as well.
By your description, you definitely need a "TerminalCustomerRelationship" entity to track the associated information. I would also convert the 'IsEnabled' flag into a first class 'Event' entity with a timestamp - this gives you the ability to save a history of the state changes (a more realistic view of what's happening in the domain.)
Here's a sample application (in VS2008) that refects your problem. You can tweak/test the code until the relationships make sense. Run "bin/debug/TerminalSampleApp.exe" and right-click "Terminal->Create Example" to get started.
Let me know if you find it useful.
Names can often clarify an object's responsibilities and bring a domain model into focus.
I am unclear what a Site is and that makes the entire model confusing, which makes it difficult for me to offer better advice. If a Site were a Vendor, for instance, then it would be easy to rename SiteCustomerRelationship as a Contract. In that context it makes perfect sense for Contract to be its own entity, and have the the model look like Vendor-Contract-Customer-Office.
There are other ways to look at this as well. Udi has a decent post on this sort of many-to-many relationship here.
You should not have a object Like SiteCustomerRelationship, its DB specific.
If its truly DDD you should have a Relation like:
Aggregate<Site> Customer.Site
IEnumerable<Aggregate<Office>> Customer.Offices
and perhaps
Aggregate<Office> Customer.DefaultOffice