Home > Software design >  TCL - Classes or dictionaries?
TCL - Classes or dictionaries?

Time:04-07

I would like to store data that transverse several levels of hierarchy.

For example:

A data structure that stores cars may store the colour, age and other aspects of each vehicle.

The question is: does it make more sense to use dictionaries or OOP for this problem? And how do I print such a structure into a table format?

Please imagine that I don't know "a priori" the number of levels (depth) of the data structure. Please check the picture attached.

Cheers,

PedroData Structure example

CodePudding user response:

If you don't intend to put behaviour with each node in that tree (e.g., will each car have a turnOnEngine method?) then it's probably easier to use a nested set of dictionaries. Tcl's classes only really make sense once you start adding significant behaviours, as they have a lot more overhead (a whole namespace each!) than a simple dict has.

As long as the overall structure is regular, with lots of repeated patterns (as your diagram seems too show), it's not too important to get “I know what I am” information stored in each node.

CodePudding user response:

If it's just for setting/retrieving key/value pairs, I also recommend a nested dictionary instead of OOP.

set cars {
    Porsche {
        color  black
        engine 3.2L
        fuel   petrol
    }

    Jeep {
        color  blue
        engine 1.6L
        fuel   diesel
    }
    Ferrari {
        color  red
        engine 4.8L
        fuel   petrol
    }
}


# Get a value
set Porsche [dict get $cars Porsche]
dict get $Porsche color
  --> black

# Get a value with nested keys
dict get $cars Ferrari color
  --> red

# Change a value with nested keys
dict set cars Jeep color yellow

For a depth with two nested keys, this will make a table.
Any deeper nested keys will be printed in $value, but in a single row.

dict for {car_name car_dict} $cars {
    dict for {key value} $car_dict {
        puts [format "%-15s %-15s %s" $car_name $key $value]
    }
}

There are options to pretty print a dict (for example, https://wiki.tcl-lang.org/page/pdict: Pretty print a dict)

  • Related