[Tutor] LCM revisited + OOP

Steven D'Aprano steve at pearwood.info
Wed Nov 28 03:27:57 CET 2012


On Tue, Nov 27, 2012 at 06:13:52PM -0700, Ray Jones wrote:
 
> Part I
> I am a good way through MIT's Introduction to Computer Science and
> Programming as offered through edX. I'm not certain I'm going to pass
> the course this first time through, the major hangup being the
> understanding of OOP.

We should come back to that.
 
> Part II
> When the LCM thread came through, I wrote some quick code do the
> computation. I began by creating a function that generates a list of
> primes and reversing the list high to low. Then I created a recursive
> function to find the prime factors for each of the numbers and
> manipulated the results to the LCM.

Seems like a complicated way to generate the least common multiple.


> What do these two things have to do with each other? I can see some of
> the vast power of OOP. Unfortunately I can't see when or why I would
> create objects in my everyday programming. So I went back to look at my
> LCM code to see if there a way to create better code by using OOP rather
> than the functions I used. I can't see a better way. I know I can use
> OOP - I just don't see how setting it up with a couple of classes would
> make it simpler or better than the non-OOP way.

For something as simple as Least Common Multiple? Using a function is 
much more sensible than writing a class.

OOP is for when you have a single data type that needs *state* and 
*behaviour*. A LCM function only has behaviour, and so a function is 
best.

If you have code that never needs to store its current state, then a 
simple function is probably best. If you have code that does store the 
current state, then OOP is probably best. Do you understand what I mean 
by "current state"?



-- 
Steven


More information about the Tutor mailing list