Comments

06/01/05: Primitive Obsession

In a g i l e l e c t r i c My Favourite Smells Chris Wheeler names a code smell that's been on my list for some time: Primitive Obsession. I frequently tell my.. (um... what's the opposite of mentor?...) proteges, it's perfectly acceptable -- no, really -- to make an object that wraps a single, primitive value.

My favorite example of this is the one Chris uses -- wrap an integer so you know whether an index is zero-based or one-based. But his solution isn't quite radical enough for my taste. He made two classes, OneBasedInt and a ZeroBasedInt. This isn't OO since it makes the mistake of naming for form rather than function. Chris, I see your value object and raise it -- that is, decrement it by one class:


public class PageNumber {
  public PageNumber fromZeroBased(int zeroBased) {
    return new PageNumber(zeroBased);
  }
  public PageNumber fromOneBased(int oneBased) {
    return new PageNumber(oneBased - 1);
  }
  private int zeroBased;
  private PageNumber(int zeroBased) {
    this.zeroBased = zeroBased;
  }
  public int asZeroBased() {
    return zeroBased;
  }
  public int asOneBased() {
    return zeroBased + 1;
  }
  public void increment() {
    zeroBased += 1;
  }
  ...
}



This way people don't even *need* to know which type of index they should pass in to a method -- they just pass the object, and if some low-level rendering code needs to extract an integer in the right format, it just asks the object to present itself in the proper form. Actually, according to Tell Don't Ask, it might do something like pass in an output stream and ask the PageNumber to render itself in one-based format (for human viewing) or zero-based format (for a URL GET parameter).

Astute readers will note that the internal representation is the One, True, Correct form of integer indexes, which is as handed down from the prophets Kernighan and Ritchie, world without end, Amen.


Comments made

This way people don't even *need* to know which type of index they should pass in to a method -- they just pass the object, and if some low-level rendering code needs to extract an integer in the right format, it just asks the object to present itself in the proper form. Actually, according to Tell Don't Ask, it might do something like pass in an output stream and ask the PageNumber to render itself in one-based format (for human viewing) or zero-based format (for a URL GET parameter).
06/03/05 22:52:31
To achieve a hip hop look snapback hats are your best option, http://www.tisasnapback.net
it was first restricted to rappers only then to players only but now there are no restrictions any more. People in general community are getting equally benefited from snapback hats.
02/28/12 23:54:10

Add comment

Sorry, but due to blog comment spam, I have to ask you to create an account before you post a comment. Please log in (using the form on the top right of the page) or click here to create an account: Create an account!