Programming/Classes: Difference between revisions

From Dev Wiki
Jump to navigation Jump to search
m (Formatting)
(Add some lines)
Line 52: Line 52:
     }
     }
  }
  }
Now, to access any of this logic, we can pass around a single instance of the class, which contains everything we need.<br>
If we need additional values or logic, we can add new variables and methods to our class.

Revision as of 02:32, 12 May 2020

Conceptually, a class can be thought of as a grouping of logic and/or variables.

Similarly, it can be though of as a struct but with extra, included logic.

General Concept

Hypothetically, let's say a business has a custom program. This program has a few "core" variables that are used throughout.
We can call them Revenue, Expenses, and Profit.

Let's also suppose that, in this program, any time one of the above variables is uses, the rest are guaranteed to be used shortly after.
So far, this is identical to our struct page example.


Now let's add in a key difference. Imagine that we want special logic (functions) associated with these variables as well.

For example, maybe we don't want Profit to be a literal variable, per say, so much as we want it to be calculated as Revenue - Expenses, every time it's called.
Suppose we also want custom validation logic to make sure Revenue and Expenses are only positive numbers.

The easiest way to do this would be to encompass all of this into a class. Depending on the language, it may look something like this:

class Costs {
    int revenue;
    int expenses;
 
    /**
     * Logic to validate revenue.
     */
    void set_revenue(int new_value) {
        // Prevent revenue from being negative.
        if (new_value <= 0) {
            raise("Revenue cannot be negative.");
        } else {
            this.revenue = new_value;
        }
    }
 
    /**
     * Logic to validate expenses.
     */
    void set_expenses(int new_value) {
        // Prevent expenses from being negative.
        if (new_value <= 0) {
            raise("Expenses cannot be negative.");
        } else {
            this.expenses = new_value;
        }
    }
 
    /**
     * Logic to calculate and return profit.
     */
    int profit() {
        return this.revenue - this.expenses;
    }
}

Now, to access any of this logic, we can pass around a single instance of the class, which contains everything we need.
If we need additional values or logic, we can add new variables and methods to our class.