扩展方法 - IsNull 和 IsNotNull,用得好还是不好?

发布于 2024-08-05 23:40:23 字数 280 浏览 9 评论 0原文

我喜欢可读性。

因此,几分钟前我想出了一个针对 (x =! null) 类型语法的扩展方法,称为 IsNotNull。相反,我还创建了一个 IsNull 扩展方法,因此

if(x == null) becomes if(x.IsNull())

if(x != null) becomes if(x.IsNotNull())

但是,我担心我可能会滥用扩展方法。您认为这是扩展方法的错误使用吗?

I like readability.

So, I came up with an extension mothod a few minutes ago for the (x =! null) type syntax, called IsNotNull. Inversly, I also created a IsNull extension method, thus

if(x == null) becomes if(x.IsNull())

and

if(x != null) becomes if(x.IsNotNull())

However, I'm worried I might be abusing extension methods. Do you think that this is bad use of Extenion methods?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

爱的十字路口 2024-08-12 23:40:23

它似乎不再具有可读性,并且可能会让阅读代码的人感到困惑,想知道这些方法中是否存在他们不知道的逻辑。

我使用了 PerformIfNotNull(Func method) (以及执行操作的重载),我可以传递一个快速 lambda 表达式来替换整个 if 块,但是如果您除了检查 null 之外没有做任何事情,那么似乎就像它没有提供任何有用的东西一样。

It doesn't seem any more readable and could confuse people reading the code, wondering if there's any logic they're unaware of in those methods.

I have used a PerformIfNotNull(Func method) (as well as an overload that takes an action) which I can pass a quick lambda expression to replace the whole if block, but if you're not doing anything other than checking for null it seems like it's not providing anything useful.

世界和平 2024-08-12 23:40:23

我不认为这非常有用,但是:

someString.IsNullOrBlank()    // Tests if it is empty after Trimming, too
someString.SafeTrim()         // Avoiding Exception if someString is null

因为这些方法实际上使您不必进行多次检查。但用方法调用替换单个检查对我来说似乎毫无用处。

I don't find that incredibly useful, but this:

someString.IsNullOrBlank()    // Tests if it is empty after Trimming, too
someString.SafeTrim()         // Avoiding Exception if someString is null

because those methods actually save you from having to do multiple checks. but replacing a single check with a method call seems useless to me.

極樂鬼 2024-08-12 23:40:23

这是完全有效的,但我不认为它非常有用。由于扩展方法只是编译器的诡计,我很难将它们的任何使用称为“滥用”,因为它们无论如何都是无用的。我只会在扩展方法损害可读性时才抱怨它们。

It is perfectly valid to do but I don't think it is incredibly useful. Since extension methods are simply compiler trickery I struggle to call any use of them "abuse" since they are just fluff anyhow. I only complain about extension methods when they hurt readability.

遮了一弯 2024-08-12 23:40:23

相反,我会选择类似的内容:

static class Check {
    public static T NotNull(T instance) {
        ... assert logic
        return instance;
    }
}

然后像这样使用它:

Check.NotNull(x).SomeMethod();
y = Check.NotNull(x);

就个人而言,比聪明地允许以下内容更清楚正在发生的事情:

if( ((Object)null).IsNull() ) ...

Instead I'd go with something like:

static class Check {
    public static T NotNull(T instance) {
        ... assert logic
        return instance;
    }
}

Then use it like this:

Check.NotNull(x).SomeMethod();
y = Check.NotNull(x);

Personally it's much clearer what is going on than to be clever and allow the following:

if( ((Object)null).IsNull() ) ...
無處可尋 2024-08-12 23:40:23

我不完全同意“这可能会造成混乱”的推理。

在某种程度上,我可以理解这意味着什么,没有理由冒险超出“共同理解”——每个人都理解 object != null。

但在 Visual Studio 中,我们拥有出色的工具,您只需将鼠标悬停在方法上即可显示一些附加信息。

如果我们说扩展方法被注释了很好的解释,那么我觉得混乱的论点就站不住脚了。

方法 .IsNotNull() 和 .IsNull() 准确地解释了它们是什么。我觉得他们说的非常有道理,也非常有用。

老实说,这是一个“你喜欢什么”的问题。如果您觉得这些方法将使其在您的项目上下文中更具可读性,那么就去做吧。如果你在你的项目中打破了惯例,那么我会说相反的。

我在这个问题上和你有同样的想法,并且询问了我工作地点的几位非常非常有经验的开发人员。他们都没有提出一个充分的理由(除了这里提到的“混乱”)来解释为什么你不应该这样做。

大胆试试吧 :-)

I don't entirely agree with the reasoning saying "it may confuse".

To some extent I can see what is meant, that there is no reason to venture outside "common understanding" -- everybody understands object != null.

But in Visual Studio, we have wonderful tools where you can simply hover over the method, to reveal some additional information.

If we were to say that the extension-method was annotated with a good explanation, then I feel that the argument of confusion falls apart.

The methods .IsNotNull() and .IsNull() explain exactly what they are. I feel they are very reasonable and useful.

In all honesty it is a matter of "what you like". If you feel the methods will make it more readable in the context of your project, then go for it. If you are breaking convention in your project, then I would say the opposite.

I have had the same thoughts as you have on the subject and have asked several very very experienced developers at my place of work. And none of them have come up with a good reason (except what has been mentioned about -confusion- here) that would explain why you shouldn't do this.

Go for it :-)

夜血缘 2024-08-12 23:40:23

有先例,只要字符串类有 IsNullOrEmpty

There is precedent, in as much as the string class has IsNullOrEmpty

轻拂→两袖风尘 2024-08-12 23:40:23

您还为 CLR 内部操作引入了方法调用开销。 JIT 可能会内联它,但也可能不会。可以肯定的是,这是一个微性能的挑剔,但我同意它并不是特别有用。当可读性显着提高时,或者如果我想要一些其他行为(例如“抛出 ArgumentNullException 并传递 arg 名称”)时,我会这样做,而一遍又一遍地进行内联是愚蠢的。

You're also introducing method call overhead for something that's a CLR intrinsic operation. The JIT might inline it away, but it might not. It's a micro-perf nitpick, to be sure, but I'd agree that it's not particularly useful. I do things like this when there's a significant readability improvement, or if I want some other behavior like "throw an ArgumentNullException and pass the arg name" that's dumb to do inline over and over again.

爱给你人给你 2024-08-12 23:40:23

例如,如果您假设您可能希望在 x 为 null 时抛出异常(只需在扩展方法中执行此操作),那么这是有意义的。然而,在这种特殊情况下,我个人的偏好是明确检查(空对象应该为空:-))。

It can make sense if you, for instance, assume that you might want to throw an exception whenever x is null (just do it in the extension method). However, I my personal preference in this particular case is to check explicitly (a null object should be null :-) ).

白云悠悠 2024-08-12 23:40:23

为了遵循该模式,它应该是一个属性而不是一个方法(但这当然不适用于扩展)。

System.Data 命名空间中的数据值具有 IsNull 属性,用于确定该值是否包含 DbNull 值。

DataRow 类有一个 IsNull 方法,但它并不确定 DataRow 是否为 null,而是确定数据行中的字段之一是否包含 DbNull 值。

To follow the pattern it should be a property rather than a method (but of course that doesn't work with extensions).

Data values in the System.Data namespace has an IsNull property that determines if the value contains a DbNull value.

The DataRow class has an IsNull method, but it doesn't determine if the DataRow is null, it determines if one of the fields in the data row contains a DbNull value.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文