[Tutor] How to refactor a simple, straightforward script into a "proper" program?

Cameron Simpson cs at cskk.id.au
Mon Jan 6 17:42:51 EST 2020


On 06Jan2020 11:29, Alan Gauld <alan.gauld at yahoo.co.uk> wrote:
>On 06/01/2020 03:25, boB Stepp wrote:
>> I think the basic unit of code organization would be a 
>> ReadingMaterial
>> class, choosing this name to reflect Alan's thoughts that ultimately
>> there might be other things to read besides paper-based books.
>
>Good thinking. But...
>
>I'd create a very thin abstract class with just the interface
> - remember think about behaviour first not attributes.
>Attributes are only there to support behaviour.
>
>Then forget about eReaders etc for now and create a subclass
>that deals with the concrete problem of a paper book.

Just to this; I often find it easier to write the concrete class (no 
abstract superclass), and _then_ consider the concrete class and pull 
out the abstract bits of it. So you start with a working:

    class SubClass:

        def __init__(self, total, blah...):
            self.units = 'pages'
            self.sofar = 0
            self.total = total
            self.blah = blah
            ...

        def portion(self):
            return self.sofar / self.total

and later, when working, split it off into a common superclass with a 
specific subclass, dividing things up between what is generic and what 
is specific.

    class SuperClass:

        def __init__(self, total, units, blah...):
            self.units = units
            self.sofar = 0
            self.total = total
            self.blah = blah
            ...

        def portion(self):
            return self.sofar / self.total

    class PagesSubClass(SuperClass):

        def __init__(self, total, blah...):
            super().__init__(total, 'pages', blah...)

Cheers,
Cameron Simpson <cs at cskk.id.au>


More information about the Tutor mailing list