Functional Programming: Immutability

This is where functional programming can seem to be quite inaccessible to Java developers. As a Java developer we are used to distinguishing between that which is stateful and therefore an object and that which is stateless and can be just a class variable or method. To try to write our everyday code without anything mutable seems almost impossible. It isn’t but does rely on having to think carefully about how we write our functions.

In Scala, state and mutability become the following concerns:

  • Mutable variables should be avoided unless completely necessary.
  • Functions should not have side effects – running a true function for a given value should always return the same value and have as small a footprint as possible.

Constants

One part of avoiding side effects is favouring constants over variables. In Scala the two are declared using different keywords – var will create a variable, val will create a constant.

Java

final String pageName = "login";
int index = 0;

Scala

val pageName = "login"
var index = 0

Writing code without variables can be particularly hard but, with Scala allowing code written in the Java style, is not entirely necessary.

No Side Effects

This means writing code that has a minimal footprint, it hopefully does not matter how many times a method is run, the return value is always the same and it does not affect its environment. In practice this tends to be about writing atomic, encapsulated methods. A key principle of functional programming in Scala is avoid shared state.

This is a bigger subject than this blog post might suggest and this is just an introduction. Avoiding variables can be incredibly hard and also has a big part to play in another big subject in functional programming – recursion.

Advertisements

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