Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Flyweights - different meaning in perl?

by adrianh (Chancellor)
on Dec 15, 2002 at 14:47 UTC ( #220002=note: print w/ replies, xml ) Need Help??


in reply to Re: Re: Yet Another Perl Object Model (Inside Out Objects)
in thread Yet Another Perl Object Model (Inside Out Objects)

Yeah, I thought about that. I figured that it more or less violated the flywieght pattern that Abigail was using...

I'm a little confused about why people keep referring to Abigail-II's object implementation as being based on the flyweight pattern.

According to my copy of Design Patterns a flyweight pattern is:

Using sharing to support large numbers of fine-grained objects efficiently

The example they use in the book is character objects in a word processor. Obviously having a separate object for each input character is going to have a huge resource overhead. So, instead, you create a single pool of objects - one per character - and use the same object for every instance of "a", etc.

Another example from my own experience in perl was when I worked on a project that had a large number of database tables that consisited of static data - lookup tables of info.

Rather than spend a lot of time doing a SELECT every time I needed the info I slurped up the entire table, made a pool of static objects, and served up the appropriate one on request.

To be useful flyweights can't have extrinsic state - no context dependant information - just intrinsic state.

So I can't see any relation between flyweights and inside out objects. Does the term mean something different in the perl world? If so - what, and why would accessing the hashes directly violate it?


Comment on Flyweights - different meaning in perl?
Re: Flyweights - different meaning in perl?
by BrowserUk (Pope) on Dec 15, 2002 at 15:48 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.

    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.

    Actually, I say only 256 objects, but even that doesn't make any sense to me. It might make sense in a pure OO, conceptual sense to have a seperate object for each char, but it my view its a very strange thing to do.

    There are to my way of thinking only two things you can do with a char.

    • Use it. Ie. give it to some other object as a parameter.
      Eg. somestring.append('A'); or somestring.append( somechar );
    • Or ask it for its ordinal value.
      Eg. 'A'.ord(); or somechar.ord();

    So even if you want to represent it at the language level as an object, in terms of what the compiler or interpreter would actually manipulate, it's just a number.

    Unless I'm missing something, which is quite possible because I often do, the idea that the compiler/interpreter would manipulate a pointer to an object or worse, a handle to an object at the binary level is simple crazy?

    Can you see a reason for having an object to represent each char? I mean, if your are going to allow attributes to be applied to individual chars (color, size, whatever), then pooling the objects isn't going to work because I wouldn't be able to have a red 'A' and a green 'A' at the same time.

    I can see the need for being able to maintain and manipulate attributes for aggragations of chars. This string is ascii, that sting is EBCDIC, but doing this at the char level does make any sense (to me). If you could do it, then you could create aggregate strings of mixed ascii and EBCDIC and then what happens when you want to compare string 'T{ascii}h{EBCDIC}e{ascii}' with 'T{EBCDIC}h{ascii}e{EBCDIC}'--do they match or not?


    Examine what is said, not who speaks.

      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.

        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'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....

Re: Flyweights - different meaning in perl?
by TheDamian (Priest) on Dec 19, 2002 at 04:13 UTC
    adrianh asked me to comment on this thread.

    Yes, the "flyweight objects" described in "OO Perl" are structurally capable of being used as Flyweight Objects (in the Gang of Four sense).

    No, the example code shown in "OO Perl" doesn't implement the full flyweight metaphor. Specifically, it doesn't include the necessary constructor code to check if an object already exists (in the logical sense) and so avoid reinstantiating it in that case.

    In other words, both sides of this debate were essentially correct. Isn't postmodernism wonderful? ;-)

    Why did I stop short of explaining the full technique? Well, even though the changes required to the constructor code would have totalled only a few lines, explaining the concept underlying the full pattern would have required several additional pages of exposition, and I was already 200 pages over my contract limit as it was.

    Besides, it was (and still is) my assessment that the most significant application of this type of class is in providing robust, yet maintainable, encapsulation. In Perl at least, its other ability -- to optimize away duplicate value-type objects -- is much less commonly needed.

      Thanks for the comments

      In other words, both sides of this debate were essentially correct. Isn't postmodernism wonderful? ;-)

      <group hug>

      :-)

      would have required several additional pages of exposition, and I was already 200 pages over my contract limit as it was.

      /me patiently waits for the directors cut to be released...

      ;-)

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

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (12)
As of 2014-08-21 17:38 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (140 votes), past polls