2

I have two Java classes that are running commands on the local system. My dev system is a Mac, my QA system is Windows and the Prod system is UNIX. So there are different commands for each one, at the moment I have to go in and comment/uncomment the differences. Both classes are structured the same with executable and command. Here is what I have.

// Linux (QA/Prod)
final String executable = "/user1/Project/Manufacturer/CommandCLI";
// final String executable = "cat"; // Mac Dev
//  final String executable = "cmd"; // Windows QA

final String command = "getarray model=" + model + " serialnum=" + serialnum;
// Windows QA(local laptop)
//final String command = "/C c:/Manufacturer/CommandCLI.bat getarray model=" + model + " serialnum=" + serialnum;
//Mac Dev
// final String command = "/TestData/" + computer.getId() + ".xml" 

So, as you can see -- I am commenting and uncommenting depending on the environment. One of my main concerns is that I am relying on the model and serialnum variable -- and I don't know if that can somehow be inserted into a property (model and serialnum are given in the method call).

We are using Maven so during "mvn clean package" we are adding the -P flag to specify a properties file.

What is an elegant way to handle this?

Enrichman
  • 11,157
  • 11
  • 67
  • 101
Envin
  • 1,463
  • 8
  • 32
  • 69

1 Answers1

2

I suggest to create 3 different method: one for each os that contains os-specific commands. And you can determine current os using system properties: check this question. And call appropriate method based on this property. Example:

private runOnLinux(int model, int serialNum) { ... }
private runOnWindows(int model, int serialNum) { ... }
private runOnMac(int model, int serialNum) { ... }

// Somewhere in source code...
String os = System.getProperty("os.name").toLowerCase();
if (os.contains("windows")) {
    runOnWindows(model, serialNum);
} else if (os.contains("linux") || os.contains("unix")) {
    runOnLinux(model, serialNum);
} else {
    // Mac!
    runOnMac(model, serialNum);
}

Of course I not sure all this checks are correct. Better check answers to the question I mentioned at the beginning. It contains much more useful information.

Community
  • 1
  • 1
Mikita Belahlazau
  • 15,326
  • 2
  • 38
  • 43
  • typo here: else if (os.contains("linux") || os.contains("unix")) { runOn->Windows<-(model, serialNum); – Jonas Eicher Jun 17 '13 at 13:57
  • Instead of having one class that contains all the `runOn` methods, which might cause problems when you port to a new architecture like IBM AS/400, try using the `ServiceLoader` system. – Eric Jablow Jun 17 '13 at 15:58