Programming/Classes: Difference between revisions
Brodriguez (talk | contribs) m (Correct typo) |
Brodriguez (talk | contribs) m (Brodriguez moved page Classes to Programming/Classes) |
Latest revision as of 17:26, 25 October 2020
Conceptually, a class can be thought of as a grouping of logic and/or variables.
Similarly, it can be thought 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.