如何命名两个含义相同但类型不同的变量
How to name two variables that have the same meaning but different types
我有一个方法可以解析字符串并将其转换为布尔值。
合法值为 "true" 和 "false".
boolean convertStringToBoolean(String text) {
if (text.equals("true") {
return true;
} else if (text.equals("false")) {
return false;
} else {
throw new IllegalArgumentException(text);
}
}
当我使用这个变量时,我遇到了命名问题。
void doSomething(String isSpecificReadString) {
boolean isSpecificRead = convertStringToBoolean(isSpecificReadString);
...
}
问题是参数带有我想保留在其名称中的含义。
意义不会因为类型改变而改变。
到目前为止,我的解决方案只是将类型作为参数的后缀。
但我不喜欢这个解决方案。
我应该怎么调用变量来解决这个问题?
So far, my solution has been to just suffix the type to the parameter.
But I don't like this solution.
Java 等强类型语言以这种方式工作。
变量不能在运行时改变它们的类型。
您必须接受语言限制。
在方法中将数据从一种类型转换为另一种类型可能会产生此问题。
但是您的实际解决方案相当不错。
意图很明确,您为目标变量保留了一个自然名称。
您确实只为将要转换的输入(temporary/intermediary 变量)添加了类型后缀,而不是为将在下一个语句中使用的输出添加类型后缀。
受 Andy Turner 的启发,我可以制作两种 doSomething
方法。
一种采用字符串的方法,另一种采用布尔值的方法。
然后 String 方法可以调用 boolean 方法。
如下:
void doSomething(String isSpecificRead) {
doSomething(convertStringToBoolean(isSpecificReadString));
}
void doSomething(boolean isSpecificRead) {
...
}
我有一个方法可以解析字符串并将其转换为布尔值。 合法值为 "true" 和 "false".
boolean convertStringToBoolean(String text) {
if (text.equals("true") {
return true;
} else if (text.equals("false")) {
return false;
} else {
throw new IllegalArgumentException(text);
}
}
当我使用这个变量时,我遇到了命名问题。
void doSomething(String isSpecificReadString) {
boolean isSpecificRead = convertStringToBoolean(isSpecificReadString);
...
}
问题是参数带有我想保留在其名称中的含义。 意义不会因为类型改变而改变。 到目前为止,我的解决方案只是将类型作为参数的后缀。 但我不喜欢这个解决方案。
我应该怎么调用变量来解决这个问题?
So far, my solution has been to just suffix the type to the parameter. But I don't like this solution.
Java 等强类型语言以这种方式工作。
变量不能在运行时改变它们的类型。
您必须接受语言限制。
在方法中将数据从一种类型转换为另一种类型可能会产生此问题。
但是您的实际解决方案相当不错。
意图很明确,您为目标变量保留了一个自然名称。
您确实只为将要转换的输入(temporary/intermediary 变量)添加了类型后缀,而不是为将在下一个语句中使用的输出添加类型后缀。
受 Andy Turner 的启发,我可以制作两种 doSomething
方法。
一种采用字符串的方法,另一种采用布尔值的方法。
然后 String 方法可以调用 boolean 方法。
如下:
void doSomething(String isSpecificRead) {
doSomething(convertStringToBoolean(isSpecificReadString));
}
void doSomething(boolean isSpecificRead) {
...
}