[Tutor] help with refactoring needed -- which approach is
morePythonic?
Alan Gauld
alan.gauld at freenet.co.uk
Thu Feb 10 08:58:58 CET 2005
> The main change in refactoring is moving it to OOP. I have a method
> that serves as the entry point for parsing the files.
Not an object? If you are thinking terms of what the methods
do its probably not OOP...
I would expect to see an object for the File, another for the Header,
a third for the Body and another for the Node. The first (containing
a header and bosdy object) is responsible for cracking open the file
and reading the lines, recognising where it has a header and sending
those lines to the header object and the rest to the bosy object.
The body object then reades those lines and creates a Node object
per node feeding it lines as appropriate...
> I want the body parser to accept a list of lines corresponding to
the
> nodes portions of my file, separate out each node (everything
between
> node end tags, the bottommost end tag included in the node), and
> send each node's contents to a further method for processing.
Or to another object? Nouns are objects, verbs are methods.
> . def body_parser(self, body_contents):
Pseudo code:
class Body:
def __init__(self,content):
self.contents = contents
self.nodes = []
def parse(self):
for line in self.contents:
if line == NodeStartTag:
node = Node()
if line == NodeEndTag:
self.nodes.append(node)
node.append(line)
def __del__(self): del self.nodes
> . self.node_parser(current_node_contents)
class Node:
def __init__(self,lines=[]):
self.lines = lines
def append(self,item):
self.lines.append(item)
def parse(self):
# your parsing method here.
Whats the advantage? If you have different node types you
can easily subclass Node and not change the File or Body
classes, just write a slightl'y different line parser.
That way your code remains more stable - you never need
to change working code to add a new node type...
Just an alternative to consider....
Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld
More information about the Tutor
mailing list