Re: Why localize structures in this case.



On Oct 30, 7:46 pm, santosh <santosh....@xxxxxxxxx> wrote:
Chad wrote:
On Oct 30, 6:36 pm, user923005 <dcor...@xxxxxxxxx> wrote:
On Oct 30, 6:21 pm, Chad <cdal...@xxxxxxxxx> wrote:

Littered through the 10,000 + lines of some Berekely Database code,
I keep seeing the following

DBHANDLE
db_open(const char *pathname, int oflag,,,)
{
DB *db;
/*code*/
return(db);

}

static DB *
_db_allocate(int namelen)
{
DB *db;
/*code*/
return(db);

}

char *
db_fetch(DBHANDLE h, const char *key)
{
DB *db=h;
/*code*/
return(ptr);

}

The question is, why have

DB *db

inside the function versus being passed as the formal parameters.
Ie, why not have something like

static DB *
_db_allocate(int namelen, DB *db)

Actually, I've seen this kind of coding move in a lot of C and Unix
code. I just chose the Berkeley Database Code because I can make
some heads or tails out of it.

The idea is to create an abstraction called DBHANDLE used to access a
table.
The reason for doing this is that you do not want the end-users
poking around inside the guts of the DB*.
All they get is some opaque little thingy to reference the table
with. If they start poking around in the innards of the DB*, chances
are good they will break something.

It is no different than fopen(), fread(), fwrite() passing around a
FILE *.
It's just another way of saying:
"This thing is mine, and as the inventor I know how to use it. If
you
start fiddling with it, we're all going to get into trouble. So
don't touch it."

Maybe I'm missing the broader picture, but couldn't a user still
fiddle with the guts of DB? I mean, couldnt a user do something like

He can reasonably do that only if the exact format of DBHANDLE is known.
The very purpose of opaque types is to hide this information from
client code.

Tell me, how would you fiddle with the internals of FILE, other than
simply stomping all over it?

<snip>

Okay, I sat and thought about what you just said. I got briefly
distracted because there was some 3.2 earthquake that just hit. I was
just sitting here thinking when I felt my apartment complex shake. At
first I thought maybe the girl upstairs was having some rough sex.
Then I saw my door shake and crap fall onto the floor. The came the
ritual of people from the east coast hitting the freaking panic button
because they've never felt a tremor.

Now, back to what original thought. I really can't think of a reason
why I would want to fiddle with the internals of FILE. Come to think
of it, I've never have fiddled with the internals of FILE. Heck, up
until tonight, I didn't realize that FILE was possibly a typedef to
some kind of private internal structure. I think I worded that
correctly.

I forgot what else.

.


Quantcast