FunHop : What Are These Side Effects?


FunHop is imagined as a series which allows us to gradually hop into the realms of Functional Programming. Our vehicle for the journey is going to be Scala but the fundamentals are applicable across languages.

In this episode we would try to decipher Side Effects. We keep hearing that pure functions are the ones where there are NO side effects. Let us begin with an example.

Do you see any side effect in this code?

case class Money(var amt: Int) {
  def add(anotherAmt: Int): Money = {
    this.amt += anotherAmt
    updateBankRecords
    this
  }
  def updateBankRecords = println("Connect to Bank & Update records")
}

If you guessed that it is using var instead of val, we are mutating thus causing a side effect then you are wrong. Ok, a hint is that you can read about the Single Responsibility Principle and then come back and answer this one.

As you would notice, the method “add” returns a Money object. However, it also makes a call to updateBankRecords. This doing some operation on the SIDE and is not returning that SIDE EFFECT as a part of the return type. Here, anything to do with the Bank Update is not a part of the return type.

What do you think happens, if we comment out the line “updateBankRecords” from the “add” method? Would the compiler complain? No, it would not!

Hence, you know if you have side effects if

  1. If you take out / comment certain portion(s) of the logic, the compiler does not complain.
  2. Testing the code is tough – Here it would NOT be easy to test “add” method because every test would end up calling the “updateBankRecords” and we would have to get into mocking.

How can you be sure that your method is not having side effects?
If you can replace the return type of a function to any function which takes it as an argument and PRODUCES EXACTLY THE SAME RESULT, then you can be confident that it is a pure function. In other words if f(a)=b and if we have g(x)=a then f(g(x)) should give us b.

So for example, look at the code below

object StepOne extends App {
  val money1 = new Money(10)
  private def showMeTheMoney(m:Money)= println(s"Your money is $m")
}
case class Money(var amt: Int) {
  def add(anotherAmt: Int): Money = {
    this.amt += anotherAmt
    updateBankRecords
    this
  }
  def updateBankRecords = println("Connect to Bank & Update records")
}

We have a method called “showMeTheMoney” which takes an argument which is Money. What would you think would be the output of

showMeTheMoney(money1) // Your money is Money(10)

showMeTheMoney(money1.add(0)) // Connect to Bank & Update records
// Your money is Money(10)

Here, results are different even though money1.add(0) gives the same money (ok, == match, i.e. money1 == money1.add(0))

Ideally, if they behave the same then we have a pure function. In this case the method “add” is impure because it results in a side effect -> Connect to Bank & Update records

This way, we would be able to distinguish between a pure and impure method.

Thus, we quickly saw the indications which tell us if we have a side effect and then we did a confirmation to see if that is indeed the case.

Any of the following would constitute a SIDE EFFECT

  • Variable reasignment
  • Changing field of an object
  • Moving outside the boundary of unit, like writing to console or file

The starter code is present on the Knoldus Github account.

About Vikas Hazrati

Vikas is the Founding Partner @ Knoldus which is a group of software industry veterans who have joined hands to add value to the art of software development. Knoldus does niche Reactive and Big Data product development on Scala, Spark and Functional Java. Knoldus has a strong focus on software craftsmanship which ensures high-quality software development. It partners with the best in the industry like Lightbend (Scala Ecosystem), Databricks (Spark Ecosystem), Confluent (Kafka) and Datastax (Cassandra). To know more, send a mail to hello@knoldus.com or visit www.knoldus.com
This entry was posted in Scala and tagged , . Bookmark the permalink.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s