4

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?

joel
  • 6,359
  • 2
  • 30
  • 55
  • Not a complete answer, but I like [this](https://docs.scala-lang.org/style/naming-conventions.html#symbolic-method-names) as a reference for symbolic method names. For other points, these are my two cents: Avoiding `.` makes sense for symbolic methods which would look strange _(nobody want this `1.+(2)`)_. Only interchange `()` with `{}` for parameters that are functions. Try to avoid excessive use of `_`. Instead of defining directly `+` on your class, consider make it a **Semigroup** instead. If you need to read the documentation to understand the name of a method, it is a bad name. – Luis Miguel Mejía Suárez Apr 10 '19 at 21:41

1 Answers1

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.

Krzysztof Atłasik
  • 21,985
  • 6
  • 54
  • 76