Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is functional programming good? [closed]

I've noticed that there are certain core concepts that a lot of functional programming fanatics cling to:

  • Avoiding state

  • Avoiding mutable data

  • Minimizing side effects

  • etc...

I'm not just wondering what other things make functional programming, but why these core ideas are good? Why is it good to avoid state, and the rest?

like image 495
Bob Avatar asked Feb 29 '12 06:02

Bob


2 Answers

The simple answer is that if you don't have extra state to worry about, your code is simpler to reason about. Simpler code is easier to maintain. You don't need to worry about things outside a particular piece of code (like a function) to modify it. This has really useful ramifications for things like testing. If your code does not depend on some state, it becomes much easier to create automated tests for that code, since you do not need to worry about initializing some state.

Having stateless code makes it simpler to create threaded programs as well, since you don't need to worry about two threads of execution modifying/reading a shared piece of data at the same time. Your threads can run independent code, and this can save loads of development time.

Essentially, avoiding state creates simpler programs. In a way, there's less "moving parts" (i.e., ways lines of code can interact), so this will generally mean that the code is more reliable and contains less faults. Basically, the simpler the code, the less can go wrong. To me this is the essence of writing state-less code.

There are plenty of other reasons to create stateless, "functional" code, but they all boil down to simplicity for me.

like image 122
Oleksi Avatar answered Oct 05 '22 02:10

Oleksi


In addition to what @Oleksi said, there is another important thing: referential transparency and transactional data structures. Of course, you do not need a functional programming language to do so, but it's a bit easier with them.

Purely functional data structures are guaranteed to remain the same - if one function returned a tree, it will always be the same tree, and all the further transforms would create new copies of it. It's much easier to backtrack to any previous version of a data structure this way, which is important for many essential algorithms.

like image 40
SK-logic Avatar answered Oct 05 '22 02:10

SK-logic