Software has two ingredients: opinions and logic (=programming). The second ingredient is rare and is typically replaced by the first.
I blog about code correctness, maintainability, testability, and functional programming.
This blog does not represent views or opinions of my employer.
Showing posts with label imperative programming. Show all posts
Showing posts with label imperative programming. Show all posts

Saturday, October 18, 2014

I don't like Hibernate/Grails part 10: Repeatable finder, lessons learned

Repeatable finder (concurrency issue described in part 2) is what started/motivated this series. I had hoped that that this issue will draw some reaction from the community. It did not. Why? Tallying up all the answers/responses from the last 2 moths amounts to: 6, none of them useful or even correct. What does that mean?

In this series I tried to sneak in some things that interest me like FP and logical reasoning of code correctness.  I will use repeatable finder problem as a way to sneak in a bit more of this stuff later in this post.

Denial isn't just a river in Egypt?
This has been a twilight-zone.
To refresh you memory:  if more than one query is executed in a single Hibernate session and the result sets intersect then the second query returns a weird combination of old and new data.  That can break the logic in your code,  for example:
       Users.findAllByNickName('bob')

can return records with nickName != 'bob'. Other things can go wrong too: Maybe you have used a DB unique key to define equals()?  Or maybe you have used a DB unique key as a key in a Map? Any of this could go very wrong.

At first, I thought that the issue must be well know and I am missing some way of handling it. This, unfortunately, is not the case. Very recently, I came across this blog from 2009: orm-sucks-hibernate-sucks-even-more
"... take a look how even a silly CRUD application would suffer, once you've got "not-very-recent" object from the session"
that quote points to a (now non-existing) page on the hibernate website. Did we know more in 2009 that we know now?  If we did know, why have we allowed for this issue to stay unresolved? Well, this is all speculation.

I tried my best to do 2 things:  make the community aware and persuade Hibernate to fix it. I have failed miserably on both accounts. Here are the results of my efforts (as of Oct 17, 2014, tallied after a bit over 2 months since I started my crusade):
  • post part 2:  effectively no replies, but over 1100 reads.
  • Grails JIRA: incorrect comments and then ignored
  • Hibernate JIRA:  rejected (works as intended) with suggested work-around which is incorrect
  • Stack Overflow question:  a whooping +4 score (started at -1) and bunch of incorrect or meaningless answers
  • Grails forum: 0 replies
Hibernate ticket was the weirdest experience.  It got rejected very fast (not a bug) with a comment to just use refresh().  After pointing out that this workaround is a total nonsense, I was sent to read some completely not relevant documentation about concurrency.  After that, my (and Tim's) comments have been ignored.

What can I conclude from these 3 facts?:
  • nobody seems to know how to resolve or even work-around this issue
  • experts provide advice that is incorrect
  • there is no interest in solving, discussing or even acknowledging it as a problem
I do not know, but probably nothing good. I think it is interesting to try to puzzle out the few responses that the problem did generate. I will try to do that here.

The replies I got from the expects fall into 2 categories. The first category are answers like this:
  • It is any ORM issue
  • Any database application will have an issue like this 
It is true that the issue can be resolved with DB locking.  In particular, I could prevent repeatable finder by having all HTTP requests wrapped in long transactions and configuring higher (repeatable read) isolation level. Indeed, it is a big framework design failure, if we need to resort to things like this.
It is NOT true that any ORM and any database application will have this problem.  The most likely explanation for this type of response is that developers do not think about side-effects. They see Hibernate query and think of a SELECT statement only.  If I see a problem, it must be from the SELECT, where else would it come from?  This is consistent with the point I tried to make in my previous posts.

The second category are answers that suggest using refresh() or discard() to fix the problem:
'To fix your problem'
  • add refresh() to your code
  • or:  add discard()/evict() to your code
My first reaction was: Grrr, my second:  Hmm.  If I could only continue this conversation I am sure it would go like this:
Me: Where do I add these?  Expert's Reply: Add them where you have that problem. 

If you have been following various Hibernate discussion forums, you must have noticed that the same type of advice (either to add refresh() or to add evict()) shows up very frequently. This advice is never right.

Grails and Hibernate experts:  I am very disappointed in you.

Add refresh()...  add evict()... Thinking in Hibernate.
(Here is where I sneak-in some interesting stuff.)
This is how we typically reason about our code: the problem is on line 57 because variable xyz is ... and then on line 89 we do that..., and then on line 127 we have an if statement that goes like that...
We reason about our code by examining chains of programming instructions.

This is called imperative thinking and imperative programming.  If you read my previous posts you may assume that I consider such programs not logical,  they are logical, only the logic is very cumbersome and complex.
A well designed OO program is where lines 57, 89 and 127 are all in the same class and the chains of instructions we need to examine are relatively short.  In a procedural program lines 57, 89, and 127 can be anywhere and chains are long.  Badly designed OO programs behave like procedural programs.

Repeatable finder is a great example where imperative reasoning fails.  The problem is not something between lines 57 and 89 or something on line 115.  The problem is (or can be) anywhere.
Answer 'add refresh()' or 'add discard()' is a very imperative thinking: it assumes I can add it on line 89.  (I can only conclude that this expert advice is not to sprinkle refresh() all over my code just for fun ... and because my code will run too fast without it.)

So what is the alternative?  The idea is to think about a block of code in a way that can prove certain behavior of that block. If we know that a code block 'A' exhibits the same behavior no matter where it is placed or how is used, then we no longer need to think about lines 57, 89, and 127 or about chains of computing instructions.

This is called declarative thinking and programming.  Logical reasoning is now simplified, I no longer need to follow chains of programming steps to reason about the correctness.

Declarative thinking works great, except, if I cannot trust any property, even that:
    Users.findAllByNickName('bob').every{it.nickName == 'bob'}
then I am stuck.
That may sound like a limitation of declarative programming:  I can still keep going using imperative approach. That is true, and we all 'keep going'.  I did not stop programming my project and no, I did not add refresh() all over my code. That is why our applications are so buggy: we ignore logical problems unless we can pin them to line 127.

Side Note: The fun starts when I start combining my declarative code blocks into bigger blocks. Code needs to be logically composable.  I want a bigger block (composed of smaller blocks) to have properties too. Some like to call it programming with combinators.

Conclusions:
I would like to suggest this as a new rule of thumb: 
  the answer to use Hibernate/GORM refresh() or evict()/discard() is wrong regardless of the question.
(with exception of Functional Tests - which may need to refresh some records used in asserts).  Please comment below if you find a counter example to this rule.

I am not claiming that I know the solution to Repeatable Finder.  Maintaining Hibernate cache synchronized with the DB is hard, maybe impossible.  One way of dealing with hard problems is: make them somebody else's.  If GORM/Hibernate just told me when the query is lying (returns stale data even if it has new data) or allowed me to request/configure the query to refresh all records... That would go a long way.

It looks like the community has decided to not acknowledge Repeatable Finder as a problem. There is really no good solution for it and acknowledging it would be admitting to that fact. This issue is likely to remain unsolved and ignored. More complex Grails apps are doomed to work incorrectly under heavier concurrent use.

I have added a label to my posts (which does not work so do not click on it - and that convinces me that blogger must be using Hibernate):  'Stop thinking in C++ and Java'.  I think we need to stop thinking imperative or at least stop thinking only in imperative terms.

Next post:  I need to do one more to wrap-up. I will be finishing this series next week.

I have a busy period ahead of me.  I started going over a set of courses published online by University of Oregon (Oregon Programming Languages Summer School) and that will be many hours of not very easy listening and learning.  I also have to start preparing/training for a ski camp in early November (I live in CO and skiing has started here already).  No, this will not be a SKI calculus camp;) - but then, believe it or not, technical skiing is (or should be) a fun intellectual activity too.

Saturday, May 25, 2013

Better Polymorphism. Polymorphism where apples are not oranges.

Subtitles:   - Polymorphism without curly braces.  - Lifting == next polymorphism.   - How to program your bike tube.  - Grandparent of Functional Programming.


I have finished my last year posting by writing about polymorphism, I want to start on the same subject and do a better job.  This is the longest post I ever wrote and I hope the longest I ever will.  I hope you will find it interesting and Thank You for reading!

POST INTRO:
- 'Doctor, each time I see a code like that in Groovy
  def listX = listY.collect{ ... }

 I see a torus and want to ride my bike.' 
- 'Oh no! you have a case of Polymorphism'

This post is not about what polymorphism is.  It is about what polymorphism can be.

POST BODY:
Definition: For an OO programmer polymorphism means a more sophisticated version of a cookie-cutter.  Typically this term is associated with the idea of applying the same 'thing' across many different 'things'.  I want to define it as Apply concept A to a set of concepts X. Most often A will be an operation/method (or a set of these) and will describe some type of a behavior, so a developer can say that A can be polymorphically applied to set X.

Classic OO imperative polymorphism suffers a bit from weak semantics where 'A' does not really mean 'A'. To achieve a 'Better Polymorphism' we will need to work on stronger semantics. Most interesting stuff happens when X contains bunch of different things and A provides a 'viewpoint' on all the things in X, but the essence of 'A' stays intact in some way. These are the cases which go beyond interesting and become an eye opening intellectual experience.

Classic Examples of OO Polymorphism: As I said, OO polymorphism is typically semantically weak:  apples become oranges so we can make ourselves a polymorphic screwdriver.
One set of such examples is when X=everything. If you can say something about everything then it is either obvious or incorrect.  Still, many programming examples do exactly that:
In obvious category:
Java Object.toString(): A='describe yourself', X=anything
In incorrect category:
Java Object.equals(Object o): A='concept of being equal', X=anything
(Why do I think that is incorrect?  Why would you think a meaningful equals comparison is always possible computationally or even logically? But that is a longer story well beyond this post ...)  
In Java, 'equals' becomes something less than what the 'real equals' should be.
More interesting example: C++ or Groovy overloading of +:   A='+ operation', X includes numbers, strings, collections, maybe a timestamp and duration, whatever else programmer decides makes sense with '+'.
This is all very imperative, programmer 'implements' and decides what '+' means.  So often '+' becomes just a neat syntax and any deeper 'essence' of '+' is lost. 

Polymorphism in Other Sciences?  Can software engineering learn something new about polymorphism from other sciences?  My examples will have a heavy bias on math, because math was my strong interest in the past and I still remember a little bit about it. I challenge you to come up with your own examples.

Partial Differential Equations (PDEs) offer many examples fitting well into my definition of polymorphism.
PDE Example 1: Often the same family of equations is used to model a range of totally different concepts. It maybe no surprise that the same set of equations models gas flow and traffic congestion. It is much harder to grasp that the famed Black–Scholes formula for pricing stock options (in Finance) is really a time-reversed (or backward) heat equation (in Physics)!
So: A=single PDE, X=parts of Physics, Finance and maybe other parts of science.
The essence of that PDE is described by the PDE itself, it is the same equation, yet it can be polymorphically applied to a large set of examples.  This is 'semantically strong' and often eye opening!
PDE Example 2: Once upon a time, I wrote a paper studying convergence of numerical solutions to a system of PDEs called Broadwell Model. I studied these using ... fractals.
So A=fractals, X=a PDE model in gass dynamics.
To do that I had to, of course, do more than just to start using fractal lingo when talking about PDEs (that would be nonsense).
PDE Example 3: Compensated Compactness Theory studies convergence of solutions to PDEs using ... measure theory.

Let us move on to something else than PDEs (or is it something else only because we have not found a polymorphic enough way to look at it yet? ;) ).
Grandparent of Functional Programming: There is this super cool part of math called Algebraic Topology.  This branch of math is just one big polymorphism and is one of the most intellectually stimulating pieces of science I have ever seen.
Algebraic Topology transforms manifolds (geometrical and topological concepts) into groups (algebraic concepts). I remember using phrases like 'thinking in CAPS' or 'functorial thinking' to describe the overall idea of such high level transforming.  I was not much into programming at that time so the term polymorphism did not cross my mind.
Still, the definition of polymorphism is matched perfectly (A=Algebra Groups, X=Manifolds). 
Many things that have been extremely hard to prove for an orthodox topologist became almost trivial to do in algebra.  This polymorphic approach offered by Algebraic Topology was a game changer in understanding of manifolds and lead to discovery of a lot of very cool math.

Algebraic Topology does its transforming in several different ways. These include concepts like homology, cohomology, homotopy .... All of these are a way to map a manifold into an algebra group preserving the 'essence' of that manifold in some way.

Side Note to get some intuition about what Algebraic Topology is about: 2-D sphere is totally different than 2-D torus (think of surface of a tube in your bike).  Both are hollow but in a very different way! 
On the sphere, all closed loops can be shrinked to a point so H1 (single dimension homology) is trivial.  On the 2-D torus you can draw loop around each of the 2 perimeters and you can start adding these loops (groups are about adding things) by rotating around one perimeter n-times and around the other k-times.  You can stretch and shrink these loops all you like, they will still rotate around torus perimeters the same number of times. So H1 of 2-D torus is the same as product of all Integers (understood as a group with + operation) with itself!

There are many other examples where concepts in one branch of math are used to solve problems in another branch...  but I need to stop, this post is not about math.

Another Side Note: I hope I did not lie too much. This post brought some very fond memories, but I have not done math, and Algebraic Topology in particular, for so long.

Functor:  We need something which is good at 'transforming concepts preserving essence of things'.  The name I am thinking about here is 'Functor' and all the transformation used in Algebraic Topology (homology, cohomology,  ...) are, in fact, functors.  (Not to be confused with C++ concept using the same name).

Functors have been studied on their own by a branch of math called Category Theory (I never embedded myself much in it).  Category Theory is arguably the parent of Functional Programming.  If that is so, Algebraic Topology is the grandparent. And that is the coolest grandma any science can have!

Before we move on, I would like to assert one observation, science seems to have no use for semantically weak polymorphism, it cares that A is still A in some deep way and that it is not just a name universally applied to different concepts.

Functor Definition:  So what is a functor?  Here is a wikipedia link for you: http://en.wikipedia.org/wiki/Functor  The most intuitive way to think about it: functors are for mapping things over. It must map identity into identity and preserve morphism composition (think for now that morphism==function and 'o'is function composition). The covariant functor definition rules are copied here:

  F(id) = id
  F(f o g) = F(f) o F(g)

Functor in Programming!: Can you think of a functor in programming?  There are actually a few of them but I will just explain one:  Think of transforming which works on a very high level (remember this is a high level thinking, thinking in CAPS).  Think of transforming types, one type into another. One such transform is  
  T -> List < T >
I like the [] notation so I will call this transform (or mapping):
   []: T -> [T]
but Java hardcores should read this as List: T -> List < T >
(which with Java type erasure means nothing, but well, still makes some sense, right?).

There is a method in Groovy working on collections called 'collect' and it's equivalent is typically called 'map' in other languages. Here is an example usage:
  assert [1,4,9] == [1,2,3].collect {it*it}

I am sure you agree that: 
Closure id = {it}
assert anyList.collect(id) == anyList == id(anyList)

and that is the first rule for being a functor. Let test the other one using an example:
assert [1,5,3].collect(it-2).collect(it * it) ==
       [1,5,3].collect((it-2) * (it-2))

Yes, Groovy's collect makes [] into a covariant functor!

Better Polymorphism (using Functor): Now since the [] operation preserves 'essence' of things, I should be able to use it.  Suppose I want to lowercase all elements from a list of strings.
You could write this:
   def lowerCaseList = ['HELLO', 'THERE'].collect {it.toLowerCase()}

but that is just missing the point altogether (and it uses evil curly braces). I want to be able to write something closer to the following (because functors preserve essence of things):
   def lowerCaseList = ['HELLO', 'THERE'].toLowerCase() 

the idea is that the function is magically lifted or mapped over by the [] functor so it can operate on functor values.  After all, compiler should know that [] is a functor!
Maybe in the future... for now, at least in Haskell, you could do something like this
   lowerCaseList = (fmap toLowerCase) ['HELLO', 'THERE']
  
That is some polymorphism for you!!!  Think of different functors ([] is just one example) and ability to write a cookie-cutter code across all of them.  Examples are Maybe (a concept replacing handling of null values) and Either (concept of handling error conditions without ugly try-catch).  You code might even end up working on the tube in your bike!  (think of a changeMe function ;).  

Even Better than Functor! (== Better than Better Polymorphism):  Functor is not the end of the story for 'preserving the essence of things' as far as programming goes, it is the begining.
There are 2 stronger super-concepts:  Applicative Functors improve upon Functors and  Monads improve upon Applicative Functors.

The idea is that I do NOT want to implement '+' operation on lists! I want the language just to know what to do!  If I know what 1+4 is and 1+5 is, etc I should automatically know what [1,2,5] + [4,5] is!  There is a little issue with using plain functors because they do not understand interactions between elements.  This is where Applicative Functor solves the problem!

It turns out that there are two natural ways to make [] an Applicative Functor (and I wrote a bit about both in my previous post).  Here is the recap: one way is so that:
  [1,2,5] '+' [4, 5]=[1+4, 1+5, 2+4, 2+5, 5+4, 5+5]

(this is called non-deterministic computing)
and the other works so that:
  [1,2,5] '+' [4, 5] = [1+4, 2+5] 

(these are zip lists).  Haskell has decided to make [] into non-deterministic computing and created a separate type called ZipList to handle the other case.
Now we could 'lift' any two or more argument operations automatically!  There is some extra typing involved in Haskell (you cannot just say [1,2,5] + [4,5]) but the work is really done for you and this extra typing is minimal.

I need to stop somewhere so I am not even going to try to define Applicative Functor. 
We have done a full loop, from OO imperative '+' example to the '+' example preserving the 'essence' of '+'.  

POST SUMMARY:  So all this transforming can lead to a very interesting polymorphism.  List is polymorphic with a tube in your bike!  So how is that useful?  I think some points are worth reiterating:

(1) The fact that mathematical concepts like homology are polymorphic with several programming concepts (like homogeneous lists, handling of nulls (Maybe) or handling of error conditions (Either)) is very much an eye opener.   That means that, in particular, we could write code that works across all these concepts!   In fact, Functor is a class type (kinda like interface) in Haskell.   OK, there is probably not that much that can be coded at such high level of abstraction, but more coding is possible (and done) against Applicative Functor (also a class type in Haskell) and even more against Monad (again a class type).  This is a true high level coding in CAPS!

(2) And these concepts are not apples and oranges polymorphic, they are 'better polymorphism' because they preserve the essence of things is some way.  That means we can 'lift' functionality.  If you wrote a library that does interesting things with type T, a lot of your work could be just 'lifted' to [T] (or any other Functors mapping T)  ... and even more of your code will 'lift' for free to any Applicative Functor.

(3) Let me emphasize the 'lifting' point.  'Lifting' is the next level of polymorphism.  This concept is equivalent to some of smartest parts of math ever,  Algebraic Topology lifts algebra into topology.  Other math examples lifted Measure Theory  or Fractals into PDEs.
But wait, examples with PDEs did not use functors!  What I am trying to say is that functor is not the only way to lift.  It is however the only way to lift I know in computing.

I hope you enjoyed this post.  It has been written by a newbe Functional Programming enthusiast, but  it covered some less than trivial stuff (maybe this is a risky combination).  It also was opinionated like my other posts, but I hope opinionated in a good way :).  And I hope it offered a unique perspective even to some Functional savvy developers.

By the way, did you notice that my post is visually organized into 3 sections making it polymorphic with other writings using this important presentation guideline.   You think that is cool,  NO, it is not cool!   That is just a contract-based, imperative, old style polymorphism, Gotcha! ;)

Thursday, July 5, 2012

Imperative curlies 9: Haskell


If you read any of my posts about bashing curly braces and you worked with Haskell then I am sure you have thought: wait until someone shows Haskell to this guy. Well you have been right.

I am reading Learn Youa Haskell for Great Good! by Miran Lipovaca. My pride got bruised because of the book subtitle: Beginners Guide. The guy showing me Haskell is a university student from Slovenia. I may have been a bit skeptical when buying a copy but I am more than happy. If only any of the semantic web writers knew how to write as well as Miran (my semantic web reading or struggling through it is another story).

Haskell learning in many ways revalidates my opinions.  The concept sitting behind curly braces in Java practically does not exist in Haskell. 
If you see curly braces {} in Haskell you probably reading record syntax.  The underlying dislike of the imperative code simply permeates throughout the language.

I think learning Haskell is a must do exercise for every imperative programmer like myself. It is an eye opening experience to see a language where if-else statement (even though unpopular in Haskell) is really a function (well so it is in SCALA, but it is more in Haskell ;). You will start thinking of Java if statements as ugly conditional side-effects.  You will think of Java for-loops as ordered collections of side-effects. You will because, well, they are.

So go get the book and enjoy it as much as I do.

Wednesday, March 28, 2012

Imperative curlies 2: GRAILS/GORM

Continuation of Previous Curlies bashing
GRAILS Domain Classes and GRAILS plugins can provide phenomenal examples of declarative programming where a simple declaration adds lots of functionality without any coding. Still the programmer is faced with choices, for example, custom domain class validation can be either done by hand (with curlies) or in a nice reusable way using more functional and declarative programming.

Here is a simple domain class to start:
1:  class Meeting {
2:    Date start
3:    Date end
4:    String title
5:  }

Looks like little ventured, little gained, but these looks are very deceiving. The above domain class is a feature rich hibernate DAO. You can do with it things like:
Meeting.findAllByStartBetween(new Date() -7, new Date())
or
Meeting.findByTitleLikeAndStartGreaterThan(…)
On a side note: this is a true Groovy magic. These methods do not really exists, in Groovy a class responds to a method, it does not necessarily have a method.

Add the following plugins to your grails project: audit-trail, spring security core, and searchable. Add simple declarative changes to the Meeting class:
1:  @gorm.AuditStamp
2:  class Meeting {
3:    Date start
4:    Date end
5:    String title
6:  
7:    static searchable = true
8:  }
New magic has happened: Meeting class has new fields representing (these names are configurable) whoCreated, createdDate, whoUpdated, updatedDate and obviously finding all Meetings that I have created in last 7 days is as simple as calling

Meeting.findAllByWhoCreatedAndStartGreaterThan(...).
The searchable plugin allows you to do things like Meeting.search(...) or easily search across different domain classes with a similar declarative configuration. GRAILS/GORM provides you with a phenomenal declarative power!

The list of plugins that can be added goes on and on and the functionality you can add to your domains in this declarative fashion is boundless.

GOING BACK TO EARTH: By default all fields are not nullable and GRAILS has no way of knowing that some data does not make sense, for example start Date should be always before end Date! So lets make the corrections:
1:  class Meeting {
2:    Date start
3:    Date end
4:    String title
5:
6:    static constraints = {
7:     end nullable: false, validator: {value, record ->
8:         if (value && record.start && value < record.start) {
9:               'endDateNotAfterStart'
10:        }
11:      }
12:    }
13:  }
The new version provides a custom validation for the end date. The logic simply returns a message string (to be translated by GRAILS i18n infrastructure) if the end date was entered, start date was entered, and end date is not after start date.
(Side note on Groovy: notice that not all paths return a value in the validating closure, this seems to be Groovy’s take on partial functions. As I understand this, Groovy allows this type of coding to support less verbose code and the concept of partial functions is not fully supported as such.)

It is imperative to have curlies. The alarm bell starts ringing: I have imperative logic which now is a part of my domain class, yuck! Can I make code improvements and get rid of these curlies?
Note that each time I have a domain class with start and end timestamps I will probably need to write a similar closure on that domain class and I will have to write separate unit test for it, I will have to maintain the code in many places. So yes, if I could 'declare' endAfterStart validation on my domain class the code would benefit:
1:  class Meeting {
2:    Date start
3:    Date end
4:    String title
5:
6:    static constraints = {
7:       end nullable: false, validator: ValidationUtil.endAfterStart.curry('start')
8:     }
9:    }
10:  }
11:
12:  class ValidationUtil {
13:    static def endAfterStart={String startDateFieldName, Date endDate, record ->
14:     if (endDate && record."$startDateFieldName" &&
15:                endDate < record."$startDateFieldName") {
16:      'endDateNotAfterStart'
17:     }
18:    }
19:  }  
Note that Groovy is clunky with functional programming terms, ‘curry’ should be really called ‘partial’. But the logic is clear, I am declaring my validation by using a function (Groovy closure) declared in a reusable (hopefully unit tested) utility class. Expected signature of validating closure is:
 {value, record -> . . .}
The declared reusable validation needs additional information so its signature is:
{startTimestampFieldName,  value,  record -> . . .}
So I need to convert one signature to another in functional terms this is called partial application. Groovy calls it (incorrectly) curry.

Now my domain class is purely declarative. Is it better for it? I believe so!
I think you should see a benefits of this declarative improvement! I hope to write more about curlie evil in future posts.

Next bashing of curlies

Tuesday, March 27, 2012

It is imperative to have many curlies

For the life of me, I could not memorize the term imperative programming (opposite of declarative and functional; the staple of traditional Java). I tried everything and nothing worked. In my brain, the word imperative did not want to associate itself with the whole concept. I guess I get it, the term is derived from commanding the computer to do something, but I just could not remember it! That is until I came up with the pun phrase: “It is imperative to have many curlies”.

Everyone is laughing when I tell them that a good programming is about removing curly brackets. Still, I have persisted in my determination and counting the curlies became a new way for me to measure my code.

Obviously, a simple way to achieve code perfection would be to change the language to one that does not have curly brackets, but that is not the point, the curlies may be still there only they would not look like curly brackets… For the sake of this argument, anything that defines a block of code, indentation in Python/CoffeeScript or Ruby’s end keyword is a curly.
The concept is simple, if I implement stuff, I use curlies, if I declare the behavior or use things like functional composition, then I don’t.
Languages like JavaScript and Groovy (GRAILS) are a good to showcase curly evil. Both are hybrid languages in the sense that you can do very imperative style Java like coding or do something else.

Let me start with a JS example. I am using Ext JS 4 in my current project. Ext comes with methods like: AbstractComponent.setDisabled(boolean disabled).

So if you want to add logic to disable/enable buttons, you can write it commending the browser to do your bidding and that would be with curlies. The code would look like somewhat similar to this:
1:  Ext.define('myView' ,{ 
2:   extend: 'Ext.form.Panel’, 
3:   ..., 
4:   
5:   items: [ 
6:      ..., 
7:      { 
8:        xtype: 'button', 
9:        label: 'save', 
10:       ... 
11:     },{ 
12:       xtype: 'button', 
13:       label: 'refresh', 
14:       ... 
15:     }, 
16:     ... 
17:   ], 
18:   
19:   enableDisableControls: function() { //curly! 
20:    //lots of if statements (curlies galore) defining when each button is 
21:    //enabled and when is disabled ... 
22:   } //another curly! 
23:  });

//  remember to add calls to enableDisableControls() each time:
//   -view is opened,
//   -refreshed,
//   -user makes changes to the data, etc, etc. (that is lots of additional curlies!)
//   -repeat the process for next 35 views you need to write...

Instead of this Object Oriented spaghetti, how about this code: (Note Ext JS adds a concepts of mixin to JS.)
1:  Ext.define('myView' ,{ 
2:   extend: '...’, 
3:   mixins: { 
4:    disableEnableOnDirtyState: '...', 
5:    disableEnableOnSecurity: '...', 
6:    disableEnableOnEditMode: '...', 
7:    ... 
8:   }, 
9:   
10:  items: [ 
11:    ..., 
12:    { 
13:       xtype: 'button', 
14:       label: 'save', 
15:       disableIfDirtystate: 'clean', 
16:       disableIfNotSecurityrole: '..._CAN_MODIFY', 
17:       ... 
18:    },{ 
19:       xtype: 'button', 
20:       label: 'refresh', 
21:       disableIfEditmode: 'new' 
22:       ... 
23:    }, 
24:    ... 
25:   ] 
26: });

The declarative definitions of buttons tell the reusable logic in the mixins that the save button should be disabled unless changes have been made to the form (dirtystate=’dirty’) and unless I have a security role allowing me to make changes or create new entries. The refresh button makes no sense for a new entry before it is saved on the backend so it stays disabled until that happens (editmode) … And I can be adding more and more orthogonal declarative conditions for enabling/disabling buttons!

Note the new version of myView is declarative, it does not implement the functionality it needs, it declares it. Also think of testability. Traditional Java code can try to place some disabling/enabling logic in the ancestor creating hard to test fat ancestors. Unit testing enable/disable mixins is very straightforward. (Note to declarative purists: this code has clear side-effects. It has to. The point is, however, that they are clear. ;)

Also note that some logical decoupling needs to happen since all of these orthogonal conditions compete for one boolean (component.disabled) (see Sencha Discussion Forum Post).

Finally a note for Ext programmers: some tweaking to Ext mixin preprocessor might be in order. Unlike SCALA Traits (or even Groovy mixins), constructor (yes, Ext adds constructor concept to JavaScript as well) is not automatically invoked for mixins so if mixin needs to, say, listen to dirtychange event it has problem arming itself.

To me, this approach is clearly a better code reuse, better code maintenance, it is also clearly better for TDD.

There are many other examples that come to mind:
GRAILS/GORM: GRAILS Domain Classes and GRAILS plugins can provide phenomenal examples of declarative programming where simple declarations load lots of functionality without any coding.

SCALA provides a great way of controlling the curlies in the code. If you coding style is very declarative and functional you will be able to code with very few curlies in SCALA.

So are curlies a measure of code quality? I hope to write more posts about my take on curlies soon.

This post continues here: Next Curlies Bashing