• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

A base type limited to two distinct subtypes

 
Garrett Rowe
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For fun I'm making a generic implementation of the Boyer Moore Algorithm which can search any random access list for a given sublist.

I'm having trouble with the abstraction of a MatchResult. A MatchResult can either be a Match or a Failure, but I'd like a Failure to store additional information about the what index and element caused the failure.

Here's the solution I came up with but I am having doubts about its Javaishness (OK, so I made that word up).

Particularly, I think I may just be overlooking a more common solution or refactoring trick in favor of this bit of strangeness.
[ July 28, 2007: Message edited by: Garrett Rowe ]
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What would worry you about someone providing a third implementation of MatchResult?
 
Garrett Rowe
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What would worry you about someone providing a third implementation of MatchResult?

I guess worry is the wrong term. It just seems unnatural, like leaving Boolean open for extension.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Then my advice would be to simply get over it...

Seriously, why unnecessarily restrict your options in the future? Just use an interface and two top-level classes. That's what I'd do.
 
Frank Carver
Sheriff
Posts: 6920
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'd also suggest you read up on the "Open-Closed Principle". You can never know when it might make sense in a future application to subclass something you have produced.

By attempting to limit the subclassing of your classes you have at the very least prevented yourself from using any of the handy tricks which depend on it, such as "self shunt" for testing, or the Decorator pattern. Even something as simple as deriving a subclass which implements a sensible toString() for use in diagnostics is not possible.
 
Garrett Rowe
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the advice guys, I'll probably go with the interface and two top level classes as Ilja suggested. I think my judgment was clouded on this issue because I first implemented this algorithm in another language where its natural to provide two separate and disparate data-type constructors. But as usual the *functional way* is different from the *object-oriented way*. If I'd done this in Java first, I probably wouldn't have even considered another way. Anyway, thanks again.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic