Grails Data Modelling dilemma - sql

I'm hoping someone can help me decide the best way to model this design for what sounds like should be a simple use case.
I have a Client domain class. I have a Person command object and a Firm command object which represents either a firm or an organization.
I also have subclasses, lets call them for ClientSubClass1 and ClientSubClass2 for the sake of naming, that both extend Client.
Where I'm puzzled is that a client should be able to be either a person or a firm.
So the best way forward I feel is to use embedding and embed both a Firm class and Person class into the Client class and add a flag that indicates whether the client is a person or firm.
Otherwise I can't see how to use inheritance to accomplish what I need.
Any thoughts would be really appreciated, thanks.

In Grails you can use inheritance in your domain classes, and GORM will create and manage a flag in the database for you without you needing to explicitly declare one. I would create Person and Firm domain classes that inherit from Client.
Command classes are mainly useful for binding parameters in requests to controller actions, which is somewhat unrelated to how your data is stored and retrieved.

Well just to answer this question and wrap it up, I decided to create a higher level Contact domain class, which has a Person and Organization sub class (tableperHierarchy false).
A Client extends Person and contains an embedded Organization, and a flag to indicate whether when referring to that Client I should use the Person details or the Organization details, for instances such as when I want to display the name of the client, I know whether to use the personal name (title, forename, initials, surname) or the firm name from the embedded Organization.
Within the Contact class definition I also use an embedded Address class, held in 'src/groovy' so it doesn't create its own table.
So I have a mixture of composition and inheritance which work quite well.

Related

Should method go in class X or class Y?

This is an opinion-based question, so chances are it will be deleted.
Let's say I have class Teacher and class Course. I want to create method GetCourseId(TeacherId) that will receive as input parameter a TeacherId and will return a CourseId.
Should this method be in class Teacher or class Course?
I guess my question is that if there's a method that can fall under any number of classes, where should it finally go? Is there some unspoken rule for that?
Thanks.
I've often seen a third class created to handle something like this, where a method requires knowing about 2 classes and it doesn't quite fit in either.
In this case, it'd be the creation of a CourseManager that could contain methods like GetCourseId, GetCourseByTeachers, AddCourse, and other 'admin' tasks.
Many of these would serve as a wrapper of sorts -- CourseManager.AddCourse would likely pass a lot of work off on the Course constructor.
Normally i define classes like Teacher, Course as java beans which just hold fields, getters/setters and some very basic methods which directly use the fields and don't include any business logic.
Based on the supported functionalities/features in my application, i create business/manager classes which implement my business through communicating with the other java beans.
So if i'm creating a simple course registration application for a university, I would define 3 java beans: Teacher, Course, Student in addition to some manager classes based on the features that i want to support in my application i.e. in our case RegistrationManager which would hold methods like: registerStudentInCourse(), getStudentCourses(), addCourseTeacher() ..
Please note that I'm just sharing my way of coding, people may or may not agree with it.
The simplest solution will be having a property like
private Course course
or
private Set<Course> courses
based on cardinality (OneToOne or OneToMany) in Teacher class. It could be ManyToMany as well depends on the requirement and data modeling. You can get or set course/s assigned to the teacher using getter/setter method.
Apart from this if the relation is bidirectional than you can have similar property in Course class. In case of bidirectional mapping you can have utility method like registerCourse in the Teacher class which will set proper relations between entities.
public boolean registerCourse(Course course){
this.course = course;
course.setTeacher(this);
}
You can have this kind of utility method in Course class as well.

Should a class named `User` be an implementation of Singleton Pattern?

Today I read a lot of articles about how Singleton Pattern is bad, such as
violating single responsibility principle
inability to subclass
inability to use abstract or interface classes
High coupling across the application
make unit test difficult
And then I remember I have a program with a class named User which has field userName and password and something else related to User. In my conceive the program should only have one user instance, which is created when a human logins in my program. Based on this, should I insist design User class as Singleton Pattern, or is there any good design conceive I should use?
Additionl:
Another doubt. Using Singleton Pattern, I can get the only instance myUser everywhere. If I should not go with Singletion Pattern, How should I get the only instance myUser?
You might want to look at dependency injection. These days there exist many frameworks to assist you with wiring of the dependency injections so that you can specify in the framework that you expect a certain object to behave like a singleton. In other words if another object also requires the same "singleton" object, the framework should not create a new instance, but "inject" the already existing instance.
If you develop in Java, you may for example look at the way Guice did it: https://github.com/google/guice/wiki/Scopes They allow you to specify whether you want to create an "eager singletons" (created even if not needed yet) or "lazy singletons" (created on the fly only when required). Even if you are not using Java other programming languages got similar concepts that you could look out for.
What I would suggest is that you make the "User" object not a singleton and "inject" your "User" object into the classes that requires the "User" object. If possible, let the dependency injection framework of your choice handle the wiring so that you do not accidentally create more than one instance.
This way you will still be able to achieve most of the above mentioned advantages you posted in your question and still enjoy the benefits of a "singleton".
It depends on your context. If your application must have one and only one User, then use Singleton pattern. Your 5 points mentioned will be completely counter-productive.
In your example, this is not the case. But just one and only one instance is mandatory for the execution of one process. You should take in account #Koning response then.
For example, Spring security implements some common patterns of user logged with static methods :
SecurityContextHolder.getContext(). getAuthentication()
If you look at Microsoft memberhship than you will see that they store all data on session level. The best way I see to implement such logic which will be stored on all session level is Singleton pattern, because you won't need two classes working with user data. As alternative you can use static classes, but you couldn't serialize your user data in this case

OOP Example - How do I avoid using a helper class

I have two classes, one for contacts and another for organisations. Each contact belongs to an organisation and an organisation can have many contacts.
I want a function which creates a contact where one of the parameters is the organisation name. If the organisation name already exists then the contact will be assigned to that existing organisation. Otherwise, a new organisation will be created on the spot for the contact.
Since this function creates a contact and can also possibly create an organisation, my first thought was to create a helper class for it since it doesn't seem to belong to either class. I've been led to believe that helper classes are bad practice in OOP so I'm looking for other suggestions. How would you implement this without the use of a helper class?
It is very difficult to define what exactly is good practice in OOP and what isn't without looking at the specific case in detail. The concerns you are stating are valid, here's my answer to those:
Helper classes are not necessarily "bad practice" in OOP
There are quite a few situations, where helper classes are the way to go. If those helper classes simplify your design, they are actually favorable.
An object function may create other objects - this does not mean it has to go into a helper class.
If your contact creates an organization, that's fine. If an organization creates a contact, that's fine as well. Those two classes are part of your object design and may depend on one another without violating any design rules in OOP. I don't see why your code "should" go into a helper class at all.

Single or multiple Abstract Factories for creating objects in an inheritance hierarchy?

I have the following health club scenario (coded in C++ BTW):
I want to create random Guest and Trainer objects (so both would have names randomly generated, but the guest would also have random health data).
I want to be able to make a lot of different random generators of differing complexities.
So clearly both would need the random forename/surname generator functionality - but I'm not sure how I can keep this code in one place.
I could have an abstract factory with all generation methods (e.g. generateForename()) in it that all the objects that require random generation can use. But should a trainer have access to a factory that can generate health data even though it has nothing to do with them?
I also thought about having an abstract factory for each class - so one for person, one for customer, one for guest and have objects generate their superclasses by passing them the appropriate factory but that sounds over complex for the situation.
I am fairly new to this so forgive me if my design is a bit off.
What do you guys suggest?
I'm not sure an Abstract Factory is what you're looking for. An Abstract Factory works best when you have the same base class but you need to create different concrete instances. Although you have the root base class of Person, you actually need to create derivatives of two, different base classes.
I would endeavour to keep the methods that generate data together with the class that contains that data. This way it can be reused.
Could you create a factory method on Guest and Trainer that would then be able to use the methods in their respective base classes to generate the data? Maybe create test-specific sub-classes to keep test stuff away from real stuff?

OOP: How do I deal with objects that have mutual relations?

Let's say there are two classes related to each other via some relations. For example, a Student maintains a list of the Classes he takes, and each Class has a list of Students taking it. Then I am afraid of letting the Student directly being able to modify its set of Classes, because each modification would have to be followed by a similar modification of a Class's list of Students, and vice versa.
One solution is to have a class whose sole purpose is to keep track of Class-Student relations, say Registrar. But then if some method in Student requires knowledge of its Class list, the Student needs to be passed the Registrar. This seems bad. It seems Student shouldn't have access to the Registrar, where it can also access other Students. I can think of a solution, creating a class that acts as a mediator between Student and Registrar, showing the Student only what it needs to know, but this seems possibly like overkill. Another solution is to remove from Student any method that needs to access its classes and put it instead in Registrar or some other class that has access to Registrar.
The reason I'm asking is that I'm working on a chess game in Java. I'm thinking about the Piece-Cell relations and the Piece-Player relations. If in the above example it wasn't OK for a Student to have access to the Registrar, is it OK here for a Piece to have access to the Board, since a Piece needs to look around anyway to decide if a move is valid?
What's the standard practice in such cases?
If relations can be changed - classes should be decoupled as much as possible, so along with each class create an interface, do not introduce tied relations between classes.
High level of separation you can achieve using intermediate services/helpers which encapsulates logic of communication between classes, so in this case you should not inject one class to an other even both are abstracted by interfaces, basically Student does not know anything about Class, and Class does not know anything about Student. I'm not sure whether such complexity is makes sense in your case but anyway you can achieve it.
Here is you may find a useful design pattern Mediator which can encapsulate interaction logic between two decoupled entities, take a look at it.
With the mediator pattern, communication between objects is
encapsulated with a mediator object. Objects no longer communicate
directly with each other, but instead communicate through the
mediator. This reduces the dependencies between communicating objects,
thereby lowering the coupling.
What I think you have found in your pretty nice example and explanation is that OO does not solve all problems well. As long as the responsibility is well shaped and sharp, everything is fine. And as long each responsibility fits in exactly one bucket (the class), it is pretty easy to design. But here you have a tradeoff:
If I define for each responsibility a separate class, I will get a bloated design that is pretty difficult to understand (and sometimes to maintain).
If I include for each separate responsibility at least one interface, I will get more classes and interfaces than I need.
If I decide that one of the two classes is responsible for the relation as well, this one object has more knowledge than usual about the other.
And if you introduce in each case a mediator or something similar, your design will be more complex than the problem.
So perhaps you should ask the questions:
What is the likelihood that the relation between the 2 objects will change?
What is the likelihood that the relation will exist between more 1 type of objects at each end?
Is that part of the system a highly visible part, so that a lot of other parts will interface it (and therefore will be dependent on it)?
Take the simplest solution that could possibly work and start with that. As long as the solution is kept simple, it is only your code (you don't design a library for others), there are chances that you can change the design later without hassle.
So in your concrete case,
the board field should have access to the whole board XOR
the figure on the field should have the responsibility of moving XOR
there should be an object type (ChessGame?) that is responsible for the overall knowledge about moving, blocking, attacking ...
I do think that all are valid, and it depends on your special "business case" which one is the most valid.