Created
November 15, 2012 07:51
-
-
Save soren/4077280 to your computer and use it in GitHub Desktop.
Hacker example from http://www.csis.pace.edu/~bergin/patterns/ppoop.html
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.HashMap; | |
import java.util.Map; | |
import com.google.common.collect.ImmutableMap; | |
public class PrintOS { | |
private static final Map<String, String> MSG = ImmutableMap | |
.of("unix", "This is a UNIX box and therefore good.", | |
"windows", "This is a Windows box and therefore bad.", | |
"mac", "This is a Macintosh box and therefore far superior."); | |
private static final Map<String, String> OS_TYPES = ImmutableMap.<String, String> builder() | |
.put("SunOS", MSG.get("unix")) | |
.put("Linux", MSG.get("unix")) | |
.put("Windows 7", MSG.get("windows")) | |
.put("Windows NT", MSG.get("windows")) | |
.put("Windows 95", MSG.get("windows")) | |
.put("Mac OS", MSG.get("mac")) | |
.build(); | |
public static void main(final String[] args) { | |
String osName = System.getProperty("os.name") ; | |
System.out.println(OS_TYPES.containsKey(osName) ? | |
OS_TYPES.get(osName) : | |
"This is not a box. It's a \"" + osName + "\""); | |
} | |
} |
Refactored into using to static Maps. The main logic is now a simple if-else construct.
The if-else construct was very verbose, as we just wanted to print one of two messages, thus it can be replaces by a ternary conditional expression.
Reformatted to K&R style.
Added Mac OS - that was easy.
Using Google's Guava library makes the initialization of the Maps simpler and better. Compile and run using:
$ javac -cp guava-13.0.jar PrintOS.java
$ java -cp guava-13.0.jar:. PrintOS
Get gauva-13.jar from https://code.google.com/p/guava-libraries/
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Now it works on Windows 7, it also tells you what it thinks the "box" is, if it is unknown.