description
our coach give an example about value Object.An amount of money consists of a number and a currency. We create a class Euro
,we use assertSame
to compare the two objects of Euro
class. Then we write a method equares
and use assertEquals
to compare two objects.
questoin
- Q1: we use
assertSame
to compare, it failed. why?
A1: I think thatassertSame(Object A, Object B)
means A==B. It is judged to be A and B memory address,so the test failed.
- Q2: when we create a method
equares
to override the the equals method of Java.lang.Object, why it the test can pass?
A2: I think that when we override the equals method ,we jedged the objects by the value not by memory address.so if the two objects have the same value,it can pass.(short cuts: command + N,quickly create the equal method)
- Q3: why the coach said "The value object should be immutable "?
A3: I think One of the good results of the value object is that I do not have to worry about whether there is a reference to the same object in memory, or the same value has a different reference.
for example:
Date retirementDate = new Date(Date.parse("Tue 1 Nov 2016"));
// this means we need a retirement party
Date partyDate = retirementDate;
// but that date is a Tuesday, let's party on the weekend
partyDate.setDate(5);
assertEquals(new Date(Date.parse("Sat 5 Nov 2016")), retirementDate);
// oops, now I have to work three more days :-(
so, A good way to avoid shared updates of value objects is to make value objects immutable.
- Q4:what's the defference between value objects and entity?
A4: Entity must have a unique identifier (ID)! To ensure that the system can clearly distinguish between each entity, and when needed to accurately find it. Value object no ID! This is because the system never directly retrieves the value object. The value object is always subordinate to an entity.
Entities have their own independent life cycle, and the value of the object is not. It is always attached to an entity. If the entity does not exist, it will die together.
There will not be more than two entities that reference a value object. If two entities have the same value, then it is only possible to have two values of the same value object, rather than the same value object.
- Q5:What are the common value objects?
A5: Date,Time
reflection
this is a new concept for me.After session,I think I have not understand it clearly. So I find some blogs to understand it.
action
if I spend some time but still can't understand it,I think the best way is to ask someone .I spend many time to understand what is Value Object ,finnally, I ask my roommate.