While working on leoAst.py, I have come to understand more fully several of 
Vitalije's suggested code patterns:

*Prefer functions to classes/methods*

Classes and methods are essential in python. They aren't going away. 
However, in some cases functions are preferable to methods, for several 
reasons:

1. Functions are available "everywhere".  In contrast, methods are 
available only within their enclosing class.

Methods can be used outside their class, say within another class, only be 
instantiating a "helper" instance of the method's class.  That's a clumsy 
pattern.

2. Functions help "disentangle" classes.

This is a direct consequence of point 1.  Code shared via functions reduces 
dependencies between classes.

Disentangling classes greatly simplified the code in leoAst.py.

*Prefer limited duplication of code*

I have come to see that there is an ongoing, never-to-be-fully-resolved, 
tension between the DRY (Don't repeat yourself) principle and other design 
principles.

In particular, *limited* duplication of code can help untangle code. The 
great Glenford Myers talked about avoiding "modules" whose only purpose was 
to avoid duplicating code. I should have paid more attention.

I have come to see that some code duplication can sometimes be seen as 
documentation. The fs.fstringify_file and fs.fstringify_file_diff methods 
both contain the following code:

tog = TokenOrderGenerator()
contents, tokens, tree = tog.init_from_file(filename)
if not contents or not tokens or not tree:
    return False
# fstringify.
self.fstringify(contents, filename, tokens, tree)
results = tokens_to_string(tokens)

Imo, this duplicated code has no series negative consequences.

*Avoid kwargs*

This has been an ongoing project. I had overused kwargs in order to "share" 
code. This often has significant negative consequences.  Better to keep 
functions and methods simple, and accept a bit of code duplication.

*Summary*

Functions can sometimes preferable to methods. They are more easily 
accessible and they may disentangle the relationships between classes.

Limited code duplication can also be useful. In some cases, they serve as 
useful documentation.

Avoiding kwargs is often a good idea, despite the potential for code 
duplication.

I thank Vitalije for his helpful suggestions.  These ideas would not have 
come to me on my own.

The code in leoAst.py is an example of my revised coding style.

Edward

-- 
You received this message because you are subscribed to the Google Groups 
"leo-editor" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to leo-editor+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/leo-editor/7de4afbe-373e-452b-89e1-e448cba2f81b%40googlegroups.com.

Reply via email to