SlideShare a Scribd company logo
Using Scala for building DSL’s

                         Abhijit Sharma
                         Innovation Lab,
                         BMC Software




                                           1
What is a DSL?
• Domain Specific Language
 • Appropriate abstraction level for domain - uses precise
   concepts and semantics of domain
 • Concise and expressive for a specific domain – not general
   purpose
 • Domain experts can communicate, critique better with
   programmers and amongst themselves
 • Math – Mathematica, UI – HTML, CSS, Database - SQL




                                                                2
DSL’s at large - Ant
• Build tool Ant is an XML based DSL
   • Task to build a jar with a dependency on task compile




                                                             3
DSL’s at large – RoR ActiveRecord
• Web App framework Ruby on Rails
   • ActiveRecord to model domain objects and persist them –
   • Domain constraint implementations do not clutter API – uniqueness,
     cardinality, null check




                                                                          4
Cloud Computing DSL
• Audience – Non tech savvy cloud end users
• DSL - English language sentence for requesting a
  machine with technical and price specifications




                                                     5
Cloud Computing DSL - Model
• Domain Concept – Machine
  • Technical specifications - cpu, os
  • Pricing specifications - spot price, pricing strategy –
    default or define inline

                 Machine

                 •cpu:Cpu
                 •os:String
                 •spotPrice:Int       Cpu

                                  •arch: String
                                  •cpus: Int




                                                         6
Cloud Computing Java DSL
• Builder pattern - Method Chaining Fluent Interface




                                                       7
Cloud Computing Java DSL - Pattern
• Builder Pattern - Method Chaining




                                      8
Cloud Computing Java DSL - Issues
• Syntax restrictions, verbosity – parenthesis, dot, semi-
  colons
• Non Domain complexity – Builder
• No Inline strategy – no higher order functions




                                                        9
DSL Classification
• Internal DSL
  • Embedded in a host language like Ruby, Scala,
    Groovy – use their features
  • Bound by host language syntax and semantics
• External DSL – standalone developed ground up
  • Define syntax and semantics as a grammar
  • Use tools like lexical analyzers, parsers,
    interpretation, code generators


                                                    10
Internal DSL Classification
• Internal DSL
  • Generative - Ruby, Groovy Techniques like
    runtime metaprogramming
      • Meta Objects – inject new behaviour at runtime
  • Embedded in host language
    • Smart API – Method chaining – Java etc.
    • Syntax tree manipulation – Groovy, Ruby libraries
    • Type Embedding – Scala – statically typed, type
      constraints, no invalid operations on types

                                                         11
Scala Language
• Scala is a “scalable” language
• JVM based – leverage libs, JVM perf,
  tools, install base etc
• Mixed Paradigm – Object Oriented +
  Functional Programming
    • Object Oriented Programming - Improves on Java
      OOP (Traits, no statics, advanced types)



                                                  12
Scala Language
• Functional Programming - Functions
  • No side effects and immutable variables
  • “First-class” citizens - Can be assigned,
    passed around, returned
  • Higher order functions promote composition
    using other more primitive functions
• Lots of powerful features – discussed later
• Statically Typed – Type Safe DSL
                                                13
Scala – Readable style - Syntax
• Elegant, succinct syntax unlike verbose Java
  • Optional dots, Operators are methods
  • Syntactic sugar method takes one/zero argument, drop
    period and parentheses




                                                           14
Scala – Readable style - Inference
• Type inference minimizes the need for explicit type
  information – still Type safe




                                                        15
Scala - Implicits
• Implicit Conversions – wrap original type e.g. Integer
  • Generative expression - Implicit conversion converts the 1,
    an Int, to a RichInt which defines a ‘to’ method
  • Lexically scoped – Unlike other languages like Groovy where
    such modifications are global in scope
• Implicit argument to function – don’t need to pass –
  Concise syntax




                                                              16
Scala - Higher order functions
• Functions as parameters or return values
• Flexible mechanism for composition
• Anonymous Functions




                                             17
Scala - Higher order functions
• Currying – set some parameters – concise &
  powerful




                                               18
Scala – Functional Combinators
• Calculate the total price of all Linux machines – uses
  several combinators – filter, map, foldLeft – all take
  other functions as predicates




                                                       19
Scala – Cloud Computing DSL - Relook




                                       20
Scala – Cloud Computing DSL - Implicits
• Consider excerpt - 8 cpus “64bit” – Using Implicit conversion we
  get the object representing the CPU - Cpu(8, 64bit)




                                                               21
Scala – Cloud Computing DSL – E2E
DSL - new Machine having (8 cpus
   "64bit") with_os “Linux“
•   Implicit Conversion
•   Method Chaining – Builder pattern –
    without the cruft
•   Syntactic sugar no parenthesis, dot,
    brackets




                                           22
Scala – Cloud Computing DSL – Functions
•   Using Higher Order
    Functions – Flexible pricing
•   Spot Price Threshold - Inline
    strategy - Anonymous
    Functions




                                          23
Scala - Pattern Matching
• Pattern Matching – Switch
  Case on Steroids
• Cases can include value,
  types, wild-cards, sequences,
  tuples, deep inspection of
  objects




                                  24
Scala - Pattern Matching &Case Classes
• Case Classes – simplified
  construction and can be used
  in pattern matching
• Pattern matching on Case
  Classes
   • Deep pattern matching on
     object contents
   • Make good succinct
     powerful DSL




                                     25
Scala - Pattern Matching – Visitor Pattern
• Pattern match and case
  classes – extensible visitor
• Different operations on tree
   • Expression Evaluation
   • Prefix Notation
• Very expressive, flexible and
  concise code




                                             26
Scala – For Comprehensions
• Loop through Iterable sequences and
  comprehend/compute something
  • E.g. Filter 32, 64 bit architectures




                                           27
Scala – For Comprehensions + Option
• Wrap vars & function returns as
  Option – Null Checks, resilient
  programming
• Option sub classes : None and Some
• Options with for comprehensions,
  automatic removal of None
  elements from comprehensions




                                       28
Scala – For Comprehensions + Option
• Validate and audit
  machines
• Using Options with for
  comprehensions eliminate
  the need for most
  “null/empty” checks.
• Succinct, safe DSL with
  uncluttered API




                                      29
External DSL in Scala
DSL - having (8 cpus "64bit") with_os "Linux" at_spot_price 30
• Parser Combinator library – available as a library on host
  language – Scala
• External Parser Generators like JavaCC – use tools to
  generate code for tokenizing, parsing
• Parser Combinator Specification is like a BNF grammar




                                                                 30
External DSL in Scala
• Each function is a parser - works on
  a portion of the input, parses it and
  may optionally pass on the
  remaining part to the next parser in
  the chain via the combinator
• Several combinators provided by the
  library like ‘~’ the sequencing
  combinator composes two parsers
  sequentially.
• Optional function application
  combinator (^^) can work, applying
  the function on the result of the
  sequencing combinator.




                                          31
Thanks

   abhijit.sharma@gmail.com
     Twitter : sharmaabhijit
Blog : abhijitsharma.blogspot.com


                                    32
Scala - Traits
•   Traits are collections of fields and
    behaviors that you can extend or mixin
    to your classes.
•   Modularize these concerns, yet enable
    the fine-grained “mixing” of their
    behaviors with other concerns at build
    or run time – Callbacks & Ordered
•   Traits can be mixed-in at class level or
    at instance creation
•   AOP Pervasive concerns - Logging,
    Ordering, Callback Handling




                                               33

More Related Content

Viewers also liked

A Field Guide to DSL Design in Scala
A Field Guide to DSL Design in ScalaA Field Guide to DSL Design in Scala
A Field Guide to DSL Design in ScalaTomer Gabel
 
Domain specific languages and Scala
Domain specific languages and ScalaDomain specific languages and Scala
Domain specific languages and ScalaFilip Krikava
 
JavaFX 2 and Scala - Like Milk and Cookies (33rd Degrees)
JavaFX 2 and Scala - Like Milk and Cookies (33rd Degrees)JavaFX 2 and Scala - Like Milk and Cookies (33rd Degrees)
JavaFX 2 and Scala - Like Milk and Cookies (33rd Degrees)Stephen Chin
 
Reactive X 响应式编程
Reactive X 响应式编程Reactive X 响应式编程
Reactive X 响应式编程Jun Liu
 
Implementing External DSLs Using Scala Parser Combinators
Implementing External DSLs Using Scala Parser CombinatorsImplementing External DSLs Using Scala Parser Combinators
Implementing External DSLs Using Scala Parser CombinatorsTim Dalton
 
University Students Fighting World Hunger - Slacktivism vs. Activism. Does a ...
University Students Fighting World Hunger - Slacktivism vs. Activism. Does a ...University Students Fighting World Hunger - Slacktivism vs. Activism. Does a ...
University Students Fighting World Hunger - Slacktivism vs. Activism. Does a ...Sascha Funk
 
Johnstown Pa Defense Hub
Johnstown   Pa Defense HubJohnstown   Pa Defense Hub
Johnstown Pa Defense HubBob Shark
 
Web Configurator
Web ConfiguratorWeb Configurator
Web Configuratormikuzz
 
IVI (Tom Nastas) Presentation At 3rd Moscow Venture Fair
IVI (Tom Nastas)  Presentation At 3rd  Moscow Venture FairIVI (Tom Nastas)  Presentation At 3rd  Moscow Venture Fair
IVI (Tom Nastas) Presentation At 3rd Moscow Venture FairThomas Nastas
 
Fairgrounds Proposal
Fairgrounds ProposalFairgrounds Proposal
Fairgrounds Proposalguest12a2146
 
Eu Kyoto Prototcol Class Presentation Sumiko
Eu Kyoto Prototcol Class Presentation SumikoEu Kyoto Prototcol Class Presentation Sumiko
Eu Kyoto Prototcol Class Presentation SumikoKeith Dickson
 
Divizare digitală și subdezvoltare tehnologică: sociologia românească pe inte...
Divizare digitală și subdezvoltare tehnologică: sociologia românească pe inte...Divizare digitală și subdezvoltare tehnologică: sociologia românească pe inte...
Divizare digitală și subdezvoltare tehnologică: sociologia românească pe inte...Eugen Glavan
 

Viewers also liked (20)

A Field Guide to DSL Design in Scala
A Field Guide to DSL Design in ScalaA Field Guide to DSL Design in Scala
A Field Guide to DSL Design in Scala
 
Domain specific languages and Scala
Domain specific languages and ScalaDomain specific languages and Scala
Domain specific languages and Scala
 
JavaFX 2 and Scala - Like Milk and Cookies (33rd Degrees)
JavaFX 2 and Scala - Like Milk and Cookies (33rd Degrees)JavaFX 2 and Scala - Like Milk and Cookies (33rd Degrees)
JavaFX 2 and Scala - Like Milk and Cookies (33rd Degrees)
 
Reactive X 响应式编程
Reactive X 响应式编程Reactive X 响应式编程
Reactive X 响应式编程
 
Eugenia
EugeniaEugenia
Eugenia
 
Implementing External DSLs Using Scala Parser Combinators
Implementing External DSLs Using Scala Parser CombinatorsImplementing External DSLs Using Scala Parser Combinators
Implementing External DSLs Using Scala Parser Combinators
 
University Students Fighting World Hunger - Slacktivism vs. Activism. Does a ...
University Students Fighting World Hunger - Slacktivism vs. Activism. Does a ...University Students Fighting World Hunger - Slacktivism vs. Activism. Does a ...
University Students Fighting World Hunger - Slacktivism vs. Activism. Does a ...
 
Detskaya Rabota2
Detskaya Rabota2Detskaya Rabota2
Detskaya Rabota2
 
Begin with ginie
Begin with ginieBegin with ginie
Begin with ginie
 
Earth Day
Earth DayEarth Day
Earth Day
 
Lourenza
LourenzaLourenza
Lourenza
 
Tamk Conference Finished 2008
Tamk Conference Finished 2008Tamk Conference Finished 2008
Tamk Conference Finished 2008
 
Johnstown Pa Defense Hub
Johnstown   Pa Defense HubJohnstown   Pa Defense Hub
Johnstown Pa Defense Hub
 
Web Configurator
Web ConfiguratorWeb Configurator
Web Configurator
 
IVI (Tom Nastas) Presentation At 3rd Moscow Venture Fair
IVI (Tom Nastas)  Presentation At 3rd  Moscow Venture FairIVI (Tom Nastas)  Presentation At 3rd  Moscow Venture Fair
IVI (Tom Nastas) Presentation At 3rd Moscow Venture Fair
 
Sentimenduak
SentimenduakSentimenduak
Sentimenduak
 
Fairgrounds Proposal
Fairgrounds ProposalFairgrounds Proposal
Fairgrounds Proposal
 
Eu Kyoto Prototcol Class Presentation Sumiko
Eu Kyoto Prototcol Class Presentation SumikoEu Kyoto Prototcol Class Presentation Sumiko
Eu Kyoto Prototcol Class Presentation Sumiko
 
Zas
ZasZas
Zas
 
Divizare digitală și subdezvoltare tehnologică: sociologia românească pe inte...
Divizare digitală și subdezvoltare tehnologică: sociologia românească pe inte...Divizare digitală și subdezvoltare tehnologică: sociologia românească pe inte...
Divizare digitală și subdezvoltare tehnologică: sociologia românească pe inte...
 

Similar to Writing DSL's in Scala

Using Scala for building DSLs
Using Scala for building DSLsUsing Scala for building DSLs
Using Scala for building DSLsIndicThreads
 
Scala in Model-Driven development for Apparel Cloud Platform
Scala in Model-Driven development for Apparel Cloud PlatformScala in Model-Driven development for Apparel Cloud Platform
Scala in Model-Driven development for Apparel Cloud PlatformTomoharu ASAMI
 
Polyglot and functional (Devoxx Nov/2011)
Polyglot and functional (Devoxx Nov/2011)Polyglot and functional (Devoxx Nov/2011)
Polyglot and functional (Devoxx Nov/2011)Martijn Verburg
 
Scala in practice
Scala in practiceScala in practice
Scala in practiceTomer Gabel
 
Intro to Big Data and NoSQL
Intro to Big Data and NoSQLIntro to Big Data and NoSQL
Intro to Big Data and NoSQLDon Demcsak
 
Ruby to Scala in 9 weeks
Ruby to Scala in 9 weeksRuby to Scala in 9 weeks
Ruby to Scala in 9 weeksjutley
 
Scala and Spark are Ideal for Big Data
Scala and Spark are Ideal for Big DataScala and Spark are Ideal for Big Data
Scala and Spark are Ideal for Big DataJohn Nestor
 
A full Machine learning pipeline in Scikit-learn vs in scala-Spark: pros and ...
A full Machine learning pipeline in Scikit-learn vs in scala-Spark: pros and ...A full Machine learning pipeline in Scikit-learn vs in scala-Spark: pros and ...
A full Machine learning pipeline in Scikit-learn vs in scala-Spark: pros and ...Jose Quesada (hiring)
 
A Survey of Advanced Non-relational Database Systems: Approaches and Applicat...
A Survey of Advanced Non-relational Database Systems: Approaches and Applicat...A Survey of Advanced Non-relational Database Systems: Approaches and Applicat...
A Survey of Advanced Non-relational Database Systems: Approaches and Applicat...Qian Lin
 
Kafka 0.8.0 Presentation to Atlanta Java User's Group March 2013
Kafka 0.8.0 Presentation to Atlanta Java User's Group March 2013Kafka 0.8.0 Presentation to Atlanta Java User's Group March 2013
Kafka 0.8.0 Presentation to Atlanta Java User's Group March 2013Christopher Curtin
 
Polyglot and Functional Programming (OSCON 2012)
Polyglot and Functional Programming (OSCON 2012)Polyglot and Functional Programming (OSCON 2012)
Polyglot and Functional Programming (OSCON 2012)Martijn Verburg
 
Yes sql08 inmemorydb
Yes sql08 inmemorydbYes sql08 inmemorydb
Yes sql08 inmemorydbDaniel Austin
 
Polyglot Plugin Programming
Polyglot Plugin ProgrammingPolyglot Plugin Programming
Polyglot Plugin ProgrammingAtlassian
 
Transitioning from Java to Scala for Spark - March 13, 2019
Transitioning from Java to Scala for Spark - March 13, 2019Transitioning from Java to Scala for Spark - March 13, 2019
Transitioning from Java to Scala for Spark - March 13, 2019Gravy Analytics
 
Sa introduction to big data pipelining with cassandra & spark west mins...
Sa introduction to big data pipelining with cassandra & spark   west mins...Sa introduction to big data pipelining with cassandra & spark   west mins...
Sa introduction to big data pipelining with cassandra & spark west mins...Simon Ambridge
 
A Global In-memory Data System for MySQL
A Global In-memory Data System for MySQLA Global In-memory Data System for MySQL
A Global In-memory Data System for MySQLDaniel Austin
 
Scala and Spark are Ideal for Big Data - Data Science Pop-up Seattle
Scala and Spark are Ideal for Big Data - Data Science Pop-up SeattleScala and Spark are Ideal for Big Data - Data Science Pop-up Seattle
Scala and Spark are Ideal for Big Data - Data Science Pop-up SeattleDomino Data Lab
 
Ruby On Rails
Ruby On RailsRuby On Rails
Ruby On Railsiradarji
 

Similar to Writing DSL's in Scala (20)

Using Scala for building DSLs
Using Scala for building DSLsUsing Scala for building DSLs
Using Scala for building DSLs
 
Scala in Model-Driven development for Apparel Cloud Platform
Scala in Model-Driven development for Apparel Cloud PlatformScala in Model-Driven development for Apparel Cloud Platform
Scala in Model-Driven development for Apparel Cloud Platform
 
Polyglot and functional (Devoxx Nov/2011)
Polyglot and functional (Devoxx Nov/2011)Polyglot and functional (Devoxx Nov/2011)
Polyglot and functional (Devoxx Nov/2011)
 
Scala in practice
Scala in practiceScala in practice
Scala in practice
 
Intro to Big Data and NoSQL
Intro to Big Data and NoSQLIntro to Big Data and NoSQL
Intro to Big Data and NoSQL
 
Ruby to Scala in 9 weeks
Ruby to Scala in 9 weeksRuby to Scala in 9 weeks
Ruby to Scala in 9 weeks
 
Scala and Spark are Ideal for Big Data
Scala and Spark are Ideal for Big DataScala and Spark are Ideal for Big Data
Scala and Spark are Ideal for Big Data
 
A full Machine learning pipeline in Scikit-learn vs in scala-Spark: pros and ...
A full Machine learning pipeline in Scikit-learn vs in scala-Spark: pros and ...A full Machine learning pipeline in Scikit-learn vs in scala-Spark: pros and ...
A full Machine learning pipeline in Scikit-learn vs in scala-Spark: pros and ...
 
A Survey of Advanced Non-relational Database Systems: Approaches and Applicat...
A Survey of Advanced Non-relational Database Systems: Approaches and Applicat...A Survey of Advanced Non-relational Database Systems: Approaches and Applicat...
A Survey of Advanced Non-relational Database Systems: Approaches and Applicat...
 
Kafka 0.8.0 Presentation to Atlanta Java User's Group March 2013
Kafka 0.8.0 Presentation to Atlanta Java User's Group March 2013Kafka 0.8.0 Presentation to Atlanta Java User's Group March 2013
Kafka 0.8.0 Presentation to Atlanta Java User's Group March 2013
 
Polyglot and Functional Programming (OSCON 2012)
Polyglot and Functional Programming (OSCON 2012)Polyglot and Functional Programming (OSCON 2012)
Polyglot and Functional Programming (OSCON 2012)
 
Yes sql08 inmemorydb
Yes sql08 inmemorydbYes sql08 inmemorydb
Yes sql08 inmemorydb
 
Polyglot Plugin Programming
Polyglot Plugin ProgrammingPolyglot Plugin Programming
Polyglot Plugin Programming
 
Transitioning from Java to Scala for Spark - March 13, 2019
Transitioning from Java to Scala for Spark - March 13, 2019Transitioning from Java to Scala for Spark - March 13, 2019
Transitioning from Java to Scala for Spark - March 13, 2019
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Sa introduction to big data pipelining with cassandra & spark west mins...
Sa introduction to big data pipelining with cassandra & spark   west mins...Sa introduction to big data pipelining with cassandra & spark   west mins...
Sa introduction to big data pipelining with cassandra & spark west mins...
 
A Global In-memory Data System for MySQL
A Global In-memory Data System for MySQLA Global In-memory Data System for MySQL
A Global In-memory Data System for MySQL
 
Hadoop and Spark
Hadoop and SparkHadoop and Spark
Hadoop and Spark
 
Scala and Spark are Ideal for Big Data - Data Science Pop-up Seattle
Scala and Spark are Ideal for Big Data - Data Science Pop-up SeattleScala and Spark are Ideal for Big Data - Data Science Pop-up Seattle
Scala and Spark are Ideal for Big Data - Data Science Pop-up Seattle
 
Ruby On Rails
Ruby On RailsRuby On Rails
Ruby On Rails
 

Recently uploaded

Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonDianaGray10
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor TurskyiFwdays
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfCheryl Hung
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)Ralf Eggert
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaRTTS
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance
 
Speed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in MinutesSpeed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in Minutesconfluent
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupCatarinaPereira64715
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Jeffrey Haguewood
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...Product School
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Product School
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform EngineeringJemma Hussein Allen
 
UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2DianaGray10
 
Demystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyDemystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyJohn Staveley
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesThousandEyes
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualityInflectra
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...BookNet Canada
 
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlPeter Udo Diehl
 

Recently uploaded (20)

Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
Speed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in MinutesSpeed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in Minutes
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2
 
Demystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyDemystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John Staveley
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
 

Writing DSL's in Scala

  • 1. Using Scala for building DSL’s Abhijit Sharma Innovation Lab, BMC Software 1
  • 2. What is a DSL? • Domain Specific Language • Appropriate abstraction level for domain - uses precise concepts and semantics of domain • Concise and expressive for a specific domain – not general purpose • Domain experts can communicate, critique better with programmers and amongst themselves • Math – Mathematica, UI – HTML, CSS, Database - SQL 2
  • 3. DSL’s at large - Ant • Build tool Ant is an XML based DSL • Task to build a jar with a dependency on task compile 3
  • 4. DSL’s at large – RoR ActiveRecord • Web App framework Ruby on Rails • ActiveRecord to model domain objects and persist them – • Domain constraint implementations do not clutter API – uniqueness, cardinality, null check 4
  • 5. Cloud Computing DSL • Audience – Non tech savvy cloud end users • DSL - English language sentence for requesting a machine with technical and price specifications 5
  • 6. Cloud Computing DSL - Model • Domain Concept – Machine • Technical specifications - cpu, os • Pricing specifications - spot price, pricing strategy – default or define inline Machine •cpu:Cpu •os:String •spotPrice:Int Cpu •arch: String •cpus: Int 6
  • 7. Cloud Computing Java DSL • Builder pattern - Method Chaining Fluent Interface 7
  • 8. Cloud Computing Java DSL - Pattern • Builder Pattern - Method Chaining 8
  • 9. Cloud Computing Java DSL - Issues • Syntax restrictions, verbosity – parenthesis, dot, semi- colons • Non Domain complexity – Builder • No Inline strategy – no higher order functions 9
  • 10. DSL Classification • Internal DSL • Embedded in a host language like Ruby, Scala, Groovy – use their features • Bound by host language syntax and semantics • External DSL – standalone developed ground up • Define syntax and semantics as a grammar • Use tools like lexical analyzers, parsers, interpretation, code generators 10
  • 11. Internal DSL Classification • Internal DSL • Generative - Ruby, Groovy Techniques like runtime metaprogramming • Meta Objects – inject new behaviour at runtime • Embedded in host language • Smart API – Method chaining – Java etc. • Syntax tree manipulation – Groovy, Ruby libraries • Type Embedding – Scala – statically typed, type constraints, no invalid operations on types 11
  • 12. Scala Language • Scala is a “scalable” language • JVM based – leverage libs, JVM perf, tools, install base etc • Mixed Paradigm – Object Oriented + Functional Programming • Object Oriented Programming - Improves on Java OOP (Traits, no statics, advanced types) 12
  • 13. Scala Language • Functional Programming - Functions • No side effects and immutable variables • “First-class” citizens - Can be assigned, passed around, returned • Higher order functions promote composition using other more primitive functions • Lots of powerful features – discussed later • Statically Typed – Type Safe DSL 13
  • 14. Scala – Readable style - Syntax • Elegant, succinct syntax unlike verbose Java • Optional dots, Operators are methods • Syntactic sugar method takes one/zero argument, drop period and parentheses 14
  • 15. Scala – Readable style - Inference • Type inference minimizes the need for explicit type information – still Type safe 15
  • 16. Scala - Implicits • Implicit Conversions – wrap original type e.g. Integer • Generative expression - Implicit conversion converts the 1, an Int, to a RichInt which defines a ‘to’ method • Lexically scoped – Unlike other languages like Groovy where such modifications are global in scope • Implicit argument to function – don’t need to pass – Concise syntax 16
  • 17. Scala - Higher order functions • Functions as parameters or return values • Flexible mechanism for composition • Anonymous Functions 17
  • 18. Scala - Higher order functions • Currying – set some parameters – concise & powerful 18
  • 19. Scala – Functional Combinators • Calculate the total price of all Linux machines – uses several combinators – filter, map, foldLeft – all take other functions as predicates 19
  • 20. Scala – Cloud Computing DSL - Relook 20
  • 21. Scala – Cloud Computing DSL - Implicits • Consider excerpt - 8 cpus “64bit” – Using Implicit conversion we get the object representing the CPU - Cpu(8, 64bit) 21
  • 22. Scala – Cloud Computing DSL – E2E DSL - new Machine having (8 cpus "64bit") with_os “Linux“ • Implicit Conversion • Method Chaining – Builder pattern – without the cruft • Syntactic sugar no parenthesis, dot, brackets 22
  • 23. Scala – Cloud Computing DSL – Functions • Using Higher Order Functions – Flexible pricing • Spot Price Threshold - Inline strategy - Anonymous Functions 23
  • 24. Scala - Pattern Matching • Pattern Matching – Switch Case on Steroids • Cases can include value, types, wild-cards, sequences, tuples, deep inspection of objects 24
  • 25. Scala - Pattern Matching &Case Classes • Case Classes – simplified construction and can be used in pattern matching • Pattern matching on Case Classes • Deep pattern matching on object contents • Make good succinct powerful DSL 25
  • 26. Scala - Pattern Matching – Visitor Pattern • Pattern match and case classes – extensible visitor • Different operations on tree • Expression Evaluation • Prefix Notation • Very expressive, flexible and concise code 26
  • 27. Scala – For Comprehensions • Loop through Iterable sequences and comprehend/compute something • E.g. Filter 32, 64 bit architectures 27
  • 28. Scala – For Comprehensions + Option • Wrap vars & function returns as Option – Null Checks, resilient programming • Option sub classes : None and Some • Options with for comprehensions, automatic removal of None elements from comprehensions 28
  • 29. Scala – For Comprehensions + Option • Validate and audit machines • Using Options with for comprehensions eliminate the need for most “null/empty” checks. • Succinct, safe DSL with uncluttered API 29
  • 30. External DSL in Scala DSL - having (8 cpus "64bit") with_os "Linux" at_spot_price 30 • Parser Combinator library – available as a library on host language – Scala • External Parser Generators like JavaCC – use tools to generate code for tokenizing, parsing • Parser Combinator Specification is like a BNF grammar 30
  • 31. External DSL in Scala • Each function is a parser - works on a portion of the input, parses it and may optionally pass on the remaining part to the next parser in the chain via the combinator • Several combinators provided by the library like ‘~’ the sequencing combinator composes two parsers sequentially. • Optional function application combinator (^^) can work, applying the function on the result of the sequencing combinator. 31
  • 32. Thanks abhijit.sharma@gmail.com Twitter : sharmaabhijit Blog : abhijitsharma.blogspot.com 32
  • 33. Scala - Traits • Traits are collections of fields and behaviors that you can extend or mixin to your classes. • Modularize these concerns, yet enable the fine-grained “mixing” of their behaviors with other concerns at build or run time – Callbacks & Ordered • Traits can be mixed-in at class level or at instance creation • AOP Pervasive concerns - Logging, Ordering, Callback Handling 33