选项包装值是一个好的模式吗?
我最近写了以下 Scala 代码:
val f: File = ... // pretend this file came from somewhere
val foo = toFoo(io.Source.fromFile(f).mkString)
我真的不喜欢这种流程。要了解发生了什么,您必须从中间的 f
开始,向左读取 fromFile
,向右读取 mkString
,再次向左读取toFoo
。啊。
特别是在习惯了序列的功能转换之后,这很难阅读。我的下一次尝试如下所示:
val foo = Some(f)
.map(io.Source.fromFile)
.map(_.mkString)
.map(toFoo)
.get
我更喜欢这种流程。你可以看看会发生什么 这是 Option
类的一个很好的用途吗?还是我滥用它?我可以使用更好的模式来实现相同的流程吗?
I recently wrote the following bit of Scala:
val f: File = ... // pretend this file came from somewhere
val foo = toFoo(io.Source.fromFile(f).mkString)
I really didn't like the way this flowed. To understand what's happening, you have to start with f
in the middle, read left to fromFile
, read right to mkString
, read left again to toFoo
. Ugh.
Especially after getting used to functional transformations of sequences, this is difficult to read. My next attempt looks like this:
val foo = Some(f)
.map(io.Source.fromFile)
.map(_.mkString)
.map(toFoo)
.get
I like the flow of this much better. You can see what happens Is this a good use of the Option
class? Or am I abusing it? Is there a better pattern that I can use to achieve the same flow?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这完全没问题。然而,Scalaz 中有一种方法
|>
可以做得更好,如果你不想要所有的 Scalaz,你可以自己创建它:就我个人而言,我倾向于编写大量需要括号的代码,并且在大多数情况下我更喜欢方法而不是运算符,所以在我的代码中我通常调用
|>
“use”,但效果是一样的:在 Scala 2.11 或更高版本中,您可以使用(稍微)更少的语法获得相同的行为和改进的性能:
This is perfectly okay. However, there is a method
|>
in Scalaz that does one better, and you can create it yourself if you don't want all of Scalaz:Personally, I tend to write a lot of code that requires parentheses and I like methods better than operators in most cases, so in my code I normally call
|>
"use", but it's the same deal:In Scala 2.11 or later, you can get the same behavior and improved performance with (slightly) less syntax:
我对这里给出的其他答案没有问题,但是您是否考虑将 toFoo 的名称更改为更“流动”的名称?我的意思是,toFoo 确实听起来应该位于表达式的右侧,但如果您将其重命名为其他名称,它也可能适合左侧。
I have no problems with the other answers given here, but did you consider changing the name of toFoo into something that 'flows' better? I mean, toFoo really smells like something that should be on the right of an expression, but if you rename it into something else, it might fit on the left as well.
您可以通过 pimp my library 模式将
toFoo
添加到String
中。那么就变成:You add
toFoo
toString
through the pimp my library pattern. Then it becomes: