[Newbies] pretty printing

Claus Kick claus_kick at web.de
Sun Sep 28 16:32:57 UTC 2008


Mark Volkmann wrote:
> Here is how one of my methods was pretty printed.
> 
> escape: aString
>     "escapes special characters in XML text"
>     | result |
>     result := ''.
>     aString
>         do: [:char | result := result
>                         , (char caseOf: {
>                                 [$<] -> ['&lt;'].
>                                 [$>] -> ['&gt;'].
>                                 [$'] -> ['&apos;'].
>                                 [$"] -> ['&quot;'].
>                                 [$&] -> ['&amp;']}
>                                  otherwise: [char asString])].
>     ^ result
> 
> Yikes! To my beginner eyes, that doesn't look good. What's the deal  
> with the excessive indentation?
> 
> BTW, comments better ways to do what this code does are welcomed.  Could 
> I use collect for this?

You could do it like this:

YourClass >> escape: aString

"escapes a String"

|result|

result := ''.
aString do:[:char | result := result, char xmlEscaped].
^result


Character >> xmlEscaped

^self caseOf:
{
	[$<] -> ['&lt;'].
	[$>] -> ['&gt;'].
	[$'] -> ['&apos;'].
	[$"] -> ['&quot;'].
	[$&] -> ['&amp;']
}
otherwise: [self asString].


The advantage is that your own methos is very short; you hide the actual 
transformation in another method you do not have to care about for the 
future.



More information about the Beginners mailing list