这种反模式/代码气味有名字吗? [英] Is there a name for this anti-pattern/code smell?

查看:82
本文介绍了这种反模式/代码气味有名字吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先让我说我不主张这种方法,但是最近我看到了它,我想知道是否可以用它来指称有罪党这个名字。

Let me start by saying that I do not advocate this approach, but I saw it recently and I was wondering if there was a name for it I could use to point the guilty party to. So here goes.

现在您有了一个方法,并且想返回一个值。您想要返回错误代码。当然,异常是更好的选择,但是无论出于何种原因,您都希望使用错误代码。记住,我在这里扮演魔鬼的拥护者。因此,您将创建一个通用类,如下所示:

Now you have a method, and you want to return a value. You also want to return an error code. Of course, exceptions are a much better choice, but for whatever reason you want an error code instead. Remember, I'm playing devil's advocate here. So you create a generic class, like this:

class FunctionResult<T>
{
    public T payload;
    public int result;
}

然后声明如下函数:

FunctionResult<string> MyFunction()
{
    FunctionResult<string> result;
    //...

    return result;
}

此模式的一种变化是对错误代码使用枚举而不是一个字符串。现在,回到我的问题:这个有名字吗?

One variation on this pattern is to use an enum for the error code instead of a string. Now, back to my question: is there a name for this, and if so what is it?

推荐答案

我同意这不是专门的反模式。根据使用情况,可能会有异味。有一些原因导致人们实际上不想使用异常(例如,对于初学者来说,返回的错误不是'exceptional')。

I'd agree that this isn't specifically an antipattern. It might be a smell depending upon the usage. There are reasons why one would actually not want to use exceptions (e.g. the errors being returned are not 'exceptional', for starters).

在某些情况下,您想让服务为其结果返回一个通用模型,包括错误和良好值。这可能被低级服务交互所包装,该服务交互将结果转换成异常或其他错误结构,但是在服务级别,它使服务可以返回结果和状态代码,而不必定义可能会导致异常的异常结构。

There are instances where you want to have a service return a common model for its results, including both errors and good values. This might be wrapped by a low level service interaction that translates the result into an exception or other error structure, but at the level of the service, it lets the service return a result and a status code without having to define some exception structure that might have to be translated across a remote boundary.

此代码也不一定是错误:考虑一个HTTP响应,它包含许多不同的数据,包括状态代码以及响应的正文。

This code may not necessarily be an error either: consider an HTTP response, which consists of a lot of different data, including a status code, along with the body of the response.

这篇关于这种反模式/代码气味有名字吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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