Object-Oriented Programming Basics: What is in a Class?

EDITORIAL NOTE: This article was published briefly back in 2016 and quickly set back to draft because I wasn't happy with its contents. It is a shame that it was taking me three years to revisit this topic and work on a new and improved version. At least, I'm hoping it will be to the liking you the reader. Keep in mind that the opening paragraph will still read as if I just wrote it for my (former) students at Texas Wesleyan.

I started working on lecture on the topic of Object-Oriented (OO) Programming by gathering some material, old and new, when I realized this might be good and simple post for my second attempt at blogging. To be completely honest, in the 8 hours I spent collecting information and preparing material for this week's lecture, I realized I still made some of the mistakes I am about to blog about. I am actually hoping I can write a series of postings regarding Object-Oriented Programming (OOP). But to do so, I must start from the very beginning. Since a class is the principal building block which makes OOP possible, I thought it was prudent to get down to the basics of what is actually in a class. Or, better put, what should and should not be in a class.

So, what is a class? Many authors in the subject call the class a template, blueprint, or prototype from which objects are created. I personally preferred the term "blueprint." A class contains a series of attributes (data members) and behaviors (methods). This sounds very simple. And, in fact, it is!

The problem is identifying what actually belongs in a class. In my years developing software, I have noticed a trend that frankly scares me. And this is that some developers nowadays are becoming packrats; putting all kinds of attributes and behaviors in a class that do not belong there. What is even scarier is the reason why most of these developers would do such a thing. But before I get into that, why not start from the very beginning. And that is to start with the typical "Hello World" program.


public class HelloWorld {
    private static String message = "Hello World!";
    
    public static void main (String[] args) {
        System.out.println(message);
    }
}
In this example, "message" is a variable (data member) of this class called "HelloWorld" which also contains a single method called "main" that takes a single "String array" argument named "args." In that long sentence, I described the entire anatomy of the class "HelloWorld." And that is about as good as it gets for this example. However, there is so much more that you will need to know to create a class that simply cannot be explained using the "HelloWorld" example. Therefore, we must graduate to a little bit more complex example. Not much more, I promise you.

What belongs in a class?

I want to illustrate the simplicity of discovering what belongs in a class by using a simple example that has been used in many text books. However, I plan to expand on this example more than the typical text book would. For this example, I am creating a Circle class. If you have not taken an introduction to Object-Oriented Programming and Design (and even if you had), the primary goal of this philosophy is to model with software entities and their relationship after similar entities and relationships in the real world. For example, a typical book is composed of a back cover, back cover, pages, copyright information (with an asterisk), table of contents, publishing data, etc. I think you get the idea. So, if I was to create a class to represent the concept of a "Book" in real life, you will need to create a class that will contain all those attributes (data members). One exception is copyright information. One can argue that copyright information does not belong in a book class directly because this can be also found in things like a Music CD. Therefore, it is possible that this information DOES NOT belong in this class. Perhaps a more appropriate place for this information could be an "Intellectual Property" class from which the "Book" class can inherit from. This concept of inheritance is discussed in one of my blogs and you can review it later.

For now, I want to get back to creating the Circle class. When we think of the attributes of a circle, other than radius, we say a circle has:

  1. Circumference
  2. Area
  3. Diameter

However, each of these attributes of a circle can be expressed in terms of its radius (i.e. diameter = 2 * radius). Therefore, it does not make sense to create additional attributes for Circle, since the other attributes can be easily derived using radius. So, my Circle class could look something like this:


public class Circle {
    private static final double PI = 3.14159265359; // This is a CONSTANT data member
    private double radius; // This is a VARIABLE data member

    /**
     * This is a getter method (it returns data)
     */
    public double getArea () {
        return PI * radius * radius;
    }

    public double getDiameter () {
        return 2 * radius;
    }

    public double getPerimeter () {
        return 2 * PI * radius;
    }

    public double getRadius () {
        return radius;
    }

    /**
     * This is a setter method (it sets values on data)
     */
    public void setRadius (double radius) {
        this.radius = radius;
    }
}
As a general rule, attributes of a class must be made private to restrict direct access to them. This is known as Information Hiding, which is also referred to as Data Encapsulation. To learn more about access modification, go to my Java Keywords (Part I) article.

To conclude, I am going to try to answer the question that most likely is in your mind: what should not be in a class? I think I answer the "what should" be in a class, but definitely not the "should not." I hinted just a bit when I gave the example of a book and copyright information. However, that is just a small part. To illustrate, let me tell you now what scares me when I see work that some so called "developers" do. Some years back, I was reviewing code written by a coworker. Without getting into unnecessary details, imagine the following scenario: You like to read the newspaper every morning before going to school or work. So, in order to get your copy of the newspaper every morning, you buy the entire printing facility... the entire company, only so that you could print the one copy you will need every morning to read while sipping a cup of coffee. That is completely insane. Isn't it? If you want a copy of the paper every morning delivered to your door, all you need to do is to subscribe to their delivery service (is this still a thing in 2019?). That's it! So the class "Professor Fontanez" doesn't need an entire newspaper printing company as an attribute in order to guarantee receiving a paper every morning. Well.... that is what this former coworker did with the changed made to our software. Even a newspaper is not a part of me. It is only something I use when I want to read it. The parts that make me are the parts of my body and organs. If I was to model myself in a software application, that will be how I would do it. I hope this illustration makes sense. If it does or not, please leave comments on the section below and please subscribe to my blog.

Comments

  1. When defining a class, it is important to consider what properties and behaviors are needed to represent it. The example about the newspaper printing company is a great illustration because we must ensure the proper data fields and methods of a class by using logical reasoning to determine if it is a direct attribute or not. Also, we should always review our own code and make needed adjustments to avoid extraneous details.

    ReplyDelete
    Replies
    1. Thank you Melissa. Sometimes I make some terrible illustrations. When I taught in college, I could often see the look on my students faces. So, I would pick up on that and IMMEDIATELY address my mistake.

      When you write, you don't get the opportunity to make such adjustments, unless people comment (good or bad). So, I truly appreciate you taking the time to let me know you liked that illustration.

      Delete

Post a Comment

Popular posts from this blog

Combining State and Singleton Patterns to Create a State-Machine

The Beauty of the Null Object Pattern

Exception Handling: File CRUD Operations Example