Friday, April 4, 2014

What the hell is a class?

So I have gone to a lot of interviews and done a lot of interviewing and sometimes you see or hear some very basic questions like "What is the difference between an interface and an abstract class?" or "Does Java/C# support multiple inheritance?"

Now these seem like simple questions with simple answers, but as I have started doing more JavaScript development and listening to Douglas Crockford talk about JavaScript I find myself coming up with very different answers to these questions.

The first question to ask yourself is what is a class. It seems very basic because most developers are constantly working with classes and they don't really question why they are there and just take them as an intrinsic part of programming. But I will try to answer the question in a clear way.

A class is a construct that does 3 things. The fact that it does those 3 things unhealthily conflates those things, but if you pull apart those things you can have a better understanding of a class.

1) A class is a contract. A class defines type information and a type checking system forces a program to live by the rules of this type checking. It also acts a promise to other objects that it can do certain things and acts in certain ways.

2) A class is an object factory. You call a method and you get back an object. Java and C# kind of hide this basic fact by wrapping it with a 'new' keyword and having special constructor syntax, but I am sure you can imagine something like:

class ClassName {
    static ClassName CreateClassName() {
        return Object.create(ClassName);
    }
}

ClassName myNewClass = ClassName.CreateClassName();

This is essentially the same thing as 'new' but the syntax here (while incomplete) makes it a little clearer that a class is actually an object factory.

3) A class is a way for objects to share methods and data. Each object with the type of this class is able to use the methods of the class. This is essentially a way for a set of objects to share methods.

Now let's go back to "What is an interface?" An interface is the contract part of the class. "What is an abstract class?" It is the code sharing and contract part of a class without the object construction. "Does Java/C# support multiple inheritance?" An object can have multiple contracts but only one object factory, but that object factory can use shared code via inheritance.

I think it is important to understand the purpose of a class when you approach a language like JavaScript enhanced by TypeScript because you can use classes or not use classes. The enhanced flexibility of a language like JavaScript means you better understand the pros and cons of various structures.

No comments:

Post a Comment