How to design Java Contract class for an Employee - java

I am designing a class for an employee management system.
Class Employee has following fields:
:Employee
id:int
firstName:String
lastName:String
contract:Contract
Class Contract has following fields:
:Contract
-contractNo:int
-contractDate:Date
-contractType:Type
-rate:Double
-function:Function
-contractCopy:File
When an individual becomes employed within the company, he/she signs a contract with an agreed rate, function etc. From time to time, management revises the contract and changes rate and/or function.
Could somebody advise how to design a class that stores revisions of the contract? The user needs to view the original information and all revisions.

You already have two nice entities to create classes for: Contract and Employee, both of which also make nice tables to store data.
I would create a ContactRevision class, that has fields of the Contract that can be revised.
For example:
:ContactRevision
-contractType
-rate
-modifiedOn
-modifiedBy
You could then add a property to your Contract entity called revisions of type List<ContractRevisions>, with operations like addRevision or getAllRevisions to show the changed values if desired.

You can use Event Sourcing Pattern. It will allow you to track the change history.
In short you create an event for each change and thanks to this you may review it whenever you want.
You can find more information here:
http://martinfowler.com/eaaDev/EventSourcing.html
https://msdn.microsoft.com/en-us/library/dn589792.aspx

Related

How can I interpret to a sequence diagram an action from an Analysis Pattern?

Based on the Accountability Analysis Pattern:
The concept is that we have a class diagram following the logic of the Accountability Analysis Pattern. How can I use the given function assignStaffContact() to assign contact?
I have undrerstood that StaffContact class is a control class and the Client, StaffMember are entity classes (we don't care about the TimePeriod class).
I cannot figure out which classes are gonna play a part in the procedure of assigning staff contact in order to create the proper sequence diagram (UML) of this action. Arbitrarily there must be a boundary class providing the wanted interface. The actor is gonna pick the case of assigning staff contact, which will trigger the method assignStaffContact() of the control class StaffContact but with which entity classes this will communicate and finally assign the staff?
I am getting confused with class ContactForCampaign and the logic behind it being connecte to the classes Client and StaffMember. I hope I explained well enough my problem and my thought process.
This diagram says that:
A StaffContact instance can be associated to several ContactForCampaign instances
Each instance of ContactForCampaign is associated with exactly one instance of a Campaign, and defines exactly one StaffMember object as responsible, and. one Client object as commissioner (probably for the campaign).
As a consequence, we can only guess that StaffContact::assignContact() requires to know which StaffMember to add (should be an argument of the operation). Since several ContactForCampaign instances can be considered, the ooeration would probably also need to know which ContactForCampaign is relevant for the assignment. Probably this can be determined with the help of a Campaign parameter. Two cases must then be considered: replacing a staff member of an existing ContactForCampaign or create a new one if no assignment exist for a campaign. You have now all the ingredients for your sequence diagram. Note also that the operation would need to know which client is to be assigned as commissioner if a new ContactForCampaign os created.
The result could look like (simplified):
Note that StaffContact::removeStaffContact() does not seem relevant, in view of the multiplicity 1 for the StaffMember, unless you condider removing as well the ContactForCampaign, which would then cause to lose the information regarding the commissioner.
Last but not least, in view of the 1 multiplicity on the side of StaffContact, it would not be a control class, since the control is in princple existing for the time of the use case execution only, and should not have a permanent semantic link to the objects that it controls.

DAO class methods naming

I am building a small Java web application using Spring MVC, Hibernate and I am confused about the DAO classes methods naming.
For example I have an InvoiceDAO.java class which I thought should contain the following methods:
Save(Invoice newInvoice);
Void(Invoice oldInvoice);
getInvoiceByID(Long invoideID);
but my boss says that best practices says that I should have methods names in DAO classes as follows:
add(Invoice newInvoice);
update(Invoice oldInvoice);
which makes no sense for me as I am not sure how I can name voiding an invoice as Update?!!
So can someone please guide me in this and tell me if I am wrong on my methods naming? In other words is it correct that I should only use add, update for naming or can I use any naming and still be considered as best practices.
thanks
Voiding an invoice is a business operation. I would say such logic lives in your service layer. You make updates to the invoice to mark it as void, and then pass it to the data layer to save.
The data layer should contain pure CRUD type methods, that is add/save/find.
Using many modern data frameworks, you don't even need to write the data layer ... e.g. see http://blog.springsource.org/2011/02/10/getting-started-with-spring-data-jpa/
I've found this refeernce some time ago about DAO naming ...
Names according to function
getData* Data Parsing Methods used internally in DAO, do not use this namespace for data accessing.
get* (e.g. getUsersByID) SELECT queries – It is encouraged that you try to use the noun in Singular or Plural according to single or multi-row return.
set* (e.g. setActive) UPDATE Queries
add* (e.g. addUser) INSERT Queries – It is encouraged that you try to use the noun in Singular or Plural according to single or multi-row insert.
delete* (e.g. deleteUser) DELETE queries
is* (e.g. isActive) IF check returns boolean, i.e., if ($user_dao->isUserActive($id)) or if ($post_dao->isPostInStorage($id))
count* (e.g. countUsers) Returns integer with the item count.
Reserved functions
insert – takes an object as argument, and inserts it to the table.
save – takes an object as an argument, and stores the data in it back to data backend
poke – Takes an ID as argument, “pokes” the record (sets “last seen” or whatever to now), returns update count (usually 1)
Other things to remember
As the storage Backend may or may not be a “database”, it would be encouraged not to create methods with names that imply that the backend is using a database.
First of all, in Java, at least, you name your methods with the first letter of each internal word capitalized, camel-case. You can see at the section Methods this: Java Naming Conventions
Regarding the specific naming of your methods inside the dao:
I would go by creating basic crud operations that can be performed to your model classes
Example:
add(Invoice invoice)
update(Invoice invoice)
// or instead
save(Invoice invoice) // which will perform either add or update
delete(Invoice invoice) // or delete(int invoiceId)
findById(int invoiceId)
// and so forth
I would not make use of the term "void" inside the dao, since that is related to the business. Do the dao as simple as possible and after that in your service that will be using the dao, you can name your methods related to the business required (i.e. voice(Invoice invoice))
There is another possibility to create a generic dao with the basic CRUD operations and maybe you can then start naming the methods as you want:
public class InvoiceDAO inherits GenericDao<Invoice> {
// all the above methods would be inherited
// add specific methods to your dao
}
Again, if I were you I would move the naming of specific stuff in the service.
Now it's up to you how you want to approach from what I showed. The idea is to keep the dao as simple as possible.
You might as well go and name your void method (since you can do name it void, since in Java is a keyword -- thanks #Marco Forberg for noticing that) either delete (Void - means that it is deleted.) or performVoid. Or go simple with update if you are not removing the invoice from the database after you void it. update can be applied to any changes you made for your invoice entry.
Save and add have 2 different meanings. As do Void and update. Use the term that accurately describes what the method is doing. Im not aware of any specific best practise here.
Also, I would tend to only pass an ID into a void method if that is enough to perform the action. This is different scenario from an update where you may expect to update multiple attributes on the invoice.

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);

Aggregate object in DDD

I have made an aggregate class named Question. This contains references to Answer, Category, Feedback objects. Should the QuestionRepository be the class that contains all methods quering the database that relates to the Question but also all the methods for quering the Feedback, Answer etc? Or should these be seperate classes such as QuestionRepository, FeedbackRepository and so on.
From the way you have explained , I am assuming that each Question will have 1 or more Answers , 1 or more Feedback and the Question belongs to a particular Category
Since the Answer and Feedback are dependent on Question and cannot exist independently , you can have a single QuestionRepository for these 3 entities .
Coming to Category , category is more of a static entity which IMO is a static list , so all such static entities can be grouped together in a StaticRepository
From the DDD web site :
For each type of object that needs global access, create an object
that can provide the illusion of an in-memory collection of all
objects of that type.
A repository is used when you need direct access to an entity, i.e. when there's no other convenient way to get hold of that entity than fetching it from a persistent store directly. In contrast, if you consider that the entity is most of the time easily obtainable through traversal of another object you've already got at hand, then there's no need for a repository. It seems to be the case with Answer, Category, and Feedback here.
Usually repositories are only for aggregate roots, though there may be exceptions.
I suggest you read the DDD blue book or some tutorial to get a basic comprehension of the DDD building blocks before you start building your domain model.

Entities in domain driven design

I am reading Eric Evans book about DDD and I have a question to the following quote. How do you make your equals() method when you should not use the attributes? I am using JPA and I have a id attribute which is unique but this is not set until you actually persist the entity. So what do you do? I have implemented the equals method based on the attributes and I understand why you shouldn't because it failed in my project.
Section about entities:
When an object is distinguished by its identity, rather than its
attributes, make this primary to its definition in the model. Keep the
class definition simple and focused on life cycle continuity and
identity. Define a means of distinguishing each object regardless of
its form or history. Be alert to requirements that call for matching
objects by attributes. Define an operation that is guaranteed to
produce a unique result for each object, possibly by attaching a
symbol that is guaranteed unique. This means of identification may
come from the outside, or it may be an arbitrary identifier created by
and for the system, but it must correspond to the identity
distinctions in the model. The model must define what it means to be
the same thing.
http://www.amazon.com/Domain-Driven-Design-Tackling-Complexity-Software/dp/0321125215
Couple approaches possible:
Use a business key. This is the most 'DDD compliant' approach. Look closely at domain and business requirements. How does your business identify Customers for example? Do they use Social Security Number or phone number? How would your business solve this problem if it was paper-based (no computers)? If there is no natural business key, create surrogate. Choose the business key that is final and use it in equals(). There is a section in DDD book dedicated to this specific problem.
For the cases when there is no natural business key you can generate UUID. This would also have an advantage in distributed system in which case you don't need to rely on centralized (and potentially unavailable) resource like database to generate a new id.
There is also an option to just rely on default equals() for entity classes. It would compare two memory locations and it is enough in most cases because Unit Of Work (Hibernate Session) holds on to all the entities (this ORM pattern is called Identity Map). This is not reliable because it will break if you use entities that are not limited to the scope of one Hibernate Session (think threads, detached entities etc)
Interestingly enough, 'official' DDD sample uses a very lightweight framework where every entity class is derived from Entity interface with one method:
boolean sameIdentityAs(T other)
// Entities compare by identity, not by attributes.
If the object is not persistent yet, then is there any harm in comparing 2 objects based on their attributes?
I am not sure why this failed in your project, but in my experience, comparison based on attributes almost always is slippery slope if your attributes are not final. That means, 2 objects that are equal now, may not be equal after sometime. This is very bad.
Given that most Java classes are written along with their accessors, equals comparing attributes are said to be a bad idea.
However, I would probably first check to see if the ID field is not null. If it is null, I would fall back to attribute comparison. If it is not null, then just use it and not do anything else. Does this make sense?
Given Person class with attributes name, surname. When Person at the age of 21 changes its name is it still the same Person (equals gives true)?
If you write equals basis on attributes, then, it would not be the same person, so in my opinion the best approach is to test equality of entities basis on their business identifier (unique and immutable over the whole entity lifecycle).
Another solution could be to use an UUID field in your entity.
In this case, you could use the UUID as primary key or just for equals.
#Entity
public class YourEntity{
#Id
private String uuid = UUID.randomUUID().toString();
// getter only...
}

Categories