Hello,

I'd say there's more than one style of code factoring. In one style,
you see a pattern that exists in multiple words. You name that
pattern, make a word, and replace the patterns with the name.

There's another kind of factoring however. Factoring calls to shuffle words. 
Here's a very simple example using the current source tree.

Take a look at the add-malloc word in the libc vocab :

: add-malloc ( alien -- ) dup mallocs get-global set-at ;

It's used by three words, malloc calloc realloc :

: malloc ( size -- alien ) (malloc) check-ptr dup add-malloc ;

: calloc ( count size -- alien ) (calloc) check-ptr dup add-malloc ;

: realloc ( alien size -- newalien )
    over malloc-exists? [ realloc-error ] unless
    dupd (realloc) check-ptr
    swap delete-malloc
    dup add-malloc ;

In each definition, find the call to add-malloc. What word is called
right before each call to add-malloc?

This is an opportunity to factor out the shuffle word 'dup'. We can
change add-malloc to be:

: add-malloc ( alien -- alien ) dup dup mallocs get-global set-at ;

The stack effect has changed from

    ( alien -- )

to

    ( alien -- alien )

Now the three dependent words are:

: malloc ( size -- alien ) (malloc) check-ptr add-malloc ;

: calloc ( count size -- alien ) (calloc) check-ptr add-malloc ;

: realloc ( alien size -- newalien )
    over malloc-exists? [ realloc-error ] unless
    dupd (realloc) check-ptr
    swap delete-malloc

In each case, we just deleted the 'dup' preceding the 'add-malloc'.

The net effect is, we added a 'dup' in one word and deleted three
'dup' calls in other places. The factor pays for itself.

Ed


-------------------------------------------------------------------------
SF.Net email is sponsored by:
Check out the new SourceForge.net Marketplace.
It's the best place to buy or sell services for
just about anything Open Source.
http://sourceforge.net/services/buy/index.php
_______________________________________________
Factor-talk mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/factor-talk

Reply via email to