如果使用远程数据,则比其他解决方案更好 [英] Better solution than else if with ranged data
问题描述
我有一个简单的java方法,它根据从RGB转换的HSB值返回颜色。它工作(需要一些调整),但我使用一系列其他if和嵌套if语句来返回我想要的数据。我听说过HashMaps和String Factories更好,但我看不出它们如何处理远程数据。有没有更好的解决方案适用于这样的远程数据?
I have a simple java method that returns colors based on the HSB value converted from an RGB. It works (needs some tweaking), but I use a series of else if and nested if statements to return the data I want. I had heard that HashMaps and String Factories were better, but I couldn't see how these worked with ranged data. Is there a better solution that works with ranged data like this?
代码段:
public static String getColorName() {
getHSB(rgb);
if(hsbH >= 45 && hsbH < 75) {
if(hsbS > 0 && hsbS < 45 && hsbB > 70){
return "White/Off White";
} else if(hsbS > 0 && hsbS < 45 && hsbB < 10) {
return "Dark Yellow";
} else {
return "Yellow";
}
} else if(hsbH >= 15 && hsbH < 45) {
if(hsbS > 0 && hsbS < 45 && hsbB > 70){
return "White/Off White";
} else if(hsbS > 0 && hsbS < 45 && hsbB < 10) {
return "Dark Orange";
} else {
return "Orange";
}
...
推荐答案
仔细看,代码中有很多重复和非常明显的结构!这就是我提出的,据我所知,大部分工作是在我最喜欢的IDE中使用自动重构完成的:
Look carefully, there is a lot of repetition and very obvious structure in your code! Here is what I came up with, as far as I remember most of the job was done using automatic refactorings in my favourite IDE:
public static String getColorName() {
getHSB(rgb);
if (hsbH < 15)
return colorName(hsbB, hsbS, "Red");
if (hsbH < 45)
return colorName(hsbB, hsbS, "Orange");
if (hsbH < 75)
return colorName(hsbB, hsbS, "Yellow");
//...
}
private static String colorName(int hsbB, int hsbS, String color) {
final boolean smallSaturation = hsbS > 0 && hsbS < 45;
if (smallSaturation) {
if (hsbB > 70)
return "White/Off White";
if (hsbB < 10)
return "Dark " + color;
}
return color;
}
如果您使用 Sean Patrick Floyd 的建议使用 TreeMap
这段代码会更简单(我可以帮助自己):
If you use Sean Patrick Floyd's advice of using TreeMap
this code will be even simpler (I could help myself):
public static String getColorName(final int hsbH, final int hsbB, final int hsbS) {
NavigableMap<Integer, String> colorRanges = new TreeMap<Integer, String>();
colorRanges.put(0, "Red");
colorRanges.put(15, "Orange");
colorRanges.put(75, "Yellow");
//...
return colorName(hsbB, hsbS, colorRanges.floorEntry(hsbH).getValue());
}
请注意 colorRanges
范围应定义一次并重复使用。
Note that colorRanges
ranges should be defined once and reused.
冒险在这里投票是一种很好的方式,你可以使用Scala和简单的DSL:
Risking being downvoted here is a nice way you can write this literally using Scala and simple DSL:
implicit def toIntBetween(x: Int) = new {
def between(left: Int) = new {
def and(right: Int) = {
x >= left && x < right
}
}
}
def getColorName = {
if(hsbH between 45 and 75) {
//...
}
}
花式 if(hsbH之间) 45和75)
构造实际上转换为:
Fancy if(hsbH between 45 and 75)
construct actually translates to:
if(toIntBetween(hsbH).between(45).and(75))
这篇关于如果使用远程数据,则比其他解决方案更好的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!