Your SlideShare is downloading. ×
Making an Object System with Tcl 8.5
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Making an Object System with Tcl 8.5

515

Published on

This was the presentation that I gave at the 11th Tcl Conference, 2004, in New Orleans. It talks through a number

This was the presentation that I gave at the 11th Tcl Conference, 2004, in New Orleans. It talks through a number

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
515
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
13
Comments
0
Likes
0
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. Making an Object System with Tcl 8.5 Donal K. Fellows <donal.k.fellows@manchester.ac.uk> Tcl 2004, New Orleans, LA
  • 2. Basic Objects
  • 3. September 29, 2013 Tcl'20043 What is an Object in Tcl? • It is some State – Dictionaries are ideal • It is a Command – Note that we can rename commands • It is an Ensemble Command – Ideal way of packaging many commands into one • It Cleans Up on Deletion – Delete traces make this easy
  • 4. September 29, 2013 Tcl'20044 Dictionaries • List of key/value pairs cow beef sheep mutton pig pork • Backed by hash table (fast!) • Values – Nestable, can build complex trees – No bizarre behind-the-scenes changes! TIP#111TIP#111
  • 5. September 29, 2013 Tcl'20045 Example # See how easy it is to nest dictionaries set states($id) [dict create foo bar language Tcl bandersnatch {frumious but shunned} animalToMeat [dict create cow beef pig pork sheep lamb deer venison
  • 6. September 29, 2013 Tcl'20046 Commands: Rename Traces • If command is reference to state, need to know when reference changed • Use command traces – Tcl 8.4 feature • Update “this” key in dictionary to hold object’s current name TIP#62TIP#62
  • 7. September 29, 2013 Tcl'20047 Example # Command name is currently in $objName # Command unique id is currently in $objId trace add command $objName rename [list RenameObject $objId] proc RenameObject {id from to operation} { global states # Ensure that the ‘this’ field is right dict set states($id) this $to }
  • 8. September 29, 2013 Tcl'20048 Ensembles • Objects require methods • Use an ensemble command to group methods together – Uses command rewriting features of the –map option dictionary in ensemble configuration • Provide get, set, unset, method methods by default for variable access and method construction and introspection TIP#112TIP#112
  • 9. September 29, 2013 Tcl'20049 Example # Set up the ensemble command namespace ensemble create –command $objName -map [dict create get “getMethodImpl $objId” set “setMethodImpl $objId” unset “unsetMethodImpl $objId” method “methodMethodImpl $objId” ] proc getMethodImpl {id fieldName} { global state return [dict get $state($id) $fieldName] } proc setMethodImpl {id fieldName value} { global state dict set state($id) $fieldName $value } proc unsetMethodImpl {id fieldName} { global state dict unset state($id) }
  • 10. September 29, 2013 Tcl'200410 Making Methods • Implement new methods (in method method) using wrapper round proc • Wrap body to turn object fields into local variables – Uses dict with to automate • Internally uses lassign to split apart args parameter TIP#212TIP#212 TIP#57TIP#57
  • 11. September 29, 2013 Tcl'200411 Example $obj method example {caller} { puts “This is $this” puts “Hello $caller” } # Changes into... proc example_12345 {caller} { dict with ::state(12345) { puts “This is $this” puts “Hello $caller” } } # And ‘example’ is rewritten to ‘example_12345’ by # the ensemble’s command mapping dictionary
  • 12. September 29, 2013 Tcl'200412 Clean on Delete • Since obj-ref is a command, delete with rename • Detect deletion with command delete trace • Delete the variable containing the dictionary TIP#62TIP#62
  • 13. September 29, 2013 Tcl'200413 Example # Command name is currently in $objName # Command unique id is currently in $objId trace add command $objName delete [list DeleteObject $objId] proc DeleteObject {id from to operation} { global states # Also do some extra work to delete any # object-specific methods in here... unset states($id) }
  • 14. September 29, 2013 Tcl'200414 Making an Object • Allocate new unique ids – use sequence counter • Pick unused command name • Create ensemble command • Initialize state, methods and traces • Basic object creator procedure just combines all this into one
  • 15. September 29, 2013 Tcl'200415 Example set myObject [NewObject] $myObject set foo 123 $myObject set bar 456 $myObject method sum {} { return [expr { $foo + $bar }] } $myObject method message {} { puts “$foo + $bar = [$this sum]” } $myObject message rename $myObject {}
  • 16. An OO System
  • 17. September 29, 2013 Tcl'200417 Building an OO System • Build on top of our basic objects • Class object / classes – Understands about object creation within object system • Object class – Understands about inheritance, constructors, etc. • Object instances – Understands about reference counting and how to convert object name to stable form
  • 18. September 29, 2013 Tcl'200418 Class Creation • Class object has define method to create new class instances – Take script argument that provides class definition • Becomes field of class instance • Inheritance through execution of superclass’s definition script – Parse using a private namespace and interp alias to create helpful subcommands
  • 19. September 29, 2013 Tcl'200419 Example # Define a basic counter class Class define Counter { property counter 0 method increment {{amount 1}} { incr counter $amount } } # Define a slightly more advanced counter class Class define Counter2 { inherit Counter method decrement {{amount 1}} { $this increment [expr {-$amount}] } }
  • 20. September 29, 2013 Tcl'200420 Object Creation • Class instances have new method to make object instances • Ensure existence of delete method (to call destructor if defined and then get rid of the command) • Call constructor (passing in arguments to new method) if one defined – Use {expand} to do safely TIP#157TIP#157
  • 21. September 29, 2013 Tcl'200421 Example # Create a counter set ctr [Counter2 new] # Increment a few times... puts [$ctr increment] ;# => 1 puts [$ctr increment 2] ;# => 3 puts [$ctr decrement] ;# => 2 # Rename the object rename $ctr myCounter puts [myCounter increment] ;# => 3 puts [myCounter increment] ;# => 4 # Delete myCounter delete
  • 22. September 29, 2013 Tcl'200422 The Object Class • Root of class hierarchy • Provides reference management – Delete objects automatically when last reference held by Container object is deleted – Supports as and return methods for automated reference management in procedures • Provides class membership test – Field holds superclass list – Use expr {$class in $superclasses} • Provides mapping to immutable references – Object renaming won’t break Container objects TIP#201TIP#201 TIP#90TIP#90
  • 23. September 29, 2013 Tcl'200423 Example # Create another counter set ctr [Counter new] # Increment a few times... puts [$ctr isa Object] ;# => 1 puts [$ctr isa Counter] ;# => 1 puts [$ctr isa Counter2] ;# => 0 # Rename the object $ctr addRef interp alias {} myCounter {} $ctr puts [$ctr eq myCounter] ;# => 1 # Delete by reference count going to zero $ctr delRef
  • 24. September 29, 2013 Tcl'200424 Example # Create a procedure that uses Snit-style automatic # variable cleaning, but which actually undoes it... proc test1 {} { [Counter new] as foo puts [$foo increment] ;# => 1 $foo return ;# Magical! } # Nest the procedures; this cleans up automatically proc test2 {} { [test1] as bar puts [$bar increment] ;# => 2 } ;# object deleted here test2
  • 25. September 29, 2013 Tcl'200425 Other example classes • List class (see code on CD) – Numerically index-able collection • UniqueList class – Subclass of List – Doesn’t allow duplicate objects • Example class – Print messages in constructor/destructor
  • 26. September 29, 2013 Tcl'200426 Example set l [List new] $l add [Example new "Demo #1"] $l add [Example new "Demo #2"] $l add [Example new "Demo #3"] $l add [Object new] rename [$l index 0] nasty $l add [$l index 0] puts “Have [$l len] items in list” $l iterate v { puts –nonewline “Item: $v” if {[$v isa Example]} { puts “ (example object)” } else { puts “ (general object)” } } $l delete # Make a list # “Demo #1 (obj11) made” # “Demo #2 (obj12) made” # “Demo #3 (obj13) made” # Doesn’t print anything # If list held object names, this # would make everything break... # “Have 5 items in list” # (since first item in twice) # Prints the list’s contents: # “Item: nasty (example object)” # “Item: obj12 (example object)” # “Item: obj13 (example object)” # “Item: obj14 (general object)” # “Item: nasty (example object)” # “Demo #2 (obj12) deleted” # “Demo #3 (obj13) deleted” # “Demo #1 (nasty) deleted”
  • 27. Speed Test
  • 28. September 29, 2013 Tcl'200428 Simple Unfair Comparison! Basic Objects OO System [incr Tcl] Create and Delete Object 350 µs 3380 µs 80 µs Invoke Method 58 µs 82 µs 19 µs Read Field 32 µs 22 µs Time to Develop One day Years! Tests carried out on unloaded 1GHz AMD Athlon with 1GB memory running Linux 2.4.20
  • 29. New Features Used
  • 30. September 29, 2013 Tcl'200430 Tcl Improvements, Provided! • TIP#57 – The [lassign] command • Useful in full method implementation • TIP#90 – Advanced [return] behaviour • Multi-level return in return method • TIP#111 – The dictionary datatype • Vital for data management • TIP#112 – Ensemble commands • Made this talk possible! • TIP#157 – The {expand} syntax • Much easier to hand off arguments to constructors • TIP#201 – The ‘in’ and ‘ni’ operators • Much easier to remember than lsearch incantations… • TIP#212 – The [dict with] subcommand • Makes it trivial to construct methods Details all at http://tip.tcl.tk/
  • 31. Any Questions?

×