Friday, February 02, 2007

Simulating Classes in C - Part 2

Well the $1 C contest has come to an end after generating lots of interest but no full blown solutions. I'm okay with that, thanks to all of you who expressed interest and started on it. From conversations with several of you over chat, I know that there were some great ideas out there. If you don't mind taking the time, please describe your idea in the comments section. As my friend Matt can attest, I love discussing software, ideas, designs, and just about anything related to creative problem solving. This is probably why I really enjoyed math in high school and college. I looked at each problem as a logic puzzle which could be solved multiple ways. Finding the most elegant solution made me feel like I had just written a poem of supreme beauty.

/* JSObject functions */
void InvokeObjectMethod(JSObject* object, char* methodName,
JSListOfObjects* inputParams,
JSListOfObjects* outputParams) {
int i;
JSClass* class_of_object;
int method_index = -1;

/* Impossible to invoke a method on a NULL pointer */
if(object == NULL) {
/* ToDo: send a "NULL object" error code in the outputParams. */
return;
}

class_of_object = (JSClass*)(object->type);

if(class_of_object == NULL) {
/* ToDo: send a "NULL class" error code in the outputParams. */
return;
}

/* Find the index of the methodName in the object's class. */
/* This part of the code is O(n) efficient, but this could be
improved if the function names were sorted or if a hash
algorithm was used. Hashing could reduce to O(1). */
/* I could also allow the calling code to specify the desired
method directly by index to avoid requiring a string
lookup for each invocation. */
for(i = 0; i <>method_count; i++) {
if(strcmp(class_of_object->method_names[i], methodName) == 0) {
method_index = i;
break;
}
}

/* If the method name was not found in the list of class methods,
return an error code. */
if(method_index == -1) {
/* ToDo: send a "method not found" error code in the
outputParams. */
return;
}

/* Invoke the method at the index corresponding to the method
name. */
(*(class_of_object->methods[method_index]))(object, inputParams,
outputParams);
}

I wrote my solution a few weeks ago, then started researching how other object oriented schemes are implemented. I found out that my code has several disadvantages and some significant advantages as well. For example, I started to comapre the likelyhood of missing the RAM cache to solutions in C++ and Java. There were a few other intersting comparisons but I won't go into all of the nitty gritty details. Overall, I'm very pleased because I learned a lot. Lets discuss!

No comments: