by forkandwait · 15y ago · 0 comments
To teach object oriented programming as if it is theoretically foundational, or should precede simpler concepts is a nice bit of foolishness that lasted from excitement over Smalltalk to, say, last week.
I think the blossoming of GUI's -- which have A LOT of state -- is the historic reason for the excitement over OOP, not any theoretical advantage to OOP.
"if a bunch of code needs to retain state, make it an object"
well, a FP wizard might argue that most problems don't need stateful code to solve -- our decision to use stateful patterns is an implementation detail.
MVC is not inherently OO - it's more about sending messages which, although a feature of modern OO (Alan Kay even said that he should have called OO Message-Oriented programming), is not its defining feature (as we see it used today).
Since the Model, the View and the Controller are just continually processing and sending messages, you could easily implement them as processes (say as in Erlang). A processes's state is then retained in immutable structures passed to recursive invocations of its main message loop (sorry if this sounds opaque - I'd recommend seeing how it's done in Erlang).
Another GUI approach to FP that is being researched is functional reactive programming. There is a neat Javascript implementation called FlapJax. You could probably argue that FRP is a generalization of MVC (though I'll hedge my statement since I'm not 100% sure of this).
I don't think GUI's have to have a lot of state.
I wrote a Haskell library (https://github.com/Peaker/vtywidgets) which can serve as a proof-of-concept of a "stateless GUI".
The idea is that a widget is a pure function like (in pseudo-Haskell syntax):
input_from_program ->
(output_to_user,
Map input_from_user
(documentation, output_to_program))
A "Map" is a dictionary. It's like a function, but its domain can also be enumerated so we can generate useful documentation about how a widget responds. So a Widget takes program and user inputs, and generates program and user outputs.Any state (e.g: cursor) will be saved elsewhere, and I've come to the conclusion that separating "GUI state" from "model state" is not a good idea. This allows me to use the "cursor" of a box of widgets as an active selection, and not just a way to navigate, for example. It also means that I can use the same persistency model/etc for the GUI as I do for the model.
I wrote a simple (again, still at the POC stage) transactional, structural, revision-controlled editor based on vtywidgets (https://github.com/Peaker/treeedit), and it persists the model, including the GUI state, in the transactional database. This means that I get undo features for GUI state (I can store it outside the revisioned store, but it's quite nice to have), and if I kill the editor and restart it later, it is at exactly the same state it was before.