Bits of Learning

Learning sometimes happens in big jumps, but mostly in little tiny steps. I share my baby steps of learning here, mostly on topics around programming, programming languages, software engineering, and computing in general. But occasionally, even on other disciplines of engineering or even science. I mostly learn through examples and doing. And this place is a logbook of my experiences in learning something. You may find several things interesting here: little cute snippets of (hopefully useful) code, a bit of backing theory, and a lot of gyan on how learning can be so much fun.

Thursday, August 23, 2007

Classes versus Functions

While working with an OO language like C++ or Java, we often stumble into an issue of choosing between a class and a function.

Let me illustrate the case. Say, we are writing a parser. A C-style way to do is to form it in the shape of a function, say parse (FILE * fin) , that returns the IR after parsing. The caller of this function would be responsible to do what he wants with the IR.

There are more one choice to do the same thing when working with an OO language. A class named Parser would possibly have a parse (FILE * fin) method returning the IR. Or it could have a constructor Parser (string FileName), and an argument-less method parse () returning the IR. The merits of choosing one over the other seem to me rather unimposing. The only difference between the two approaches is that the input for parsing is defined while making a call to the method in the former case, while, in the latter, it gets defined at the time of the creation of the parser object. It hardly matters!

For me, in a basic case, having a parser class is little more than syntactic sugar. May be, in a more advanced scenario, it helps having a class for the Parser, so that parser states can be encapsulated in private attributes. Among these, FileName is surely not one. It can always be passed to the parse method while calling.

I arbitrarily prefer having a parameterised method parse (FILE * File) or parse (string FileName), so that I can use the same parser object for parsing many times. Nothing fundamental about this choice.