Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

newbie - class question

Status
Not open for further replies.

fishysheep

Programmer
Oct 13, 2001
54
GB
hi

I'm new to OOP and I've been working my way through the "Bank Account" class. Now i understand the logic of it all but what I can't grasp is its real-life use. All I can think when I'm doing the Bank Account class/derived classes is that this information belongs in a database. They only benefit I can see is that using classes could stop a programmer applying certain functions to an object. But surely that only applies if the original class is non-inheritable and doesn't that somewhat defeat the reasoning behind OOP?

I'd be grateful for any explanation of why (as an example) Bank Accounts are better held as classes then stored in a database. Apologies if this is a stupid newbie question.

 
Well, here is one example. Lets say the bank has prefered members. They will be in different types of accounts

Code:
class BankAccount
{
public:
   // regular stuff
   virtual double GetServiceCharge() = 0; // pure virtual
   virtual double GetIntrestRate(){return 1.1;}

   // other stuff
};

class GoldAccount: public BankAccount
{
  ...
// must define pure virtual
  virtual double GetServiceCharge() { return 2.00;}
  
  // dont override Interest Rate because it will remain 1.1
}

class PlatinumAccount: public BankAccount
{
....
// pure virtual
  virtual double GetServiceCharge(){return 0.0;}

// prefered member, give em a better rate
  virtual double GetIntrestRate(){ return 2.2;}
};

// usage

BankAccount* pAcct = new GoldAccount;
cout<<"Gold Account:\n";
cout<<"IntrestRate: "<<pAcct->GetIntrestRate()<<endl;
cout<<"ServiceCharge: "<<pAcct->GetServiceCharge()<<endl;

delete pAcct;
pAcct = new PlatinumAccount;
cout<<"Pl;atinum Account:\n";
cout<<"IntrestRate: "<<pAcct->GetIntrestRate()<<endl;
cout<<"ServiceCharge: "<<pAcct->GetServiceCharge()<<endl;

delete pAcct;


Untested code, but that is the gist of the inheritance with oop.

Matt
 
Dear Matt

YES - I GET ALL OF THAT. I don't have a problem with the logic of classes at all.

I posted because I can't see why I would be better to write classes for all my bank accounts than to simply use a database. It seems fair to suppose that classes are the preferred solution as so many books use the "bank account" example. Why would classes be preferred over a database for the "bank account" situation?

thanks

 
If you're dealing with databases, you would use the data in the database to fill the values in the classes. The classes are needed to operate on the data.

-----------------------------------------------
"The night sky over the planet Krikkit is the least interesting sight in the entire universe."
-Hitch Hiker's Guide To The Galaxy
 
yesss... I get that - I know that info is stored in data members and that methods/member functions do whatever is nec to that (and other) data.

Lemme try again as I'm not getting my point across. If I had to build a bank account program why should I create/inherit classes for the accounts rather than stick it all in a database?

Why is using classes better?
 
Strictly speaking, a program can't process data in databases directly. A database is an external artifact from the other world. Any program (i.e. processor) used objects (bit patterns) in a memory.

To deal with database records you must define any program structures. For example, in the simplest case, the only text field of database record must be previously mapped on the char array or STL string or what else, and you must invent some mechanics to read/write database data from/to this internal program object.

You may distribute these internal data structures and access codes in your program - or may collect them in a compact well-defined and well-controlled construct (class in C++).

Central point: in both cases you have two different artifacts: database data and processed data.

Now:
1st case: database access data structures and codes are spreaded (more or less;) all over your sources;
2nd case: database record image and its access methods are localized in your class declaration, you have well-defined handle to deal with (external!) entities, you may separate data processing codes and details of database internal structures and access methods etc.

Can you do it (database processing) without classes? Yes, of course (remember Cobol). You may drive Ford T, but better try Cadillac or BMW...
 
Ok, this is a bit long.

If you are doing some small application programming, then the benefits of using classes may not be that obvious to you. However, as your project gets larger, you will realize that the abstraction that the classes provide helps you tackle the problem better.

For instance, let's say that your project is developing a bank account server database application. Let's say that the requirements are as follow:

[ol][li]Basic input/output mechanism to change and get the accounts[/li]
[li]Able to detect invalid/bogus/redundant/corrupt accounts[/li]
[li]Some printing and print preview capability[/li]
[li]Some security (password) identification[/li]
[li]Back-up mechanism[/li]
[li]Ability to upgrade existing data structure (for future application upgrade)[/li]
[li]Leeway for update/patch[/li]
[li]Ability to connect with client programs[/li]
[/ol]

One way to tackle the problem is to do a linear programming (the C style programming). Just write the necessary functions for all those features, then write a main() function where all those sub-functions are brought into play.

Pros: Simple
Cons: As your program gets longer, the source codes get very messy. They become less readeable to other programmers who will continue your work (or even to you when you are called back several months -in my case was years- later to fix/adjust your codes).

An alternate approach is to use an Object Oriented approach. In our case, we can create several classes, such as Database Manager (to handle IO on the database), Security Manager (to handle authentication and such), Printing Manager (to handle printing), Update Manager (to handle future update and data conversion), Task Scheduler (to handle timing for scheduled task such as scheduled back-up), Connection Manager (for remote logon).

Pros: By using objects, you can see clearly who do what. In the future, if you need to re-learn your codes, you can read the codes easily. Also, you can design some of your classes to be reusable (such as file IO, TCP/IP connection, Printing, etc.) so that for future projects, you can just reuse these classes instead of rewriting them from a scratch. In addition, object oriented approach helps you keep track of your memory allocation easily. You can see the variables that each class is responsible for and deallocate them properly at the appropriate destructor.
Cons: Slightly more complicated and time consuming. New programmers can get carried away with fancy OOP features.

Furthermore, in the real world, the requirements are not so easily defined. Most often users don't really know what they want. So we, software engineers, often have to define and redefine the requirements for the application. Often, we may feel like adding features while halfway working on the project, which sometimes require a lot of changes in the existing codes. If you are doing linear programming in a big project, it gets very very messy as you are traversing from one part of the codes to another. In OO apporach, you know exactly what class you need to alter.

However, OO approach is not necessarily better. Using classes does not solve all the problems. I have seen new programmers make classes out of everything and inherit them to death. I believe that you should know both approaches and use the one that suits your needs.

(I generally find that it's better to use struct to group simple data rather than using a class with a bunch of set/get methods. In my opinion, those set/get methods create unnecessary overhead.)

Hope this helps.

Zech
 
Ok, I read my own post above and it gets a little long-winded. :p This is the summary of what I was trying to say:

A class is just a way to group / organize your functions (methods) and data. The primary reasons for such organization are:
[ol][li]For easy reading and future adjustments[/li]
[li]For reusability[/li][/ol]
If you feel that such organization is not necessary, then I guess it's your call. There are many fine programmers who survive without classes.

Zech
 
>I posted because I can't see why I would be better to write classes for all my bank accounts than to simply use a database

Note that OO is more than just have a bunch of methods and attributes wrapped together. You have for example the concept of encapsulation (which is more than just making data private and having access methods).
It is also to design the class interfaces so it can easily be used properly.

Bad example:
Code:
// BAD EXAMPLE
class BankAccount
{
	BankAccout():mBalance(0) {}
	int getBalance() const { return mBalance; }
	void setBalance(int v) { mBalance=v; }
private:
	int mBalance;
};

The above example is bad because it gives no hint on how to use the class. It is just encapsulation in its most trivial and useless form.
By encapsulating properly your code can help to enforce an 'intended use'.


Better example:
Code:
class BankAccount
{
	BankAccout():mBalance(0) {}
	int getBalance() const { return mBalance; }
	bool withdraw(int v) { if (getBalance()>v) { mBalance-=v;return true; } else return false; }
	void deposit(int v) { mBalance+=v; }
private:

	int mBalance;
};

Even better example:
Code:
class BankAccount
{
	BankAccout():mBalance(0) {}
	int getBalance() const { return mBalance; }

	static bool performTransaction(BankAccount& from, BankAccount& to, int amount)
	{
		if (from.withdraw(amount))
		{
			to.deposit(amount);
			return true;
		}
		else
			return false;
	}
private:
	bool withdraw(int v) { if (getBalance()>v) { mBalance-=v;return true; } else return false; }
	void deposit(int v) { mBalance+=v; }

	int mBalance;
};

The point Im trying to make is that by using classes and OO you can make sure you access data in a way that makes sense and not just randomly.
Of course, there is nothing stopping the BankAccount class itself internally store the data in some DB.

/Per

&quot;It was a work of art, flawless, sublime. A triumph equaled only by its monumental failure.&quot;
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top