SlideShare ist ein Scribd-Unternehmen logo
1 von 22
Introducing Scala Idioms

Rishi Khandelwal
Software Consultant
Knoldus Software LLP
Email : rishi@knoldus.com


Using null in Scala code is not idiomatic at all
private var author:Author = null (Don't Do)
If you can’t give a default value, you really should use
var author: Option[Author] = None



Use short names for small scopes :
is, js and ks are all but expected in loops.



Use longer names for larger scopes :
External APIs should have longer and explanatory names that confer
meaning. Future.collect not Future.all.



Use common abbreviations :
ex : ok, err


Don't rebind names for different uses :
Use vals



Avoid using `s to overload reserved names :
typ instead of `type`



Use active names for operations with side effects :
user.activate() not user.setActive()



Use descriptive names for methods that return values :
file.isExist not file.exist



Don't prefix getters with get
money.count not money.getCount


Don't repeat names that are already encapsulated in package or object
name
Prefer:
object User {
def get(id: Int): Option[User]
}
to
object User {
def getUser(id: Int): Option[User]
}





Sort import lines alphabetically. This makes it easy to examine visually, and
is simple to automate.
Use braces when importing several names from a package :
import com.twitter.concurrent.{Broker, Offer}


Use wildcards when more than six names are imported :
import com.twitter.concurrent._



When using collections, qualify names by importing
scala.collection.immutable and/or scala.collection.mutable
e.g. "immutable.Map"



Do not use relative imports from other packages :
Avoid
import com.twitter
import concurrent
in favor of the unambiguous
import com.twitter.concurrent



Put imports at the top of the file. The reader can refer to all imports in one
place


Use pattern matching directly in function definitions whenever applicable
instead of :
list map { item =>
item match {
case Some(x) => x
case None => default
}}
Use this :
list map {
case Some(x) => x
case None => default
}
Use the following style:
**
* ServiceBuilder builds services
* ...
*/
but not the standard ScalaDoc style:
/** ServiceBuilder builds services
* ...
*/


Scala allows return type annotations to be omitted.
Return type is especially important for public methods.
Return type is especially important when instantiating objects with mixins
Instead: trait Service
def make() = new Service {
def getId = 123
}
Use : def make(): Service = new Service{}



Use the mutable namespace explicitly. Don’t import
scala.collection.mutable._ and refer to Set,
use this :
import scala.collection.mutable
val set = mutable.Set()
Use the default constructor for the collection type



val seq = Seq(1, 2, 3)
val set = Set(1, 2, 3)
val map = Map(1 -> "one", 2 -> "two", 3 -> "three")



It is often appropriate to use lower level collections in situations that require
better performance or space efficiency. Use arrays instead of lists for large
sequences (the immutable Vector collections provides a referentially
transparent interface to arrays); and use buffers instead of direct sequence
construction when performance matters.

for (item <- container) {



if (item != 2) return
}
It is often preferrable to call foreach, flatMap, map, and filter directly — but
do use fors when they clarify.


Querying and transforming data: map, flatMap, filter and fold
List(1, 2, 3).map(_ * 2)
.filter(_ > 2)
.foldLeft(0)(_ + _) //> res1: Int = 10



Pattern matching works best when also combined with destructuring
instead of
animal match {
case dog: Dog => "dog (%s)".format(dog.breed)
case _ => animal.species
}
write
animal match {
case Dog(breed) => "dog (%s)".format(breed)
case other => other.species
}
Don’t use pattern matching for conditional execution when defaults make more sense.
avoid
val x = list match {
case head :: _ => head
case Nil => default
}
use
val x = list.headOption getOrElse default
Traits that contain implementation are not directly usable from Java: extend an abstract class with the
trait instead.
// Not directly usable from Java
trait Animal {
def eat(other: Animal)
def eatMany(animals: Seq[Animal) = animals foreach(eat(_))
}
// But this is:
abstract class JavaAnimal extends Animal




Use private[this] = visibility to the particular instance. Sometimes it aid performance
optimizations.

In singleton class types , visibility can be constrained by declaring the returned type:
def foo(): Foo with Bar = new Foo with Bar with Baz {
...
}



Do not use structural types in normal use.
private type FooParam = {
val baz: List[String => String]
def bar(a: Int, b: Int): String
}
def foo(a: FooParam) = ...
Keep traits short and orthogonal: don’t lump separable functionality into a trait, think of the
smallest related ideas that fit together.
For example, imagine you have an something that can do IO:
trait IOer {
def write(bytes: Array[Byte])
def read(n: Int): Array[Byte]
}
separate the two behaviors:
trait Reader {
def read(n: Int): Array[Byte]
}
trait Writer {
def write(bytes: Array[Byte])
}
and mix them together to form what was an IOer:
new Reader with Writer…
Fluent” method chaining : You will often see Scala code that looks like this:



people.sortBy(_.name)
.zipWithIndex
.map { case (person, i) => "%d: %s".format(i + 1, person.name) }
.foreach { println(_) }

Scala provides an exception facility, but do not use it for commonplace errors,



Instead, encode such errors explicitly: using Option
Instead :
trait Repository[Key, Value] {
def get(key: Key): Value
}
Use :
trait Repository[Key, Value] {
def get(key: Key): Option[Value]
}
Some exceptions are fatal and should never be caught; the code
try {
operation()
} catch {
case _ => ...
} // almost always wrong, as it would catch fatal errors that need to be
propagated.
Instead :
use the com.twitter.util.NonFatal extractor to handle only nonfatal exceptions.
try {
operation()
} catch {
case NonFatal(exc) => ...
}


Use implicits in the following situations:

a) Extending or adding a Scala-style collection
b) Adapting or extending an object (“pimp my library” pattern)
c) Use to enhance type safety by providing constraint evidence
d) To provide type evidence (typeclassing)
e) For Manifests
Do not use implicits to do automatic conversions between similar datatypes (for
example, converting a list to a stream); these are better done explicitly because the
types have different semantics, and the reader should beware of these implications.



Phrasing your problem in recursive terms often simplifies it, and if the tail call
optimization applies (which can be checked by the @tailrec annotation), the compiler
will even translate your code into a regular loop.
Type aliases :
Use type aliases when they provide convenient naming or clarify purpose,
but do not alias types that are self-explanatory.
() => Int
is clearer than
type IntMaker = () => Int
IntMaker
since it is both short and uses a common type. However
class ConcurrentPool[K, V] {
type Queue = ConcurrentLinkedQueue[V]
type Map = ConcurrentHashMap[K, Queue]
...
}
is helpful since it communicates purpose and enhances brevity.
Don’t use subclassing when an alias will do.
trait SocketFactory extends (SocketAddress => Socket)
a SocketFactory is a function that produces a Socket.
Using a type alias
type SocketFactory = SocketAddress => Socket
is better. We may now provide function literals for values of type
SocketFactory and also use function composition:
val addrToInet: SocketAddress => Long
val inetToSocket: Long => Socket
val factory: SocketFactory = addrToInet andThen inetToSocket
Returns can be used to cut down on branching and establish
invariants.This is especially useful in “guard” clauses:
def compare(a: AnyRef, b: AnyRef): Int = {
if (a eq b)
return 0
val d = System.identityHashCode(a) compare
System.identityHashCode(b)
if (d != 0)
return d
// slow path..
}
Use returns to clarify and enhance readability, but not as you would in an
imperative language; avoid using them to return the results of a computation.
Instead of
def suffix(i: Int) = {
if

(i == 1) return "st"

else if (i == 2) return "nd"
else if (i == 3) return "rd"
else

return "th"

}
prefer:
def suffix(i: Int) =
if

(i == 1) "st"

else if (i == 2) "nd"
else if (i == 3) "rd"
else

"th"
require and assert both serve as executable documentation. Both are useful for
situations in which the type system cannot express the
required invariants. assert is used for invariants that the code assumes (either internal
or external), for example
val stream = getClass.getResourceAsStream("someclassdata")
assert(stream != null)

Whereas require is used to express API contracts:
def fib(n: Int) = {
require(n > 0)
...
}
Scala idioms

Weitere ähnliche Inhalte

Was ist angesagt?

Accelerate Your Apache Spark with Intel Optane DC Persistent Memory
Accelerate Your Apache Spark with Intel Optane DC Persistent MemoryAccelerate Your Apache Spark with Intel Optane DC Persistent Memory
Accelerate Your Apache Spark with Intel Optane DC Persistent MemoryDatabricks
 
LF_DPDK17_Serverless DPDK - How SmartNIC resident DPDK Accelerates Packet Pro...
LF_DPDK17_Serverless DPDK - How SmartNIC resident DPDK Accelerates Packet Pro...LF_DPDK17_Serverless DPDK - How SmartNIC resident DPDK Accelerates Packet Pro...
LF_DPDK17_Serverless DPDK - How SmartNIC resident DPDK Accelerates Packet Pro...LF_DPDK
 
事例で学ぶApache Cassandra
事例で学ぶApache Cassandra事例で学ぶApache Cassandra
事例で学ぶApache CassandraYuki Morishita
 
Neo4j et ses cas d'usages
Neo4j et ses cas d'usagesNeo4j et ses cas d'usages
Neo4j et ses cas d'usagesNeo4j
 
CPBSB 2022 - Big Data e Machine Learning na Prática Construindo um Data Lake...
CPBSB 2022 - Big Data e  Machine Learning na Prática Construindo um Data Lake...CPBSB 2022 - Big Data e  Machine Learning na Prática Construindo um Data Lake...
CPBSB 2022 - Big Data e Machine Learning na Prática Construindo um Data Lake...Cicero Joasyo Mateus de Moura
 
AF Ceph: Ceph Performance Analysis and Improvement on Flash
AF Ceph: Ceph Performance Analysis and Improvement on FlashAF Ceph: Ceph Performance Analysis and Improvement on Flash
AF Ceph: Ceph Performance Analysis and Improvement on FlashCeph Community
 
鯨物語~Dockerコンテナとオーケストレーションの理解
鯨物語~Dockerコンテナとオーケストレーションの理解鯨物語~Dockerコンテナとオーケストレーションの理解
鯨物語~Dockerコンテナとオーケストレーションの理解Masahito Zembutsu
 
Activate Data Governance Using the Data Catalog
Activate Data Governance Using the Data CatalogActivate Data Governance Using the Data Catalog
Activate Data Governance Using the Data CatalogDATAVERSITY
 
大量のデータ処理や分析に使えるOSS Apache Spark入門 - Open Source Conference2020 Online/Fukuoka...
大量のデータ処理や分析に使えるOSS Apache Spark入門 - Open Source Conference2020 Online/Fukuoka...大量のデータ処理や分析に使えるOSS Apache Spark入門 - Open Source Conference2020 Online/Fukuoka...
大量のデータ処理や分析に使えるOSS Apache Spark入門 - Open Source Conference2020 Online/Fukuoka...NTT DATA Technology & Innovation
 
Apache spark - Architecture , Overview & libraries
Apache spark - Architecture , Overview & librariesApache spark - Architecture , Overview & libraries
Apache spark - Architecture , Overview & librariesWalaa Hamdy Assy
 
グローバル空調メーカーによるIoTプラットフォームへの挑戦
グローバル空調メーカーによるIoTプラットフォームへの挑戦グローバル空調メーカーによるIoTプラットフォームへの挑戦
グローバル空調メーカーによるIoTプラットフォームへの挑戦Takuya Kitamura
 
Using an employee knowledge graph for employee engagement and career mobility
Using an employee knowledge graph for employee engagement and career mobilityUsing an employee knowledge graph for employee engagement and career mobility
Using an employee knowledge graph for employee engagement and career mobilityNeo4j
 
0円でできる自宅InfiniBandプログラム
0円でできる自宅InfiniBandプログラム0円でできる自宅InfiniBandプログラム
0円でできる自宅InfiniBandプログラムMinoru Nakamura
 
Presto: Fast SQL-on-Anything (including Delta Lake, Snowflake, Elasticsearch ...
Presto: Fast SQL-on-Anything (including Delta Lake, Snowflake, Elasticsearch ...Presto: Fast SQL-on-Anything (including Delta Lake, Snowflake, Elasticsearch ...
Presto: Fast SQL-on-Anything (including Delta Lake, Snowflake, Elasticsearch ...Databricks
 
【GOJAS Meetup-10】Splunk:SmartStoreを使ってみた
【GOJAS Meetup-10】Splunk:SmartStoreを使ってみた【GOJAS Meetup-10】Splunk:SmartStoreを使ってみた
【GOJAS Meetup-10】Splunk:SmartStoreを使ってみたtokita-r
 
A Comparative Study of Data Management Maturity Models
A Comparative Study of Data Management Maturity ModelsA Comparative Study of Data Management Maturity Models
A Comparative Study of Data Management Maturity ModelsData Crossroads
 
علم البيانات والبيانات الضخمة- الذكاء الاصطناعي للجميع -جديد
علم البيانات والبيانات الضخمة- الذكاء الاصطناعي للجميع -جديدعلم البيانات والبيانات الضخمة- الذكاء الاصطناعي للجميع -جديد
علم البيانات والبيانات الضخمة- الذكاء الاصطناعي للجميع -جديدAreege Alangari
 

Was ist angesagt? (20)

Accelerate Your Apache Spark with Intel Optane DC Persistent Memory
Accelerate Your Apache Spark with Intel Optane DC Persistent MemoryAccelerate Your Apache Spark with Intel Optane DC Persistent Memory
Accelerate Your Apache Spark with Intel Optane DC Persistent Memory
 
LF_DPDK17_Serverless DPDK - How SmartNIC resident DPDK Accelerates Packet Pro...
LF_DPDK17_Serverless DPDK - How SmartNIC resident DPDK Accelerates Packet Pro...LF_DPDK17_Serverless DPDK - How SmartNIC resident DPDK Accelerates Packet Pro...
LF_DPDK17_Serverless DPDK - How SmartNIC resident DPDK Accelerates Packet Pro...
 
事例で学ぶApache Cassandra
事例で学ぶApache Cassandra事例で学ぶApache Cassandra
事例で学ぶApache Cassandra
 
Neo4j et ses cas d'usages
Neo4j et ses cas d'usagesNeo4j et ses cas d'usages
Neo4j et ses cas d'usages
 
CPBSB 2022 - Big Data e Machine Learning na Prática Construindo um Data Lake...
CPBSB 2022 - Big Data e  Machine Learning na Prática Construindo um Data Lake...CPBSB 2022 - Big Data e  Machine Learning na Prática Construindo um Data Lake...
CPBSB 2022 - Big Data e Machine Learning na Prática Construindo um Data Lake...
 
AF Ceph: Ceph Performance Analysis and Improvement on Flash
AF Ceph: Ceph Performance Analysis and Improvement on FlashAF Ceph: Ceph Performance Analysis and Improvement on Flash
AF Ceph: Ceph Performance Analysis and Improvement on Flash
 
鯨物語~Dockerコンテナとオーケストレーションの理解
鯨物語~Dockerコンテナとオーケストレーションの理解鯨物語~Dockerコンテナとオーケストレーションの理解
鯨物語~Dockerコンテナとオーケストレーションの理解
 
Activate Data Governance Using the Data Catalog
Activate Data Governance Using the Data CatalogActivate Data Governance Using the Data Catalog
Activate Data Governance Using the Data Catalog
 
大量のデータ処理や分析に使えるOSS Apache Spark入門 - Open Source Conference2020 Online/Fukuoka...
大量のデータ処理や分析に使えるOSS Apache Spark入門 - Open Source Conference2020 Online/Fukuoka...大量のデータ処理や分析に使えるOSS Apache Spark入門 - Open Source Conference2020 Online/Fukuoka...
大量のデータ処理や分析に使えるOSS Apache Spark入門 - Open Source Conference2020 Online/Fukuoka...
 
Apache spark - Architecture , Overview & libraries
Apache spark - Architecture , Overview & librariesApache spark - Architecture , Overview & libraries
Apache spark - Architecture , Overview & libraries
 
グローバル空調メーカーによるIoTプラットフォームへの挑戦
グローバル空調メーカーによるIoTプラットフォームへの挑戦グローバル空調メーカーによるIoTプラットフォームへの挑戦
グローバル空調メーカーによるIoTプラットフォームへの挑戦
 
Apache Spark 101
Apache Spark 101Apache Spark 101
Apache Spark 101
 
Using an employee knowledge graph for employee engagement and career mobility
Using an employee knowledge graph for employee engagement and career mobilityUsing an employee knowledge graph for employee engagement and career mobility
Using an employee knowledge graph for employee engagement and career mobility
 
0円でできる自宅InfiniBandプログラム
0円でできる自宅InfiniBandプログラム0円でできる自宅InfiniBandプログラム
0円でできる自宅InfiniBandプログラム
 
Presto: Fast SQL-on-Anything (including Delta Lake, Snowflake, Elasticsearch ...
Presto: Fast SQL-on-Anything (including Delta Lake, Snowflake, Elasticsearch ...Presto: Fast SQL-on-Anything (including Delta Lake, Snowflake, Elasticsearch ...
Presto: Fast SQL-on-Anything (including Delta Lake, Snowflake, Elasticsearch ...
 
【GOJAS Meetup-10】Splunk:SmartStoreを使ってみた
【GOJAS Meetup-10】Splunk:SmartStoreを使ってみた【GOJAS Meetup-10】Splunk:SmartStoreを使ってみた
【GOJAS Meetup-10】Splunk:SmartStoreを使ってみた
 
Apache Spark + Arrow
Apache Spark + ArrowApache Spark + Arrow
Apache Spark + Arrow
 
RDF Refineの使い方
RDF Refineの使い方RDF Refineの使い方
RDF Refineの使い方
 
A Comparative Study of Data Management Maturity Models
A Comparative Study of Data Management Maturity ModelsA Comparative Study of Data Management Maturity Models
A Comparative Study of Data Management Maturity Models
 
علم البيانات والبيانات الضخمة- الذكاء الاصطناعي للجميع -جديد
علم البيانات والبيانات الضخمة- الذكاء الاصطناعي للجميع -جديدعلم البيانات والبيانات الضخمة- الذكاء الاصطناعي للجميع -جديد
علم البيانات والبيانات الضخمة- الذكاء الاصطناعي للجميع -جديد
 

Ähnlich wie Scala idioms

Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaMichael Stal
 
ES6 General Introduction
ES6 General IntroductionES6 General Introduction
ES6 General IntroductionThomas Johnston
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalMichael Stal
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Languageleague
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Martin Odersky
 
Programming in Scala: Notes
Programming in Scala: NotesProgramming in Scala: Notes
Programming in Scala: NotesRoberto Casadei
 
Stepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to ScalaStepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to ScalaDerek Chen-Becker
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java ProgrammersEric Pederson
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side JavascriptJulie Iskander
 
Inheritance And Traits
Inheritance And TraitsInheritance And Traits
Inheritance And TraitsPiyush Mishra
 
Type script - advanced usage and practices
Type script  - advanced usage and practicesType script  - advanced usage and practices
Type script - advanced usage and practicesIwan van der Kleijn
 
Functional programming with Scala
Functional programming with ScalaFunctional programming with Scala
Functional programming with ScalaNeelkanth Sachdeva
 
K is for Kotlin
K is for KotlinK is for Kotlin
K is for KotlinTechMagic
 

Ähnlich wie Scala idioms (20)

Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scala
 
ES6 General Introduction
ES6 General IntroductionES6 General Introduction
ES6 General Introduction
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation Stal
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Language
 
Scala - core features
Scala - core featuresScala - core features
Scala - core features
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
 
Programming in Scala: Notes
Programming in Scala: NotesProgramming in Scala: Notes
Programming in Scala: Notes
 
Scala - brief intro
Scala - brief introScala - brief intro
Scala - brief intro
 
Scala in a nutshell by venkat
Scala in a nutshell by venkatScala in a nutshell by venkat
Scala in a nutshell by venkat
 
Stepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to ScalaStepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to Scala
 
Scala
ScalaScala
Scala
 
JavaScript.pptx
JavaScript.pptxJavaScript.pptx
JavaScript.pptx
 
scala.ppt
scala.pptscala.ppt
scala.ppt
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java Programmers
 
WD programs descriptions.docx
WD programs descriptions.docxWD programs descriptions.docx
WD programs descriptions.docx
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
Inheritance And Traits
Inheritance And TraitsInheritance And Traits
Inheritance And Traits
 
Type script - advanced usage and practices
Type script  - advanced usage and practicesType script  - advanced usage and practices
Type script - advanced usage and practices
 
Functional programming with Scala
Functional programming with ScalaFunctional programming with Scala
Functional programming with Scala
 
K is for Kotlin
K is for KotlinK is for Kotlin
K is for Kotlin
 

Mehr von Knoldus Inc.

Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingMastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingKnoldus Inc.
 
Akka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On IntroductionAkka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On IntroductionKnoldus Inc.
 
Entity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxEntity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxKnoldus Inc.
 
Introduction to Redis and its features.pptx
Introduction to Redis and its features.pptxIntroduction to Redis and its features.pptx
Introduction to Redis and its features.pptxKnoldus Inc.
 
GraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdfGraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdfKnoldus Inc.
 
NuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptxNuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptxKnoldus Inc.
 
Data Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable TestingData Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable TestingKnoldus Inc.
 
K8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose KubernetesK8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose KubernetesKnoldus Inc.
 
Introduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptxIntroduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptxKnoldus Inc.
 
Robusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxRobusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxKnoldus Inc.
 
Optimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxOptimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxKnoldus Inc.
 
Azure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxAzure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxKnoldus Inc.
 
CQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxCQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxKnoldus Inc.
 
ETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationKnoldus Inc.
 
Scripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics PresentationScripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics PresentationKnoldus Inc.
 
Getting started with dotnet core Web APIs
Getting started with dotnet core Web APIsGetting started with dotnet core Web APIs
Getting started with dotnet core Web APIsKnoldus Inc.
 
Introduction To Rust part II Presentation
Introduction To Rust part II PresentationIntroduction To Rust part II Presentation
Introduction To Rust part II PresentationKnoldus Inc.
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
Configuring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAConfiguring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAKnoldus Inc.
 
Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)Knoldus Inc.
 

Mehr von Knoldus Inc. (20)

Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingMastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
 
Akka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On IntroductionAkka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On Introduction
 
Entity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxEntity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptx
 
Introduction to Redis and its features.pptx
Introduction to Redis and its features.pptxIntroduction to Redis and its features.pptx
Introduction to Redis and its features.pptx
 
GraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdfGraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdf
 
NuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptxNuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptx
 
Data Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable TestingData Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable Testing
 
K8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose KubernetesK8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose Kubernetes
 
Introduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptxIntroduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptx
 
Robusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxRobusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptx
 
Optimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxOptimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptx
 
Azure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxAzure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptx
 
CQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxCQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptx
 
ETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake Presentation
 
Scripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics PresentationScripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics Presentation
 
Getting started with dotnet core Web APIs
Getting started with dotnet core Web APIsGetting started with dotnet core Web APIs
Getting started with dotnet core Web APIs
 
Introduction To Rust part II Presentation
Introduction To Rust part II PresentationIntroduction To Rust part II Presentation
Introduction To Rust part II Presentation
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Configuring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAConfiguring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRA
 
Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)
 

Kürzlich hochgeladen

Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 

Kürzlich hochgeladen (20)

Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 

Scala idioms

  • 1. Introducing Scala Idioms Rishi Khandelwal Software Consultant Knoldus Software LLP Email : rishi@knoldus.com
  • 2.  Using null in Scala code is not idiomatic at all private var author:Author = null (Don't Do) If you can’t give a default value, you really should use var author: Option[Author] = None  Use short names for small scopes : is, js and ks are all but expected in loops.  Use longer names for larger scopes : External APIs should have longer and explanatory names that confer meaning. Future.collect not Future.all.  Use common abbreviations : ex : ok, err
  • 3.  Don't rebind names for different uses : Use vals  Avoid using `s to overload reserved names : typ instead of `type`  Use active names for operations with side effects : user.activate() not user.setActive()  Use descriptive names for methods that return values : file.isExist not file.exist  Don't prefix getters with get money.count not money.getCount
  • 4.  Don't repeat names that are already encapsulated in package or object name Prefer: object User { def get(id: Int): Option[User] } to object User { def getUser(id: Int): Option[User] }   Sort import lines alphabetically. This makes it easy to examine visually, and is simple to automate. Use braces when importing several names from a package : import com.twitter.concurrent.{Broker, Offer}
  • 5.  Use wildcards when more than six names are imported : import com.twitter.concurrent._  When using collections, qualify names by importing scala.collection.immutable and/or scala.collection.mutable e.g. "immutable.Map"  Do not use relative imports from other packages : Avoid import com.twitter import concurrent in favor of the unambiguous import com.twitter.concurrent  Put imports at the top of the file. The reader can refer to all imports in one place
  • 6.  Use pattern matching directly in function definitions whenever applicable instead of : list map { item => item match { case Some(x) => x case None => default }} Use this : list map { case Some(x) => x case None => default }
  • 7. Use the following style: ** * ServiceBuilder builds services * ... */ but not the standard ScalaDoc style: /** ServiceBuilder builds services * ... */
  • 8.  Scala allows return type annotations to be omitted. Return type is especially important for public methods. Return type is especially important when instantiating objects with mixins Instead: trait Service def make() = new Service { def getId = 123 } Use : def make(): Service = new Service{}  Use the mutable namespace explicitly. Don’t import scala.collection.mutable._ and refer to Set, use this : import scala.collection.mutable val set = mutable.Set()
  • 9. Use the default constructor for the collection type  val seq = Seq(1, 2, 3) val set = Set(1, 2, 3) val map = Map(1 -> "one", 2 -> "two", 3 -> "three")  It is often appropriate to use lower level collections in situations that require better performance or space efficiency. Use arrays instead of lists for large sequences (the immutable Vector collections provides a referentially transparent interface to arrays); and use buffers instead of direct sequence construction when performance matters. for (item <- container) {  if (item != 2) return } It is often preferrable to call foreach, flatMap, map, and filter directly — but do use fors when they clarify.
  • 10.  Querying and transforming data: map, flatMap, filter and fold List(1, 2, 3).map(_ * 2) .filter(_ > 2) .foldLeft(0)(_ + _) //> res1: Int = 10  Pattern matching works best when also combined with destructuring instead of animal match { case dog: Dog => "dog (%s)".format(dog.breed) case _ => animal.species } write animal match { case Dog(breed) => "dog (%s)".format(breed) case other => other.species }
  • 11. Don’t use pattern matching for conditional execution when defaults make more sense. avoid val x = list match { case head :: _ => head case Nil => default } use val x = list.headOption getOrElse default Traits that contain implementation are not directly usable from Java: extend an abstract class with the trait instead. // Not directly usable from Java trait Animal { def eat(other: Animal) def eatMany(animals: Seq[Animal) = animals foreach(eat(_)) } // But this is: abstract class JavaAnimal extends Animal
  • 12.   Use private[this] = visibility to the particular instance. Sometimes it aid performance optimizations. In singleton class types , visibility can be constrained by declaring the returned type: def foo(): Foo with Bar = new Foo with Bar with Baz { ... }  Do not use structural types in normal use. private type FooParam = { val baz: List[String => String] def bar(a: Int, b: Int): String } def foo(a: FooParam) = ...
  • 13. Keep traits short and orthogonal: don’t lump separable functionality into a trait, think of the smallest related ideas that fit together. For example, imagine you have an something that can do IO: trait IOer { def write(bytes: Array[Byte]) def read(n: Int): Array[Byte] } separate the two behaviors: trait Reader { def read(n: Int): Array[Byte] } trait Writer { def write(bytes: Array[Byte]) } and mix them together to form what was an IOer: new Reader with Writer…
  • 14. Fluent” method chaining : You will often see Scala code that looks like this:  people.sortBy(_.name) .zipWithIndex .map { case (person, i) => "%d: %s".format(i + 1, person.name) } .foreach { println(_) } Scala provides an exception facility, but do not use it for commonplace errors,  Instead, encode such errors explicitly: using Option Instead : trait Repository[Key, Value] { def get(key: Key): Value } Use : trait Repository[Key, Value] { def get(key: Key): Option[Value] }
  • 15. Some exceptions are fatal and should never be caught; the code try { operation() } catch { case _ => ... } // almost always wrong, as it would catch fatal errors that need to be propagated. Instead : use the com.twitter.util.NonFatal extractor to handle only nonfatal exceptions. try { operation() } catch { case NonFatal(exc) => ... }
  • 16.  Use implicits in the following situations: a) Extending or adding a Scala-style collection b) Adapting or extending an object (“pimp my library” pattern) c) Use to enhance type safety by providing constraint evidence d) To provide type evidence (typeclassing) e) For Manifests Do not use implicits to do automatic conversions between similar datatypes (for example, converting a list to a stream); these are better done explicitly because the types have different semantics, and the reader should beware of these implications.  Phrasing your problem in recursive terms often simplifies it, and if the tail call optimization applies (which can be checked by the @tailrec annotation), the compiler will even translate your code into a regular loop.
  • 17. Type aliases : Use type aliases when they provide convenient naming or clarify purpose, but do not alias types that are self-explanatory. () => Int is clearer than type IntMaker = () => Int IntMaker since it is both short and uses a common type. However class ConcurrentPool[K, V] { type Queue = ConcurrentLinkedQueue[V] type Map = ConcurrentHashMap[K, Queue] ... } is helpful since it communicates purpose and enhances brevity.
  • 18. Don’t use subclassing when an alias will do. trait SocketFactory extends (SocketAddress => Socket) a SocketFactory is a function that produces a Socket. Using a type alias type SocketFactory = SocketAddress => Socket is better. We may now provide function literals for values of type SocketFactory and also use function composition: val addrToInet: SocketAddress => Long val inetToSocket: Long => Socket val factory: SocketFactory = addrToInet andThen inetToSocket
  • 19. Returns can be used to cut down on branching and establish invariants.This is especially useful in “guard” clauses: def compare(a: AnyRef, b: AnyRef): Int = { if (a eq b) return 0 val d = System.identityHashCode(a) compare System.identityHashCode(b) if (d != 0) return d // slow path.. }
  • 20. Use returns to clarify and enhance readability, but not as you would in an imperative language; avoid using them to return the results of a computation. Instead of def suffix(i: Int) = { if (i == 1) return "st" else if (i == 2) return "nd" else if (i == 3) return "rd" else return "th" } prefer: def suffix(i: Int) = if (i == 1) "st" else if (i == 2) "nd" else if (i == 3) "rd" else "th"
  • 21. require and assert both serve as executable documentation. Both are useful for situations in which the type system cannot express the required invariants. assert is used for invariants that the code assumes (either internal or external), for example val stream = getClass.getResourceAsStream("someclassdata") assert(stream != null) Whereas require is used to express API contracts: def fib(n: Int) = { require(n > 0) ... }

Hinweis der Redaktion

  1. {}