Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Scala Patterns in the Linked Data Writer

Avatar for Sam Starling Sam Starling
February 14, 2013

Scala Patterns in the Linked Data Writer

Avatar for Sam Starling

Sam Starling

February 14, 2013
Tweet

More Decks by Sam Starling

Other Decks in Programming

Transcript

  1. 1 Rethrowing Exceptions – Can be assigned to a val

    and re-used – We deal with fewer exception types – Slightly verbose – Not immediately obvious
  2. 2 Custom Matchers val rdf = fixture("some_turtle.rdf") val value =

    "Newsnight" rdf must containTriple(None, "cwork:about", aidy)
  3. 3 Enums & RDF Types object CreativeWorkType extends Enumeration {

    type CreativeWorkType = Value val Video, Gallery, BlogPost = Value } import CreativeWorkType.CreativeWorkType
  4. 3 Enums & RDF Types – DRY-er than using strings

    – Helps with validation of types – Odd syntax for creation – Odd syntax for imports – Another mirror of the ontology
  5. 4 Chunky Constructors case class CreativeWork( locator: Urn, title: String,

    modified: DateTime, format: Option[FormatType.FormatType] = None, created: Option[DateTime] = None, uri: Option[String] = None, primaryContentOf: List[PrimaryContentOf] = List(), about: List[String] = List(), mentions: List[String] = List(), type: CreativeWorkType = CreativeWorkType.CreativeWork, provenance: Option[CreativeWorkProvenance] = None, thumbnails: List[Thumbnail] = List(), audience: Option[AudienceType] = None)
  6. 4 – Mostly hidden from 'general use' – ...at least,

    in our code – Not particularly nice to read – Forced by immutability – If it were mutable, we could use setters – No logical grouping of arguments – Alternative: builder pattern using .copy – But, the constructor uses named args anyway Chunky Constructors
  7. 5 Validation The not-so-good way case class Dataset { def

    checkHasNoBlankNodes = { // do some stuff throw new InvalidDatasetException("Oh no!") } } put("/dataset") { // construct dataset dataset.checkHasNoBlankNodes }
  8. 5 Validation The better way case class Dataset { def

    hasBlankNodes: Boolean = { // do some stuff } } put("/dataset") { // construct dataset require(dataset.hasBlankNodes == false) }
  9. 5 – Clearer than calling methods that throw – Always

    throws IllegalArgumentException – Error always starts with requirement failed – Disclaimer: I ♥ require Validation
  10. 5 – In my opinion... – Requirements that are always

    true should – happen inside the constructor – Other requirements (those which are only – true in some cases) should exist outside – the class. Validation