The intent of VISITOR is to let you define a new operation for a hierarchy without changing the hierarchy classes. (Java Design Patterns)
Josh Kerievsky puts it this way, “The job of many real world Visitors is to accumulate information.”
So what exactly does that mean in practice? The classes in the hierarchy must have a method called accept() that takes in an specified interface. Then the interface will have visit() methods on there. The visit signature will be determined by which class in the hierarchy you want to visit, and thus extend functionality to.
The tricky part for me to understand was the “double-dispatch” that needs to take place for Visitor to function. An object that conforms to the interface needed by the visitor takes the visitor in the accept() method. Inside the accept() method the visit method is called by the object which then passes itself to the correct visit() method of the Visitor.
Confusing? Yes, it seems to be rather.
I like the quote by Ralph Johnson about Visitor, “Most of the time you don’t need Visitor, but when you do need Visitor, you really need Visitor!”
That tells me, to not go out of my way to find uses for Visitor, but to stay far away from it until the light bulb comes on in a particular project where this makes perfect sense. It may never happen, in which case I won’t lose any sleep.
Visitor does not apply to ruby or any dynamic language where you can change the class hierarchy whenever you wish, on the fly. Even so, I am going to show this code in ruby, pretending to be Java. The interesting thing here is that ruby does not have method overloading since it is dynamically types. So the actual java example would look different, in that the visit methods would be overloaded with the different types that we know of. The ruby example has to check inside the visit method for the appropriate type and handle it accordingly. Method overloading is a nice thing to have when you want it.
My TreeVisitor example in ruby.
Learn 4 to 6 Editors Adequately
Unfortunately, I suffer from what a coworker of mine calls, editor ADD. My new motto is this: “Learn 4 to 6 editors and learn them adequately.” I have kind of given up on learning one editor very well, since I can’t make up my mind. About a year ago, I narrowed down my list to 4 development tools / editors (Textmate, vim, eclipse, IntelliJ). I also tried to separate them by operating system. When I was on the Mac I was going to use IntelliJ for Java work and Textmate for everything else. On windows it was going to be Eclipse for Java and VIM for everything else. So far it hasn’t been too bad.
I was worried that having too many keystrokes in my head would end up becoming a nightmare, but surprisingly, the many different sets of keystrokes can coexist in my mind without too much conflict. There is roughly a ½ hour context switch for me, where keystrokes are sometimes blurred moving from one environment to the other after a prolonged period of using just one. But for the most part, my brain knows vim, Textmate, eclipse, or IntelliJ, and doesn’t seem to complain about the switching.
I am not actually advocating this approach to anyone else, but there may be one aspect of learning several editors adequately that has some tangible benefit. That is, when pair programming with different people, you can adapt to the style of your pair with minimal disruption. Now, if each person has their own laptop and their own set of tools, then it doesn’t really matter.
[Update: I forgot about Xcode. That makes 5.]
Update 2013: Now I am leaning toward jetbrains products with the vim plugin and vim for everything else. (Well, textmate is still handy for stuff as well)
Pomodoro and Flow
I have been hearing about the pomodoro technique and so I started trying it for myself. I really like the concept, and often times, I need some help staying focused and not getting distracted. However, when I am tuned in to my code and really focused on what I am doing, I can go for hours at a very high level. This happened to me lately as I was working on an iPhone project. I knew what I wanted to get done, and trying to use pomodoro was just getting in the way.
When you are in “flow” from a programmer’s perspective, then go with the flow and skip the pomodoro. I don’t want any breaks, especially breaks in my concentration at that point.
Waterfall Presentations
I just finished watching a presentation on how to incorporate Lean into IT. After watching the presentation, I realized that most presentations are waterfall. The really engaging presentations do not usually follow the format we all learned in school:
History of Lean
How Manufacturing uses Lean
How IT does things now
Problems we have in delivering things in IT
How lean ideas map to IT
Practical advice on how to apply lean concepts to IT
Questions?
The most interesting and engaging parts of a presentation are probably the last two items, the practical advice, and the questions from the audience. But after being put to sleep for the first 45 minutes, people are not ready to get into the questions.
Even if the presentation is interesting, does all the outline verboseness really give people what they want to know? What would be the Lean way of giving a presentation?
You can’t just stand up there and ask “So, what do you all want to learn about Lean in IT?”, can you?
Pattern of the Week - Adapter
From Java Design Patterns:
The intent of ADAPTER is to provide the interface that a client expects while using the services of a class with a different interface.
This actually makes sense to me right out of the gate. I’ve probably read about and used Adapter before but needed a refresher on what it actually was.
So lets say that I have a lab processing class that takes LabOrder objects and processes them somehow. Another team in my company has a service that supplies LabResults from a different vendor than the one I work with but they like the processing class I made and want me to process their LabResult class also.
I see that the objects do similar things but have slightly different methods, so I create an adapter class that implements the LabOrder interface and delegates to the LabResult object that is passed in to the constructor. No code changes required for the lab processing class.
githup Adapter code
OCUnit Configuration for iPhone Development
On an iPhone project I am currently working on, I have been experimenting with some unit testing frameworks. Actually, I tried the rbiphonetesting ruby framework from Dr. Nic and that got me started down the TDD path on this project.
It was actually pretty sweet, since I couldn’t test any UIKit classes from the ruby framework since it was using MacRuby which does not run on the iPhone sdk. This was a nice constraint, as I was forced to put any code I wanted to test into a non UI class. This helped me clean out the UI and delegate to models, presenters, etc.
Then I hit an issue with differences in string handling between MacRuby and the iPhone sdk. My unit tests were no longer reliable, since they were passing but when running on the iPhone, I could obviously see incorrect behavior.
I knew going in, that this could be a problem. It was a fun experiment, and actually gave me a good perspective on testing apps on the iPhone.
I have recently ported all my ruby tests over to OCUnit and am back up and running. If I had started with OCUnit, I think my tests may be quite different, as well as the structure of my object model.
One thing that stuck out for me after porting all the tests over to OCUnit, is that they are incredibly fast compared to the ruby version. Which is good, since they run every time I build my code in Xcode.
Over Releasing Objects in Objective-C
I just learned the difference between over releasing an object and attempting to release an unallocated object. I saw this example in an iPhone book where an instance variable was being released before it was assigned.
1 2 3 4 5 |
|
I was wondering why the release on the first line was not blowing up, since I have experienced errors in my code when I over release an object (that is, I call release on an object more than once).
So I tried an experiment and put multiple [tweetString release]; calls all in a row, thinking this would blow up.
But it works just fine.
The reason is that a nil object (one that has never been allocated) is never sent any messages. There are no NullPointerExceptions since the messages are just discarded. Objective-C is a no-op language on nil, and you can rely on that in your code this way. So it is safe to call release on an unallocated object, but you cannot send release to an object more than once AFTER it has been allocated.
I should have realized this before, since this is the way properties work when set to retain.
Pattern of the Week - Composite
The intent of the COMPOSITE pattern is to let clients treat individual objects and compositions of objects uniformly. (Java Design Patterns)
There are objects that have children and there are objects that don’t. The objects that have children can have a common interface with the objects that do not have children, and so Composite.
The example I used in my code (see below) was that of a Menu and MenuItems. Swing uses this model for its menus. A Menu may or may not have sub menus. A MenuItem, however, never has sub menus; it is always the end of the road, a leaf.
A process may want to traverse a tree of objects but it does not want to have to figure out who has child elements and who does. Composite attempts to solve this problem by establishing a common interface between the two types. Then the object that has children can traverse its children when the common method is called and call the common method on the child objects.
Here is a link to the ruby code I wrote up to help me understand Composite better.
I ran into another good example over the weekend. We went to a tree identification outing and the naturalist there had a identification key. It used decision tree logic, and I thought to myself, “Hey, the Composite pattern in real life!”. What a geek I am sometimes.
Each question led to either one or many follow up questions. I thought of putting the logic into an iPhone application, and realized I could model the questions as Composites. Some questions would be trees, and others would be leaves. Perfect for a tree identification app!
Pattern of the Week - Builder
The intent of the BUILDER pattern is to move the construction logic for an object outside the class to be instantiated.
A builder class offloads construction logic from a domain class and can accept initialization parameters gradually, as a parser discovers them.
(Java Design Patterns)
A common motivation for refactoring to a Builder is to simplify the client code that creates complex objects.
(Refactoring to Patterns)
One place that I frequently will use the builder pattern in the future is creating objects for my unit tests in Java. Test Data Builder works really well for this since it allows for having immutable objects without having to specify all the parameters in the constructor of the class. It also allows for introducing test doubles easily for only specific cases, etc.
For Test Data Builders in Java see Jay Fields article.
For a Ruby test data builder, check out Factory Girl
Immutability simplifies concurrency issues, but complicates construction by forcing all state to be passed into the constructor. When we were using Google Protocol Buffers, I noticed their diligence in making sure the only mutable objects were Builder objects. This gives us the flexibility of building up the data in the builder class however it seems to work best, but then once the REAL object is built, it is immutable.
Whenever there is pain putting together a complex object graph, test objects, composite objects, and the like, the Builder pattern is very useful.
Pattern of the Week - Flyweight
The intent of the FLYWEIGHT pattern is to use sharing to support large numbers of fine-grained objects efficiently. (Java Design Patterns)
I have always wondered what exactly the Flyweight pattern was all about so this week I decided I would learn. Right away in the definition is the use of another term that I usually find confusing, “fine-grained vs coarse-grained” objects.
It turns out fine-grained and coarse-grained are terms used in physics and have also come to be used in other technical fields. For objects, to be fine-grained generally means to be small with a focused responsibility whereas coarse-grained objects generally encapsulate the functionality of many fine-grained objects.
J2EE uses these terms a lot because of the problems involved in having fine-grained objects being too “chatty” in a distributed system.
Anyway, to get back to Flyweight, lets say there is a fine-grained object like a Unit. Unit is a measurement that can be anything from inches to liters to moles. The point being, a Unit is immutable and one instance can be shared safely across the entire system. An inch is always going to be an inch, so lets share the inch Unit instead of having everyone create there own instance of inch anytime they need it.
One approach (used in the book) is to create a factory like UnitFactory that will return the shared instance of each Unit. Enforcing the use of UnitFactory was done by hiding all the Unit implementations in an inner class of the Factory so that they can not be instantiated directly. The Unit interface is exposed to all. Asking the UnitFactory for a Unit could either be done by passing in a string or an enum representing the Unit to be returned.
So, if you really want to prematurelly optimize your next project, analyze all the objects that could potentially be shared and tell everyone on your team that the Flyweight pattern would be a really good idea.