Re: "data hiding" prototype code



On Apr 11, 12:37 pm, "sofeng" <sofeng...@xxxxxxxxx> wrote:
I'm not sure if "data hiding" is the correct term, but I'm trying to
emulate this object-oriented technique.

I like to call it encapsulation.

I'd just like some feedback to find out
if I've done anything wrong.

I think there are some things you can do to improve your strategy
here, comments to follow.

I realize there is overhead with using an "accessor" function.

There are, and there are a couple of ways to mitigate that. However,
unless your accessors are being called in a tight loop, it's probably
not an issue you need to solve.

I'm trying to:
1.) "hide" data (variables declared as static at file scope) within a
file (algorithm.c)

First of all, making the variables static at file scope doesn't really
achieve the goal of encapsulation, particularly when you publish the
struct definition in the header. Secondly, static variables at file
scope are not much better than globals: they're certainly not thread
safe, and you open yourself to other sorts of errors as well.

2.) manipulate the data using an algorithm function (Algorithm())
3.) provide external access to the data using an "accessor" function
(GetAlgorithmData())

Your design does not make it clear who "owns" this data. An algorithm
is typically a particular pattern applied to someone else's data,
although it may store some of it's own in the process. Thus, using
"Algorithm" as the generic placeholder for your OO class could be
confusing. Typical algorithms will *take* data and return *results*.

However, assuming that Algorithm really does own this data, I would
define the struct inside the .c file, providing the typedef in the .h
file. *This* hides your data. Algorithm() can return a pointer to this
type, and then you can call accessors with the pointer to obtain
individual elements of the data.

Don't have time to rewrite your code, so I hope that helps.

-bluejack

.