流畅的 C# 有多远才算太远?
public static class Th
{
public static T e<T>(T theObject) where T : class
{
return theObject;
}
}
public static class ObjectExtensions
{
public static bool Is<T>(this T o, Func<T, bool> a) where T : class
{
return a(o);
}
}
//...
//logic in a method somewhere
Func<string, bool> valid = property => _myService.SomeValidationMethod(property);
if (Th.e(_request.Property).Is(valid))
{
//do something
}
这段代码适合生产吗?为什么?
编辑:感谢您的所有评论。我希望您在阅读我将 C# 语法延伸至断点时获得了与我阅读您的回复一样的乐趣。
public static class Th
{
public static T e<T>(T theObject) where T : class
{
return theObject;
}
}
public static class ObjectExtensions
{
public static bool Is<T>(this T o, Func<T, bool> a) where T : class
{
return a(o);
}
}
//...
//logic in a method somewhere
Func<string, bool> valid = property => _myService.SomeValidationMethod(property);
if (Th.e(_request.Property).Is(valid))
{
//do something
}
Is this code suitable for production and why?
Edit: Thank you for all your comments. I hope you had as much fun reading my stretching of the C# syntax to breaking point as I did reading your responses.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我对流畅的 API 没有任何问题,但这似乎违反了最小惊喜原则。我无法理解名为
Th
的类和名为e
的方法的用途。I have no problem with fluent APIs, but this seems to violate the principle of least surprise. I would not understand the purpose of a class named
Th
nor of a method namede
.那太远了。不,该代码不适合生产。
The.e
既不是措辞正确的散文,也不是适当命名的代码——在这两种情况下它都是毫无意义的。That is too far. No, the code is not suitable for production.
Th.e
is neither correctly phrased prose nor appropriately-named code - it's meaningless in both contexts.是什么让您认为这段代码“流畅”?
这绝对不流畅,也不是自记录的。
What makes you think that this code is 'fluent' ?
this is absolutely not fluent, nor self documenting.
虽然你所说的“流畅性”非常重要,而且大多数开发人员都忽略了这一点(即使是真正应该关心这一点的人,比如 CS 算法编写者),但你向我们展示的代码风格滥用了语言的可表达性,而且不是很有用,IMO ,有两个原因:
Th
类和Th.e
if (_request.Property.Is(valid)) 也足够“流畅”代码>方法;if (Th.e(_request.Property2).Is(valid))
或if (Th.e(_request2.Property).Is(valid))
吗?如果您需要进行另一次测试怎么办?你会if (Th.e(_request.Property).Is(valid2))
吗?While what you call "fluency" is extremely important, and most developers are missing that (even who should really care about this, like CS algorithm writers), the code style you showed us is abusing expressibility of the language and not very useful, IMO, for 2 reasons:
if (_request.Property.Is(valid))
would be "fluent" enough even without thoseTh
class andTh.e
method;if (Th.e(_request.Property2).Is(valid))
orif (Th.e(_request2.Property).Is(valid))
? What if you need to perform another test? You doif (Th.e(_request.Property).Is(valid2))
?