Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re^2: Flyweights - different meaning in perl?

by adrianh (Chancellor)
on Dec 15, 2002 at 17:22 UTC ( [id://220027]=note: print w/replies, xml ) Need Help??


in reply to Re: Flyweights - different meaning in perl?
in thread Yet Another Perl Object Model (Inside Out Objects)

I've studiously avoided the term "flyweight objects" as I have only ever seen it here and didn't really understand its meaning. I'll stick to "Inside-out" which only has meaning in perl terms as far as I am aware.

Fair enough, but other people have - which makes me suspect it means something different in the perl and design pattern worlds.

Which would be annoying. One of the main advantages of the design pattern movement for me is the development of a common vocabularly (finally, everybody knows what a singleton is :-). If it means something different in the perl world it would be useful to know.

With regard to the example you describe, that may have made some sense in the world of 8-bit chars as you only need a pool of 256 object, but in the world of UCS, it becomes excessive I think...

I don't really want to repeat everything in the chapter from the book, but basically...

  • The context is a word processor, so "character" doesn't just mean the code, it might support methods like draw(), intersects(), etc. We're talking WYSIWYG layout support.
  • I didn't mean to imply you had to create the whole pool of characters at once, you would create them as needed for a document and add them to the pool.

As for practicality, the example was in the book was adapted from the Doc editor, produced using InterViews 3.0. Take a look at:

  • Paul R. Calder and Mark A Linton. Glyphs: Flyweight bjects for user interfaces. In ACM User Interface Software Technologies Conference, pages 92-101, Snowbird, UT, October 1990.
  • Paul R. Calder and Mark A Linton. The object-oriented implementation of a document editor. In Object-Oriented Programming Systems, Languages and Applications Conference Proceedings, pages 154-165m Vancouver, British Columbia, Canada, October 1992. ACM Press.

To quote from the Design Patterns chapter on flyweights:

Doc uses glyph objects to represent each character in the document. The editor builds one Glyph instance for each character in a particular style (which defines its graphical attributes); hence a character's intrinsic state consists of the character code and its style information (an index into a style table). This means only position is extrinsic making Doc fast.

If you're interested in the details I'd recommend picking up a copy of Design Patterns and giving the flyweight chapter a read.

Replies are listed 'Best First'.
Re: Re: Re: Flyweights - different meaning in perl?
by demerphq (Chancellor) on Dec 15, 2002 at 20:50 UTC
      I've studiously avoided the term "flyweight objects" as I have only ever seen it here and didn't really understand its meaning. I'll stick to "Inside-out" which only has meaning in perl terms as far as I am aware.
    Fair enough, but other people have - which makes me suspect it means something different in the perl and design pattern worlds.

    Which would be annoying. One of the main advantages of the design pattern movement for me is the development of a common vocabularly (finally, everybody knows what a singleton is :-). If it means something different in the perl world it would be useful to know.

    Well following this thread, and diotalevis comment I did a little research into the flyweight pattern. And it would seem that there are two different ideas being discussed. Its possible (and I think likely) that the concepts were originally the same, but I suspect the design pattern movement redefined and extended the concept from its earlier use. But i have little evidence to back up this hunch. Heres a quote from a design pattern site about the design pattern schools concept of a flyweight pattern

      If instances of a class that contain the same information can be used interchangeably, the Flyweight pattern allows a program to avoid the expense of multiple instances that contain the same information by sharing one instance.
      Overview of Design Patterns

    however this concept seems to be different from that briefly mentioned elsewhere and more importantly discussed in TheDamians book Object Oriented Perl. I think the later is the source of many peoples concept of the flyweight pattern in Perl, and probably derives from the earlier usage of the term "flyweght".

      Flyweight objects are most frequently used in OO languages that pass objects around by value because flyweight objects objects remain extremely small (no matter how much data they contain). Hence they are cheap to pass around. Because Perl Objects are invariably accessed via references, this advantage is not signifigant.

      However, the flyweight pattern still has something to offer in Perl, because it provides a simple mechanism for preventing direct access to abject attributes, thereby enforcing encapsulation. As a bonus, it also provides a means of easily keeping track of every object in a class, something closure-based encapsulation doesnt provide.

      Damian Conway -- Section 11.3 Object Oriented Perl (Manning)

    He then goes on to frame an object model that he calls the Flyweight Pattern. The idea of this is simple. Instead of storing attribute data in the object directly an object only holds a key into a lexically held hash that holds all of the objects for the class. The accessors extract this key from the object and then use it to look up the real object from the privately held table. In his example he uses soldiers and their ids, with a reference to the ID being blessed. (He points out that this has the weakness that it provides a means to violate encapsulation as an object can magicaly "transform" itself into using a different set of attributes. He discusses various approaches to making this less likely or impossible.)

    Now the pattern he describes is still compliant with the both usgaes of "flyweight". Two distinct objects can share attributes, furthermore the actually item that represents the object is "small" from an outside POV, even if the fact that its blessed is ignored.

    So I think this is a stuation that is similar to the term "closure" in perl. Generally speaking closures in Perlspeak are the same thing as closures in CSspeak. However all too often you see the term used as a synonym for "anonymous subroutine". In fact I would say that most non CS types would volunteer this is a defintion for a closure (assuming they knew what one was at all.) And just as much as this usage is a distortion and oversimplification of the real concept of "closure", I think that the term flywieght pattern has come to reflect primarily the idea of indexing a class specific lexically held register of objects, and not so much the idea of sharing attribute data between those objects. So from that point of view I would say its obvious that InsideOut objects fits that pattern. But....

    And this is where I take the other point of view, and try to answer diotalevis question

      I don't have my copy of _Design_Patterns_ handy but isn't this just a Flyweight implementation?
    At first glance the flyweight object design as described by TheDamian is very similar to Abigail-IIs inside out objects. The fact that inside out objects use a seperate hash for each attribute is a minor twist that doesnt distract much from the flyweight pattern. However the use of the references ID or some other reference/object specific unique identifier as the key into the attribute table(s) does in my opinion mean that it is not a flyweight implementation. Two distinct objects have in principle completely unique attribute representation, the objects do not by design share attributes. (Excepting that they can reference shared data if they so choose, but this is true of all object representations in Perl).

    Furthermore, Abigail-IIs pattern means that we can wrap an arbitrary number of InsideOut subclasses around any class/object. InsideOut objects fundamentally don't care about what item their blessed reference points at. However the flyweight pattern the data is small for sure, but it is very relevent to the objects internal state. You couldn't just wrap the Soldier class in TheDamians book around an IO::File object for instance. You could however do so with his BaseballPlayer example.

    So to sum up, the flyweight pattern in perl seems to focus on aspects that design pattern enthusiasts will see as inconsequential, but it still shares the same underlying ideas. InisdeOut objects are in my opinion not flyweight objects from the design pattern point of view, but have similar enough perl implementations that they are easily mistaken as being the same.

    Updated: Minor typographical errors have been corrected.

    --- demerphq
    my friends call me, usually because I'm late....

      Well following this thread, and diotalevis comment I did a little research into the flyweight pattern.

      Thanks for the info! It's been so long since I read TheDamian's book I'd completely forgotten this. (You've also made me realise that somebody has nicked my copy since it's not on my bookshelf... grrr... darn sneaky coworkers...).

      Fortunately the relevant chapter is online.

      Its possible (and I think likely) that the concepts were originally the same, but I suspect the design pattern movement redefined and extended the concept from its earlier use.

      It looks like it was the other way around. TheDamian references Design Patterns in his book.

      Personally, I don't think the technique described is an instance of a flyweight pattern, since we're taking not taking the state information from the class, just rearranging its location within the class.

      The whole point of using flyweights is to cut down on the number of objects you create by removing the context-dependant information from the class. The context specific state being passed to the flyweight objects as and when necessary by its client objects.

      TheDamian's technique might use some of the same stratagies as flyweights, but with a different intent.

        It looks like it was the other way around.

        Actually I disagree with this POV. He may reference Design patterns, but I suspect he had experience with flyweight objects before the movement developed. (Why else would he discuss flyweight objects the way he did.) Of course we wont know unless he tells us...

        Personally, I don't think the technique described is an instance of a flyweight pattern, since we're taking not taking the state information from the class, just rearranging its location within the class.

        The whole point of using flyweights is to cut down on the number of objects you create by removing the context-dependant information from the class. The context specific state being passed to the flyweight objects as and when necessary by its client objects.

        It seems to me that you are taking a little more prescriptive approach to what a flyweight object is than is perhaps justified. From what I can tell the central tennet is to reduce overhead by not duplicating data. If this means reusing literal objects then so be it. If it means reusing attribute data in a transparent way then so be it. I dont see anything in the design pattern documentation that explicitly specifies that actual objects must be reused, only their attribute data. (Note in the definition you published there is no mention of reused objects,
            Using sharing to support large numbers of fine-grained objects efficiently
        and in the one I published it only says "allows for" not that it is mandated.)

        Personally I think the model as described by TheDamian perfectly fits the design pattern definition. Multiple objects can share attribute information. The fact that the pattern as used in the book isnt intended to utilize these features doesnt change the fact that this model is designed to facilitate this type of activity. And once you start doing so, storing state specific information no longer makes sense. And there you have a "normal" flyweight object. Or at least thats my understanding... Further comment is welcome.

        TheDamian's technique might use some of the same stratagies as flyweights, but with a different intent.

        Well if I choses to use a wrench as a hammer I havent changed the fact that the item is indeed a wrench. But I agree that at least in his discussion and in his usage he isnt trying to use the feature of flywight objects that the design pattern folks seem to consider so important.

        I have to admit that I dont get too hung up on the whole design pattern movement. I agree its useful, and I agree its a positive step forward, but Im not particularly interested in interpretations that says "thats not an X because the design pattern guys say that an X must have features Y and Z". Design patterns are guidlines for how to approach and resolve real life problems. They arent end all be all solutions in of themselves. And im not really interested if solutions that I come up with meet the letter of their definitions, or if they adopt and borrow bits and pieces from everywhere.

        So to recap, I personally think that the flyweight pattern as described by TheDamian is the closest published Perl OO model to what the design pattern guys would also call flyweight objects. However it is also my opinion that in Perl it is unusal to need the design patterns concept of a flyweight, and if the model offers other benefits then so be it. (In other words I dont think its that important..)

        Cheers,

        :-)

        --- demerphq
        my friends call me, usually because I'm late....

Re: Re: Re: Flyweights - different meaning in perl?
by BrowserUk (Patriarch) on Dec 15, 2002 at 18:33 UTC

    If you'd talked about Gylph objects instead of 'character' objects, I wouldn't have had to sit here and get all confused and indignant:)

    Doc uses glyph objects to represent each character in the document. The editor builds one Glyph instance for each character in a particular style (which defines its graphical attributes); hence a character's intrinsic state consists of the character code and its style information (an index into a style table). This means only position is extrinsic making Doc fast.

    Ah! They mean Fonts! How original.


    Examine what is said, not who speaks.

      I do think you got lost in the specifics of the example and failed to see the forest for the trees there. The point, as far as I understood, was that when you have to handle a huge number of tiny objects of the same (ancestral) class, whatever they may represent, and you can split the intrinsic and extrinsic states, then you do so and create a pool of object instances to refer to for the representation of a particular "thing"'s intrinsic state. That's a "flyweight object" - a class that contains only intrinsic state in order for its instances to be usable in multitude.

      Makeshifts last the longest.

        Update: Having found and read this description of Flyweight objects, I noticed first that the equipment being used was a DECstation 3100 (a machine I well remember playing "moonlander" on 16 or more years ago. It was "state-of-the art then and wowed everyone that saw it) and then noticed that the dates on the paper and the references therein were 1987,1988 & 1989. I then realised that this description of flyweight objects comes from a time when it may well have been considered unusual and new, though I don't recall them having a great impact at the time.

        Prior to this I was under the impression that "flyweight objects" were being hailed as something new and different, and was intrigued to learned more, but was confused by what I read. Effectively the referenced paper puts that idea to bed and makes the rest of this post redundant.

        I'll leave it here as is the apparent preference of the community as testimony that just because you haven't encountered the name of something, that you haven't been unwittingly using it for years. I guess what goes around comes around:^)

        End update

        Getting by the fact that I was arguing against the example given rather than the definition itself.

        Can you explain to me how an object can have extrinsic state?

        Using the Glyph example. The text given said that Doc was fast because it used Glyphs, which had no extrinsic state. The example give for what they did not have was position. If you add the position at which a Glyph is displayed or formatted to the Glyph itself, then you do indeed need many more instances than you would without it.

        However, if you add the position information to the Glyph class it then becomes intrinsic? But what you now have is no longer a Glyph class, but a Glyph_At_This_Position class. To my way of thinking that just doesn't make sense.

        You have a list (small-l) of Positions at which to display Glyphs, and you give the Glyph to the Position not vice-versa. That way, when you reformat to a different page width, you run down the list of Posistions and adjust them and the Glyphs move appropriately. If that means I'm wanting to use Flyweight objects for my Glyphs, then so be it, but it seems like a strange name for the concept and hardly new.

        I mean, we build strings from chars, we don't tell a char that it occupies position 7 in this string?


        Examine what is said, not who speaks.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://220027]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (4)
As of 2024-03-29 12:29 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found