Results 1 to 17 of 17
- 12-11-2008, 01:00 PM #1
Member
- Join Date
- Dec 2008
- Posts
- 3
- Rep Power
- 0
- 12-11-2008, 01:47 PM #2
Until someone with greater OO comes in on this, I will put on the board that camp practice tends to bury these, and that the correct approach, the only effective approach is to tediously work throught the switch - but whenever we see this is should be possible to consider the matter as a variable ... thus being able to often collapse the giant switch if the matter to which it is applied an be forced to be a variable.
There are some stituations it would seem to me where this cannot be done. We may want to order hamburgers or car parts - those are differing things. Java being strongly typed makes this challenging.Introduction to Programming Using Java.
Cybercartography: A new theoretical construct proposed by D.R. Fraser Taylor
-
Could you instead use a Map such as a HashMap here? It would be hard for me to guess given the information you've presented so far. Or are we discussing the general case and not a specific problem? Because I don't see a general solution to this as the solution will depend I think on the specifics.
Good luck.
- 12-11-2008, 04:15 PM #4
Member
- Join Date
- Dec 2008
- Posts
- 3
- Rep Power
- 0
Thanks Nicholas for your reply...
In my situation i can't able to use switch bacause my condition checking dataType is String...i tried "Command Pattern" also but problem is 40 inner class should introduce...that's why i am looking some other better solution...
-
A Map would also likely need 40 anon inner classes. I'm wondering if no matter what your requirements are going to force some ugliness here, and that your decision will be to figure out just where that ugliness should be.
But as long as it's "maintainable" ugliness, you should be alright. :)
Good luck.
- 12-11-2008, 09:44 PM #6
Member
- Join Date
- Dec 2008
- Posts
- 30
- Rep Power
- 0
Can you post the code?
With the information presented we can only assume that if/then conditionals are the only way around. There should however be a solid OO solution if we can see it.
- 12-12-2008, 07:44 AM #7
Member
- Join Date
- Dec 2008
- Posts
- 3
- Rep Power
- 0
Team,
Fubarable & uncommon thanks for your reply...
Please see the below code...
public String getViewContent(String caModule) {
String viewContent = null;
if ( Constants.INPUT_MODULE.equals(caModule) ) {
viewContent = Constants.INPUT_MODULE;
} else if (Constants.ASSET_EXCHANGE_MODULE.equals(caModule)) {
viewContent = Constants.ASSET_EXCHANGE_MODULE;
} else if (Constants.EXCHANGE_MODULE.equals(caModule)) {
viewContent = Constants.EXCHANGE_MODULE;
}. . .
return viewContent;
}
Problem is :
1. PMD & FindBug issue for above code (more number of if..elseif statement)
2. HashMap is Costly memory consuming
i want to avoid this issue. I hope now you understand my problem.
- 12-12-2008, 02:21 PM #8
Member
- Join Date
- Dec 2008
- Posts
- 30
- Rep Power
- 0
I'm thinking you could either use Enums, Arraylist or Hashmaps and loop through the constants.
It could turn your 40 if/thens into only a few lines.
Java Code:import java.util.*; public class Card { public enum Rank { DEUCE, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE } public enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES } private final Rank rank; private final Suit suit; private Card(Rank rank, Suit suit) { this.rank = rank; this.suit = suit; } public Rank rank() { return rank; } public Suit suit() { return suit; } public String toString() { return rank + " of " + suit; } private static final List<Card> protoDeck = new ArrayList<Card>(); // Initialize prototype deck static { for (Suit suit : Suit.values()) for (Rank rank : Rank.values()) protoDeck.add(new Card(rank, suit)); } public static ArrayList<Card> newDeck() { return new ArrayList<Card>(protoDeck); // Return copy of prototype deck } }
- 12-13-2008, 02:23 PM #9
String.hashCode()
Looks like uncommon has an effective reduction to OO, as for cannot switch on a String, I got some good help early from EFH at JR on building a Map / TreeMap using an effective reduction of a string to a numeric value - I was working on Word Count, wanted to build an effective data structure. Slogged along awhile working on hashed data structures and when I saw what bucket chaining involved, I just decided to waste a few words if as the program goal would work at 80% effectiveness, thus the 1/Integer.MAX_INT even with the birthday paradox would not be of consequence. The gain from an effective reduction in processor cycles to do a find() on an int seemed to be to be likely and so much so that I never did testing.
So what we get ( that I can see ) is rtti v compile time typing - I think typing is ..... ( place obscure humor here )Java Code:String aString = new String("Who says Beans cannot Boogie?"); Integer StringAsKey = new Integer(aString.hashCode()); switch(StringAsKey).....
Consider closest common ancestor of two classes, what I see in Java is massive directory listings, with deep trees and conflicting cross-alliances, a consequence of strong typing. If your design is trying to effect a bouncing-ball, figure it out when we get there, then a loose-type programming language would be a candidate. In my opinion and experience, somewhere, some person wrote some code so if your application is to be robust in the face of routine mistakes then I just gleefully write the massive switch.
The difficulty in writing the switch is whether the strings are known at compile time and what to do for default and fine splitting of exception / error from intentional attacks and routine curiosity seekers. One cannot reduce the keyspace and not lose keyspace, those who do will be writing small, tight code for the rest of their life.Introduction to Programming Using Java.
Cybercartography: A new theoretical construct proposed by D.R. Fraser Taylor
- 12-14-2008, 07:33 PM #10
I would recommend the Enum approach. It doesn't solve all of your problems. But it does let you use a switch {}
A higher level question is why in the world do you have 40 cases? That itself strikes me as poor design. Humans can't remember or understand that many things. It would be easier to write and easier to use if you could have a hierarchy of commands.
create [movie|song|photo|blog]
send [message|file|twit]
rather than having seven unique commands, have two commands with four subcommands.
- 12-14-2008, 08:42 PM #11
All that code does is return a copy of the String passed in as the sole parameter. Why do you need to do this?Java Code:public String getViewContent(String caModule) { String viewContent = null; if ( Constants.INPUT_MODULE.equals(caModule) ) { viewContent = Constants.INPUT_MODULE; } else if (Constants.ASSET_EXCHANGE_MODULE.equals(caModule)) { viewContent = Constants.ASSET_EXCHANGE_MODULE; } else if (Constants.EXCHANGE_MODULE.equals(caModule)) { viewContent = Constants.EXCHANGE_MODULE; }. . . return viewContent; }
db
- 12-15-2008, 12:10 AM #12
I venture he needs a data structure:
on the basis that each class poster has now represents on of a collection of data that has a similar common bond but is in need of retaining identifiying discernable behaviour or dispostion.Java Code:ArrayList Dictionary Enumeration EnumMap EnumSet HashMap HashSet Hashtable IdentityHashMap LinkedHashMap LinkedHashSet LinkedList List Map PriorityQueue RegularEnumSet Set SortedMap SortedSet Stack TreeMap TreeSet Vector
Introduction to Programming Using Java.
Cybercartography: A new theoretical construct proposed by D.R. Fraser Taylor
- 12-15-2008, 01:42 AM #13
Senior Member
- Join Date
- Nov 2008
- Posts
- 286
- Rep Power
- 5
Cost of hash map really isn't so bad...!
Just to allay the OP's fears about the cost of using a hash map:
- it's true that you "waste" a slight amount of memory, but with 40 items we're really not talking very many bytes -- if you really want to count bytes, then think of the bytecodes you save from not needing the long list if/else statements...!
- with default values, in about two thirds of cases, looking up a value will be essentially as fast as Nicholas' switch statement with the hash code (that is, in about 67% of cases, after calculating the hash code, the item will be the first in the bucket corresponding to that hash code)
Nicholas -- I think you worry unduly about the chaining issue -- again, in the "average ideal" case with default values, we expect the average chain length of a bucket to be 1.42 -- i.e. we calculate the hash code then expect on average 1.42 comparisons. Unless I'm missing something in what you're suggesting, switching over the hash code as you suggest would mean an average of 20 comparisons and a worst case of 40 (as with the list of if/elses), wouldn't it?Neil Coffey
Javamex - Java tutorials and performance info
- 12-15-2008, 02:28 AM #14
compile time constants ....
Mostly, I was trying to work to posters advantage - short is that I could not figure out how to do bucket chaining in sources and chose to use the libraries ... that is use the libraries once I got "over the hill" in Java...using any of the collections would likely enhance Opie's work and I chose to include the remark about bucket chaining to show a short version of I could not figure it out in the hopes of directing original poster's work toward java.util.* to save argumentation over some nasty issues that result in staring at the screen, getting nothing done. Right at the moment, I prefer giant switches - but that's just the mood of the moment. I find nothing challenging nor intimidating in 1.42 conditional branches v 20/40 or whatever .... my first Java effort, a WordCount instinctively used Integer Key = new Integer(Word.hashCode()); as a key in a TreeMap. I spent most of my time wrestling with beginner issues that got nothing done.
Looking back on that, I can see in poster's original issue a common binding that makes a Collection the obvious choice. The chaining remark was just what came to mind as I wrote the response. I, today, would probably write "Hello World" as a Hashtable .... busy right now && might have to go to List to get ordering or something....but we see in Darryl.Burke's observation that OP has not been able to disentangle the key used to access the data from the data....for one thing, we see in code "if ( Constants.INPUT_MODULE.equals(caModule)" so these are likely constants, thus known at compile time. Generating a data structure that keys on compile time values has in my experience been done manually by writing a program to generate the String.hashCode()'s then writing these codes to source file using a one-off utility:Sorta clumsy but I just cannot see trying to squeeze financials through small, tight, code - probably the people I have to work with but the problem is ubiquitousJava Code:/* * CommonPasswords builds, stores and retireves common passwords so that they may be rejected or accepted * according to the determination of system admin or module user. The list is archived as String.hashcode * using Java Language's String.hashCode() method. */ class CommonPasswords extends java.util.TreeSet { int[] hashedPWList = { -2118473344,-2084611850,-2083503259,-2034983908, ...... // .... and so onIntroduction to Programming Using Java.
Cybercartography: A new theoretical construct proposed by D.R. Fraser Taylor
- 12-15-2008, 04:16 AM #15
Senior Member
- Join Date
- Nov 2008
- Posts
- 286
- Rep Power
- 5
OK, if you're looking for a pointless way to obfuscate your code with no benefit, then do this. If you want to write comprehensible code that actually performs better in all probability, just use an Enum or HashMap keyed on strings.
Neil Coffey
Javamex - Java tutorials and performance info
- 12-16-2008, 06:14 AM #16
we've lost the OP. I think having 40 cases is poor design, no matter what structure the code uses.
- 01-28-2011, 10:25 AM #17
Member
- Join Date
- Jan 2011
- Posts
- 13
- Rep Power
- 0
Unless there is something else different to the code you are showing I would agree with Darryl Burke. So far your method has the potential to return some value for viewContent or viewContent = null, it doesn't return any information about wether it was ASSET_EXCHANGE_MODULE or INPUT_MODULE etc. that matched caModule so you are as well just putting your constant values into an array, as suggested, and seeing if the value is in the array or use one of the other data structures mentioned. It's not going to consume all your computers resources finding a value in a small array.
And Never have 40 If/else statements, you are just looking to introduce errors into your program.
Similar Threads
-
JFrame (closing under a condition)
By Java Tip in forum Java TipReplies: 0Last Post: 03-12-2008, 11:17 AM -
problem with using string in if condition
By sireesha in forum New To JavaReplies: 2Last Post: 11-20-2007, 10:40 PM


LinkBack URL
About LinkBacks


Bookmarks