Reputation: 16755
I want to write a piece of code (in Functional Programming Style) which should keep track of whether a user is logged in or not. I suppose I have to do things in immutable way.
Following pseudo code seem functional. It takes a state and returns its reverse value. It hasn't got side effects
changeState(Boolean state){
return !state
}
Somewhere in my logic, once the user logs in (or logs out), I'll call the above function passing it current value of logged in status. I am unable to think of how to store logged in status in Function way. This is wrong because currentLoggedState is val
val currentLoggedState = false;
//user entered login details correctly, change state
currentLoggedState = changeState(currentLoggedState)
How can I write such logic in Functional way?
Upvotes: 2
Views: 622
Reputation: 9698
State cannot be avoided. Point of functional programming is to enable better reasoning, not to make a purely mathematical model from your program.
For example, database is literally one giant state storage. When you're creating, updating, deleting etc. you are manipulating some state.
There are environments (such as akka actors model) where state is unavoidable as well. Try implementing a non-trivial system with actors and I guarantee that you'll have your actors full of lists and hashmaps. At some point it becomes inevitable. For example, even Coursera course held under the courtesy of EPFL, called "Reactive programming" (it's been renamed to FP Design in Scala or something like that), had a section held by Roland Kuhn himself and it involved working with actors and throughout the course assignments there was a shitload of state. I'm saying this to let you know that there are authoritative people in the Scala community saying that sometimes state cannot be avoided.
In your situation, it's best if you can push it to Redis or a similar storage, so that state is not present in the code itself (only mutability would be the persistence layer / storage).
Upvotes: 4