[英]java getting concept of OOP right
嗨,大家好,我已经搜索了很多,但对我的发现并不满意。 希望这是问这个问题的正确地方。
我现在使用Java的时间很短(与C相比有所变化),并且在掌握如何最好地为OOP构建代码方面遇到问题。
让我们举一个简单的例子:
如果我使用一些预定义的字符串(例如文件路径或错误消息),那么我当前正在创建一个自己的类,执行以下操作:
private static final String libPath = "\\this\\is\\a\\path\\";
private static final String notFoundMessage = "This hasn't been found";
public static String getLibPath() {
return libPath;
}
public static final String getNotFoundMessage() {
return notFoundMessage;
}
...
创建地图,将其添加到所有内容并通过密钥获取它会更好吗? 还是我做的完全错误?
第二个例子:假设我在某处返回错误字符串
public String getSomething() {
if (something != null) {
return something;
} else {
//handle error, return string below
}
return "I HAVE AN ERROR";
}
在程序的其他任何地方,我都在检查返回值:
if (!string.equals("I HAVE AN ERROR")) {
//do something
}
else {
// handle error
}
一旦错误消息更改,这显然是一种必须两次更改代码的坏方法。 是的,我可以像在第一个示例中一样定义错误字符串,但是由于我对那个错误字符串感到不满意,或者我快要死胡同了。
很高兴听到您有关如何正确进行OOP的建议!
第一个例子:
private static final String libPath = "\\this\\is\\a\\path\\";
private static final String notFoundMessage = "This hasn't been found";
public static String getLibPath() {
return libPath;
}
public static final String getNotFoundMessage() {
return notFoundMessage;
}
...
在这种情况下,无需创建地图。 这是正确的方法。 只需注意libPath
可以像这样更好地定义:
private static final Path libPath = Paths.get("this", "is", "a", "path");
(类Path
自Java 7开始存在,当前版本为Java 8)。
第二个例子 :
public String getSomething() {
if (something != null) {
return something;
} else {
//handle error, return string below
}
return "I HAVE AN ERROR";
}
否: 永远不要以Java 返回错误代码 。 优先使用异常。
范例:
public class ElementNotFoundException extends Exception {
...
}
public String getSomething() {
if (something == null) {
throw new ElementNotFoundException();
} else {
return something;
}
}
然后,您可以像这样处理异常:
try {
myObject.getSomething();
} catch(ElementNotFoundException e) {
//handle error
}
对于第一个示例,请看一下国际化: http : //docs.oracle.com/javase/tutorial/i18n/
您可以使用静态或映射,但是迟早需要以多种语言显示消息。
对于第二个示例,最好使用异常,因为异常是在异常情况(例如错误)发生时使用的。
无论如何,对于异常请注意不要将其用作流控制结构: 为什么不将异常用作常规控制流?
以下是一些处理代码中常量的示例:
public final class MyConstants {
public static final int ERROR_CODE = -1;
}
if (getSomething() == MyConstants.ERROR_CODE) {
// ...
}
public interface MyConstantsHolder {
int ERROR_CODE = -1;
}
public MyClass implements MyConstantsHolder {
public void myMethod() {
if (getSomething() == ERROR_CODE) {
// ...
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.