SlideShare uma empresa Scribd logo
1 de 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

Mais conteúdo relacionado

Mais procurados

ファントム異常を排除する高速なトランザクション処理向けインデックス
ファントム異常を排除する高速なトランザクション処理向けインデックスファントム異常を排除する高速なトランザクション処理向けインデックス
ファントム異常を排除する高速なトランザクション処理向けインデックスSho Nakazono
 
データベース技術の羅針盤
データベース技術の羅針盤データベース技術の羅針盤
データベース技術の羅針盤Yoshinori Matsunobu
 
ClojureではじめるSTM入門
ClojureではじめるSTM入門ClojureではじめるSTM入門
ClojureではじめるSTM入門sohta
 
1 motores de indução
1 motores de indução1 motores de indução
1 motores de induçãoDorival Brito
 
LTspiceでDCモータ系のシミュレーションをやってみる
LTspiceでDCモータ系のシミュレーションをやってみるLTspiceでDCモータ系のシミュレーションをやってみる
LTspiceでDCモータ系のシミュレーションをやってみるTatsuya Sanada
 
[ZigBee 嵌入式系統] ZigBee Architecture 與 TI Z-Stack Firmware
[ZigBee 嵌入式系統] ZigBee Architecture 與 TI Z-Stack Firmware[ZigBee 嵌入式系統] ZigBee Architecture 與 TI Z-Stack Firmware
[ZigBee 嵌入式系統] ZigBee Architecture 與 TI Z-Stack FirmwareSimen Li
 
20221111_JPUG_CustomScan_API
20221111_JPUG_CustomScan_API20221111_JPUG_CustomScan_API
20221111_JPUG_CustomScan_APIKohei KaiGai
 
SAP Extractorのソースエンドポイントとしての利用
SAP Extractorのソースエンドポイントとしての利用SAP Extractorのソースエンドポイントとしての利用
SAP Extractorのソースエンドポイントとしての利用QlikPresalesJapan
 
[D14] 【詳解】インメモリーデータベース SAP HANA:実際の仕組みと動きを理解しよう!by Toshiro Morisaki
[D14] 【詳解】インメモリーデータベース SAP HANA:実際の仕組みと動きを理解しよう!by Toshiro Morisaki[D14] 【詳解】インメモリーデータベース SAP HANA:実際の仕組みと動きを理解しよう!by Toshiro Morisaki
[D14] 【詳解】インメモリーデータベース SAP HANA:実際の仕組みと動きを理解しよう!by Toshiro MorisakiInsight Technology, Inc.
 
VLDB2015 会議報告
VLDB2015 会議報告VLDB2015 会議報告
VLDB2015 会議報告Yuto Hayamizu
 
PostgreSQLでスケールアウト
PostgreSQLでスケールアウトPostgreSQLでスケールアウト
PostgreSQLでスケールアウトMasahiko Sawada
 
PostgreSQL Unconference #29 Unicode IVS
PostgreSQL Unconference #29 Unicode IVSPostgreSQL Unconference #29 Unicode IVS
PostgreSQL Unconference #29 Unicode IVSNoriyoshi Shinoda
 
第10回solr勉強会 solr cloudの導入事例
第10回solr勉強会 solr cloudの導入事例第10回solr勉強会 solr cloudの導入事例
第10回solr勉強会 solr cloudの導入事例Ken Hirose
 
TIME_WAITに関する話
TIME_WAITに関する話TIME_WAITに関する話
TIME_WAITに関する話Takanori Sejima
 
ISID×MS_DLLAB_企業のデータ&AI活用をAzureで加速する
ISID×MS_DLLAB_企業のデータ&AI活用をAzureで加速するISID×MS_DLLAB_企業のデータ&AI活用をAzureで加速する
ISID×MS_DLLAB_企業のデータ&AI活用をAzureで加速するMiyuki Mochizuki
 
哥寫的不是程式,是軟體 - 從嵌入式系統看軟體工程全貌
哥寫的不是程式,是軟體 - 從嵌入式系統看軟體工程全貌哥寫的不是程式,是軟體 - 從嵌入式系統看軟體工程全貌
哥寫的不是程式,是軟體 - 從嵌入式系統看軟體工程全貌Tun-Yu Chang
 

Mais procurados (20)

ファントム異常を排除する高速なトランザクション処理向けインデックス
ファントム異常を排除する高速なトランザクション処理向けインデックスファントム異常を排除する高速なトランザクション処理向けインデックス
ファントム異常を排除する高速なトランザクション処理向けインデックス
 
Exadata X8M-2 KVM仮想化ベストプラクティス
Exadata X8M-2 KVM仮想化ベストプラクティスExadata X8M-2 KVM仮想化ベストプラクティス
Exadata X8M-2 KVM仮想化ベストプラクティス
 
データベース技術の羅針盤
データベース技術の羅針盤データベース技術の羅針盤
データベース技術の羅針盤
 
ClojureではじめるSTM入門
ClojureではじめるSTM入門ClojureではじめるSTM入門
ClojureではじめるSTM入門
 
1 motores de indução
1 motores de indução1 motores de indução
1 motores de indução
 
LTspiceでDCモータ系のシミュレーションをやってみる
LTspiceでDCモータ系のシミュレーションをやってみるLTspiceでDCモータ系のシミュレーションをやってみる
LTspiceでDCモータ系のシミュレーションをやってみる
 
[ZigBee 嵌入式系統] ZigBee Architecture 與 TI Z-Stack Firmware
[ZigBee 嵌入式系統] ZigBee Architecture 與 TI Z-Stack Firmware[ZigBee 嵌入式系統] ZigBee Architecture 與 TI Z-Stack Firmware
[ZigBee 嵌入式系統] ZigBee Architecture 與 TI Z-Stack Firmware
 
20221111_JPUG_CustomScan_API
20221111_JPUG_CustomScan_API20221111_JPUG_CustomScan_API
20221111_JPUG_CustomScan_API
 
SAP Extractorのソースエンドポイントとしての利用
SAP Extractorのソースエンドポイントとしての利用SAP Extractorのソースエンドポイントとしての利用
SAP Extractorのソースエンドポイントとしての利用
 
5. 心律調節器
5. 心律調節器5. 心律調節器
5. 心律調節器
 
[D14] 【詳解】インメモリーデータベース SAP HANA:実際の仕組みと動きを理解しよう!by Toshiro Morisaki
[D14] 【詳解】インメモリーデータベース SAP HANA:実際の仕組みと動きを理解しよう!by Toshiro Morisaki[D14] 【詳解】インメモリーデータベース SAP HANA:実際の仕組みと動きを理解しよう!by Toshiro Morisaki
[D14] 【詳解】インメモリーデータベース SAP HANA:実際の仕組みと動きを理解しよう!by Toshiro Morisaki
 
VLDB2015 会議報告
VLDB2015 会議報告VLDB2015 会議報告
VLDB2015 会議報告
 
PostgreSQLでスケールアウト
PostgreSQLでスケールアウトPostgreSQLでスケールアウト
PostgreSQLでスケールアウト
 
PostgreSQL Unconference #29 Unicode IVS
PostgreSQL Unconference #29 Unicode IVSPostgreSQL Unconference #29 Unicode IVS
PostgreSQL Unconference #29 Unicode IVS
 
第10回solr勉強会 solr cloudの導入事例
第10回solr勉強会 solr cloudの導入事例第10回solr勉強会 solr cloudの導入事例
第10回solr勉強会 solr cloudの導入事例
 
TIME_WAITに関する話
TIME_WAITに関する話TIME_WAITに関する話
TIME_WAITに関する話
 
ISID×MS_DLLAB_企業のデータ&AI活用をAzureで加速する
ISID×MS_DLLAB_企業のデータ&AI活用をAzureで加速するISID×MS_DLLAB_企業のデータ&AI活用をAzureで加速する
ISID×MS_DLLAB_企業のデータ&AI活用をAzureで加速する
 
PostgreSQL Query Cache - "pqc"
PostgreSQL Query Cache - "pqc"PostgreSQL Query Cache - "pqc"
PostgreSQL Query Cache - "pqc"
 
Dmz aa aioug
Dmz aa aiougDmz aa aioug
Dmz aa aioug
 
哥寫的不是程式,是軟體 - 從嵌入式系統看軟體工程全貌
哥寫的不是程式,是軟體 - 從嵌入式系統看軟體工程全貌哥寫的不是程式,是軟體 - 從嵌入式系統看軟體工程全貌
哥寫的不是程式,是軟體 - 從嵌入式系統看軟體工程全貌
 

Semelhante a 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
 

Semelhante a 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
 

Mais de Knoldus 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.
 
Azure Databricks (For Data Analytics).pptx
Azure Databricks (For Data Analytics).pptxAzure Databricks (For Data Analytics).pptx
Azure Databricks (For Data Analytics).pptxKnoldus Inc.
 
The Power of Dependency Injection with Dagger 2 and Kotlin
The Power of Dependency Injection with Dagger 2 and KotlinThe Power of Dependency Injection with Dagger 2 and Kotlin
The Power of Dependency Injection with Dagger 2 and KotlinKnoldus Inc.
 
Data Engineering with Databricks Presentation
Data Engineering with Databricks PresentationData Engineering with Databricks Presentation
Data Engineering with Databricks PresentationKnoldus Inc.
 
Databricks for MLOps Presentation (AI/ML)
Databricks for MLOps Presentation (AI/ML)Databricks for MLOps Presentation (AI/ML)
Databricks for MLOps Presentation (AI/ML)Knoldus Inc.
 
NoOps - (Automate Ops) Presentation.pptx
NoOps - (Automate Ops) Presentation.pptxNoOps - (Automate Ops) Presentation.pptx
NoOps - (Automate Ops) Presentation.pptxKnoldus Inc.
 
Mastering Distributed Performance Testing
Mastering Distributed Performance TestingMastering Distributed Performance Testing
Mastering Distributed Performance TestingKnoldus Inc.
 
MLops on Vertex AI Presentation (AI/ML).pptx
MLops on Vertex AI Presentation (AI/ML).pptxMLops on Vertex AI Presentation (AI/ML).pptx
MLops on Vertex AI Presentation (AI/ML).pptxKnoldus Inc.
 
Introduction to Ansible Tower Presentation
Introduction to Ansible Tower PresentationIntroduction to Ansible Tower Presentation
Introduction to Ansible Tower PresentationKnoldus Inc.
 
CQRS with dot net services presentation.
CQRS with dot net services presentation.CQRS with dot net services presentation.
CQRS with dot net services presentation.Knoldus Inc.
 

Mais de Knoldus Inc. (20)

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)
 
Azure Databricks (For Data Analytics).pptx
Azure Databricks (For Data Analytics).pptxAzure Databricks (For Data Analytics).pptx
Azure Databricks (For Data Analytics).pptx
 
The Power of Dependency Injection with Dagger 2 and Kotlin
The Power of Dependency Injection with Dagger 2 and KotlinThe Power of Dependency Injection with Dagger 2 and Kotlin
The Power of Dependency Injection with Dagger 2 and Kotlin
 
Data Engineering with Databricks Presentation
Data Engineering with Databricks PresentationData Engineering with Databricks Presentation
Data Engineering with Databricks Presentation
 
Databricks for MLOps Presentation (AI/ML)
Databricks for MLOps Presentation (AI/ML)Databricks for MLOps Presentation (AI/ML)
Databricks for MLOps Presentation (AI/ML)
 
NoOps - (Automate Ops) Presentation.pptx
NoOps - (Automate Ops) Presentation.pptxNoOps - (Automate Ops) Presentation.pptx
NoOps - (Automate Ops) Presentation.pptx
 
Mastering Distributed Performance Testing
Mastering Distributed Performance TestingMastering Distributed Performance Testing
Mastering Distributed Performance Testing
 
MLops on Vertex AI Presentation (AI/ML).pptx
MLops on Vertex AI Presentation (AI/ML).pptxMLops on Vertex AI Presentation (AI/ML).pptx
MLops on Vertex AI Presentation (AI/ML).pptx
 
Introduction to Ansible Tower Presentation
Introduction to Ansible Tower PresentationIntroduction to Ansible Tower Presentation
Introduction to Ansible Tower Presentation
 
CQRS with dot net services presentation.
CQRS with dot net services presentation.CQRS with dot net services presentation.
CQRS with dot net services presentation.
 

Último

Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 

Último (20)

Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 

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) ... }

Notas do Editor

  1. {}