How to avoid writing confusing DSLs in Scala

穿精又带淫゛_ 提交于 2020-08-07 05:23:07

问题


I've read comments stating that Scala's flexibility makes it easy for developers to write DSLs that are difficult to understand and reason about.

DSLs are possible because

  • we can sometimes omit . and parentheses (e.g. List(1) map println)
  • we can sometimes interchange () and {}
  • we have implicit values, parameters, and classes (also conversions, which are now discouraged)
  • there is a relatively small number of reserved symbols in the language (e.g. I can define + for my class)

and possibly other language features.

How can I avoid writing confusing DSLs ... what are the common antipatterns? Where is a DSL not appropriate?


回答1:


Whenever you create DSL of your own you're embedding new language into Scala, which is not standard, so it doesn't follow standard code guides, conventions, etc.

I would say it's nothing wrong with adding new DSL as long you add proper documentation, explain the purpose of creating it and add examples of usage. If you feel adding new DSL would increase readability of your code, just go for it, but remember that whenever anyone encounters your DSL and it won't be documented enough, they will be very confused.

A good example of well-documented and serving good purpose DSL would be matchers of scalatest or Scala duration.



来源:https://stackoverflow.com/questions/55620690/how-to-avoid-writing-confusing-dsls-in-scala

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!