20.3. Think “Expression-Oriented Programming”
Problem
You’re used to writing statements in another programming language, and want to learn how to write expressions in Scala, and the benefits of the expression-oriented programming (EOP) philosophy.
Solution
To understand EOP, you have to understand the difference between a statement and an expression. Wikipedia provides a concise distinction between the two:
“Statements do not return results and are executed solely for their side effects, while expressions always return a result and often do not have side effects at all.”
So statements are like this:
order
.
calculateTaxes
()
order
.
updatePrices
()
Expressions are like this:
val
tax
=
calculateTax
(
order
)
val
price
=
calculatePrice
(
order
)
On Wikipedia’s EOP page, it also states:
“An expression-oriented programming language is a programming language where every (or nearly every) construction is an expression, and thus yields a value.”
As you might expect, it further states that all pure FP languages are expression-oriented.
The following example helps to demonstrate EOP. This recipe is similar to Recipe 20.1, so it reuses the class from that recipe to show a poor initial design:
// an intentionally bad example
class
Stock
(
var
symbol
:
String
,
var
company
:
String
,
var
price
:
String
,
var
volume
:
String
,
var
high
:
String
,
var
low
:
String
)
{
var
html
:
String
=
_
def
buildUrl
(
stockSymbol
:
String
)
:
String
=
{
...
}
def
getUrlContent
(
url
:
String
)
:
String
=
{
...
}
def
setPriceUsingHtml
()
{
this
.
price
=
... ...
Get Scala Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.