• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Scala in practice
 

Scala in practice

on

  • 397 views

Manchester Geek Night 8 Feb 2012, Scala Experience - Pat Fornasier, Marc Hofer

Manchester Geek Night 8 Feb 2012, Scala Experience - Pat Fornasier, Marc Hofer

Statistics

Views

Total Views
397
Views on SlideShare
397
Embed Views
0

Actions

Likes
0
Downloads
3
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Scala in practice Scala in practice Presentation Transcript

    • Scala Practicein patric.fornasier@thoughtworks.com marc.hofer@thoughtworks.com
    • 2&/82..9+8$&+&"0+&/;0+2-3+0<10-*0+#7+7=&"0=2>#50+2-3+;#(0?+ ience Exper ign Optimising IT Des Organ isations Co nsulting Build & Release Man agement technology Testing
    • Offices 2
    • a r n in g Wpresentation Contains code examples
    • A bit ofContext about the project
    • Why Scala
    • What isScala
    • Object Functional Oriented Sc ala ScriptableStatically Typed JVM- based
    • Scala Compile Byte Code JVM
    • Benefits
    • unc tio nal “F n g” ram miP rog
    • List<String> features = Arrays.asList("noFeature", "featureC", "featureB", "featureA");for (String feature : features) { System.out.println(feature);}
    • List<String> javaFeatures = Arrays.asList("noFeature", "featureC", "featureB", "featureA");for (String feature : javaFeatures) { System.out.println(feature);} val scalaFeatures = List( "noFeature", "featureC", "featureB", "featureA") scalaFeatures foreach { println _ }
    • val currentFeatures = List("noFeature", "featureC", "featureB", "featureA")Result: "featureA_toggle, featureB_toggle"currentFeatures.filter { _.startsWith("feature") } .sorted .take(2) .map { _ + "_toggle" } .mkString(", ")
    • String result = "";List<String> currentFeatures = Arrays.asList("noFeature", "featureC", "featureB", "featureA");Collections.sort(currentFeatures);int i = 0, j = 0, take = 2; while(i < take && j < currentFeatures.size()) { String feature = currentFeatures.get(j++); if(feature.startsWith("feature")) { result += feature + "_toggle" + ((i++ != take) ? ", " : ""); }} currentFeatures.filter { _.startsWith("feature") } .sorted .take(2) .map { _ + "_toggle" } .mkString(", ")
    • “L ess ilerpla te ”Bo
    • public class Property {}
    • class Property {}
    • public class Property { private final String key; private final String value; private final String defaultValue; public Property(String key, String value, String defaultValue) { this.key = key; this.value = value; this.defaultValue = defaultValue; }}
    • class Property(key: String, value: String, default: String) {}
    • public class Property { // ... public String getKey() { return key; } public String getValue() { return value; } public String getDefaultValue() { return defaultValue; }}
    • class Property(val key: String, val value: String, val default: String) {}
    • public class Property { // ... public Property changeTo(String newValue) { return new Property(key, value, newValue); } public Property reset() { return new Property(key, value); } @Override public String toString() { return String.format("%s=%s", key, value); }}
    • class Property(val key: String, val value: String, val default: String) { def changeTo(newValue: String) = new Property(key, newValue, default) def reset = new Property(key, default) override def toString = "%s=%s" format(key, value)}
    • public class Property { // ... @Override public boolean equals(Object obj) { if (!(obj instanceof Property)) return false; Property other = (Property) obj; return other.key.equals(key) && other.value.equals(value) && other.defaultValue.equals(defaultValue) } @Override public int hashCode() { int result = 17; result = 31 * result + key; result = 31 * result + value; result = 31 * result + defaultValue; return result; }}
    • case class Property(key: String, value: String, default: String) { def changeTo(newValue: String) = Property(key, newValue, default) def reset = Property(key, default) override def toString = "%s=%s" format(key, value)}
    • public class Property { private final String key; private final String value; private final String defaultValue; public Property(String key, String value, String defaultValue) { this.key = key; this.value = value; this.defaultValue = defaultValue; } public String getKey() { return key; } public String getValue() { return value; } public String getDefaultValue() { return defaultValue; } public Property changeTo(String newValue) { return new Property(key, value, newValue); } public Property reset() { return new Property(key, value); } @Override public String toString() { return String.format("%s=%s", key, value); } @Override public boolean equals(Object obj) { if (!(obj instanceof Property)) return false; Property other = (Property) obj; return other.key.equals(key) && other.value.equals(value) && other.defaultValue.equals(defaultValue) } @Override public int hashCode() { int result = 17; result = 31 * result + key; result = 31 * result + value; result = 31 * result + defaultValue; return result; }}
    • case class Property(key: String, value: String, default: String) { def changeTo(newValue: String) = Property(key, newValue, default) def reset = Property(key, default) override def toString = "%s=%s" format(key, value)}
    • public class Property { case class Property(key: String, value: String, default: String) { def changeTo(newValue: String) = Property(key, newValue, default) private final String key; def reset = Property(key, default) private final String value; override def toString = "%s=%s" format(key, value) private final String defaultValue; } public Property(String key, String value, String defaultValue) { this.key = key; this.value = value; this.defaultValue = defaultValue; } vs 5 public String getKey() { return key; 45 } public String getValue() { return value; } L OCs public String getDefaultValue() { return defaultValue; } public Property changeTo(String newValue) { return new Property(key, value, newValue); } public Property reset() { return new Property(key, value); } @Override public boolean equals(Object obj) { if (!(obj instanceof Property)) return false; Property other = (Property) obj; return other.key.equals(key) && other.value.equals(value) && other.defaultValue.equals(defaultValue) } @Override public int hashCode() { int result = 17; result = 31 * result + key; result = 31 * result + value; result = 31 * result + defaultValue; return result; } @Override public String toString() { return String.format("%s=%s", key, value); }} * ignoring blank lines
    • “L ess ilerpla te ” BoAnother Example: { Blocks }
    • int statusCode = httpSupport.get("http://foo.com", new Block<Integer>() { public Integer execute(HttpResponse response) { return response.getStatusLine().getStatusCode()); }});String content = httpSupport.get("http://foo.com", new Block<String>() { public Integer execute(HttpResponse response) { return EntityUtils.toString(response.getEntity()); }});httpSupport.get("http://foo.com", new VoidBlock() { public void execute(HttpResponse response) {}}); val statusCode = get("http://foo.com") { statusCode } val content = get("http://foo.com") { toString } get("http://foo.com")
    • “J ava p at ibi lity”Com
    • java -cp "lib/*" com.springer.core.app.Casper Scala library goes in here!
    • val java = new java.util.ArrayList[String]val scala: Seq[String] = foo filter { ... }
    • val log = Logger.getLogger("com.foo")log.debug("Hello!")
    • Libraryre-use JVM “ Ge n tle gC urv e” L e arn in “Java without ;”
    • Su ppo rt/><XM L-
    • val pdfInfo = <PdfInfo hasAccess="false"> <DDSId>12345</DDSId> <ContentType>Article</ContentType> </PdfInfo> val contentType = (pdfInfo "ContentType").textval hasAccess = (pdfInfo "@hasAccess").text.toBoolean
    • val pdfInfoList = <PdfInfoList> <PdfInfo hasAccess="false"> <DDSId>12345</DDSId> <ContentType>Article</ContentType> </PdfInfo> <PdfInfo hasAccess="true"> <DDSId>54321</DDSId> <ContentType>Book</ContentType> </PdfInfo> </PdfInfoList>case class PdfInfo(xml: NodeSeq) { val ddsId = (xml "DDSId").head.text val hasAccess = (xml "@hasAccess").head.text val contentType = (xml "ContentType").head.text}(pdfInfoList "PdfInfo") map { PdfInfo(_) }
    • “D SL-Fri e nd ly”
    • Levels of Testing SystemFunctional Unit App2 App1 Integration DB App3
    • Unit Test DSLclass PropertyTest extends Spec with ShouldMatchers { it("should render key and value separated with an equals sign") { Property("shark", "fish").toString should equal ("shark=fish") }}
    • Functional Test DSLclass ForgottenPasswordPageTests extends FunctionalTestSpec with ForgottenPasswordSteps with Uris { it("should validate user email") { given(iNavigateTo(ForgottenPasswordPage)) when(iSubmitEmail("invalid@email.com")) then(iShouldSeeInvalidEmailErrorMessage) }}
    • Document Validation DSLtrait DDSValidationRules extends JournalXPaths with APlusPlusElements { val journalRules = List( No(JournalTitle) is Invalid, MoreThanOneElementIn(JournalArticle) is Invalid, BadLanguageIn(JournalArticleLanguage) is Invalid, JournalIssue With No(JournalIssueCoverYear) is Invalid, Bibliography With No(BibliographyHeading) is Invalid, MarkupIn(JournalTitle) is Unsupported, MarkupIn(JournalAuthor) is Unsupported )}
    • “Ac tiv e mm un ity”Co
    • “F un”
    • “F un”
    • “F un”val foo = (7 to 21)
    • “F un”List<Integers> foo = new ArrayList<Integers>()for (int i = 7; i <= 21; i++) { foo.add(i);}
    • “F un”def eat(food: String = "plankton")
    • “F un”public void eat(String food) {...}public void eat() { eat("plankton");}
    • “F un”get("http://foo.com") { statusCode }
    • “F un”httpSupport.get("http://foo.com", new Block<Integer>() { public Integer execute(HttpResponse response) { return response.getStatusLine().getStatusCode()); }});
    • Drawbacks
    • “T oolSu ppo rt”
    • !?
    • 1:10
    • re rop e ...”“ Mo
    • Scala Collection Librarydef ++ [B >: A, That](that: TraversableOnce[B])(implicit bf: CanBuildFrom[List[A], B, That]):That
    • Traits Galore in our codebase... class JournalPageTests extends Spec with FunctionalTestSpec with JournalPageSteps with SearchResultsPageSteps with LanguageSteps with LanguageSupport with JavascriptSupport with Uris with IssuePageSteps with VolumesAndIssuesPageSteps with CoverImageUrlBuilders with FakeEntitlementSteps with FullTextPageSteps with CommonAbstractSteps with GoogleAnalyticsSteps with ActionSectionSteps { ... }
    • xsbt
    • scalaz
    • Can→Should
    • RiskMitigations
    • Would wedo it again
    • l a im erd isc use scala at your own risk
    • Thanks for Listening @patforna | @mhoefi