Making a simple UML class diagram for a school - java

I'm trying to create a simple class diagram for a school. Within my class-hierarchy, a school typically consist of two main stakeholders (student & teacher) and many students can be assigned to a teacher. May I know how I can show this relationship?
I have used aggregation and enumeration in my class diagram however, I'm not exactly sure if it's correct. Could you please advise me?

Multiplicity: The way you are using multiplicities is correct (as I can foresee it). It means that there must be at least one student per teacher. Without student, there is not teacher. Sounds like a hire and fire school with no permanent teachers.
Aggregation: You may use the shared aggregation (open diamond) the way you did. It's correct but see my remarks below.
Enumeration: Regarding the <<enumeration>> you would just need a dependency rather than an association. Unlike relations to classes an <<enumeration>> is kind of a "primitive" which is not represented as object.
Role names: As #Oguz points out it's a good idea to use role names at the end of the associations. So you would put teacher near Teacher and students (plural because you have 1..*) near Student at the association. These roles would be implemented as attributes.
Additional remarks on shared aggregation:
You must not care much about shared aggregation. As per UML specification it has no common semantics (p. 110 of UML 2.5):
Indicates that the Property has shared aggregation semantics. Precise semantics of shared aggregation varies by application area and modeler.
Aggregation is more about lifetime of objects and real life applications are rather rare than often (mainly if you have to be memory aware in terms of cost or security).
So in your (and most other) case(s) the multiplicity is what you want to show. This is usually more important than showing e.g. a composite aggregation (where the child objects dies with its parent) let alone shared composition.

You can change the aggregation name to students. And In the java code, teacher class has an array, arraylist or set etc. which name is students. And there is one more thing, is this relation 1 to many or 0 to many(0..*)?
public class Teacher extends StakeHolders{
public Student[] students;
public void markAttendance(){
}
}

Related

DDD - Value Object flavor of an Entity

I've seen some DDD projects with value object representations of entities.
They usually appear like EmployeeDetail, EmployeeDescriptor, EmployeeRecord, etc. Sometimes it holds the entity ID, sometimes not.
Is that a pattern? If yes, does it have a name?
What are the use cases?
Are they value objects, parameter objects, or anything else?
Are they referenced in the domain model (as property) or are they "floating" just as parameters and returns of methods?
Going beyond...
I wonder if I can define any aggregate as an ID + BODY (detail, descriptor, etc) + METHODS (behavior).
public class Employee {
private EmployeeID id;
private EmployeeDetail detail; //the "body"
}
Could I design my aggregates like this to avoid code duplication when using this kind of object?
The immediate advantage of doing this is to avoid those methods with too many parameters in the aggregate factory method.
public class Employee {
...
public static Employee from(EmployeeID id, EmployeeDetail detail){...};
}
instead of
public class Employee {
...
public static Employee from(EmployeeID id, + 10 Value Objects here){...};
}
What do you think?
What you're proposing is the idiomatic (via case classes) approach to modeling an aggregate in Scala: you have an ID essentially pointing to a mutable container of an immutable object graph representing the state (and likely some static functions for defining the state transitions). You are moving away from the more traditional OOP conceptions of domain-driven design to the more FP conceptions (come to the dark side... ;) ).
If doing this, you'll typically want to partition the state so that operations on the aggregate will [as] rarely [as possible] change multiple branches of the state, which enables reuse of as much of the previous object graph as possible.
Could I design my aggregates like this to avoid code duplication when using this kind of object?
What you are proposing is representing the entire entity except its id as a 'bulky' value object. A concept or object's place in your domain (finding that involves defining your bounded contexts and their ubiquitous languages) dictates whether it is treated as a value object or an entity, not coding convenience.
However, if you go with your scheme as a general principle, you risk tangling unrelated data into a single value object. That leads to many conceptual and technical difficulties. Take updating an entity for example. Entities are designed to evolve in their lifecycle in response to operations performed on it. Each operation updates only the relevant properties of an entity. With your solution, for any operations, you have to construct a new value object (as value objects are defined to be immutable) as replacement, potentially copying many irrelevant data.
The examples you are citing are most likely entities with only one value object attribute.
OK - great question...
DDD Question Answered
The difference between an entity object and a value object comes down to perspective - and needs for the given situation.
Let's take a simple example...
A airplane flight to your favourite destination has...
Seats 1A, 10B, 21C available for you too book (entities)
3 of 22 Seats available (value object).
The first reflects individually identifiable seat entities that could be filled.
The second reflects that there are 3 seats available (value object).
With value object you are not concerned with which individual entities (seats) are available - just the total number.
It's not difficult to understand that it depends on who's asking and how much it matters.
Some flights you book a seat and others you book a (any) seat on a plane.
General
Ask yourself a question! Do I care about the individual element or the totality?
NB. An entity (plane) can consider seats, identity and / or value object - depending on use case. Also worth noting, it has multiple depends - Cockpit seats are more likely to be entity seats; and passenger seats value objects.
I'm pretty sure I want the pilot seat to have a qualified pilot; and qualified co-pilot; but I don't really care that much where the passengers seats. Well except I want to make sure the emergency exit seats are suitable passengers to help exit the plane in an emergency.
No simple answer, but a complex set of a pieces to thing about, and to consider for each situation and domain complexity.
Hope that explains some bits, happy to answer follow-up questions...

Modeling circular depedencies

I am trying to model down the relationship between student and course. Below are the 2 high level queries i need to support down :
Finding all the courses a student is enrolled in
Find all the students enrolled for a course.
The relationship is a M:N relation ship (many to many, i.e. multiple students enroll to multiple courses).
How can i model them in terms of java objects. Intuitively, Student and Course seem to refer each other, creating circular dependency (or back reference).
class Student{
Long id
String name
List<Course> enrolledCourses;
Long rollNumber
}
Course{
Long id
String name
List<Student> enrolledStudents;
}
Is it the right behaviour to model such requirements in the above manner.
I am a little hesitant to create such circular dependencies, but not sure how i can model it otherwise.
Is above the right approach ?
Or does there exist a better way to model these sort of behaviour's ?
If I understand you correctly you're a bit afraid of the redundancy. If Student X visits Course Y, you have Course Y in the student's list of courses and Student X in the course's list of students.
If you pay attention to the modifying methods, this will probably be the best way to model this situation.
But if your fear of ending up with a student visiting a course he wasn't in (according to the course), you'll have to do it like in relational databases and create a relation object.
Now if you think a little more about the situation, there's probably a lot to tell about this course-visit. When did the student visit the course? Did he do any exams? what were the results? Which professor lead this instance of the course? After analysing that, you'll have a much better picture of the situation.
My approach is usually to analyse the situation thoroughly first. Then I analyse my operations on the data. Finally I start thinking about an optimal representation of my data.
This is without problems in Java, and the right approach. A bijective relation, being regularly used in both directions. In JPA they would typically get an annotation to fetch them lazily.
In fact modeling with JPA annotations would allow you to express primary key, many-to-one and such.
I personally would prefer long rollNumber instead of the nullable Long rollNumber.
Of course not always a sensible thing to do, especially when the entities are subordinate.

Does it make sense to use JPA inheritance as a way to get different method implementations?

So, I have been working on familiarizing myself with JPA's inheritance features and have really liked them so far. One thing that occurred to me recently is that they could actually be used for something other than just retrieving data. Given that it can get subclasses based on a discriminator value, inheritance is actually a convenient way to transform configuration fields into implementations. Being in that stage where my knowledge-to-experience ratio is in the 'just enough to be dangerous/not enough to always realize it zone', I thought it might be best to ask if this was a good idea.
Take this example with a PRODUCT and BILLTYPE table.
Product:
int Id
int billtypeid
Billtype:
int id
varchar[15] description
Billtype is simply a billing strategy for the product (We'll say some orders may be billed by weight, while others could just be billed by case). Each bill type will require the use of different methods during the invoicing process. The Billtype table will likely only have a handful of entries, and shouldn't grow to be very large.
Would it make sense to use inheritance to subclass an abstract Billtype entity that also defines an interface for the different methods the invoice code will need? Something like this:
#Entity
#DiscriminatorColumn("description")
public abstract class BillType {
// Getters, setters
// Abstract methods that could be used elsewhere - ex:
// BigDecimal calculateInvVal(...)
}
#Entity
#DiscriminatorValue("by case")
public class CaseBillType extends BillType {
// Implementation of calculateInvVal - now when invoicing code needs this method,
// the right one is always associated with the current product!
}
This provides a convenient way to associate behaviors with fields in the database that represent configuration data, but mixes business code with entities (which, by most accounts, is very very naughty). There could be a design pattern to fix this issue that I am missing from my repertoire, but I'd really like to avoid having to write lots of, "if bill type is this, get this subclass, if bill type is this, etc" code.
What I am looking for from an answer is an explanation of potential drawbacks to this technique I may not be seeing that would justify looking for another solution to this problem.
It's useful to link a product with a BillType entity if it's possible to add, remove and modify bill types at runtime without any need to rebuild and redeploy a new version of the application. This is not the case with your example.
So if what you have is a static set of bill types, each defining a static behavior encapsulated by the BillType subclass, you could simply have a BillType enum instead. Each instance of this enum defining its own behavior. You don't need an entity hierarchy and an additional table for this.
The code to calculate the InVal in the Product entity would be exactly the same:
BigDecimal computeInVal() {
billType.calculateInVal(this);
}
The code to get all the bill types would be
return BillType.values();
And instead of the following code to associate a bill type to a product:
product.setBillType(em.find(BillType.class, ID_OF_CASE_BILL_TYPE));
you would simply have
product.setBillType(BillType.BY_CASE);

Bidirectional collection in java

I have Many-to-Many associated entities information with me.
I would like to show the user the list of "students" and if user chooses an student, show his teachers.
Conversely, user may opt to see list of teachers and he/she can select a teacher to see all the students that teacher is teaching.
I am looking to have a java collection class (java built in or 3rd party) to represent such data so that I can query for teachers based on student or vice versa.
Bidi map comes quite close but it enforces 1:1 relationship. I have many to many relationship.
Any clues?
i think you couldn't do that with a map. the most simple way would be, to create a Student class and a Teacher class. both of it could have a method like addTeacher(Teacher teacher) / addStudent(Student student). So each Student objects knows it Teachers and each Teacher object knows it Student.
I am not sure if this is what you are looking for, but you can have a look at Guava BiMap
Does this not suffice?
Map<Student, Set<Teacher>> studentsToTeachers;
Map<Teacher, Set<Student>> teachersToStudents;
It's not a single collection, but it would solve your problem, provided your implementation was correct.

On abstract classes in Java and Hibernate annotations

I am planing to create an application relying on DB using Hibernate. I will have some similar classes like teacher and student and so on. In DB they will have some fields with similar names. So I wonder If I can create a class Human with annotations for standard fields like Name, SName and so on so to just extend that class in teacher student and so on. Will it work? Does any one use it in such way?
I would suggest that teacher and student are not subclasses of human, but rather are roles that a human can play. If you make them subclasses then you are effectively saying that teacher can never be a student and vice versa.
Also, if one goes from being a student to teacher (or vice versa) then you lose any associations and history for that object.
Consider roles instead. Consider composition and delegation instead of inheritance in this example.
Take a look at Peter Coad's book: Java Design for more on this.
Also, you do want to think about the table implementation if you do decide to use inheritance: single table (with null cols for the subtype attribs) separate table or single table for super class and separate tables for subclasses.
Hibernate has extensive support for different scenarios involving inheritance and polymorphism. See the documentation
http://docs.jboss.org/hibernate/stable/core/reference/en/html/inheritance.html
The short answer is, yes you can do exactly what you want -- create a base class with fields common to subclasses. How hard/involved it is depends on how you structure the tables.

Categories