Dear gurus,
I was recently thinking how I'm not always using the beautiful concepts of OO when writing Pythonic programs. In particular, I thought I'd be interested in seeing a language where I could write the typical web script as
# Fictional language
# This script's combined effect is to transform (Template, URI, Database) -> HTTPOutput
HTTPOutput:
HTTPHeaders + Maintext
Flags: # This is a transform URI -> Flags
value = URI.split('?').after
refresh = 'r' in value
sort = /sort=([a-z])/.search(value)
HTTPHeaders: # This is a transform Flags -> HTTPHeaders
'Content-type:...' + Flags.refresh ? 'Refresh: ...' : ''
Maintext:
Template.replace('$questions', PresentedQuestions [:20] )
Questions:
(Flags.sort = 'r') ? RecentQuestions : TopQuestions
PresentedQuestions:
Questions % '<h4>{title}</h4><p>{body}</p>'
RecentQuestions:
Database.Questions . sort('date')
TopQuestions:
Database.Questions . sort('votes')
See what happens? I am trying to make as many objects as possible; each paragraph declares something I call transform. For example, there is a transform HTTPHeaders
. In an imperative language that would be a declaration of class, object and function combined:
class HTTPHeaders_class
{
public char* value
HTTPHeaders_class()
{
value = ... + Flags.refresh ? + ... // [1]
}
}
class Flags_class
{
public char* flagstring;
public bool refresh;
...
Flags_class()
{
value = ... /* [3] */
refresh = ...
}
}
Flags = new Flags_class (URI)
HTTPHeaders = new HTTPHeaders_class (Flags) // [2]
However, I want to have no way to specify that an object should change unless the inputs from which the objects is made change; and no way to have side effects. This makes for a drastic simplification of language. I believe this means we're doing a functional programming ("a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data").
I certainly try to use things like Python classes, M-V-C framework and Django (thanks to the answer), but I don't think they have the concepts above and below.
- Each object has a
value
field that can be referred just by writing the class name. - If
HTTPHeader
is referred somewhere, this means that a static, unchangeable objectHTTPHeader
is created as soon as possible. All references toHTTPHeader
then refer to this object. - Suppose I want to repeat the program with the same
URI
object while the interpreter is still in memory. SinceFlags
depends only onURI
andHTTPHeaders
only onFlags
, those are not recalculated. However, ifDatabase
is modified, thenQuestions
need to be recalculated, and thus theHTTPOutput
may change too. - The interpreter automatically deduces the correct sequence of initializing the classes. Their dependency must form a tree for that to happen, of course.
I believe this will be a useful models for programs like web scripts where there are no side effects. Is there a useful language where one writes program similar to this already?