Tuesday, January 11, 2005

Object BootCamp - day2

The day started with Fred asking us what was the wierdest thing that we heard yesterday. I said i was surprised to find that the names of the methods should not have get/set(forget about having getters/setters, the name should not even have the string get/set as in getArea in Rectangle class). He said that well designed do not have getters/setters. For example, the JDK APIs hardly have getters/setters. Objects should not be modified through setters after they are constructed. For changeability of an app, objects should do what they are supposed to do.

He said having multiple levels of calls like a.b().c().d() was a code smell. This is a tight coupling. Instead the behavior c()/d() should be moved to a. I asked that this might increase the size of the classes, so how to keep it small. Fred suggested refactoring to find embedded objects as a key to keeping small classes.

Fred then asked us to design a class for Probability. The goal was to represent Probability in objects. We had a fairly long discussion as to what would the class Probability would look like. We ended up designing a class called Probability which would be treated as its mathematical equivalent. It would have behaviours like and, not, etc.

We followed TDD and wrote tests for equality. Fred suggests writing the assert statement first in a test method. When we are not able to come up with an assert statement, it means that we have to design. Fred suggested designing and "conversation"(as covered in yesterday's post) to overcome this. This way we can arrive at better design. We started with an assertion as below:
assertEquals(0.5, new Probability(1,2).chance());

Fred did not like it. He said what is 0.5? Its a number. What are the operations possible on it. Addition, subtraction, multiplication etc? Why should a probability have those opertations? Probability is not a number. So we modified it to
assertEquals(new Probability(0.5), new Probability(1,2));

Other things that were covered in today's session was how to override equals method effectively. equals method cannot throw exceptions, so all condional checks should be made explicitly. Also, instead of using the instanceof operator to check the class, Fred suggested using getClass method as that will allow sub-classing without breaking equals. Also, when equals method is overridden, hashcode method should also be overridden.

0 Comments:

Post a Comment

<< Home