type FeatureValueId = int

Full name: index.FeatureValueId
Multiple items
val int : value:'T -> int (requires member op_Explicit)

Full name: Microsoft.FSharp.Core.Operators.int

--------------------
type int = int32

Full name: Microsoft.FSharp.Core.int

--------------------
type int<'Measure> = int

Full name: Microsoft.FSharp.Core.int<_>
type FeatureValue =
  | Discrete of FeatureValueId
  | Numeric of decimal
  | Literal of string
  | Date of DateTime

Full name: index.FeatureValue
union case FeatureValue.Discrete: FeatureValueId -> FeatureValue
union case FeatureValue.Numeric: decimal -> FeatureValue
Multiple items
val decimal : value:'T -> decimal (requires member op_Explicit)

Full name: Microsoft.FSharp.Core.Operators.decimal

--------------------
type decimal = System.Decimal

Full name: Microsoft.FSharp.Core.decimal

--------------------
type decimal<'Measure> = decimal

Full name: Microsoft.FSharp.Core.decimal<_>
Multiple items
union case FeatureValue.Literal: string -> FeatureValue

--------------------
type LiteralAttribute =
  inherit Attribute
  new : unit -> LiteralAttribute

Full name: Microsoft.FSharp.Core.LiteralAttribute

--------------------
new : unit -> LiteralAttribute
Multiple items
val string : value:'T -> string

Full name: Microsoft.FSharp.Core.Operators.string

--------------------
type string = System.String

Full name: Microsoft.FSharp.Core.string
union case FeatureValue.Date: System.DateTime -> FeatureValue
namespace System
Multiple items
type DateTime =
  struct
    new : ticks:int64 -> DateTime + 10 overloads
    member Add : value:TimeSpan -> DateTime
    member AddDays : value:float -> DateTime
    member AddHours : value:float -> DateTime
    member AddMilliseconds : value:float -> DateTime
    member AddMinutes : value:float -> DateTime
    member AddMonths : months:int -> DateTime
    member AddSeconds : value:float -> DateTime
    member AddTicks : value:int64 -> DateTime
    member AddYears : value:int -> DateTime
    ...
  end

Full name: System.DateTime

--------------------
System.DateTime()
   (+0 other overloads)
System.DateTime(ticks: int64) : unit
   (+0 other overloads)
System.DateTime(ticks: int64, kind: System.DateTimeKind) : unit
   (+0 other overloads)
System.DateTime(year: int, month: int, day: int) : unit
   (+0 other overloads)
System.DateTime(year: int, month: int, day: int, calendar: System.Globalization.Calendar) : unit
   (+0 other overloads)
System.DateTime(year: int, month: int, day: int, hour: int, minute: int, second: int) : unit
   (+0 other overloads)
System.DateTime(year: int, month: int, day: int, hour: int, minute: int, second: int, kind: System.DateTimeKind) : unit
   (+0 other overloads)
System.DateTime(year: int, month: int, day: int, hour: int, minute: int, second: int, calendar: System.Globalization.Calendar) : unit
   (+0 other overloads)
System.DateTime(year: int, month: int, day: int, hour: int, minute: int, second: int, millisecond: int) : unit
   (+0 other overloads)
System.DateTime(year: int, month: int, day: int, hour: int, minute: int, second: int, millisecond: int, kind: System.DateTimeKind) : unit
   (+0 other overloads)
val displaySize : FeatureValue

Full name: index.displaySize

Scala vs Java and
What the ... FP ?

Scala vs Java

  • statically typed
  • strong(er) type inference
  • Functional + Object oriented
  • everything is an object, including functions
  • every function is a value - including methods

Scala vs Java



\(e = mc^2\)

\(errors = (more\ code)^2\)

Java
1: 
2: 
Pair p = new Pair<Integer, String>(1, "Scala");
String p1 = p.Item1;
Scala
1: 
2: 
3: 
val p1 = new MyPair(1, "Scala")
val p2 = (1, "Scala")
val (nr, name) = p2

Object oriented programming

OOP

What the ... FP ?

  • OOP -- objects everywhere
  • FP - functions everywhere
  • OOP Design patterns
  • Functional design...

    Patterns

    Tips

    Approaches

OOP Design Patterns

  • Factory
  • Strategy
  • Decorator
  • Visitor
  • Builder
  • ...
  • def factory()
  • def sort(f)
  • def decorate(x)
  • def rec visit(x)
  • def build(part1,part2)
  • ...

SOLID principes

  • Single Responsibiity (SRP)
  • Open/Closed (OCP)
  • Liskov Substitution (LSP)
  • Interface segregation (ISP)
  • Dependency inversion (DIP)

Functional patterns

Some obligatory basic terms. It's really easy!

  • Monoid, Monad, Comonad
  • Functor, Bifunctor, Endofunctor
  • Apomorphism, Isomorphism, Sigomorphism

FlatMap this shit!

Actually not needed, relax!

Functional patterns

  • Core principles:
    • functions are things
    • composition everywhere
    • types are not classes
  • Functions as parameters
    • interface -> function
    • dependency injection -> partial application
    • chaining, continuation

Function is a thing

  • not attached to a class
  • always one input, always one output
    • apple => banana
    • (apple,banana) => ftuitSalad
    • apple => banana => fruitSalad
    • def mkSalad(apple)(banana): fruitSalad

Function is a thing

partial application

1: 
2: 
3: 
def add(x:Int)(y:Int) : Int = x + y // Int => Int => Int
def add5 = add(5) _                  // Int => Int
def add5mul2(add5 : Int => Int, x : Int) = add5(x) * 2

functional dependency injection

1: 
2: 
3: 
4: 
5: 
6: 
def persist[T](insert: T => ID)(log: T => Unit)(entity: T): ID
def saveToMongo = persist(mongoInsert) _ _
def saveToMongoLogToKafka = persist(mongoInsert)(kafkaLog) _
saveToMongoLogToKafka(MdmProduct) // ObjectId(...)

def mockPersist = persist(addToHashMap)(logToConsole)

Function composition

1: 
2: 
(apple => banana) andThen (banana => cherry)
(apple => cherry) // new function

composition

Function composition

OOP

  • objects in the large
  • functions in the small

FP

  • functions in the large
  • functions in the small

Scala

  • what ever you need

Function composition

1: 
2: 
3: 
4: 
5: 
6: 
// low level operation (micro service)
String --> toUpper --> String

// high level operation (service)
--> lowLevel --> lowLevel --> lowLevel -->
MdmProduct --> FeatureCleanup --> EncodexProduct

service is just like a microservice but without "micro"

Types are not classes

  • Data (List->List)
    • set of valid inputs
    • set of valid outputs
  • Behavior (map, collect, filter, etc...)
    • not methods - functions
  • Composition
    • AND - Product types - case class
    • OR - Algebraic Data Types (ADT)

Product types - case class

AND-composition

1: 
2: 
3: 
4: 
5: 
6: 
case class User(
    id: Int
    name: String
    address: Address
    contats: List[Contact]
)

ADT - algebraic data types


OR-composition

1: 
2: 
3: 
4: 
5: 
6: 
7: 
8: 
type FeatureValueId = Int
sealed trait FeatureValue
object FeatureValue {
    final case class Discrete(value: FeatureValueId) extends FeatureValue
    final case class Numeric(value: Double) extends FeatureValue
    final case class Literal(value: String) extends FeatureValue
    final case class Date(value: LocalDate) extends FeatureValue
}

val displaySize = FeatureValue.Numeric(7.0) // Numeric

the same in F#

1: 
2: 
3: 
4: 
5: 
6: 
7: 
type FeatureValueId = int
type FeatureValue =
    | Discrete of FeatureValueId
    | Numeric of decimal
    | Literal of string
    | Date of System.DateTime
let displaySize = Numeric 7.0m // FeatureValue

ADT - algebraic data types

  • Simple representation for complex cases
  • Make invalid state impossible
  • Each case is independent in scala
  • Pattern matching ensures all* cases handled
    • (actually in scala not all)
    • sealed trait and final case class

Scala tips and pitfalls

Things to avoid if not necessary. What to use instead

  • var ==> val
    • prefer immutable
    • but mutable if performance critical
  • def without parameters is also a function
  • foreach ==> map, flatMap, filter, fold
    • scala's for is just syntactic shugar for flatMap
  • if .. else ==> pattern matching
  • Inheritance
    • ADTs
    • Composition over inheritance
    • CakePattern wit traits - popular in scala

Scala tips and pitfalls

Option: Some(value) or None

  • Option is new null
  • gives a meaning to null, not eliminates it
  • ADT - must be handled on the place
  • can cause NRE if comes from java
    • new Option(javaObject)
  • slight performance drawback - heap instead of stack
  • not overuse it, not propagate if not necessary
    • flatMap it away early or getOrElse
    • don't use get - runtime exception!

Scala tips and pitfalls

1: 
2: 
3: 
val name: Option[String] = request getParameter "name"
val upper = name map { _.trim } filter { _.length != 0 } map { _.toUpperCase }
println(upper getOrElse "")

the same with for:

1: 
2: 
3: 
4: 
5: 
6: 
val upper = for {
    name <- request getParameter "name"
    trimmed <- Some(name.trim)
    upper <- Some(trimmed.toUpperCase) if trimmed.length != 0
} yield upper
println(upper getOrElse "")

Scala tips and pitfalls

import scala.util.{Try, Success, Failure}

Scala tips and pitfalls

1: 
2: 
3: 
4: 
5: 
6: 
7: 
def getURLContent(url: String): Try[Iterator[String]] =
for {
    url <- parseURL(url)
    connection <- Try(url.openConnection())
    is <- Try(connection.getInputStream)
    source = Source.fromInputStream(is)
} yield source.getLines()

FlatMap this shit!

IntelliJ Tipps

  • Ctrl+Shfit+A - search for commands
  • Ctl+Q - Quick documentation. Shows which type infers scala if not explicit
  • Ctl+Shift+P - Implicit parameters
  • Scala Worksheet - REPL with interactive mode

The Reality of a Developer's Life

When I show my boss that I've fixed a bug:

When I show my boss that I've fixed a bug

When your regular expression returns what you expect:

When your regular expression returns what you expect

from The Reality of a Developer's Life - in GIFs, Of Course

Links