java获得OOP的概念权利

时间:2015-02-23 09:48:30

标签: java oop

大家好,我已经搜索了很多,但对我发现的东西并不满意。希望这是提出这个问题的正确位置。

我现在正在使用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;
}

...

创建一个Map,向它添加所有内容并通过密钥获取它会更好吗? 或者我完全错了吗?

第二个例子: 假设我在某处返回错误字符串

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!

3 个答案:

答案 0 :(得分:2)

第一个例子:

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;
}

...

在这种情况下,无需创建Map。这是正确的方法。请注意,libPath将更好地定义如下:

private static final Path libPath = Paths.get("this", "is", "a", "path");

(自Java 7以来,类Path存在,当前版本为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
}

答案 1 :(得分:0)

对于第一个示例,请查看国际化:http://docs.oracle.com/javase/tutorial/i18n/

您可以使用静态或地图,但迟早您需要以多种语言显示消息。

对于第二个例子,最好使用Exceptions,因为它们是在发生异常情况(如错误)时使用的。

无论如何,Exceptions注意不要将它用作流控制结构:Why not use exceptions as regular flow of control?

答案 2 :(得分:-1)

以下是通过代码处理常量的一些示例:

1。类

public final class MyConstants {
     public static final int ERROR_CODE = -1;
}

if (getSomething() == MyConstants.ERROR_CODE) { 
   // ...
}

2。接口

public interface MyConstantsHolder {
     int ERROR_CODE = -1;
}

public MyClass implements MyConstantsHolder {
     public void myMethod() {
       if (getSomething() == ERROR_CODE) { 
          // ...
       }
     }
}