HiveBrain v1.2.0
Get Started
← Back to all entries
snippetMinor

Processing XML configuration which stores regular expressions and format strings for a documentation tool

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
processingformatstoresregularandexpressionsxmldocumentationforwhich

Problem

I'm investigating some feature for the ScalaDoc tool, which would allow library writers to link to documentation created by third party tools like JavaDoc.

My idea is to have some (XML) configuration which specifies which package prefixes belong to which vendor and how to create a valid URL from the the class name, stored in the XML as regular expressions and format strings.

I only need one public method getLink(entity: String): Option[String] which either returns Some(validURL) or None, if the package name is not supported by the given configuration. Everything else can be changed as much as I want if it improves the code.

Consider this code:

```
object ExternalReferences2 {
import java.util.regex._
import collection.mutable._

private object Mapping {
def fromXml(mapping: scala.xml.NodeSeq) = {
new Mapping(mapping \ "vendor" text, mapping \ "match" text, mapping \ "format" text)
}
}
private case class Mapping(vendor: String, matches: String, format: String) {
private val pattern = Pattern.compile(matches)
private var currentMatcher: Matcher = null

def hasValue(entity: String) = {
currentMatcher = pattern.matcher(entity);
currentMatcher.matches
}

def getValue = {
val range = 0 until currentMatcher.groupCount()
val groups = range
.map (currentMatcher.group(_))
.filterNot (_ == null)
.map (_.replace('.', '/'))
format.format(groups: _*)
}
}

private val config =


OpenJDK
{ """^(javax?|sunw?|com.sun|org\.(ietf\.jgss|omg|w3c\.dom|xml\.sax))(\.[^.]+)+$""" }
{ "http://download.oracle.com/javase/7/docs/api/%s.html" }



private def lookUp(entity: String) =
(config \ "mapping").view
.map(m => Mapping.fromXml(m))
.find(_.hasValue(entity))
.map(_.getValue)

private val links: Map[String, Option[String]] = Map[String, Option[String]]()
.withDefault

Solution

Any idea on how to improve lookUp?

Use a concurrent cache. The point is, regardless how good or bad you lookup function is, nothing beats a cache-hit performance wise..


Is there a better way to do simple caching than using withDefault to
mutate the underlying map?

getOrElseUpdate(key, value)

Code Snippets

getOrElseUpdate(key, value)

Context

StackExchange Code Review Q#4215, answer score: 2

Revisions (0)

No revisions yet.