异常处理:如何颗粒状,当涉及到参数验证你会去? [英] Exception handling: how granular would you go when it comes to argument validation?

查看:150
本文介绍了异常处理:如何颗粒状,当涉及到参数验证你会去?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编码一个单一的方法简单的小类发送电子邮件。我的目标是实现它在传统的Visual Basic 6项目,揭露它作为通过COM互操作设备的COM对象。

I'm coding a simple little class with a single method send an email. My goal is to implement it in a legacy Visual Basic 6 project, exposing it as a COM object via the COM Interop facility.

有一个细节我发现很难解决,这是我应该怎么颗粒处于参数验证。在那光,我真的很不高兴,和一个东西是不是一个细节都被我其实异常处理的方式:

There's a detail I'm finding difficult to resolve, that being how granular should I be at validating parameters. On that light, a thing I'm really not happy about, and which is not a detail at all, is the way I'm actually handling exceptions:

public class MyMailerClass
{
    #region Creation
    public void SendMail(string from, string subject, string to, string body)
    {
        if (this.IsValidMessage(from, subject, to, body)) // CS1501
        {
            MailMessage msg = new MailMessage();
            msg.IsBodyHtml = true;
            msg.From = new MailAddress(from);
            msg.To.Add(to);
            msg.Subject = subject;
            msg.Body = body;
            SmtpClient srv = new SmtpClient("SOME-SMTP-HOST.COM");
            srv.Send(msg);
        }
        else
        {
            throw new ApplicationException("Invalid message format.");
        }
    }
    #endregion Creation

    #region Validation
    private bool IsValidMessage(string from, string subject, string to, string body)
    {
        Regex chk = new Regex(@"(\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,6})");
        if (!chk.IsMatch(from))
        {
            return false;
        }
        if (!chk.IsMatch(to))
        {
            return false;
        }
        if (!string.IsNullOrEmpty(subject))
        {
            return false;
        }
        if (!string.IsNullOrEmpty(body))
        {
            return false;
        }
        else
        {
            return true;
        }
    }
    #endregion Validation
}

任何建议将非常感激,这样的多亏得多提前为所有您的意见!

Any suggestion will be much appreciated, so thanks much in advance for all your comments!

注意:这将是实现企业库的验证应用程序块在这种特殊情况下?

Note: Would it be convenient to implement Enterprise Library's Validation Application Block on this particular case?

推荐答案

考虑您的SendMail时的主叫方强加的合同。他们必须通过你一个有效的电子邮件地址。谁决定什么是有效的? Sendmail的一样。基本上,你的方法是高维护 - 它想要的东西究竟喜欢的方式,告诉你打算给这将是令人满意的是否是尽量希望最好的必由之路

Consider the contract that you are imposing upon the callers of SendMail. They are required to pass you a "valid email address". Who decides what is valid? SendMail does. Basically your method is "high maintenance" -- it wants things exactly the way it likes, and the only way to tell whether what you're going to give it will be satisfactory is to try and hope for the best.

不要写高维护的方法而不给调用者有机会知道如何去满足它,或者至少有办法避免该异常。提取验证逻辑,它返回一个布尔一个IsValidAddress的方法。然后让你的SendMail方法调用IsValidAddress并抛出,如果它是无效的。

Don't write high-maintenance methods without giving the caller a chance to know how to satisfy it, or at least have a way to avoid the exception. Extract the validation logic to an "IsValidAddress" method that returns a Boolean. Then have your SendMail method call IsValidAddress and throw if it is invalid.

您从这个变革几个不错的效果:

You get several nice effects from this change:

(1)的担忧加剧分离。 sendmail的任务是使电子邮件机制工作,而不是传递的电子邮件地址是否有效的判断。 。隔离到专门的验证码的决策

(1) Increased separation of concerns. SendMail's job is to make the email mechanism work, not to pass judgment on whether an email address is valid. Isolate that policy decision to code that specializes in verification.

(2)地址验证是在其本身的有用工具;有很多时候,你想知道是否一个地址,而不发送邮件到它良好。

(2) Address validation is a useful tool in of itself; there are lots of times when you want to know whether an address is well-formed without sending mail to it.

(3)您可以更新,轻松地提高您的验证逻辑因为它是在一个说理的地方。

(3) You can update and improve your validation logic easily because it is all in one sensible place.

(4)主叫方有办法,他们可以保证没有会抛出异常。如果主叫方不能调用方法没有低保的论点是正确的,那么他们必须抓住例外。理想情况下,你应该从来不来电者必须处理异常让自己的代码正确的;应该有他们可以编写正确的代码,从来没有抛出的话,即使他们已经交到数据是坏的。

(4) Callers have a way that they can guarantee that no exception will be thrown. If a caller cannot call a method without guaranteeing that the arguments are valid, then they have to catch the exception. Ideally you should never make a caller have to handle an exception to make their code correct; there should be a way they can write correct code that never throws, even if the data they've been handed is bad.

下面是一对夫妇的文章中,我已经写关于这个问题,你可能会发现有用的:

Here are a couple of articles I've written on this subject that you might find helpful:

异常处理:的 http://ericlippert.com/2008/09/10/vexing-exceptions/

高保养方法:的http://博客。 msdn.com/ericlippert/archive/2008/09/08/high-maintenance.aspx

这篇关于异常处理:如何颗粒状,当涉及到参数验证你会去?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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