How Many (Java) Classes Do You Need To Go (XP) Bowling?

An object-oriented developer searches for a reason to add more of them.

Ron Jeffries recently posted a couple of articles on simple design, with the
specific example of code to score a bowling game:

In a thread on the subject on the XP Mailing List, various posters expressed
a preference for one solution or the other.

With the caveat that I’m normally a very object-oriented guy, I prefer the
second (procedural) solution, in that I find has approriately simple design:
it work, expresses the programmer’s intentions, has (almost) no duplication
of ideas, and has the minimal amount of code needed to do all those things.

The point was made, though, that perhaps the procedural solution would fall
apart once the complexity of the problem increased. To test this idea, I decided
to extend it with the following features:

  • Know what frame the bowler is current done with / working one
  • Know the score of each frame
  • Know if the game is over
  • Reject erroneous input data

My first step was to convert the example C# code to Java. (I like C# at least
as much as Java, but for the moment I’m happier with the code-editing features
of Eclipse compared to VS.NET.) Here’s the Java code, the starting point before
adding any features:

I also converted the NUnit tests to JUnit. (Formerly this was available for download,
but I’ve misplaced the file since then.)

With this in hand, I started adding tests for my new features. An example test:

This test, and others like it, verify that after each roll, the game object
know what frame has been completed, what frame is scorable, and when the game
is over. (I also added the feature to report the score of each frame, but didn’t
get around to testing it explicitly. I found that to get things right, I needed
a variety of tests for things happening in the last frame, since there are special
rules there.

Without further ado, here is working code to score the game, with the new features:

Here is what I like about this solution:

  • There are tests to show that it actually works
  • The method names are, at least to me, intention-revealing
  • The methods are short and straightforward
  • The main scoring loop, which still happens in one straight-line pass, is
    simply this:
  • There’s not much duplication left in there; perhaps someone can suggest
    a way to get rid of the bits that remain

The real question, of course, is whether this is too much for one class to
do – whether there are any parts of this code that should be a separate class.
The obvious candidates are the pairs of methods: should isStrike() and scoreStrike()
somehow be in a Strike class? They have an obvious parallel structure, a form
of duplication that I might be able to get rid of by adding classes.

I thought these new features would push me there – but they didn’t. Perhaps
a future story would do so. This implementation is still not quite “finished”,
in that I know there are more kinds of error conditions to consider, test for,
and implement. I don’t see any reason to think that adding those now would add
much to the conversation, so I didn’t add them.

One lesson of this exercrise, to me, is a common one: the problem space is
not the solution space
. Just because we have a thing called a Foo in the problem
domain, doesn’t mean we need a class Foo in the solution. We might, we might
not; with test-driven design, the need for a Foo should eventually become obvious.

Comments welcome, via email (address below) or on the XP mailing list.

Word Chains Kata Solution

I worked out a solution for “Pragmatic” Dave Thomas’s Code Kata 19 (Word Chains) in Java; it’s somewhat different than Dave’s published solution.

I’ve been watching PragDave’s Code Katas with interest, since I am also in the habit of occassionally solve a small, standalone programming problem just for the learning experience. Today I worked out a solution for Kata 19, Word Chains. I did this Kata the “pure” way, i.e. without looking at any of the discussion of solution approaches before coding. Here are the results (also on github). I wrote the code this time in Java.

Unlike Dave’s published solution, I didn’t precalculate adjacency lists; rather I took the more brute-force approach of scanning the word list at each step looking for neighbor words. In spite of that non-optimization, this still calculates the word chains for a bunch of examples in a few seconds (total).

I was curious how much of the program’s time is spent checking for neighbor words; this provided a good reason to try out a profiler plug for Eclipse, available on SourceForge. The profiler worked fine, and told me, as I would have guessed, that the program spends approximately 100% of it’s time looking at words to decide if they are neighbors (in the word-chains sense). Of course the usual optimization advice applies: it would have been actively stupid of me to optimize without measuring where the slow parts are.

Upcoming talk at SD 2004

I’m giving a talk on data handling in a disconnected mode appliction next year at SD Expo 2004.

I’m giving a talk on data handling in a disconnected mode appliction next year at SD Expo 2004. This applies to wireless / mobile applications running on notebook PCs, PDAs, even smaller devices like “SmartPhones”.

Details are here

Java / J2EE and .NET Talk

At the September 2003 Gateway JUG, I gave a talk on the similarities and differences between Java/J2EE and .NET.

At the Sep. 2003 Gateway Java User Group, I gave a talk on the technical similarities
and differences between Java/J2EE and .NET, as well as the non-technical issues
in adoption of each. The presentation is available for download here, as well
as the plain text of it.

Java / .NET Talk PowerPoint Presentation: J2eeNET.ppt

In the past, readers have asked how I got the text of a powerpoint presentation
in to plain HTML. This is a multi-step process, since PowerPoint itself generates
graphic-intensive, frames-based HTML with limited, JavaScript-only navigation.
PowerPoint lost the ability to generate more reader-friend HTML in recent versions.
In its defense, the HTML it generates does a good job of capturing the exact
look of the slides, which is very important to some users but not important
to me; I want the plain text so that search engines can find it and any browser
can read it.

The process is:

  • In PowerPoint, choose Save As, then select Outline/RTF from the file type
    list. Save the file.
  • Open the RTF file in Word. Save As an HTML file
  • Open the HTML file in DreamWeaver; use the “Clean Up HTML” and
    “Clean Up Word HTML” repeatedly to get rid of the massive amount
    of Word-specific HTML in the file. Also remove the span tags. Save it.
  • Open the HTML file in a text editor. Use search and replace operations to
    change the numerous H1 H2 H3 etc. tags to whatever markup you want around
    your bullet items. Replace whatever special character is present for the bullets,
    with something innocous like an asterisk.
  • Now you have clean HTML. Use some CSS to format it as needed.

The text of the talk follows:

Continue reading “Java / J2EE and .NET Talk”

Attacking Code Duplication in Java

An important principle of XP is that duplication of ideas in source code is to be avoided. I gave a talk at the XPSTL group on this topic.

On Feb. 5, 2003, I gave a talk at XPSTL about code duplication in Java. The presentation is available for download here, as well as the plain text of it. If you download the presentation, you’ll find the code snippets inside. The samples did not come along for the (very rough) plain text export below.

Attacking Code Duplication in Java

Kyle Cordes

Oasis Digital Solutions Inc.


Feb. 5, 2003

Once and Only Once

z OAOO is shorthand for the principle that each idea should be expressed exactly once in the source code.

z A tenet of XP

z Predates XP, a good design principle

z Not specific to OO development

A Quote…

“So, duplication sucks. The more rabidly a person hates duplication, the more I trust their opinions on managing information. A programmer, upon noticing some redundancy, should be thrown into a panic, begin hyperventilating, and stammer something about “¡El diablo! !El diablo está en mi software!”.”

Why Not Duplicate?

z Duplication is not just inconvenient.

z OAOO is not an “architecture astronaut” nitpick.

z Duplication is a clear sign of bad information management and complexity management.

z Building large systems consists significantly of complexity management and dependency management.


z OAOO makes systems easier to change.

z OAOO holds back entropy.

z I admit – I follow that quote. I use hatred of duplication as a barometer of design skill.

How Do We Achieve OAOO?

z Usually by refactoring code that contains duplication.

z Usually, a little bit at a time.

z However, when doing or evaluating up-front design, OAOO is a excellent criteria to apply.

Spotting Duplication

z Sometimes it’s obvious

z Other times it’s subtle

z Kent Beck is known for being able to see extremely subtle duplication, refactoring the code to make it clear duplication, then removing it.

Examples and Techniques

z Trivial duplication can be removed with Extract Method, adding a variable, etc.

z Some duplication is harder to address – we’ll look at examples and techniques for attacking it.

z These slides outline the ideas, we’ll do a few examples “live” in the presentation.

Tools to Achieve OAOO

z Anonymous Inner Classes

z Create a class hierarchy

z Command Pattern

z Replace Case with Polymorphism

y Code Generation

y Dynamic Proxies

y Replace class hierarchy with runtime relationships

Fighting a try / finally

z (One solution on the next slide.)

z Simple try / finally example…

z multiple try / finally example…

Anonymous Inner Classes

z They’re not just for Swing listeners.

z They are Java’s version of code blocks (Smalltalk, Ruby).

z Example…

Create a Class Hierarchy

z Raise the duplicated code to a base class.

z Example…

Command Pattern

z (Also the Template Method pattern)

z Base class has a doFoo() and abstract realFoo()

z Descendants have a realFoo()

z doFoo() wraps realFoo() with whatever code would have been duplicated.

“Heavy Lifting” to Achieve OAOO

z Replace class hierarchy with runtime object relationships

z Replace application code with code generation

z Dynamic Proxies

z Aspect Oriented Programming – makes it much easier to remove many kinds of duplication.

Replace Class Hierarchy…

z An extreme step, not in the XP sense

z Useful when a previous designed has created a great number of “glue” classes that don’t contain much information

Code Generation

z The essence of code generation is to have a specification, and set of rules for producing code.

z Example: the many support and utility classes, coded in a formulaic way, in a typical EJB application

z Example: O-R persistance code

z Example: GUI code

What about Generated Duplicated Code?

z This doesn’t bother me – I only care about duplication in the checked in code

z If it bothers you, nearly every problem that can be solved with code gen, can be solved with a dynamic mechanism instead.

z (Note – Don’t check in generated code. Please.)

Adding a Field

z As an example of large scale duplication issue… if you want to add a field to some entity in a typical J2EE application, how many places in the code/configuration do you need to touch?

Duplication in Legacy Systems

z Legacy systems often contain extensive duplication

z Can we find some in JBidWatch?


z OAOO in software design, is closely related to normalization in DB schema design.

What About Tests?

z Sometimes I find that things are duplicated between test code and production code.

z I’m not comfortable with this…

z But sometimes getting rid of it seems to negate the point of the test.

Discussion Topics:

z More examples, anyone?

z War stories?

z What additional / different tools does C# have to offer?

z Why do we see so much duplication in software?

z What about people who like duplication?

Code Examples

z These are some snapshots of the code we worked through during the presenation.

Starting Point – Parallel Loops

Extract Methods

Anonymous Inner Class

AIC, with Template Method

Lessons Learned

z AICs are the Java syntax for blocks / closures.

z AICs are really ugly syntax compared to Smalltalk, Ruby, etc.

z OAOO techniques sometimes create code that non-expert Java developers find very hard to fathom.

z The syntax is a big pain for small examples, but OK in real apps.


Slides will be on my site:

Windows Clients, Java Servers

Problem / Scenario:

You have server code in Java implementing business logic, or you want to have such code. Java is your strategic choice.

But… you have a need for a client application that will be a native Windows application, for whatever reason. Sample reasons: (1) they need to run quickly and smoothly on a factory floor full of Pentium 150 or slower machines with limited RAM. (2) they need to work in disconnected mode, or talk to local hardware, so a web application won’t work.

How do you write server code in Java (in EJBs, for example) but access it easily from a native Windows clients, for example a Delphi application?

Possible Solutions:

Solution #1: Talk JRMP from Delphi

Implement the Java RMI JRMP protocol in Delphi. This will be nearly impossible, since it is built on Java object serialization. So there are various approaches you could take.

Solution #2: Java on the Client, use JNI

Run Java on the client as well, and use JNI to communicate between Delphi and Java, then Java to do the client side RMI. This defeated the goal of keeping the client lean, though… a Delphi thin client can run well on an old, slow machine with 32 meg of RAM, Java can’t.

Solution #3: RMI-IIOP / CORBA

Some Java application servers can seamlessly (?) expose Java services (like EJBs) as CORBA objects. Borland has CORBA support available for Delphi. This will avoid the overhead of Java on the client, but is too vendor-specific for my tastes.

Solution #4: Your own Proxy on the server

Use a non-RMI way to communicate between the Delphi client and an extra "tier" at the server; this piece of middleware would communicate with Delphi using any of a number of methods, including DCOM. Then use JNI or other means to access the Java services on the same (server) machine.

Solution #5: ASTA-Java

ASTA has a product (though I don’t know if it’s in development, or ready to go) that provide an generic mechanism for invoking EJB operations, from a Delphi client. The challenge here is how to send and receive complex types, which are defined by Java classes.

Solution #6: Web Services with SOAP

Expose the server-side services as web services via SOAP. Choose an application server which will automatically expose your EJBs this way, if possible. Then use any available way to make a Delphi client talk SOAP. PureSOAP and Microsoft’s SOAP support are two possible ways. (This is really the most appealing choice to me, as of 2001.)

Solution #7: Homegrown web services

It’s really not all that hard to write wrapper code that exposes your server services via HTTP requests with parameters, via XML strings, etc. Such a thing would not be language specific, so the server could be on one language, the client in another. This solution has some appeal in cases where you want the pieces to be tightly "wrapped up" and not exposes in anything as standard as SOAP for some reason.


There many, many paths to use to get from point A to point B… if you have a different scenariou in mind, tell me about it and I will try to expand this page to cover it.

Need to do this for your own project? Consulting services are available.