Summary:
This article describes a simple Scala design pattern that allows library designers to provide services that their clients can access either through mixins or imports. Giving users a choice between mixin composition and importing makes a library easier to use.
The ability to add new comments in this discussion is temporarily disabled.
Most recent reply: September 30, 2009 4:29 AM by
Antonio R.
|
This article describes a simple Scala design pattern that allows library designers to provide services that their clients can access either through mixins or imports. Giving users a choice between mixin composition and importing makes a library easier to use. http://www.artima.com/scalazine/articles/selfless_trait_pattern.htmlWhat do you think of the Selfless Trait pattern?
|
|
|
Before JDK 5 and its static imports, I would often define abstract classes with protected constructors and protected-static-final methods to sort of support this. That way, people could subclass it to avoid qualified names, or import it if the single inheritance chain was already taken.
Of course, the tools Scala provides are much more sophisticated - in the good way - and make this a lot cleaner.
Do you remember what first tipped you off that this could be done?
|
|
|
> Do you remember what first tipped you off that this could > be done? > I think it was born out of need. I wanted at one point to exercise ScalaTest's ShouldMatchers DSL in the interpreter, and realized it was not easy. It hit me that if I made a companion object to ShouldMatchers that mixed in the ShouldMatchers trait, it would let me import the whole DSL and use it in the interpreter. I then went looking for other opportunities to make the same thing possible. I did this with Assertions, but there may still be some more traits in ScalaTest I can do this with, because I think I may have one or two traits in there with self types that aren't necessary and should be removed. One of the items on my very short list of remaining things to do for the 1.0 release is look for extraneous self types that I can remove, and then apply this pattern to the trait.
|
|
|
> This article describes a simple Scala design pattern
based on what i've see on the scala mailing lists, these things turn out to easily not be that simple in real world situations. so i'm always a little wary of claims of it slices it dices now how much would you pay. :-)
|
|
|
I would remark, that in order the import-variant to be an equivalent alternative, the library trait must be stateless and full functional. I found the article helpful, thanks for stating the pattern clearly.
Cheers.
|
|