Version 8 of Compact Code Formatting Style

Updated 2007-09-06 21:57:58 by LEG

The code formatting style used for Tcl programs as reflected on the man pages and elsewhere is similar to C code formatting. I propose an alternative, more compact style: CCFS. Not because I want it to be the standard, but rather to share the idea.

After reading (once again) '1% the code' [L1 ] and while writing (once again) a medium size Tcl application, I started to think that there are too many braces in the files. Python [L2 ] does without them, however Python lacks nice syntax at other points, I won't discuss this here though.

CCFS rules:

  • no lonely braces on a single line, except:
  1. when a namespace, or a proc larger then 24 lines (buh) ends, or
  2. for delimiting data
  • braces in if {expr} only when it is an expression
  • braces around arguments only if there are more then one

Some recommendations:

  • rather return, continue, break then else
  • don't while, foreach, for, if you can avoid it - recurse

Illustrating with an example:

 proc ccfs param {
     if !$param return
     puts "we are in"

     if [llength $param] {puts "and we've got a list"}

     switch -- [lindex $param] {
         stop {return}
         continue {
             # test the second parameter 
             set test [lindex $param 1]}
         default {puts "don't know what todo with: $param}}}
    if {$test eq "stop"} {
        puts "we stopped on the second param"}}

Observations:

  • If a line is empty, it clearly denotes that something new is going to happen.
  • Of course I use a syntax aware editor to get the indenting and the parent matching right
  • Conditional are: either flags - $var, results - script, or expressions - {expr}, which is visually conveyed by the CCFS
  • Some say (A question of style) that run time is slightly longer; I don't care! (If you need it fast, postprocess the code to insert the braces).

If an if/else branch is too long to fit into the same line, you have to decide upon formatting. Instead of giving a lot of rules i cut&paste a real code example from TTP's ttp.tcl. Please don't try to read and understand the code, just skim over the text to see the syntactic patterns:

  ...
    proc tcl {args} {
        variable state
        if [llength $args] {
            switch $state {
                parse {set state tclline}}
            catch {eval $args} result
            return $result
        } else {
            switch $state {
                parse {set state tclstart}
                tcl {set state tclend}}}
        return}

    # cmd: preproces lines instead of subst
    proc cmd {args} {
        variable state
        variable cmdLine
        switch $state {
            parse {
                set cmdLine $args
                set state cmdstart}}}

    namespace export out parse skipline -- literal tcl cmd
 }

 namespace import ::ttp::*

 proc stamp {} {
    set host ""
    if [info exists ::env(HOST)] {set host $::env(HOST)}
    if [info exists ::env(HOSTNAME)] {set host $::env(HOSTNAME)}
    if {$host eq ""} {catch {exec hostname} host}
 ...

Mhm.. if/then/else is bad, however, sometimes we need it, if you prefer it more traditional use:

 if ..cond.. {
     ..then..
     ...
 } else {
    ..else..
    ...}

I really think it looks ok and compact. Or be somewhat more funky:

 if ..cond.. {
     ..then..
     ...
 } {
    ..else..
    ...}

The idiom '} {' meaning "else" from now on.

Loops

'for' and 'while' use expressions for iteration, however for reasons explained elsewhere you must enclose the expression within braces, which is ugly. Use the intrinsic list processing of the Tcl 'proc' instead. The command line parser of TTP is an example for this. Iff:

  • the iteration is not very deep
  • does not get called all the time

The notational and expressive elegance of recursion is almost every time better then looping (says I, but .. who am I to say this?).

'foreach' is an exception, especially if you iterate over more then one variable.

Ugly example:

 proc printlist args {
    while {[llength $args]} {
        puts [lindex $args 0]
        set args [lreplace $args 0 0]}}

Good looking:

 proc printlist {item args} {
     puts $item
     if [llength $args] {eval printlist $args}}

Of course this is a very constructed example since the following is the way to do it:

 proc printlist args {foreach item $args {puts $item}}

However i hope to illustrate the point of using 'proc' and 'args' for list iteration. For counting stuff consider:

 proc forloop i {
      if $i {puts $i;  forloop [incr i -1]}}

Oh.. this counts down and stops with '1'! Ahem, does that really matter? Yes! Then use:

 proc forloop {i n} {
     if $n {puts $i;  forloop [incr i 1] [incr n -1]}}

See Tail call optimization for more on recursion and: program language specialists please jump in.

LEG


RLH That code is hard to read. Much more so than regular Tcl syntax style.

jcw - Check out an indentation syntax for Tcl ...


Category Discussion