2

In Scala, sometimes class extends a trait to provide some methods to extending class inside.

ScalaTest

import org.scalatest._

class ExampleSpec extends FlatSpec with Matchers { ...

Matchers trait provides useful method like startWith, endWith or include.

string should startWith ("Hello")
string should endWith ("world")
string should include ("seven")

Problem is simple, "ExampleSpec is not Matchers". Extends for feature breaks OOP fundamental principle. This extends is confusing especially for code-reader or newcomer.

I think we should use import like import scalatest.matchers._. This doesn't taint inheritance tree.

Is extends for feature bad practice in Scala ? or reasonable extends usage ?

1

As a DSL (domain-specific language), ScalaTest uses many names that are likely to appear in other code and overloads operators that might be used by other libraries.

To control the scope, they allow their users to mix in the DSL to their test classes. While it is possible to use the DSL with just import, this strategy makes it easier to mix libraries and other DSLs in the same file.

Yes, it doesn't make much sense through the lens of an "is-a" relationship or even a "has-a", but test suites are not generally candidates for reuse and the scoping concerns are overriding engineering considerations.

Also, with is not extends. The test class ExampleSpec is a FlatSpec, and that inheritance relationship makes sense. The trait inheritance tree is more flexible and allows for this sort of (ab)use.

Your Answer

By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.