Fork me on GitHub

Sunday, November 17, 2013

Usage driven design - choosing parameters

Scaloid is originally made to improve my daily life that codes Android apps. Although Scaloid relies on some core design principles that is behind of automatic wrapper generator, sometimes code can be improved from some heuristics. For example, I found that my code has several functions much like this:

def createMyPaint(): Paint = {
    val p = new Paint()
    p.setColor(0xffff6666)
    p.setTextSize(14.sp)
    p
}

Soon I added a wrapper class of android.graphics.Paint to Scaloid. Then the code above is improved as:

def createMyPaint() = SPaint().color(0xffff6666).textSize(14.sp)

All of my codes and a Google search reveals that setColor() is always called after a new Paint instance is initialized. It is very natural to think about a color when we tried to paint something. So I added it as the first parameter of the method SPaint.apply(); then the code can be rewritten as:

def createMyPaint() = SPaint(0xffff6666).textSize(14.sp)

We have reached the minimum code as possible.

This feature is shipped with Scaloid 3.0-M2. You can include this version of Scaloid into a maven project by:
<dependency>
    <groupId>org.scaloid</groupId>
    <artifactId>scaloid_2.10</artifactId>
    <version>3.0-8-M2</version>
</dependency>
or a sbt project by:
libraryDependencies += "org.scaloid" %% "scaloid" % "3.0-8-M2"

No comments:

Post a Comment