Friday, November 23, 2007

The Importance of Reading Classic Texts

Hi,
As the name of topic suggests, this is on classic texts. However, the domain considered is a narrow one. This is about technical books, mostly computer science books. This is one of the series of informal discussions that I keep on having with my friend Raghvendra. Raghvendra is from a Mathematics background and helps me with Maths, especially Algebra. I complement this by helping him (as well as I can) in the CS stuff. More importantly, he is fun-loving, sometimes lazy and casual like me and so we gel well :-)

Coming to the topic, this is an observation we had on the books that students study in colleges generally. Our observation leads us to conclude that most students prefer to read books that are easy-going, non-challenging and quick-fix solutions to exams. Let me once again remind you that this discussion is technical books centric, India centric.

Let me start with CS books. When you observe what books people read for programming these mostly turn out to be Kanetkars, Balagurusamys, Schaums, Teach Yourselfs, Schildts, Eckels and stuff like that. There is one fact I am going to tell you and I can bet on this. If you really want to learn a programming language, understand it's subtleties and nuances, develop your understanding so that you can appreciate deeper issues, you got to read the programming language creator(s) book PERIOD ... Why is this so ? Let me start with where these other books fail. First of all, if you take any of these books to a really good programmer, he will tell you how many incorrect statements they have. A classic example is telling that C is both call-by-value and call-by-reference. Second they talk too much on something and then miss out critical points which leave your understanding incomplete and dangerously insufficient. Third, they teach you bad coding styles. Look at code written in K&R, Stroustrup etc ... they look beautiful and elegant. Fourth, many of these books really mess-up your learning as they take you unnecessarily into things you don't need when you are starting to learn a language (stuff like hardware interaction, graphics, Windows and Linux programming). Last, and the most important and interesting reason is that they don't force you to think, they are too easy going. The creator books are difficult for beginners, I agree but, if you proceed patiently and put in some effort, you understand the right concepts and these things stick into your mind. You save a lot of time and effort later on.

Maths. There are so many classics, really wonderful books like Herstein's Algebra, Thomas-Finney's Calculus, Erwin Kreyzig's Engg Mathematics. I got some other names like Rudin's Real Analysis text, Dugundji's and Joshi's texts on Topology. Though, I really can't tell you why they are beautiful but Raghvendra prefers to read classics in Mathematics like I do in CS, so I believe they are going to be good. I am reading Herstein's Algebra and it is so wonderful when you have that AHA! moment, you can see the beauty that's there in those abstract structures. Thomas-Finney was one book I loved simply because of its style of presentation and the way it kept you showing how the mathematics related to some real world situations. Do you feel shaky about your concepts on limits, continuity and differentiability ? Pick up Thomas-Finney, give it a couple of days and you will see these things will come so naturally to you ever after.

Physics. Feynman's Lectures. Absolute joy to read this trilogy. You feel like attending a real lecture and the insights that you gain are awesome. Equations come but there are interpretations, the emphasis on understanding the content of equations is throughout the books. The difference between how a mathematician sees equations and what they mean to a physicist is something really important to know if you are serious about Physics, or are interested.

Hope, I got you to rethink on the topic of choosing a book when studying something. Let me know what you think, this is a nice thing to discuss :-)


Wednesday, November 21, 2007

Object Oriented Programming in C - Proof of Concept (Part 2)

Explanation of Code in the first part

Let us now try to understand the C code that was put in the first part of this post. The files new.h and class.h are files that will be common for any user-defined objects (i.e. stacks, queues, complex number or any class that you would like to implement in C). The purpose of new.h is that it declares two functions new and delete that will be used to create and destroy, respectively, any type of objects. The declaration of new tells us that its first argument is a pointer to the type of object that is going to be created. The ellipsis indicates that it can take a variable number of arguments. The arguments will be fetched and passed to the constructor function (here Stack_ctor) of the particular object. Now, there are still some issues like multiple constructors but believe me, that can be handled. I haven't given the implementation of new or delete as I want to convey to you the idea and not bog you down with the details. delete just accepts the pointer to the object to be destroyed, calls the object's destructor (here Stack_dtor) and finally frees the pointer to the object. Yes, we do not have the facility of automatic destruction like the one provided in C++, this is a limitation, you need to call delete explicitly.

Now for class.h, this contains a structure Class, which is nothing but a container for information common to any object. It is something similar to the Object class in Java from which all objects are derived. It contains the size of the object, and then four function pointers. These are for the constructor, destructor, clone and differ functions (see comments for clone and differ functions, they don't affect much the discussion here). Every object is now going to have a pointer to this Class structure (and more importantly, it is going to be the first member of every object, since it gives us an interface to access the constructor, destructor functions of any object).

Now, the header file stack.h, contains a void pointer named Stack. The user needs to be know this header file only for his task. The pointer Stack points to information represented by the structure Class. Later when we allocate an object using new, new will copy this information into the object and then call the object's constructor (here Stack_ctor). Keeping Stack a void pointer does not reveal any details to the user. Then, there are prototypes for the push and pop functions. Yes, you can point out that the void pointer arguments cannot be checked at compile time for the correct type. I have seen some compilers do that for the void pointers but yes this cannot be taken to be a standard behaviour. Proper runtime checks can be done with graceful exit in case of error.

Now, coming to the implementation of the stack in the file stack.c. First we see a structure Stack declared at the top. This structure holds the information generic to every object (the const void pointer class points to the Class structure for this object, this pointing is accomplished by the new function) and it may also hold some variables. Then we have the variables declared with static storage type (this is done to get the effect of private variables in classes in object-oriented languages, same can be done for functions). Next come definitions for the constructor, destructor, clone and differ functions for the stack. Finally we make an instance of the Class structure, _Stack, and then make the our pointer Stack from stack.h file to point to it. Later, new will use the pointer Stack to carry out complete initialization as I described earlier. The file ends with definitions for push and pop functions.

Monday, November 19, 2007

Object Oriented Programming in C - Proof of Concept

Hi,
I believe that the title of this post will come as a surprise to quite a few people in India (I don't know what is the situation outside). The major reason being that probably none of the books in the market on C programming, reveals that this is possible. Now, most people follow the textbooks and rarely try to question what the author is trying to teach them. If the author castigates C for something and praises C++/Java (your OO supporting language here), it is taken for granted, without ever questioning if what the book says is really correct (I mean things the authors say are problems with C or cannot be done in C).

What I want to say is that there are a lot of biased programming texts in the market which do not the convey the true picture. C is their favourite scapegoat when they teach (?) object-oriented programming. Object-Oriented programming at its core is nothing more than a set of best practices, it is not a silver bullet. Any language that supports OO well is called object-oriented, C does not support it very well hence it is not called so. That does not mean you can't do it, it only requires true skill and solid knowledge of the concepts.

Now we will see how to construct the equivalent of class in C. Since class is the thing from where distinction starts between C and OO languages, this should be a convincing proof of concept. Let's put down the main (or you might say basic) features of the class construct and try to get the equivalent in C.
  • A class contains variables (state) and methods/member functions that operate on the state.
  • A class provides you with data encapsulation so that only those methods that need to access the state of class and change it are allowed to do so.
  • A class has constructor method(s) which allow for safe initialization.
  • A class has a destructor that allows for reclamation of memory when it is not to be used again.
For the demo, let us take a simple class that represents a stack. The stack is being implemented using an array.

class Stack {
char *symbols; // pointer to a character array containing the symbols (single chars) in the stack
int top; // top of stack index
int max_size; // maximum size
public:
Stack(int size); // constructor
~Stack( ); // destructor

void push(char symb);
char pop( );
};

Here's the C equivalent. However, I must first point out that much of the following has been taken from the ebook by Axel-Tobias Schreiner, ooc.pdf, from where I learned this. There a couple of pages that point out an altenative and less frightening method to use object-oriented techniques in C. I will be listing them soon.

Header File: new.h

/* methods for creating and destroying any object */
void *new (const void * type, ...);
void delete (void * item);

/* methods common to all objects */
void *clone (const void *self);
int differ (const void *self, const void *other);
size_t sizeOf (const void *self);

Header File: class.h

struct Class {
size_t size;
void * (* ctor) (void * self, va_list * app);
void * (* dtor) (void * self);
void * (* clone) (const void * self);
int (* differ) (const void * self, const void * b);
};

Header File: stack.h

extern const void *Stack; /* the ADT representation for Stack */

void push (void *, char);
char pop (void *);

Implementation of Stack: stack.c

#include "class.h"
#include "stack.h"

struct Stack {
const void *class; /* this should be the first member of the structure always */
/* can put data that is publicly accessible here */
};

/* Data Encapsulation provided by giving the following variables internal linkage in this file,
only functions in this file can access and modify these variables directly */
static char *symbols;
static int top;
static int max_size;

static void *Stack_ctor (void *_self, int size) { ... } /* the constructor function */
static void *Stack_dtor (void *_self) { ... } /* the destructor function */
static void *Stack_clone (const void *_self) { ... } /* this function completely copies one object to other */
static void *Stack_differ (const void *_self, const void *other) { ... } /* this function can check if two objects are the same */

/* initialize the generic Class structure with function pointers specific to the object */
static const struct Class _Stack = {
sizeof(struct Stack),
Stack_ctor,
Stack_dtor,
Stack_clone,
Stack_differ
};
const void *Stack = &( _Stack );

void push (struct Stack *, char symb) { ... }
char pop (struct Stack *) { ... }

User Code

#include "stack.h"
#include "new.h"

int main (void)
{
void *mystack = new (Stack, 20);
char popsymb;

push (mystack, 'X');
popsymb = pop (mystack);
delete(mystack);
return 0;
}

To keep it easier, I have divided this topic into more than one posts. The explanation of above C code comes in the next part of this topic.

Sunday, November 18, 2007

The Question of Which Tire & Focal Point Strategy

There's a mail that has been circulated a lot in student groups as well as among people in software companies (as I came to witness during my software job).

This is about two friends who had a very good preparation for Chemistry (whatever) final for the semester. However, they had a party on weekend to attend and they decided to go for it. The party went really well and they missed to reach for the final on time. So, they concocted a story about their car tire being punctured and presented it to the professor as the reason why they were unable to reach on time. They asked for a makeup final and the professor agreed. When the final came, they were made to sit in different rooms and had two questions in the paper. First one was quite easy, 10 marks scored and they thought it was going to be cool when they turned the paper and found the second question, "Which tire ?".

Now this incident is claimed to be real and that it took place in IIT-Bombay. However, I doubt that this is true since I have been reading Game Theory (you must have heard this name if you have watched the movie, A Beautiful Mind) from a very nice book (Games of Strategy - Avinash Dixit, Susan Skeath) and there I found this to be a Duke University incident. Anyways, that's not the interesting stuff. What makes this thing interesting is that it presents an example of what are called focal point strategies.

In fact, there is one more strategic lesson from this story. That is, to recognize that professor is an intelligent (rational, in game theory jargon) player in this game. The students failed to take into account that professor may suspect their story to be fake, and that he may come up with such a question (whether in the final or maybe before it).

Now, coming back to the focal point strategies. The probability that both the friends picked up the same tire is easy to calculate and it is 1/4 or 25% (4 times 1/4 times 1/4). So they need to come up with some reasoning besides pure luck. Say, you are one of the students and you have some reasons to believe that the front right tire is most likely for puncture (pointed objects are more likely to be on side of the road, the trip had right turns mostly or anything you can come up with). What makes your choice good is not the reasons which you have thought of but, whether your friend has also made the same choice. So you need to consider whether your friend would think the same way (and pick the same choice as yours) and, that he thinks that you will also think the same way that he thinks that you think ... and so on. A chain of reasoning, and it needs to converge for the outcome to be in your favour (and your friend's). Hence, the name focal point. So to quote from the book, "what is needed is a convergence of expectations about what should be chosen in such circumstances. Such a commonly expected strategy on which players can successfully coordinate is called a focal point."

There is obviously more than this to focal points but, for starters it is quite a good example. I will be putting some more as I keep learning from the book.

Saturday, November 17, 2007

The First Post

Hi,
This is my first post now. I don't know how many people will read what I will be posting here from now onwards. However, it's going to start with my friends ;) ... most probably.

I aim to put in here mostly Computer Science and Mathematics stuff but it's not going to be too geeky from the start. The reason being that I am a student currently and I really don't have the time and energy to put in the "hardcore" geeky stuff, as I would be better using my time working on those things. So what do I put in here and why ?

Well, after some years of studying programming (and CS), being in a software job for a while, I realized that many people (whom I encountered) who program/code still have a lot of misconceptions, that I myself had some time back . So, there will be some programming and design stuff, things that I have learned (and tested) from the programming gurus.

I have a major interest in cryptography and computer security right from the college days. As a result I have spent time on the Internet and waded through books in an attempt to be a "hacker" (No, I'm not going to hack someone, it's just the desire to learn the craft and it takes some time to become a real hacker). Hence, I feel that I can share my experience with students and people who want to get into this area but have no idea of how to start learning these things.

Finally (Sorry, I took so much time of yours), I intend to put in here some Maths stuff. Please don't feel uneasy as there won't be abstruse equations all over the place. I have observed that people in India generally have a disregard for this beautiful subject (which is in fact at the base of all modern science and technology). So, in a humble effort, I intend to show some examples of how beautiful Mathematics is. I hope some people will catch up with some Maths as a result of this blog :)

Thanks a lot for reading up to this point :D ... Abhinav.