从函数返回数据时的最佳做法是什么.返回Null或空对象更好吗?为什么要一个人做另一个呢?
考虑一下:
public UserEntity GetUserById(Guid userId)
{
//Imagine some code here to access database.....
//Check if data was returned and return a null if none found
if (!DataExists)
return null;
//Should I be doing this here instead?
//return new UserEntity();
else
return existingUserEntity;
}
Run Code Online (Sandbox Code Playgroud)
让我们假设在这个程序中有效的案例,数据库中没有该GUID的用户信息.我想在这种情况下抛出异常是不合适的?此外,我的印象是异常处理可能会损害性能.
考虑以下一般形式的功能:
Foo findFoo(Collection<Foo> foos, otherarguments)
throws ObjectNotFoundException {
for(Foo foo : foos){
if(/* foo meets some condition*/){
return foo;
}
}
throw new ObjectNotFoundException();
}
Run Code Online (Sandbox Code Playgroud)
例如,一个具体的案例是:
User findUserByName(Collection<User> users, String name)
throws ObjectNotFoundException {
for(User user : users){
if(user.getName().equals(name)){
return user;
}
}
throw new ObjectNotFoundException();
}
Run Code Online (Sandbox Code Playgroud)
如果找不到对象,这些函数会抛出异常.我可以为此目的创建一个自定义异常类(在示例中ObjectNotFoundException),但我更喜欢使用现有的类.但是,我在标准java库中找不到具有此含义的任何异常类.您知道是否有可以在这里使用的标准例外吗?
在发布这个问题并阅读那个问题后,我意识到知道一个方法是否应该返回null是非常重要的,或者如果这被认为是错误条件并且应该抛出异常.还有一个很好的讨论,何时返回'null'或抛出异常.
我正在写一个方法,我已经知道如果我想返回null或抛出异常,表达我的决定的最佳方式是什么,换句话说,记录我的合同?
我能想到的一些方法:
我主要讨论java,但它也可能适用于其他语言:为什么有一种正式的方式来表达是否会抛出异常(throws关键字)但是没有正式的方式来表达是否可能返回null?
为什么没有这样的东西:
public notnull Object methodWhichCannotReturnNull(int i) throws Exception
{
return null; // this would lead to a compiler error!
}
Run Code Online (Sandbox Code Playgroud)
表达合同的方式有很多种:
我正在编写代码来查找和交叉2行.当线的斜率相等时,它们不相交.但另一方面,具有相等值斜率的输入是完全有效的.
public static Point calculateIntersection(Line line1, Line line2) {
if (line1 == null || line2 == null) {
throw new NullPointerException(" some message ");
}
if (line1.getConstant() == line2.getConstant()) {
return new Point(0, line1.getConstant());
}
if (line1.getSlope() == line2.getSlope()) {
throw new IllegalArgumentException("slopes are same, the lines do not intersect.");
}
int x = (line2.getConstant() - line1.getConstant()) / (line1.getSlope() - line2.getSlope());
int y = line1.getSlope() * x + line1.getConstant();
return new Point(x, y);
}
Run Code Online (Sandbox Code Playgroud)
问题是抛出非法争论异常是正确的事情吗?由于输入有效,它并不能完全说服我.
自定义异常是正确的做法吗?听起来是一个不错的选择,但额外的意见会有所帮助.
谢谢
通常,在编程中我们会遇到null检查显示特别大的情况.我说的是:
if (doc != null)
{
if (doc.Element != null)
{
... and so on
}
else
throw new Exception("Element cannot be null");
} else {
throw new Exception("document cannot be null");
}
Run Code Online (Sandbox Code Playgroud)
基本上,整个事情变成了一个难以理解的噩梦,所以我想知道:有没有更简单的方法来描述我上面要做的事情?(除了空检查,我string.IsNullOrEmpty不时会得到类似的东西.)
接受的答案:我接受了具有此链接的答案,因为所描述的方法具有创新性,正是我想要的.谢谢肖恩!
如果你认为有可能获得空指针异常,你应该使用if语句来确保变量不为null,还是应该捕获异常?
我没有看到任何区别,因为你可以把你的逻辑处理if语句或catch块中的空指针,那么哪一个是最好的做法?
我提出了以下实用程序类:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class MySqlConnection
{
private static String dbUrl = "jdbc:mysql://localhost:3306/database";
private static String dbUsername = "root";
private static String dbPassword = "mysql";
public static Connection getConnection()
{
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(dbUrl, dbUsername, dbPassword);
} catch (ClassNotFoundException e) {
System.out.println("Could not load JDBC driver: " + e.getMessage());
} catch (SQLException e) {
System.out.println("Could not connect to DB: " + e.getMessage());
}
return connection;
}
}
Run Code Online (Sandbox Code Playgroud)
问题是:我不想从我的方法返回null …
我在这里发现问题如果检索方法返回'null'或者当它无法产生返回值时抛出异常?和是否应函数返回null或一个空对象?,但我认为我的情况完全不同.
我正在编写一个由Web服务和客户端组成的应用程序.Web服务负责访问数据并将数据返回给客户端.我设计我的应用程序是这样的:
//网络服务
try
{
DataTable data = GetSomeData(parameter);
return data
}
catch (OopsException ex)
{
//write some log here
return null;
}
Run Code Online (Sandbox Code Playgroud)
//客户:
DataTable data = CallGetSomeData(parameter);
if(data == null)
{
MessageBox.Show("Oops Exception!");
return;
}
Run Code Online (Sandbox Code Playgroud)
好吧,有一个不返回null的规则.我不认为我应该重新抛出异常并让客户端捕获SoapException.你有什么评论?有没有更好的方法来解决这个问题?
谢谢.
如果我有以下功能,有两个选择
private MyObject findBlank() {
for (int i = 0; i < pieces.length; i++) {
if(pieces[i].isBlank()){
return pieces[i];
}
}
return null;
}
private MyObject findBlank() {
for (int i = 0; i < pieces.length; i++) {
if(pieces[i].isBlank()){
return pieces[i];
}
}
throw new NoSuchFieldError("No blank piece found!");
}
Run Code Online (Sandbox Code Playgroud)
从这个方法我知道它应该总是返回一个对象,其中一个'件'总是isBlank() == true,最后的返回null只是为了取悦编译器.既然是这种情况,如果它返回null我的代码无论如何都不会工作,这是正确的请抛出异常吗?
我的选择是:
我想我要问的是,这是抛出异常的正确位置吗?也就是说,如果遇到这种情况,我无能为力.这被归类为'例外'还是我应该检查我的方法返回什么(这使我的代码看起来很糟糕).如果我知道它不应该返回null那么我应该抛出异常吗?
另外,我如何选择什么异常,或者扩展一个并抛出我自己的异常呢?