Hello,

I think you should look at the STON framework. STON looks like JSON for
smalltalk objects. Basically it does the same as your idea but instead of a
dictionary it loads fields of an objects from a STON file which looks like
a JSON file (a STON is kind of an extended Dictionary exported as a string,
but it has support for more that instance variables).

Now if you want to go your way, to me what you want to do looks fine. These
methods can be used for development tools but also for frameworks and stuff
like that. The thing to do it is to add this method in Object and add
support so it can work on all objects in the system.

Object>>#intializeWithDictionary: aDictionary
    self class isVariable ifTrue: ["specific case ?"]
    self class isBytes ifTrue: ["specific case ?"]
    self class isCompiledMethod ifTrue: ["specific case ?"]
    self class isSmallInteger ifTrue: ["specific case"]
    aDictionary keysAndValuesDo: [ :key :value |
        self instVarNamed: key put: value ifAbsent: [ self error: 'no ',
key , ' found'].

But as you can see there are many specific cases: CompiledMethod, bytes
objects, word objects, immediate objects, variable-sized objects, weak
objects and for Pharo 4 even others that you may need to handle in your
code (Ephemerons, 2bytes and 4 bytes objects).

If you don't get the specific cases (you may not know programming language
internals), then imagine how you would make your code work to initialize an
Array, a ByteArray or a CompiledMethod from a dictionary. Not easy, huh ?

That's why I strongly recommend to use something like STON, because it is
very easy to use, handle already all the specific cases, well documented
(Sven always does fancy documentation) and it will be maintained in Pharo 4
for recent changes (because Sven likes to use the bleeding edge version of
Pharo).

Regards,

Clement


2014-05-22 19:37 GMT+02:00 sergio_101 <sergio....@gmail.com>:

>
> is it possible to initialize a class with a dictionary? my first thought
> would be to create a method like:
>
> intializeWithDictionary: aDictionary
>
> then, loop through the elements and do something like:
>
> instVarNamed: key put: value
>
> but the book says:
>
> Caveat: Although these methods are useful for building development tools,
> using them to develop conventional applications is a bad idea: these
> reflective methods break the encapsulation boundary of your objects and can
> there- fore make your code much harder to understand and maintain.--
>
> should i avoid this?
>
>
> ----
> peace,
> sergio
> photographer, journalist, visionary
> #BitMessage BM-2D8VWUJSS41RFKh1ec83preVabHrnniExa
>
> http://www.Village-Buzz.com
> http://www.ThoseOptimizeGuys.com
> http://www.CodingForHire.com
> http://www.coffee-black.com
> http://www.painlessfrugality.com
> http://www.twitter.com/sergio_101
> http://www.facebook.com/sergio101
>

Reply via email to