• Welcome to TechPowerUp Forums, Guest! Please check out our forum guidelines for info related to our community.

The Official OOP guide for Rednecks ™

Kreij

Senior Monkey Moderator
Joined
Feb 6, 2007
Messages
13,817 (2.21/day)
Location
Cheeseland (Wisconsin, USA)
The Official OOP Guide for Rednecks ™ * ** ***
(* I'm a northern redneck. If you take offense at the term KMA)
(** this guide assumes you know at least a little about programming, like what a variable is)
(*** TPU, all it's affiliates and especially Kreij take no responsibility for anything)

Object Oriented Programming (OOP) has been around for quite some time and this guide is meant to try to make it as easy as possible to understand the terms and ideas associated with it. No more, no less. So grab yourself a beer and we'll get started.

What is OOP?
OOP is a paradigm or programming methodology. WUT?
It's just a way of looking at programming. OOP programming looks at the program from the standpoint of … you guessed it … objects.
That beer in your hand? That's an object.
The fact that's it's almost empty now? That's not an object. Go get another.
We'll get to all that shortly.

What is the history of OOP?
Google it, this is a guide, not a history lesson.
They say that those that forget history are destined to repeat it. I say grab another beer. You're call.

When should I use OOP?
When your program requires the use of objects. Duh.

What's an object?
Anything that has a state (one or more properties) AND a need for some way to manage a change of those states. WUT?
As I said, that beer is an object. One of it's properties might be “Amount left”, which will change over time. The program may have a function (or method as they are usually called) named “Get Another Beer”, based on the “Amount Left” property.

How do I make an object?
It's really easy. You just create a class that defines the object, it's properties and state management methods. WUT?
Okay, let's look at some code (all examples are in C# 'cause it's easy to understand what you are looking at).
Code:
[color=Blue]public class[/color] Beer
{
    [color=Blue]private[/color] [color=Teal]Int32[/color] _AmountLeft = 100; 
    [color=Green]// This makes the beer full when you create it.[/color]
    [color=Blue]private[/color] [color=Teal]Boolean[/color] _GetAnotherBeer = [color=Blue]false[/color]; 
    [color=Green]// This is true or false, depending on how much beer is left.
    // We set it to false originally because the beer is full when you open it[/color]

    [color=Blue]public[/color] Beer() {};

    [color=Blue]public[/color] [color=Teal]Boolean[/color] GetAnotherBeer { [color=Blue]get[/color] { [color=Blue]return[/color] _GetAnotherBeer; } }

    [color=Blue]public void[/color] TakeAnotherGulp()
    {
        _AmountLeft = _AmountLeft – 20; [color=Green]// Subtract 20% of the beer each gulp.[/color]
        if (_AmountLeft < 40) _GetAnotherBeer = [color=Blue]true[/color]; 
        [color=Green]// If your down to your last gulp, set GetAnotherBeer to true[/color]
    }
}

Coming Soon … What to do with the class you just made and an explanation of everything in it. I'll append it to this post.
(Give me a break, these guides take a lot of time to write, proofread and get right. :p)
Comments always appreciated.
 

char[] rager

New Member
Joined
Jun 9, 2010
Messages
310 (0.06/day)
Location
Massachusetts Institute of Technology, Computer Sc
System Name Obsidianight
Processor Intel Core i7 950 @ ~ 4 GHz
Motherboard Asus P6T Deluxe
Cooling Custom Liquid Cooling
Memory 6GB (3 x 2GB) Corsair XMS3 DDR3 Triple-Channel @ ~ 1.6 GHz (9-9-9-24-1T)
Video Card(s) Zotac AMP! GTX 580 @ 900 MHz Core / 1025 MHz Memory / 1800 MHz Shader
Storage 180 GB OCZ Vertex 2 SSD
Display(s) Sceptre 24 Inch (1920 x 1200) 2 MS Response
Case Corsair Obsidian 800D
Audio Device(s) Onboard
Power Supply 1 kW Antec TruePower Quattro
Software Microsoft Windows 7 Ultimate 64-Bit / Linux Mint 9 And Fedora 13 KDE Through VirtualBox
Thanks. I was recently wondering how games keep track of things, and I tried to simulate enemies using classes. I made some pretty obfuscated code, but it clearly demonstrates the power of object oriented programming.

I await what information somebody with your programming experience will be able to shed on OOP:toast:

Enemy Class
Code:
namespace EnemySoldier
{
    class Enemy
    {
        public int health;

        public Enemy()
        {
            health = 100;
        }

        public Enemy(int newHealth)
        {
            health = newHealth;
        }

        public void shootThisEnemySoldier(int damageDone)
        {
            health -= damageDone;
        }

        public bool isThisEnemySoldierDead()
        {
            return health <= 0;
        }
    }
}

Implementation
Code:
using System;
using System.Collections.Generic;
using EnemySoldier;

class Game
{
    static void PrintEnemySoldierHealth(List<Enemy> enemyList)
    {
        foreach (Enemy enemyObject in enemyList)
        {
            Console.WriteLine(enemyObject.health);
        }
    }
    
    static int IsEnemySoldierDead(List<Enemy> enemyList)
    {
        int numberOfEnemySoldiersDead = 0;
        
        foreach (Enemy enemyObject in enemyList)
        {
            Console.WriteLine(enemyObject.isThisEnemySoldierDead());

            if (enemyObject.isThisEnemySoldierDead() == true)
            {
                numberOfEnemySoldiersDead++;
            }
        }

        return numberOfEnemySoldiersDead;
    }
    
    static void Main()
    {
        int numberOfEnemySoldiersDead;
        
        List<Enemy> enemyList = new List<Enemy>();
        Random randomHealth = new Random();
        
        Console.Write("How Many Enemies Do You Want?  ");
        int numberOfEnemies = int.Parse(Console.ReadLine());
        Console.WriteLine();

        for (int counter = 0; counter < numberOfEnemies; counter++)
        {            
            enemyList.Add(new Enemy(randomHealth.Next(1, 500)));
        }

        PrintEnemySoldierHealth(enemyList);

        do
        {
            Console.WriteLine();

            Console.Write("How Much Damage Do You Want To Inflict On The Enemy?  ");
            int damageDelivered = int.Parse(Console.ReadLine());

            foreach (Enemy enemyObject in enemyList)
            {
                enemyObject.shootThisEnemySoldier(damageDelivered);
            }

            Console.WriteLine();

            PrintEnemySoldierHealth(enemyList);

            Console.WriteLine();

            numberOfEnemySoldiersDead = IsEnemySoldierDead(enemyList);

            Console.WriteLine();
        } while (numberOfEnemySoldiersDead != numberOfEnemies);
    }
}
 
Joined
Jan 9, 2010
Messages
481 (0.09/day)
Location
Kansas
System Name Late 2013 rMBP 13'' w/ 250 GB SSD
Display(s) Dell P2416D @ 2560x1440 & Dell U2211H @ 1920x1080
Audio Device(s) NuForce uDAC-2 w/ Klipsch Promedia 2.1 & Sennheiser HD595
Mouse Logitech G400 @ 1600 DPI
Keyboard Razr Black Widow
Software OS X
I like creating arrays in which each index in the array is an object I created by creating my own custom class and creating an instance of it.... Have I confused you yet ? Yeah, this is OOP! :laugh:

I like playing around with arrays of objects. It is very elegant way of programming because each index in your array can have multiple "instance variables". This makes it easier to store information in an array more efficiently and accomplish more using less memory (RAM). Don't forget to destroy objects when they are not needed, you expert programmers!

Example (This is VB.NET) -
Here is my "serials" class.
Code:
Public Class Serials
    Public systemSerial As String
    Public boughtFrom As String
    Public tradeDate As String
    Public employee As String

    Public Sub New(ByVal system As String, ByVal customer As String, ByVal tDate As String, ByVal emp As String)
        systemSerial = system
        boughtFrom = customer
        tradeDate = tDate
        employee = emp
    End Sub
End Class

Now I create a big fat array of the type serials in my main form's code.
Code:
    Public systemSerials(1000000) As Serials

[edit]
Almost forgot, I need to create an instance of this class.
Code:
     For k = 0 To systemSerials.Length - 1
            systemSerials(count) = New Serials("", "", "", "")
        Next
'^^^^^ count is being incremented elsewhere


Then I play around :~)
Code:
    Public Sub WriteSerials()
        Using Writer As New StreamWriter(selectedSystem + ".txt", False)
            For k = 0 To lsbDisplay.Items.Count - 1
                Writer.Write(systemSerials(k).systemSerial + ",")
                Writer.Write(systemSerials(k).boughtFrom + ",")
                Writer.Write(systemSerials(k).tradeDate + ",")
                Writer.Write(systemSerials(k).employee + ",")
                Writer.WriteLine()
            Next
            Writer.Write(systemSerial + ",")
            Writer.Write(boughtFrom + ",")
            Writer.Write(Now.Date + ",")
            Writer.Write(employee + ",")
        End Using
    End Sub

I really like this thread Kreij, it helps noob programmers like myself that are still in college. I learned OOP first in a Java programming course, I'm very glad I understand it at the bare level I do.

I hope maybe this example can help some VB noobies like myself :rockout:
 
Last edited:

olithereal

New Member
Joined
May 24, 2008
Messages
1,262 (0.22/day)
System Name Geometro
Processor i5 760 @ Stock (need 1156 brackets for my cooler)
Motherboard MSI P55A-G55
Cooling Kingwin RVT-12025 HDT
Memory 2x4GB Mushkin Blackline Frostbyte 1600 C9-9-9-24
Video Card(s) GTX 275 MSI Twin Frozr OC
Display(s) Samsung 2333SW 23"
Case Lancool PC-K62
Power Supply Corsair VX550W 550W ATX 12V
Software Windows 7 64 bit / Arch Linux x64
Great thread Kreij! I'm sure this will help a TON of new programmers! It probably will clarify and teach me more than a couple things as well! I'm still in college, so I try to read as much as I can on the subject!

Keep it up, and a big thanks!
 

streetfighter 2

New Member
Joined
Jul 26, 2010
Messages
1,655 (0.33/day)
Location
Philly
This would probably be a good time to mention that programmers should be careful about passing an entire object instance to a function unless a good chunk of the object is going to be modified by the function. This relates to a program I wrote some years ago where the instances were rather large (~50MB of memory) and one of my functions was creating a huge slow down when all I needed to do was assert a single property of an object instance.
 
Top