SpecialistOff.NET / Вопросы / Статьи / Фрагменты кода / Резюме / Метки / Помощь / Файлы

Назад

Recycling with Prototyping


Метки: python

Now you can see the revised version of RecycleA.py using the prototyping technique:

# PatternRefactoring/recycleap/RecycleAP.py
# Recycling with RTTI and Prototypes.

class RecycleAP(UnitTest):
    Collection
        bin = ArrayList(),
        glassBin = ArrayList(),
        paperBin = ArrayList(),
        alBin = ArrayList()
    def __init__(self):
        # Fill up the Trash bin:
        ParseTrash.fillBin(
          "../trash/Trash.dat", bin)

    def test(self):
        Iterator sorter = bin.iterator()
        # Sort the Trash:
        while(sorter.hasNext()):
            Object t = sorter.next()
            # RTTI to show class membership:
            if(t instanceof Aluminum)
                alBin.add(t)
            if(t instanceof Paper)
                paperBin.add(t)
            if(t instanceof Glass)
                glassBin.add(t)

        Trash.sumValue(alBin.iterator())
        Trash.sumValue(paperBin.iterator())
        Trash.sumValue(glassBin.iterator())
        Trash.sumValue(bin.iterator())

    def main(self, String args[]):
        RecycleAP().test()

All of the Trash objects, as well as the ParseTrash and support classes, are now part of the package patternRefactoring.trash, so they are simply imported.

The process of opening the data file containing Trash descriptions and the parsing of that file have been wrapped into the static methodParseTrash.fillBin( ), so now it’s no longer a part of our design focus. You will see that throughout the rest of the chapter, no matter what new classes are added, ParseTrash.fillBin( ) will continue to work without change, which indicates a good design.

In terms of object creation, this design does indeed severely localize the changes you need to make to add a new type to the system. However, there’s a significant problem in the use of RTTI that shows up clearly here. The program seems to run fine, and yet it never detects any cardboard, even though there is cardboard in the list! This happens because of the use of RTTI, which looks for only the types that you tell it to look for. The clue that RTTI is being misused is that every type in the system is being tested, rather than a single type or subset of types. As you will see later, there are ways to use polymorphism instead when you’re testing for every type. But if you use RTTI a lot in this fashion, and you add a new type to your system, you can easily forget to make the necessary changes in your program and produce a difficult-to- find bug. So it’s worth trying to eliminate RTTI in this case, not just for aesthetic reasons-it produces more maintainable code.