Refactoring if/else logic - java

I have a java class with a thousand line method of if/else logic like this:
if (userType == "admin") {
if (age > 12) {
if (location == "USA") {
// do stuff
} else if (location == "Mexico") {
// do something slightly different than the US case
}
} else if (age < 12 && age > 4) {
if (location == "USA") {
// do something slightly different than the age > 12 US case
} else if (location == "Mexico") {
// do something slightly different
}
}
} else if (userType == "student") {
if (age > 12) {
if (location == "USA") {
// do stuff
} else if (location == "Mexico") {
// do something slightly different than the US case
}
} else if (age < 12 && age > 4) {
if (location == "USA") {
// do something slightly different than the age > 12 US case
} else if (location == "Mexico") {
// do something slightly different
}
}
How should I refactor this into something more managable?

You should use Strategies, possibly implemented within an enum, e.g.:
enum UserType {
ADMIN() {
public void doStuff() {
// do stuff the Admin way
}
},
STUDENT {
public void doStuff() {
// do stuff the Student way
}
};
public abstract void doStuff();
}
As the code structure within each outermost if branch in your code looks pretty much the same, in the next step of refactoring you might want to factor out that duplication using template methods. Alternatively, you might turn Location (and possibly Age) into a strategy as well.
Update: in Java4, you can implement a typesafe enum by hand, and use plain old subclassing to implement the different strategies.

The first thing I would do with this code is create the types Admin and Student, both of which inherit from the base type User. These classes should have a doStuff() method where you hide the rest of this logic.
As a rule of thumb, any time you catch yourself switching on type, you can use polymorphism instead.

Thousands? Maybe a rules engine is what you need. Drools could be a viable alternative.
Or a Command pattern that encapsulates all the "do something slightly different" logic for each case. Store each Command in a Map with the concatentation of age, location, and other factors as the key. Lookup the Command, execute it, and you're done. Nice and clean.
The Map can be stored as configuration and read in on start up. You can add new logic by adding new classes and reconfiguring.

First - use enums for userType and location - then you can use switch statements (improves readability)
Second - use more methods.
Example:
switch (userType) {
case Admin: handleAdmin(); break;
case Student: handleStudent(); break;
}
and later
private void handleAdmin() {
switch (location) {
case USA: handleAdminInUSA(); break;
case Mexico: handleAdminInMexico(); break;
}
}
Further, identify duplicate code and put it in extra methods.
EDIT
If someone forces you to code Java without enums (like you're forced to use Java 1.4.2), use 'final static's instead of enums or do something like:
if (isAdmin(userType)) {
handleAdmin(location, age);
} else if (isStudent(userType)) {
handleStudent(location, age));
}
//...
private void handleAdmin(String location, int age) {
if (isUSA(location)) {
handleAdminInUSA(age);
} else if (isUSA(location)) {
handleAdminInMexico(age);
}
}
//...
private void handleAdminInUSA(int age) {
if (isOldEnough(age)) {
handleAdminInUSAOldEnough();
} else if (isChild(age)) {
handleChildishAdminInUSA(); // ;-)
} //...
}

The risk of this is not just that it is unsightly, but that it is very error prone. After a while, you could run into a risk of overlaps in your conditions.
If you can really distinguish the condition by user type, you can at the minimum break the body of each condition into a separate function. So that you check based on the type, and call an appropriate function specific to that type. A more OO solution is to represent each user as a class, and then override some calculation method to return a value based on the age. If you can't use classes but can at least use enums, then you will be able to do a nicer switch statement on the enums. Switches on Strings will only come in Java 7.
What worries me is situations of overlaps (e.g., two user types with some shared rules, etc.). If that ends up being the case, you might be better off representing the data as some external file (E.g., a table) which you would read and maintain, and your code will essentially operate as a driver that does the appropriate lookup in this data set. This is a common approach for complex business rules, since nobody wants to go and maintain tons of code.

I would probably first check whether you can parametrize the code doStuff and doSimilarStuff.

You may use Chain of Responsibility pattern.
Refactor if-else statements into classes with an interface IUserController for instance.
Initialize your chain within a list or a tree or any suitable data structure, and execute desired functionality in this chain. You may use Builder pattern to create mentioned data structure. It resembles to strategy pattern but in chain of responsibility pattern, an instance in the chain can call linked instance(s).
Moreover, you can model location specific functionality by using strategy pattern. Hope it helps.

If the code in the blocks fits within a few standard patterns, I would create a table with columns (type, location, minAge, maxAge, action), where 'action' is an enum indicating which of several types of processing to do. Ideally, this table would be read from a data file or kept in SQL.
Then, you can just do a table lookup in the Java code to determine the action to take for a user.

You could make userType an enum, and give it a method that performs all of your "do something slightly different" actions.

without more information there is no good answer
but fair guess would be this: use OO
first define a User, define Admin, Student and all other types of users and then let polymorphism take care of the rest

Based just on the variable names, I'm guessing that you should subclass User (or whatever it is that has a userType variable) into AdminUser and StudentUser (and possibly others) and use polymorphism.

Take a look at the Visitor pattern. It makes use of polymorphism but is a little more flexible in that it is easier to add new cases later.
The downside is you'd need some way to convert the state info into different instances. The benefit is a cleaner way to add behavior without having to modify your inheritance hierarchy.

You really need to break these cases into object methods. I'm assuming these strings and numbers are being pulled out of a database. Instead of using them in their raw form in giant nested conditional logic, you need to use these pieces of data to construct objects that model the desired interactions. Consider a UserRole class with a StudentRole and AdminRole subclasses, a Region class with USA and Mexico subclasses, and an AgeGroup class with appropriate partitioned subclasses.
Once you have this object oriented structure in place, you'll be able to make use of well understood object oriented design patterns to re-factor this logic.

Use OOP Concepts:
This is dependent of the rest of the design, but maybe you should have a user interface, Student,Admin interfaces the extends it and UsaStudent,MexicoStudent,UsaAdmin,MexicoAdmin implementation that do some stuff. Hold a User instance and just call its doStuff method.

Related

Is it good practice to often use instanceof?

The scenario. I'm writting game-related code. In that game a Player(its also a class) has a list of Item. There are other types of items that inherit from Item, for example ContainerItem, DurableItem or WeaponItem.
Obviously it is very conveniant for me to just have List<Item>. But when I get the players items, the only way for me to distinguish between what type of item is by using the instanceof keyword. I'm sure I've read that reliaing on it is bad practice.
Is it ok to use it in this case? Or should I rethink all of my structure?
Let's say I am writing some inventory code:
public void showInventory(List<Item> items) {
for (Item item : items) {
if (item instanceof ContainerItem) {
// container display logic here
}
else if (item instanceof WeaponItem) {
// weapon display logic here
}
// etc etc
}
}
That will compile and work just fine. But it misses out on a key idea of object oriented design: You can define parent classes to do general useful things, and have child classes fill in specific, important details.
Alternate approach to above:
abstract class Item {
// insert methods that act exactly the same for all items here
// now define one that subclasses must fill in themselves
public abstract void show()
}
class ContainerItem extends Item {
#Override public void show() {
// container display logic here instead
}
}
class WeaponItem extends Item {
#Override public void show() {
// weapon display logic here instead
}
}
Now we have one place to look, the show() method, in all our child classes for inventory display logic. How do we access it? Easy!
public void showInventory(List<Item> items) {
for (Item item : items) {
item.show();
}
}
We are keeping all the item-specific logic inside specific Item subclasses. This makes your codebase easier to maintain and extend. It reduces the cognitive strain of the long for-each loop in the first code sample. And it readies show() to be reusable in places you haven't even designed yet.
IMHO using instanceof is a code smell. Simply put - it makes your code procedural, not object oriented. The OO way of doing this is using the visitor pattern.
The visitor pattern also allows you to easily build decorators and chain of responsibility on top of it, thus achieving separation of concerns, which results in shorter, cleaner and easier to read and test code.
Also do you really need to know the exact class ? Cant you take advantage of polymorphism ? After all Axe IS a Weapon just as Sword is.
You should rethink maybe and try to use polymorphism to implement your List<Item> idea.
Here is some references for your problem that can probably help :
Prefer polymorphism over instanceof and downcasting
instanceof versus getClass in equals Methods (Interview with Josh Bloch)
Polymorphism and Interfaces (see section about When to use instanceof)
(References from Is instanceof considered bad practice? If so, under what circumstances is instanceof still preferable? )
You should rethink your structure, instanceof in non-meta code is almost always a sign for an anti-pattern. Try to define the behaviour all Items have in common (like having a picture, a description and something happening when you click on them) in the Item-class/interface, making use of the abstract-keyword if appropiate, and then use polymorphism to implement the specifics.
It's ok if it's easy for you to understand.
Moving branching logics from where they naturally belong all to subclasses is not necessarily a good idea. It may create the wrong dependency; it may cause bloated classes, and it may be hard to navigate and understand.
In the end, it's all about how to physically organize our code with multiple dimensions of concerns in a one dimensional space. It's not a trivial problem, it is subjective, and there is no panacea.
In particular, our industry inherited a lot of rules of thumbs that were made in the last century based on technical and economical constraints of that era. For example, tooling were very limited; programmers were highly expensive; applications evolved slowly.
Some of these rules may no longer apply today.
I don't necessarily think instanceof is bad for coders who know what they are doing and use it to avoid having to write more complicated code to get around it. There is a use for everything, and also a mis-use.
With that said, the description you provide does not require instanceof. There are various ways you can implement this without instanceof, and (the most important thing) the alternate solution must be better than using instanceof. Don't just go with a non-instanceof solution to avoid instanceof because you heard it is bad.
I think that for your scenario an non-instanceof solution has benefits in making the solution more easily extensible.
for (Item i: items) {
if (ItemTypes.WEAPON_ITEM.equals(i.getType)) {
processWeaponType(i);
}
}
or
for (Item i: items) {
if (WeaponItem.class.equals(i.getType)) {
processWeaponType(i);
}
}

Design Pattern in real world [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am learning design pattern from Head first book and I understood most of them. But when I try to apply in real world, it becomes more difficult. In every example, it has created lot of sub classes. But do we really create so much classes in real time projects?
E.g. Consider an example of Bank Account
Approach 1:
Account {
String name;
double balance;
operation1() {
}
}
SavingAccount extends Account {
// some extra fields and methods related to saving account
operation1() {
}
}
CurrentAccount extends Account {
// Some extra fields and methods related to current account.
operation1() {
}
}
When I map these classes with database, using Hibernate using one of the inheritance strategy, e.g. table per sub class, I will end up with three tables. Account, Saving_account and Current_account.
Advantage: I can call operation1() depending on the type of object using polymorphism.
Disadvantage: more tables and classes. If project is more complex and big, It will end up with thousands of classes.
Approach 2:
Account {
string name;
double balance;
string type;
operation1() {
}
}
I need only 1 table for this approach called Account. And "type" field will identify the type of the account.
Advantage: Only 1 table and class.
Disadvantage: I will lose Object oriented world and every place I have to put the condition as below.
if (type == saving) {
// do this;
} else if (type == current) {
// do that;
}
As per theory, approach 1 is correct and best. But currently in my project, approach 2 is used. My project is not banking. I took it as an example for the simplicity.
I know this is very basic question. But due to my current project implementation, I could not stop myself asking this question.
EDIT: maintainability of approach 1 is more better than approach 2.
Design patterns like inheritance are difficult to describe in terms of their importance, because it takes a very large project to realize the power of it. Usually examples end up with stuff like:
class A {
}
class B extends A {
}
class C extends B {
}
class D extends A {
}
And then you get a lot of not so real life questions like which method foo() really refers to when it's implemented four separate times.
The motivation for using inheritance is to group similar types of things together in a class. A basic example is if you want to have a bunch of different objects all in a list together. This isn't possible if they're all different types, but if they're in an inheritance hierarchy, you can group them all together.
For your example, you can put every Account object into a single list, no matter which subclass the objects are really in.
List<Account> list = new ArrayList<Account> ();
list.add(new Account());
list.add(new SavingsAccount());
list.add(new CurrentAccount());
Say you want to process every thing in that list. If you have one common method, you can use polymorphism to make each Account do its own specific action:
for(Account a : list) {
a.operation1();
}
Much simpler than having a separate list for each type of object, no? And then if you want to make more types of accounts, if you extend the base Account class, you don't have to add new lists and new loops to your code. Everything can remain as is.
Using inheritance also helps to use code that other people have written. If you want to add something to a class that someone else has written, you can include it in a package and then extend it with one of your own classes. That way you don't have to do a lot of copy and pasting and navigating through the other class's source code. You also can extend another class even if you only have its .class file, rather than the source code in a .java file.
So the power of inheritance depends on how you use it. In a small example, it doesn't really make sense. But the bigger the project, the more it makes sense.
Both approaches are valid as you just mentioned and the pros and cons you explained are also valid.
But for example you if you are Giving this Accounting package (compiled jar) as a library to be extended by other people, the approach 1 is ideal because;
You don't need to modify any source code of Account, just extend it and then implement your own version. Ex:- FixedDepositAccount
Won't break your Account code.
No need of Testing again for Account.operation1()
But if you are willing to share the source code and willing to do above mentioned steps then it is best to use method 2.
In Java we can have String type; (not string type;), but even better would be an Enum type (that way we could have add a Money Market Account or a Platinum Preferred Savings Account, possibly without re-implementing the caller code). Something like,
enum AccountType {
CHECKING(0.005), SAVINGS(0.01), MMA(0.02);
final double rate;
private AccountType(double rate) {
this.rate = rate;
}
public double getRate() {
return this.rate;
}
}
And with an AccountType you can safely use == for equality, while doing if (type == saving) { with a String is asking for trouble. That is
if (type == AccountType.CHECKING) {
} else if (type == AccountType.SAVINGS) {
will function as you would expect. Finally, it would be better to try and avoid the if chains and instead encapsulate whatever you plan to do with the account type into the enum itself when you can. For example,
Account acct = getAccount(accountNumber);
if (acct != null && acct.isValid()) {
acct.balance += acct.balance * type.getRate();
}

Does this method belong to Value object or Manager

In an e-commerce application, below are the high level API
interface Order{
public List<PaymentGroup> getPaymentGroups();
}
interface PaymentGroup{}
class PaymentGroupImpl implements PaymentGroup{}
class CreditCard extends PaymentGroupImpl{}
class GiftCard extends PaymentGroupImpl{}
class OrderManager{ //Manager component used to manipulate Order}
There is a need to add some utility methods like hasGiftCard(), hasCreditCard(), getGiftCards(), getCreditCards()
Two approaches -
1) Add these in Order. However, this would result in coupling between Order and PaymentGroup implementors (like CreditCard, GiftCard) Example -
interface Order {
public List<GiftCard> getGiftCards();
}
2) Move these to OrderManager.
class OrderManager{
public List<GiftCard> getGiftCards(Order order){}
}
I personally prefer 2), am just curious would there be any reason to choose 1) over 2)
I have two answers. One is what I'll call Old Skool OOP and the other I'll call New Skool OOP.
Let's tackle New Skool first. The GoF and Martin Fowler changed the way people look at OOP. Adding methods like hasGiftCard() leads to adding conditional logic/branching into the code. It might look something like this:
if (order.hasGiftCard()) {
//Do gift card stuff
} else {
//Do something else
}
Eventually this kind of code becomes brittle. On a big application, lots of developers will be writing predicate methods. Predicate methods assert something and return true or false. These methods usually start with the word "has", "is" or "contains". For example, isValid(), hasAddress(), or containsFood(). Still more developers write conditional logic that uses those predicate methods.
To avoid all of this conditional logic software engineers changed how they thought about object-orientation. Instead of predicate-methods-and-conditional-logic, they started using things like the strategy pattern, visitor pattern, and dependency injection. An example from your problem domain might look like this:
//Old Skool
if (this.hasCreditCard()) {
orderManager.processCreditCard(this.getCreditCards());
}
Here is another approach to solving the same problem:
//New Skool
for(PaymentItem each : getPaymentItems()){
each.process(this);
}
The New Skool approach turns the problem on its head. Instead of making the Order and OrderManager responsible for the heavy lifting the work is pushed out to the subordinate objects. These kind of patterns are slick because:
they eliminate a lot of "if" statements,
the code is more supple and it is easier to extend the application, and
instead of every developer making changes to Order and OrderManager, the work is spread out among more classes nd code merges are easier.
That's New Skool. Back in the day, I wrote a lot of Old Skool object-oriented code. If you want to go that route, here are my recommendations.
IMHO, you don't need both a PaymentGroup interface and a PaymentGroupImpl class. If all payment classes extend PaymentGroupImpl, then get rid of the interface and make PaymentGroup a class.
Add methods like isCreditCard(), isGiftCertificate() to the PaymentGroup class. Have them all return "false".
In the subclasses of PaymentGroup, override these methods to return true where appropriate. For example, in the CreditCard class, isCreditCard() should return "true".
In the Order class, create methods to filter the payments by type. Create methods like getCreditCards(), getGiftCertificates(), and so on. In traditional Java (no lambdas or helper libraries), these methods might look something like this
List getCreditCards() {
List list = new ArrayList();
for(PaymentGroup each : getPaymentGroups()){
if(each.isCreditCard()) {
list.add(each);
}
return list;
}
-In the Order class, create predicate methods like hasCreditCards(). If performance is not an issue, do this:
boolean hasCreditCards() {
return !getCreditCards().isEmpty();
}
If performance is an issue, do something more clever:
boolean hasCreditCards() {
for(PaymentGroup each : getPaymentGroups()){
if(each.isCreditCard()) {
return true;
}
return false;
}
}
Realize that if you add a new payment group, a code must be added in a lot of places in the Old Skool paradigm.

How to avoid lots of checks for null when using get() on a Java Collection?

I have a statement as follows
getLD().get(cam.getName()).getAGS().get(aG.getName())
getLD(), getAGS() return Java collections
I would not consider it to be an error if getAGS() were empty, nor if the result of getAGS().get(aG.getName()) were empty. However it is rather messy and somewhat of a pain checking for these null conditions.
e.g. if(getLD().get(camp.getName()).getAGS() !=null && getLD().get(cam.getName()).getAGS().get(aG.getName()) != null) {
Can anyone suggest the best way to deal with this? Obviously I could create a variable x = getLD().get(camp.getName()).getAGS() to shorten the code, but is there a way in which I would not have to do the two checks for null?
All help is much appreciated!
IMO, the best strategy is to design your data structures so that there aren't any nulls in the first place. For example, use empty collections or zero length arrays, or "" instead of null. For application classes, consider implementing special instance that you can use instead of null.
A second strategy is to replace use of exposed generic data structures (e.g. maps, lists, arrays) with custom classes. This hides the implementation details inside a class, and allows you to make use of Java's static typing to avoid many of the situations where a null check would be required.
A third strategy is to create a helper class with a bunch of methods that implement common operations; e.g. "get the Cam for an LD". (IMO, this approach is a poor alternative, compared with the others, but at least it reduces the amount of code repetition.)
To the extent that you cannot get rid of the nulls, you've got no option but to explicitly test for them. (There was a proposal to add an "elvis" operator to Java 7 as part of project Coin, but unfortunately it was cut.)
The best way would be to avoid the chain. If you aren't familiar with the Law of Demeter (LoD), in my opinion you should. You've given a perfect example of a message chain that is overly intimate with classes that it has no business knowing anything about.
Law of Demeter: http://en.wikipedia.org/wiki/Law_of_Demeter
The apache commons project has a library called Bean Introspection Utilities (BeanUtils), which looks like it can do what you need. Check out the nested property access section, in the user guide, and look at the BeanUtils class:
http://commons.apache.org/beanutils/
It has utility classes that I think can do what you need.
Another thing to consider: you should try to avoid doing this many levels of nested property access. This is a code smell called "feature envy", where an object wants to use features of another object regularly. Consider creating methods on the top-level object, or find a way to redesign so that the feature you need is shared more readily.
try {
foo().bar().baz();
} catch (NullPointerException e) {
// Check if it was actually an error
}
Code in groovy!.
Not always possible depending on your environment and performance requirments. But its a joy to just type
if (getLD(camp?.GetName())?.getAGS(ag?.GetName()))
Alternativly you could just code what you mean and catch the null pointer exception. In your case this would be much more readable especially of you dont care which element is null.
I think Something is more complext than needed if you require to do
getLD().get(cam.getName()).getAGS().get(aG.getName())
If you need to check if the second collection or the result is null you can do something like:
Map<?,?> firstList= getLD();
Object value = null;
if (firstList!=null && !firstList.isEmpty() && fistList.containsKey(cam.getName())){
Map<?,?> secondList = firstList.get(cam.getName());
if (secondList!=null && !secondList.isEmpty() && secondList.containsKey(aG.getName())){
value = secondList.get(aG.getName());
}
}
if(value != null){
// Do the required operations if the value is not null
}else{
// Do the required operations if the value is null
}
With this code i checked if the first collection is not null, is not empty and if it has the content. The i get the second collection and i repeated the process in the second collection.
Also a method can be created to do this operation:
private Map<?,?> getItem(Map<?,?> map,Object key){
if (map!=null && !map.isEmpty() && map.containsKey(key)){
return map.get(key);
}
return null;
}
and in your code:
Object value = getItem(getItem(getLD(),cam.getName()),aG.getName());
if(value != null){
// Do the required operations if the value is not null
}else{
// Do the required operations if the value is null
}

How should I implement a map of string to method in Java?

I have a list of XML tags and a method for each of them inside my class, getting that tag as an argument and doing its work. So all the methods get the same input and I want to loop through the list of tags, calling appropriate method each time.
In Python I've made it with a hash of strings (names of tags) to lambdas (self.methodName()) and I want to translate it to Java.
Now in Java, I can't (?) make such a hash and even can't use strings (tag names) in a switch statement (with each branch calling a certain method). The possibility of using 10 or so subsequent ifs seems horribly ugly and I'm looking for a better way to code that.
Map string to a class instance by instantiating classes and saving them (probably in a hash). All the classes must implement the same interface of course.
You'll find that if you code this way a better structure starts to emerge from your code--for instance you might find that where before you might have used 2, 3 or 10 similar methods to do slightly different things, now the fact that you can pass data into your constructor allows you to do it all with one or two different classes instead.
This interface and the classes that implement it (for me at least) nearly always evolve into a full-featured set of classes that I needed all along but might not have recognized otherwise.
Somehow I never seem to regret writing code the "Hard" way, but nearly always regret when I choose the easier path.
What do people think of this?
public static enum Tags {
TAG1, TAG2, TAG3
}
public class Stuff {
...
switch (Tags.valueOf(str)) {
case TAG1: handleTag1(); break;
case TAG2: handleTag2(); break;
case TAG3: handleTag3(); break;
}
}
The upside is that this is concise and efficient (at least in this case). The downside is that it is not so good with mixed case tags and tags with Java non-identifier characters in them; e.g. "-". (You either have to abuse accepted Java style conventions for the enum member identifiers, or you have to add an explicit String-to-enum conversion method to the enum declaration.)
Using a switch statement for dispatching is evil in some peoples' book. But in this case, you need to compare what you are gaining with what you are loosing. And I'd be surprised if polymorphic dispatching would give a significant advantage over a switch statement in terms of extensibility and maintainability.
I'd go with what Bill K suggested in regards to implementing the same interface. But if you have the issue of wanting to call methods with different names you could try using reflection and do something like this:
Method method = Foo.class.getDeclaredMethod("methodName", parametersTypes); // Get the method you want to call
Foo foo = new Foo();
method.invoke(foo, args); // invoke the method retrieved on the object 'foo' with the given arguments
you can invoke the method using reflection:
Class.getMethod
therefore you don't need a switch or a set of ifs.
Here is an example of the proposal of Bill K (if I understood it right)
public class Example {
static interface TagHandler {
void handle(String tag);
}
static final Map<String, Example.TagHandler> tagHandlers = new HashMap<String, Example.TagHandler>() {
{
put("tag_1", new Example.TagHandler() {
public void handle(String tag) {
System.out.println("Handling tag_1: " + tag);
}
});
put("tag_2", new Example.TagHandler() {
public void handle(String tag) {
System.out.println("Handling tag_2: " + tag);
}
});
}
};
public static void main(String[] args) {
String[] tags = { "tag_1", "tag_2", "tag_1" };
for (String tag : tags) {
tagHandlers.get(tag).handle(tag);
}
}
}
An indirect answer: XML typically represents data, not instructions. So it is probably more useful to map parser handling onto fields. This is what JAXB does. I suggest using JAXB or similar.
Unless you have a huge amount to do, I would strongly advise against reflection in a statically typed language. A string of } else if (tag.equals("blah")) { (or with interning, } else if (tag == "blah") { isn't going to kill you. You can even map strings onto their enum namesakes, but that is a little reflectiony. Switch-on-string should be with us in JDK7.

Categories