This week's book giveaway is in the OCMJEA forum. We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line! See this thread for details.
Agree, an interesting article with a simple and easy to understand examples. I've few questions though and I tried to answer them myself. Correct me wherever I am wrong. Questions revolve around the good practices on the getter method of second example (Calendar object):
Q1. Is it a good practice to create and return a new object if it is not set? Ans: Depends on your requirements, if you want to return null or want to throw an error, you can do that. Author is considering the case, where call to get() should not return a null.
Q2. If object is not set, then why after creating a new object it is not stored to avoid the work of creating a new object one every time? Ans: Author wants to demonstrate the scenario when every call to get gives back a calendar with todays date i.e. equivalent of calling a new GregorianCalendar();
Q3. Is it a good practice to not to set an object inside get()? Ans: Again depends on your requirements, but a practice you should not.
Q4. Why cloned object is sent back, if Calendar is not null? Ans: To isolate the operations on set object and returned (after cloning) object. OR it is again a good practice to return a cloned object (anywhere related to mock ready)?
Pardon me if these questions look silly, or if this is not the right place to ask them.
It's a very interesting article that promotes delegation of object life-cycle management. Right now, in my project we are implementing some agile methodologies that includes TDD. [It's an spring + hibernate app]
I think mock objects for testing isolated layers would be useful, the only tradeoff that I see is the use of MockObjectTestCase class through inheritance.
I think we will follow a more decoupled approach, fortunately in the jmock's geeting started site, there are plenty of examples to accomplish this by favoring composition [desing principle: favor composition over inheritance] or even by using annotations. [ April 14, 2008: Message edited by: Omar Palomino Sandoval ]
The whole reason-for-being for this calendar example is to allow a test to inject a date for the unit to work on. Another solution to writing testable code in the unit might be to have all the methods in the unit accept a Calendar as an argument and return a Calendar.
The Calendar getter returns a clone if the member is not set. If it's not cloned then I couldn't have multiple calendars like: Calendar startDate = getCalendar(); Calendar endDate = get Calendar(); because they would be the same date and changing one would change the other.