gpt4 book ai didi

design-patterns - 当一个操作需要传递的不仅仅是结果时,你是元组/抛出/还是getContextual?

转载 作者:行者123 更新时间:2023-12-04 06:56:59 25 4
gpt4 key购买 nike

我正在尝试重构一些“发送电子邮件”代码,方法是将步骤(验证、附加相关内容、格式化、发送)划分到单独的类中,这样可以更轻松地测试、记录和更新。

作为其中的一部分,我必须想出一种方法让操作将验证或暂时性错误(“该项目已删除”)反馈给发起者,以便它可以向用户询问更多信息或告诉他们坏消息。这是线程采用的路径(是的,涂鸦)

     "Controller"                     
. -> Outbox
. -> Validator
. -> Formatter
. -> Sender
. <-

-> Parameters, work in progress
<- Good, not so good, "you better sit down" news

所以您是一个深思熟虑的人,在“回归”、“异常(exception)”或“背景”之间……哪一个让您最开心?

A. Throw an exception at any problem and let the controller divide up the ones it can handle gracefully and the ones that know my “beeper”.

B. Return some sort of Result<T>class to carry both the product of the operations (an email) and the enumerated results of various operations.

C. Pass a context into/outof all the steps where they can indicate any parameters they can’t deal with and keep the method signatures very straightforward.

D. Son, you’re overthinking this.. Here is what you’re gonna do : <YourSpecialJujuHere/>

感谢所有贡献,你们一起摇滚。

最佳答案

您可以使用 Template Method图案与 Strategy图案:

您的 Controller 成为模板方法。对于电子邮件发送过程的每个步骤,您调用实现该步骤的委托(delegate)/策略类。

public class EmailSender
{
private iOutboxGetter outboxGetter;
private iMsgValidator validator;
private iMsgFormatter formatter;
private iMsgSender sender;

//setters for each stragegy, or a constructor
//good use for IOC container

public iSendResult SendMessage(iMsgParams params)
{
try
{
var outbox = outboxGetter.getOutbox(params.outbox);
var validationResults = validator.validate(params);
if(validationResults.IsValid)
{
var msg = formatter.formatMsg(params.message);
sender.send(msg);
return new AllGoodSendResult();
}
else
{
return new ValidationFailedSendResult(validationResults);
}
}
catch(CatastrophicException e)
{
Pager.SendCriticalPage(e.message);
return new CatistrophicFailureSendResult(e);
}
}
}

当代码必须偏离 Happy Path 时,我更喜欢使用异常。我觉得他们将逻辑和错误处理完全分开。

编辑:SendMessage 方法的返回值向调用者指示验证是否通过,以及验证失败的内容。然后调用者可以提示用户提供更多信息并重试,或者指示成功。只有在真正异常的情况下才会抛出异常。

使用这种方法,您的算法的每个组件都可以独立模拟和测试,并且没有 Strategy 需要知道任何其他 Strategy 是如何工作的,也不需要知道如何处理其他人的错误。最后,您的所有错误处理都集中在一个地方。

关于design-patterns - 当一个操作需要传递的不仅仅是结果时,你是元组/抛出/还是getContextual?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1662466/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com