Any way to refactor this?

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Fri Apr 13 18:04:09 EDT 2007


James Stroud:
> Probably best is to code the parameters as
> a set of tuples and iterate over them.

I agree. Before:

def _create_3D_xhatches(...pass more parameters here...):
    for x in xrange(-axis_length, axis_length + 1):
        if x == 0:
            continue
        visual.cylinder(pos=(x, -hatch_length, 0),
                        axis=(0, hatch_length*2, 0),
                        radius=hatch_radius)
        visual.cylinder(pos=(x, 0, -hatch_length),
                        axis=(0, 0, hatch_length*2),
                        radius=hatch_radius)
        visual.cylinder(pos=(-hatch_length, x, 0),
                        axis=(hatch_length*2, 0, 0),
                        radius=hatch_radius)
        visual.cylinder(pos=(0, x, -hatch_length),
                        axis=(0, 0, hatch_length*2),
                        radius=hatch_radius)
        visual.cylinder(pos=(-hatch_length, 0, x),
                        axis=(hatch_length*2, 0, 0),
                        radius=hatch_radius)
        visual.cylinder(pos=(0, -hatch_length, x),
                        axis=(0, hatch_length*2, 0),
                        radius=hatch_radius)


And after:

def _create_3D_xhatches(...pass more parameters here...):
    hl2 = hatch_length * 2
    for x in xrange(-axis_length, axis_length + 1):
        if x == 0:
            continue
        params = [[(x, -hatch_length, 0), (0, hl2, 0)],
                  [(x, 0, -hatch_length), (0, 0, hl2)]
                  [(-hatch_length, x, 0), (hl2, 0, 0)],
                  [(0, x, -hatch_length), (0, 0, hl2)],
                  [(-hatch_length, 0, x), (hl2, 0, 0)],
                  [(0, -hatch_length, x), (0, hl2, 0)]]
        for pos, axis in params:
            visual.cylinder(pos=pos, axis=axis, radius=hatch_radius)

More cleaning can be done.

Bye,
bearophile




More information about the Python-list mailing list