Can't figure out what's wrong with my domain object design - java

I have this 2 classes, and someone told me that I did it wrong.
class Employee {
private int employeeID;
private String employeeName;
private Seat employeeSeat;
}
This is for my employee class which has a relationship with the Seat class
class Seat {
private int seatID;
private String seatCode;
private Employee occupant;
}
I also added an employee attribute to my seat because when I retrieve the seat, I want to determine who is the current occupant of the seat. Same thing with my employee, when I retrieve it, I want to determine the employee's current seat. Now, they said that because the employee has a seat attribute, and the seat has an employee attribute, it's a terrible design.

You would have to ask the person that told you it was wrong to explain in detail what they mean. It may or may not be, but that would depend on the overall system architecture and requirements for navigating between objects.
Likely what they mean is that you should have an EmployeeSeat object to hold the relationship and any details pertaining to that relationship (start date, end date, hours, whatever). But then you have to worry about other problems like enforcing cardinality constraints (can an employee have multiple seats, or vice versa)?

Because the risk of updating one side of the relationship at runtime to point to another entity and forgetting to update the other side (leaving the model in an inconsistent state) is generally considered way worse than the slight inconvenience of working with a one-direction association. It's not always possible though.

Related

Create method to calculate a field in the Domain or in the Service

If we have a Class Book and we want to calculate the score of a Book following some rules like "if the number of pages is lower than X then we need to substract Y from the score" and using an Hexagonal Architecture. Should we place this method calculateScore() in a separate Service in case this logic changes in the future using different fields or this reponsibility should be in the Domain itself?
1st approach
package com.xxx.domain;
[...]
public class Book {
[...]
public Double score() {
[...]
}
[...]
}
2nd approach
package com.xxx.application;
[...]
public interface ScoreService {
[...]
void calculateScore(Book book);
[...]
}
Should we place this method calculateScore() in a separate Service in case this logic changes in the future using different fields or this reponsibility should be in the Domain itself?
First the clean architecture is very clear when it comes to the question "Where should business logic be placed?".
Application agnostic business logic in the entities layer.
Application specific business logic in the use case layer.
But I think your question is about something a bit different, it's about anemic or rich domain models. I can't tell you every of my thoughts here, but I have written down most of them in the blog I linked in the sentence before.
The condensed statement of mine is
rich domain models combine data and logic while anemic models separate them.
Let's think about the anemic way...
If you place the logic in a separate service it usually means that you have to expose all properties of the book. You will make them public or at least package scope if the service is in the same package.
Your question also focuses on change. You make the statement that logic changes can be better handled if the logic is put in a separate service. That's true, but it comes at a cost.
It's true that an anemic model let you add logic easier, but it is also true that each logic (each service) must have the same interpretation of the anemic model. I mean each service must know how to modify the data structure properly to keep it consistent and that will be hard to maintain when the number of services grows.
But implementing the service can also be a good intermediate step, because it will give you a hint about cohesion. The cohesion usually shows you where to place a method. E.g.
public class ScoreService {
public BookScore calculateScore(Book book, BookRentals rentals){
int pageCount = book.getPageCount();
Author author = book.getAuthor();
// calculate a new value based on pageCount and the author
// ...
OtherValue ov = book.getSomeOtherValue();
// do something with ov
int rentalCount = rentals.getCountSince(someDate);
// ... and so on
}
}
When you look at the calculateScore above you will recognize that there are a lot of get invocations on Book and less on BookRentals. This is a hint that most of the data that calculateScore needs is placed in the Book. Thus the calculateScore's cohesion is higher to Book and the method might be placed in the Bookclass. E.g.
public class Book {
public BookScore getScore(BookRentals rentals){
int pageCount = this.getPageCount();
Author author = this.getAuthor();
// calculate a new value based on pageCount and the author
// ...
OtherValue ov = this.getSomeOtherValue();
// do something with ov
int rentalCount = rentals.getCountSince(someDate);
// ... and so on
}
}
The difference is obvious:
the number of method parameters decreases. Maybe you apply DDD and Book is an aggregation root and also has access to BookRentals. Then your parameters might decrease to zero.
Since most of the properties that getScore needs are located in the Book class, you might want to lower their visibilily to private. So that uncontrolled access is not allowed.
One question that often arises when developers put the logic in the entities is: "How can an entity access data from a data store?"
My solution is to just pass a repository to the methods that need it. E.g.
public class Book {
public BookScore getScore(BookRentalRepository repo){
// ...
int rentalCount = repo.getRentalCountSince(this, someDate);
}
}
Whatever way you want to go, anemic or rich, keep the logic in a POJO. Also keep in mind that a POJO can be more than a simple data structure.
I hope my answer helps you to make a decision for your specific application.
If the calc of the score depends only on the book state, i would create a method in the book entity to calc it.
Otherwise, if it depends on other domain objects also, i would create a domain service for calculating it.
Regarding to persist the score. I would persist it just if the calc process is very complicated and takes a lot of time. Otherwise, I wouldn't persist it and calc it when need it.
In case you persist jt, you have to consider that you have to recalculate it and persist the new value every time the other values it depends on change too.

2 threads want to execute the same object , what problem will come?

For example 1 employee class is there contains employee id and employee name,and i created object for this employee class, then here 2 threads are there, these 2 threads want to execute the same employee object, then what problem will occur?
If 1 thread(t1) changes the value of employee id to 1 and another thread(t2) change the value of employee id to 2, then what problem will occur? and how to resolve it?
I checked in internet and i got it as race condition, but didn't understand completely.
Here thread names are t1,t2 and employee class is
public class Employee{
private int employeeid;
private string empname;
}
employee object creation:
Employee employee = new Employee()
if 1 thread(t1) changes the value of employee id to 1 and another thread(t2) change the value of employee id to 2, then what problem will occur?
That scenario is called a data race. If two threads each set the same variable to one value or another, then the end result will be that the variable holds one value or the other. It is not actually possible for two threads to store to the same location at the same time: The memory system will serialize the stores. So, the outcome depends on which one went first and which one went second.
There's no practical way to predict which one will go first and which will go second, so that means there's no practical way to predict the outcome. In most programs, that's considered to be a Bad Thing.
and how to resolve it?
That's up to you. Really! There is no correct answer to which thread should win the race. Usually, we "resolve" the problem by designing our programs so that their behavior doesn't depend on data races.
In your example, you have two threads that are trying to do two incompatible things. They both want to assign the same variable, but they disagree on what its value should be. That's a sign of Bad Design. It probably means that you haven't really thought about what that variable stands for in your program, or you haven't really thought about why or when it should ever be changed.
P.S., If a field of an Employee object holds an employee's ID, then it almost certainly should be a final field.

What is a good way to implement composition in Java?

The following classes display the concept of Composition in Java:
//Imagine constructors, accessors & mutators has already been created..
class Person{
private String name;
private Job job; //Person has Job
}
class Job{
private String name;
private double salary;
}
My question is: If I want to get the salary from Person, which of the following 2 options is a better practice?
1. Get job of person, then get salary from job of person
System.out.println( person.getJob().getSalary() );
OR
2. Create a getSalary method in person, so I can do this:
System.out.println(person.getSalary());
Create a method to get salary from job first.
class Person{
private String name;
private Job job;
public static double getSalary(){ //Is doing this redundant and bad practice?
job.getSalary();
}
}
Method 2 is a little bit better than method 1 because the code that gets the salary from a person is not dependent on any kind of Person->Salary relation implementation. You are free to change the way the salary is computed. In real life you can ask somebody what is is salary without knowing anything about his job. In your code, a liar can even returns an imaginary salary for him, etc.
To be honest I insist on the fact that method 1 cannot be considered as bad or false in any way, it has only small disadvantage in common situations...
Generally and personally I like method 1 because every redirection (how call this right?) make code a little bit more complicated. Imagine whole code has redirections for every relation. Even it's harder to communicate: 'do you mean Person.Salary or Person.Job.Salary?'.
But in your example I prefer method 2 because I can imagine extend Person to have multiple jobs or jobs beside pension or like.
There is a "Law" saying that option number 1 should be avoided, it's the Demeter's law aka principle of least knowledge
in particular
an object A can request a service (call a method) of an object
instance B, but object A should not "reach through" object B
to access yet another object, C, to request its services
HTH,
Carlo

Programming a one-to-many relationship

So I am surprised that doing a search on google and stackoverflow doesn't return more results.
In OO programming (I'm using java), how do you correctly implement a one-to-many relationship?
I have a class Customer and class Job. My application is for a fictious company that completes jobs for customers. My current implementation is so that the Job class doesn't have anything to do with the Customer class, there is no reference to it at all. The Customer class uses a collection and methods to hold, retrieve and modify information about the Jobs that have been assigned by and/or completed for a customer.
The question is, what if I'd want to find out for which customer a particular Job has been done? I've only found this article that's relevant: http://www.ibm.com/developerworks/webservices/library/ws-tip-objrel3/index.html.
According to the implementation of the author, I would let the Job constructor take a Customer parameter, and store it so I can retrieve it. However, I see no guarantee at all that this model can be consistent. There are no restirctions to set the related customer for a job as a customer that the job was not for, and add jobs to customers that were done for someone else. Any help on this would be appreciated.
There's no 100% surefire way to maintain the integrity.
The approach which is usually taken is to use one method to construct the relationship, and construct the other direction in that same method. But, as you say, this doesn't keep anyone from messing with it.
The next step would be to make some of the methods package-accessible, so that at least code which has nothing to do with yours can't break it:
class Parent {
private Collection<Child> children;
//note the default accessibility modifiers
void addChild(Child) {
children.add(child);
}
void removeChild(Child) {
children.remove(child);
}
}
class Child {
private Parent parent;
public void setParent(Parent parent){
if (this.parent != null)
this.parent.removeChild(this);
this.parent = parent;
this.parent.addChild(this);
}
}
In reality, you won't often model this relationship in your classes. Instead, you will look up all children for a parent in some kind of repository.
Maybe you didn't expect a complex (and zero-code) answer, but there is no solution to build your bombproof API the way you intend it. And it's not because the paradigm (OO) or the platform (Java), but only because you made a wrong analysis. In a transactional world (every system that models real life problems and their evolution over time is transactional) This code will ever break at some point:
// create
Job j1 = ...
Job j2 = ...
...
// modify
j1.doThis();
...
// access
j2.setSomeProperty(j1.someProperty);
because at the time j1.someProperty is accessed, j1 and j2 could not even exist :)
TL;DR
The long answer to this is immutability, and it also introduces the concepts of life cycle and transactions. All other answers tell you how to do it, instead I want to outline why. A one-to-many relationship has two sides
has many
belongs to
Your system is consistent as long as if Customer A has Job B, the Job B belongs to Customer A. You can implement this in a number of ways, but this must happen in a transaction, ie a complex action made of simple ones, and the system must be unavailble until the transaction has finished execution. Does this seem too abstract and unrelated to your question? No, it isn't :) A transactional system ensures that clients can access system's objects only if all these objects are in a valid state, hence only if the whole system is consistent. From other answers you see the amount of processing needed to solve some problems, so that guarantee comes at a cost: performance. This is the simple explanation why Java (and other general purpose OO languages) can't solve your problem out of the box.
Of course, an OO language can be used to both model a transactional world and accessing it, but special care must be taken, some constraints must be imposed and a special programming style be required to client developers. Usually a transactional system offers two commands: search (aka query) and lock. The result of the query is immutable: it's a photo (ie a copy) of the system at the very specific moment it was taken, and modifying the photo has obviously no effect on the real world. How can one modify the system? Usually
lock the system (or parts of it) if/when needed
locate an object: returns a copy (a photo) of the real object which can be read and written locally
modify the local copy
commit the modified object, ie let the system update its state based on provided input
discard any reference to (now useless) local objects: the system has changed changed, so the local copy isn't up to date.
(BTW, can you see how the concept of life cycle is applied to local and remote objects?)
You can go with Sets, final modifiers and so on, but until you introduce transactions and immutability, your design will have a flaw. Usually Java applications are backed by a database, which provides transactional functionalities, and often the DB is coupled with an ORM (such as Hibernate) to write object oriented code.
You can ensure that there are no duplicates by using a Set implementation like HashSet instead of using other data-structure.
And instead of adding Job to a customer, create an final inner class in Job class that has private constructor. That ensure that the wrapper inner class can only be created by a job object. Make you Job constructor take in jobID and customer as parameter. To maintain consistency -if customer is Null throw Exception as dummy jobs shouldn't be created .
In add method of Customer, check to see if the Job wrapped by JobUnit has the same customer ID as the its own id, if not throw Exception.
When replacing a customer in Job class remove the JobUnit using the method provided by Customer class and add itself to the new customer and change the customer reference to the newly passed customer.
That way you can reason with your code better.
Here's what your customer class might look like.
public class Customer {
Set<JobUnit> jobs=new HashSet<JobUnit>();
private Long id;
public Customer(Long id){
this.id = id;
}
public boolean add(JobUnit unit) throws Exception{
if(!unit.get().getCustomer().id.equals(id))
throw new Exception(" cannot assign job to this customer");
return jobs.add(unit);
}
public boolean remove(JobUnit unit){
return jobs.remove(unit);
}
public Long getId() {
return id;
}
}
And the Job Class:
public class Job {
Customer customer;
private Long id;
final JobUnit unit;
public Job(Long id,Customer customer) throws Exception{
if(customer==null)
throw new Exception("Customer cannot be null");
this.customer = customer;
unit= new JobUnit(this);
this.customer.add(unit);
}
public void replace(Customer c) throws Exception{
this.customer.remove(unit);
c.add(unit);
this.customer=c;
}
public Customer getCustomer(){
return customer;
}
/**
* #return the id
*/
public Long getId() {
return id;
}
public final class JobUnit{
private final Job j;
private JobUnit(Job j){
this.j = j;
}
public Job get(){
return j;
}
}
}
But one thing I'm curious about is why do you even need to add jobs to a customer object?
If all you want to check is to see which customer has been assigned to which job, simply inspecting a Job will give you that information. Generally I try not to create circular references unless unavoidable.
Also if replacing a customer from a job once its been created is not necessary, simply make the customer field Final in the Job class and remove method to set or replace it.
The restriction for assigning customer for a job should be maintained in database and the database entry should be used as a checking point.
As for adding jobs to customer that were done for someone else, you can either check for customer reference in a job to ensure that the customer to which a job is being added is the same one it holds or even better-simply remove any reference in customer for Job and it will simplify things for you.
If the Customer object owns the relationship then you can possibly do it this way:
Job job = new Job();
job.setStuff(...);
customer.addJob(Job job) {
this.jobs.add(job);
job.setCustomer(this); //set/overwrite the customer for this job
}
//in the job class
public void setCustomer(Customer c) {
if (this.customer==null) {
this.customer = c;
} // for the else{} you could throw a runtime exception
}
...if the ownership is the other way around, just substitute customer for job.
The idea is to have the owner of the relationship maintain consistency. Bi-directional relationships generally imply that the consistency management sits in both entities.
Make a proper setter-function that maintains consistency. For instance, whenever you create a job, you supply the customer in the constructor. The job constructor then adds itself to the customer's list of jobs.
Or whenever you add a job to a customer, the add function has to check that the job's customer is the customer it's being added to.
Or some combination of this and similar things to what suits your needs.
Just implement some sort of collection in the object that has the other objects
For example in customer you could say:
private List<Job> jobs;
then by using getters and setters you can add values jobs to this list.
This is basic OO stuff, I don't think you searched enough on the internet. there is a lot of info available on these subjects.
Btw, you can use all sort of collections (Sets, Lists, Maps)
I know this is late but I think another way to this would be to look at the problem a bit differently. Since customer holds a collection of all jobs assigned by or completed for a customer, you could consider the job class to be a sub class of customer with extra information of having all the jobs completed by the customer. Then you would only have to maintain customer id in the main class and it would be inherited. This design would ensure that each job can be linked to a customer. Also if for a customer you want to find out how many jobs are present that too also would be got.
I am sorry I know this is very late but I have come across a similar problem where I feel the best solution is to follow a inheritance model. Think of job as being jobs done/asisgned by a particular customer. So in that case the Customer would be a super class with the Job(Lets call is customer job) being a sub class since a Job cannot exists without a customer. A customer would also have a list of jobs primarily for ease of data fetching. Intutively this does not make sense since Job and Customer done seem to have any relation, however once you see that Job cannot exist without a customer, it just becomes an extension of customer.

I need to search for a "customer" in a db, what would be a good design here?

We're a couple of students trying to implement a design to search for customer-information in a database. When the GUI-class is asking for any customer with the surname "Jensen", would a customer-class then create many objects for each customer with that surname, give all those objects to the GUI-class, let the GUI-class e.g change something or add something, and then use some method in the customer-class to update it in the database?
Customer class:
Surname
Email
getSurname()
setSurname()
static List getCustomerFromDb(surname, email):
Customer customer = new Customer()
customer.setSurname(surname from db)
..
..
return listOfCustomers
updateThisCustomerInDb():
//updates all fields in db
Our implementation now is that we send a ResultSet to the GUI-class from a static method in the customer to search for customers.. And if the GUI-class want to change a field like email in the customer, it sends a HasMap with the keys and values to change.
Wouldn't it be bad to create like 300 customer objects and only need one of them?
The reason we ask for help, is that we've heard that it's a bad OO-design to not update, change, find (in the database) customers using objects, but using ResultSets and HasMaps.
Thanks =)
Assuming that a ORM-framework like Hibernate is either overkill or not allowed for your assignment this is what I suggest:
Implement the DAO Design pattern. In a nutshell this means that you declare an Interface with methods for retrieving and altering database data. Their signatures should look something like the example code you supplied and should return Domain objects, that is objects not specific to the implementation of the database access code. A typical Domain Object for customer could look like this:
public class Customer {
private String surname;
private String email;
private long id;
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
}
Then create an implementation of the interface where all the gritty DB-specific code is placed.
What you were told regarding poor design seems correct to me, you don't want to expose db-specific code in the upper layers of your design. You should use your own, domain specific objects or collections of them.
Good Luck
Your code doesn't have to hold onto every record in a database when it doesn't need it. What would happen if you had 50,000,000 customers in your database?
Utilize your database! If you know exactly what objects you want, write a query to return only those objects within a list. If you know exactly what rows you want to update without first viewing them, then write a query to update only the relevant rows directly in the database without returning the result set at all.
Sorry if this isn't relevant to your question.
You may want to alter the process a little, do your search and return search results that allow the user to select which customer to edit, as Kobi said the customer should have a unique identifier, once you have this you can obtain just the single customer object you are wanting to work with.
Hope that helps.
Chris
<speculation>
I'm a .net developer, but I'm pretty sure that if the ResultSet contains all data it also contains 300 objects (as rows?) - there's no way around this. 300 is considered a tiny number, by the way, but if you return rows you absolutely don't need you may have scaling problems, when you have a million times more records (give or take).
</speculation>
On the long run, returning your own classes and using them between the data-access layer and presentation layer is better practice - it will save you from duplicated code. In fact, the GUI should not contain this code, and it is better if that layers doesn't relay directly on the structure of your tables and columns' names (as this gets messy).
Creating your own classes and using them is common and advisable. It also improved the reliability and maintainability of your code - this may not be of interest in collage, but considered by some to be more important the speed or memory use.
I can see here two options:
There is 300 customers named Jensen and you want to present them to end user
There is 1 customer named Jensen and 299 other customers
In first case it is OK to create 300 objects of customers and modify only one - user searched for a guy named Jensen and there was 300 of them. In second you should create only one object and use it in GUI.
Plus it is also good idea to separate DB code (transforming ResultSets into objects) from GUI. The idea with DAO pattern is justified here.
Hope it helps
EDIT: too early enter pressed

Categories