• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to make this code extensible?  RSS feed

 
rakesh sugirtharaj
Ranch Hand
Posts: 151
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi I currently have this logic in my code - that assigns importance of a word based on some weightage calculation.
How can i refactor this code so that it becomes easier to add another category (say too low) in the future. The multiple 'if-else' is freaking me out.
 
Campbell Ritchie
Marshal
Posts: 56578
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Since the weighting goes up in steps of 10.55m you could divide the weighting by 10.55, cast to an int and use it in a switch block. But it will restrict you to using multiples of 10.55 in future.
 
rakesh sugirtharaj
Ranch Hand
Posts: 151
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

Any other ideas on this?
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well you can get rid of the right hand side of the &&s. The code will only get to the first else if the weight is greater than or equal to 10.55. I know this doesn't exactly answer your question but it does make your current code simpler.Note that your original code didn't allow for weights of 10.55 or 21.10. This assumes they equate to Medium and High respectively.
 
rakesh sugirtharaj
Ranch Hand
Posts: 151
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Neal,
But I came up with a different solution which I would like to share. I used a property file that stores values as
0-10.55=LOW
10.55-21.10=MODERATE
..
..
Then in a utility method i parse the 'key' string to get the numbers (range) and do a single comparison with only one 'if'. The next time i want to add a new range i just have to change the properties file.
Thanks for your replies.
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But you're shifting the problem to your properties file now. If you want to add range 10.55 - 15.00, you need to modify the 10.55 - 21.10 range as well.

If you combine Joanne's solution of just using the upper bound in the check, and your solution of the properties file, that would be the best solution you can find for this I think.

By the way, you'd want to use a TreeMap for storing the values to labels since that one is sorted.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!