The building blocks of FP: pure functions, immutability, and Referential transparency -Part 3-

An expression is said to be referentially transparent if you can substitute it by its output at any time without changing the behaviour of your program. In order to do that for all expressions of your code base, all your functions have to be pure and all your variables have to be immutable.

How does that work, let’s take an example

def getUserName(id: Int): String = {
  val name = "Some random name $id"
  println("Log: Requested user: $name")
  name
}

can we replace the call by it’ result

//is
val res = getUSerName(5)
//the same as
val res = "Some random name 5"

Well obviously the result is different because we are writing to the log, that’s a side effect .
What about if we rewrite it this way :

def getUserName(id: Int): (String, String) = {
  val name = "Some random name $name"
  val sideE = "Log: Requested user: $name"
  return (name, sideE)
}

Now the substitution would work, all the side effect are reflected in the return type

Generally encountered side effects

As functional programing aims at removing side effects, it is reasonable to name some of them

Error: It is produced in your program when something goes wrong, it is modeled by an exception, if unhandled it will propagate to the parent program and disturb the execution.

Absence of result: Lets imagine we try to retrieve an user from the DB by Id, the user doesn’t exist in the imperative code we would return NULL, although the compiler is expecting an object, this is force us to have the overhead to remember to test the code

Delay and async computation: Making an http call might block other threads, the fact that you wait or a specific long-running operations a side effect.
usually, when something in a program is not apparent, this indicates need for abstraction.

In/Out operation: they are side effects because they depend on the environment, does the file exist ? do we have access to the file ? ….

Logging: Just like the IO operations logging depends highly of the external environment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s