« Flash of Brilliance--Flash cards for kids | Main | Don't end up with RavioliCode! »

Learning OOP in Flash, part 2

After a lot of reading and thinking, I'm giving this another shot. I'm thinking out loud--trying to build a clear mental picture of object oriented programming in Flash and how it compares with traditional procedural programming.

With object oriented programming's classes and subclasses, there are really two things going on. Firstly, a subclass expands the code of its base class. Secondly, the subclass describes a more specialized object than its base class does.

Let's say we want our project to generate a random fraction. No problem. We just write a class that generates two random numbers and returns them in an array: one number for the numerator(top) and one for the denominator(bottom). Great, now we've got random fractions whenever we want them. But what if we get a fraction like 4/6? We may want to simplify that to 2/3.

If I were writing this procedurally, I'd write a subroutine to simplify the fraction and call it from within the routine for generating a random fraction. My routine would be dependent on the subroutine,and if I needed both simplified and "raw" fractions, I'd have to write two separate routines.

With OOP, I can write a general class, and call it from within a more specialized class. But I can also call it from anywhere. The general case is no longer dependent on the specific case. Pretty cool.

When the subclass (let's call it "simpleFraction") is called, it executes code from the base class as well as the subclass. I'd call that expansion of the class' code. From the object model, the object created from the subclass is a subset of objects that could be created from the base class. For example, a class that generates random fractions may return 4/6 and 2/3, but a subclass that simplifies those results would only return 2/3.

By the way, the comments on my first post on this topic have been very illuminating.


In the fraction example, I'd say that you're probably subclassing needlessly. I'd be more included to have a Fractions class with a public
getRandomFraction() method, which can take a boolean argument, 'simple'

public function getRandomFraction(simple:Boolean):Array;

If the 'simple' argument is true, the method would generate its random fraction and then return the simplified version. If simple is false, or undefined, you get the original random fraction.

Inside your class you could break the general task of calculating a fraction into a few private methods such as getRandomNumber() and simplifyFraction().

Personally, I don't dive in right away making base classes and sub classes. Generally I make the classes I need and eventually I'll see that two or more classes are starting to get a lot of duplicate code. Then I do some refactoring to see if I can either make one of them extend the other, or make them both extend some new class. As already mentioned, check out Refactoring by Martin Fowler.