Re: Static vs Dynamic

From: Darren (pyedarren_at_hotmail.com)
Date: 11/02/04


Date: 1 Nov 2004 19:04:04 -0800

Pascal Costanza <costanza@web.de> wrote in message news:<cm5h1k$cvk$1@newsreader2.netcologne.de>...

> Your code is just imperative. Darren's code is a dirty hack that turns a
> system identification string into a class name, a solution that probably
> breaks when the conversion routine fails to create a class name that is
> acceptable for Java.

I beg your pardon? That wasn't a dirty hack at all! True, it wasn't
solid and would only work with the examples given, but dirty? No.

Suppose I made it rock solid with a 12 character addition to the code.
Will you still think it's a dirty hack?

  Class.forName(System.getProperty("os.name").replaceAll("\\p{Punct}|[
]", "")).newInstance();

The change is: "\\p{Punct}|[ ]". With that change any occurences of:
!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~ will be removed from the os.name
result.

Lets evaluate:
 - The code is easy to read
 - There is no adhoc-polymorphism anywhere
 - There is no object registration
 - There is no singleton usage
 - All OS's are represented as objects
 - The OS inheritence hierarchy represents thier RL historical lineage
 - The code doesn't use any if conditions
 - To add new OS's, you create a class using its normal name minus any
punctuation
 - New OS classes can be added without ANY code change or even
recompiling

What criteria are you judging it on? According to that link, I met
every possible criteria they had and threw in a few more! Seriously,
why is it a "dirty hack"?

I am starting to see a trend here. Every time I do something with
Java that you hadn't thought of, you call it a hack. What I did there
is called "factory loading" and it's done all the time in java
software!!

---- Updated OSDetector.java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
  class Unix {
    public Unix() {
      System.out.println("This is a UNIX based box and therefore
good.");
    }
  }
  class Windows {
    public Windows() {
      System.out.println("This is a Windows based box and therefore
bad.");
    }
  }
  
  class Linux extends Unix {}
  class SunOS extends Unix {}
  class Windows95 extends Windows {}
  class WindowsXP extends Windows {}

  public class OSDetector {
  public static void main(String[] args) {
      try {
        String os = System.getProperty("os.name").replaceAll("\\p{Punct}|[
]", "");
        Class.forName(os).newInstance();
      } catch (Exception e) {
        System.out.println("This is not a box.");
      }
  }
}