设计问题:我应该在多大程度上依赖控制流程的例外? [英] Design issue: to what extent should I rely on exceptions for the flow of control?

查看:153
本文介绍了设计问题:我应该在多大程度上依赖控制流程的例外?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个java Web应用程序,我有一些关于设计的问题。

I am working on a java web application and I have a few questions regarding design.

基本上在当前版本中,在很大程度上依赖于捕获异常确定控制流程

Basically in its current version, it relies heavily on catching exceptions to determine the flow of control.

例如,在我的一个Spring服务类中,我有以下方法检查作为参数提供的电子邮件存在于数据库中。

For instance in one of my spring service classes, I have the following method that checks whether an email given as a parameter exists in the database.

@Override
public boolean validateEmailAddressDoesNotExist(String accountEmailAddress) {
    try {
         return !dao.checkIfEmailAddressAlreadyExists(accountEmailAddress);
    } catch (NoResultException re) {
        log.error("NoResultException", re);
    } catch (RuntimeException re) {
        log.error("RuntimeException", re);
    }
    return true;
}

//from "dao" class
public boolean checkIfEmailAddressAlreadyExists(String accountEmailAddress) {
    return (loadAccountFromAccountEmailAddress(accountEmailAddress) == null ? false : true);
}

//also from "dao" class
public Account loadAccountFromAccountEmailAddress(String accountEmailAddress) {
    return entityManager.createNamedQuery("Account.findByEmailAddress", Account.class).setParameter("accountEmailAddress", accountEmailAddress).getSingleResult();
}

我怀疑我目前的设计可能不对,但我很感激阅读您对它的意见和看法,以及您认为它有多大程度上存在缺陷。

I suspect that my current design is probably wrong but I would be grateful to read your comments and opinion about it and to what extent you believe it is flawed.

推荐答案

您的服务模型中的验证方法不应该是捕捉异常。由于以下几个原因,这很糟糕:

Validation methods in your service model should not be catching exceptions. That's bad for a few reasons:


  • 这不是特例。 没有结果是一种常见的情况。

  • It's not an exceptional condition. "No results" is a common situation.

间接地将验证与框架的数据检索方法的实现结合起来。要想知道为什么这不好,想象一下如果你的框架发生变化,现在它会引发 EmptyResultSetException 。您必须更新所有验证方法。哎呀!

It indirectly couples your validation to the implementation of the framework's data-retrieval methods. To see why that's not good, imagine if your framework changes such that it now raises a EmptyResultSetException. You'd have to update all your validation methods. Yikes!

如果您的基础框架引发异常以表明没有结果,那么您不一定能帮助它,但是您当然可以控制 checkIfEmailAddressAlreadyExists 的内容。

You can't necessarily help it if your underlying framework raises exceptions to indicate "no results", but you can certainly control what checkIfEmailAddressAlreadyExists does.

更改此方法以使其返回 true 如果地址存在, false 如果没有或没有找到结果。

Change this method so that it returns true if the address exists, and false if it doesn't or if no results were found.

这篇关于设计问题:我应该在多大程度上依赖控制流程的例外?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆