Question

I've been comparing the advantages of Scala over Java for concurrent programming.

Obviously the first point I came over is Scala is a functional programming language(partly) using FP avoids side effects naturally

Compared to imperative language how side effects are avoided in functional programming and how it works on multi-threaded/concurrent programming ?

Was it helpful?

Solution

What that statement means is, I think, that Scala as a functional-OO hybrid language encourages (and sometimes enables) you to use functional constructs and rules which will result in no side effects. You can well enough write non-functional stateful Scala code with side effects ;-) On the other hand you can try to write functional Java (for instance) but since functions are not first class objects there it might just look ugly. So I wouldn't say it does so naturally but more like helps you in some ways and overall encourages you to do so.

Well there are several principals which you should stick to when doing functional programming which in result give you no side effects:

  • immutable is good - prefer structures that are once created and cannot be modified. For instance in a Java list you can modify an n-th element but in Scala you return a copy of that list with the new element. Yes this might mean more objects in your programme but should also result in more reusable and safer code.
  • pass values as parameters, don't store state in member variables - shared state is a reason for many problems and managing shared state is problematic (for instance you need to use locks etc.)
  • prefer recomputing values IF it is cheap, instead of caching them (this has some exceptions to the rule for instance http://en.wikipedia.org/wiki/Memoization is a pretty frequently used technique!)

Actually one of the biggest benefits of avoiding side effects by following the above rules is easier concurrent programming! The biggest hurdle in concurrent programming is managing shared state, after all!

Since one of the rules is that mutable and shared states are bad you don't use it! Instead many functional languages (such as Erlang or Scala) prefer the so called Actor model where Actors (which you can compare to threads) communicate only by sending messages to each other (see? passing values instead of storing them somewhere!).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top