473,811 Members | 3,532 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

why use a class

Hi Folk

I was wondering to hear from you why you use classes in some instances
rather than functions. I have never used a class, but I use a lot of
functions.

I don't have a comp sci background, so I may miss some of the basics.

TIA

- Nicolaas
Aug 10 '05 #1
6 1636

A class is really more analogous to a structure than to a function.

A class is like a structure but it can 'inherit' from another class,
and it can have functions (aka methods) that are members of the class.
--
brianleahy

OS X 10.4
G5 Dual 2GHZ / 160GB / 1GB RAM / Superdrive
Apple 20" Cinema Display
SmartDrive 120GB Firewire HD
Maxtor 250GB SATA
Visit my wife's eBay store !!

http://stores.ebay.com/Catchy-Creations-by-brendaonline

Not thrilled about the Intel switch, but trying to remain optimistic.
------------------------------------------------------------------------
brianleahy's Profile: http://www.macosx.com/forums/member.php?userid=456
View this thread: http://www.macosx.com/forums/showthread.php?t=237525
macosx.com - The Answer to Mac Support - http://www.macosx.com

Aug 10 '05 #2
Following on from windandwaves's message. . .
Hi Folk

I was wondering to hear from you why you use classes in some instances
rather than functions. I have never used a class, but I use a lot of
functions.

I don't have a comp sci background, so I may miss some of the basics.

TIA

- Nicolaas

I know where you're coming from.

Look on classes and OO as a good way to do lots of things. You'll still
use 'stand alone' functions but _thinking about_ things in an OO way
should make a big difference. Just like your function library took time
to develop so will your collection of handy objects.

For example I have database and table classes to replace my collection
of database related functions. A lot of the code is the same, but one of
the things I can do now is prepare and cache certain things to assist
performance.
There are plenty of easy examples. See chapter 14 of the PHP manual. An
excellent example is creating an email. There are a number of classes
around which basically let you set a load of elements then do the dirty
work for you.
One example is having a user class (and working with instance objects).
[You can think of _class_ as being the ideas that make it work, the
design and interrelationsh ips with other objects, and the _object_ as
the practical realisation which gets processed.] My standard user class
handles creating a new user, interfacing with a database table, managing
passwords, managing permissions and change of email address etc. At the
top of every page I can do /something/ like

session_start() ;
$cu = GetCurrentUser( ); // this is a stand alone function
$cu.CheckPermis sions('IsAdmin' ); // this is an object-function

The thing is I know that all my user related data and procedures are in
the one place and the messy bits are nicely wrapped up. If experience
shows that the user class could usefully be enriched then I only have to
visit one bit of code to do it knowing that the behaviour will not be
adversely affected by no-longer applicable functions. For example there
is a class-function to validate a password then I thought it would be
great to allow another developer to plug-in their own function. Not a
single bit of page code had to be changed to make use of this feature,
it was all handled 'inside' the class.

There are other good reasons for adding the ability to write and use
classes to your repertoire but it is too large a subject to go into
here.

--
PETER FOX Not the same since the bolt company screwed up
pe******@eminen t.demon.co.uk.n ot.this.bit.no. html
2 Tees Close, Witham, Essex.
Gravity beer in Essex <http://www.eminent.dem on.co.uk>
Aug 11 '05 #3
Peter Fox wrote:
Following on from windandwaves's message. . .
Hi Folk

I was wondering to hear from you why you use classes in some
instances rather than functions. I have never used a class, but I
use a lot of functions.

I don't have a comp sci background, so I may miss some of the basics.

TIA

- Nicolaas

I know where you're coming from.

Look on classes and OO as a good way to do lots of things. You'll
still use 'stand alone' functions but _thinking about_ things in an
OO way should make a big difference. Just like your function library
took time to develop so will your collection of handy objects.

For example I have database and table classes to replace my collection
of database related functions. A lot of the code is the same, but one
of the things I can do now is prepare and cache certain things to
assist performance.
There are plenty of easy examples. See chapter 14 of the PHP manual. An
excellent example is creating an email. There are a number of
classes around which basically let you set a load of elements then do
the dirty work for you.
One example is having a user class (and working with instance
objects). [You can think of _class_ as being the ideas that make it
work, the design and interrelationsh ips with other objects, and the
_object_ as the practical realisation which gets processed.] My
standard user class handles creating a new user, interfacing with a
database table, managing passwords, managing permissions and change
of email address etc. At the top of every page I can do /something/
like
session_start() ;
$cu = GetCurrentUser( ); // this is a stand alone function
$cu.CheckPermis sions('IsAdmin' ); // this is an object-function

The thing is I know that all my user related data and procedures are
in the one place and the messy bits are nicely wrapped up. If
experience shows that the user class could usefully be enriched then
I only have to visit one bit of code to do it knowing that the
behaviour will not be adversely affected by no-longer applicable
functions. For example there is a class-function to validate a
password then I thought it would be great to allow another developer
to plug-in their own function. Not a single bit of page code had to
be changed to make use of this feature, it was all handled 'inside'
the class.
There are other good reasons for adding the ability to write and use
classes to your repertoire but it is too large a subject to go into
here.

Hi Peter

Thank you for your in-depth answer. I am just trying to wrap my head around
it ;-)

In VB it was really nice (paradox?) when I created a class that when I
typed, for example, "myclass." then it would show all the methods for the
class (i.e.the autocomplete). However, in PHP I work in Notepad2, which
does not have that function (well, as far as I know).

Now, I have a function in a file called dropdown.php. It creates a dropdown
for any given table and field:

<?php
//creates a dropdown for a table
//$table = the name of the table
//$name = the name of the select control
//$class = the class of the select control
//$select = the ID of the item that should be selected as default
//$fieldname = the name of the field in the table that should be shown
//requires the primary key in the table to be named as ID

function dd($table, $name, $class, $select, $fieldname){
$sql = 'SELECT `ID`, `'.$fieldname.' ` FROM `'.$table.'` '.$sqlw.' ORDER BY
`ID`;';
$query = mysql_query($sq l);
$v = '<select name="'.$name.' " id="'.$name.'" class="'.$class .'">';
while ( $row = mysql_fetch_row ($query) ) {
$v .= '<option';
if ( $select && $row[0] == $select ) {
$v .= ' SELECTED ';
}
$v .= ' VALUE="'.$row[0].'">'.$row[1].'</OPTION>';
}
$v .= "</SELECT>";
return $v;
}
?>
dont worry about the code, I am sure you get the gist. How would this
function benefit from being put into a class? I am not doubting that this
would be useful, I just trying to understand the concept better.

Thank you again for your great answer... It made it such much clearer.
Aug 11 '05 #4
windandwaves wrote:
Here is another bunch of functions that I think may benefit from being in a
class, but I am not sure how...
The file is called mysql.php and it is part of my library.

<?php

//this file provides basic sql functions that are used by other scripts
//you have to be careful with SQL because it can screw with your data
//therefore, never use " quotes but always use ' to encapsulate queries
//also, encapsulate fields and tables with ` symbols
//actual values (e.g. `ID` = "3") to be inserted should be encapsulated with
"-style quotes
//it does not make much difference, but it definitely protects against basic
SQL injection.

//used for action queries (delete, insert, update)
function sqler($s) {
sqllog($s);
$query = mysql_query($s) ;
if($query){
return 1;
}
else {
sqllog("error in previous entry");
return 0;

}
}

//allows you to select the first field of the first row in a query (can have
only one row)
//e.g. $s = select d from final where id =1;
function mysql_zz($s) {
sqllog($s);
$query = mysql_query($s) ;
if($query) {
if (mysql_num_rows ($query) != 1) {
sqllog("error in previous entry");
return false;
}
return mysql_result($q uery, 0,0);
}
else {
sqllog("error in previous entry");
}
}

//return value in table (t) for field (f) where (id)
function look($t, $f, $id) {
return mysql_zz('SELEC T `'.$t.'`.`'.$f. '` FROM `'.$t.'` WHERE ID =
"'.$id.'";' );
}

//like look but returns a string if the record can not be found
function lookd($t, $f, $id) {
$v = look($t, $f, $id);
if ( $v ) {
return $v;
}
else {
return 'record not defined';
}
}

//looks up the value for a certain table where a certain field is a certain
value
function idlook($t, $f, $v) {
return mysql_zz('SELEC T `'.$t.'`.`ID` FROM `'.$t.'` WHERE '.$f.' =
"'.$v.'";') ;
}

function tcount ($t, $w) {
return mysql_zz('SELEC T (COUNT(`'.$t.'` .`ID`)) a FROM `'.$t.'` WHERE '.$w.'
;');
}
//checks if ID exists and makes sure no sql is injected, mainly useful for
autonumber IDs
function idok($t, $id) {
$min = maxi($t, true);
$max = maxi($t, false);
$id = sanitize_int($i d, $min, $max);
if($id) {
return mysql_zz('SELEC T `'.$t.'`.`ID` FROM `'.$t.'` WHERE ID =
"'.$id.'";' );
}
else {
return 0;
}
}

//check if ID exists for short lookup lists
function idok_byte($t, $id) {
$id = sanitize_int($i d, 0, 255);
return mysql_zz('SELEC T `'.$t.'`.`ID` FROM `'.$t.'` WHERE ID =
"'.$id.'";' );
}
//finds the max and/or min ID-value for a certain table
function maxi($t, $min = false){
if ($min) {
$word = 'MIN';
}
else {
$word = 'MAX';
}
return mysql_zz('SELEC T '.$word.'(ID) FROM `'.$t.'`;');
}

function sqllog ($s) {
$sql = 'INSERT INTO `SQL` ( `MEM` ) VALUES ("'.removequote s($s).'");';
return mysql_query($sq l);
}

?>
Aug 12 '05 #5
Following on from windandwaves's message. . .
windandwaves wrote:
Here is another bunch of functions that I think may benefit from being in a
class, but I am not sure how...


What would you say to someone who said: "I think I might benefit from
changing my car into a motorbike"? Probably something like "you're
looking at it the wrong way." Then perhaps (a) Learn what a motorbike is
good for (b) Learn how to ride it (c) Use whichever mode of transport
suits whatever you happen to want to do at the time.

If a genie jumped out of a lamp and said "Thou must go on a long and
dangerous quest" then popped back into his lamp without further
information would you pack your bags and head off in any direction not
knowing what you were looking for? - Probably not.

The bottom line is you have to study the OO subject a bit more by
reading the basic principles and theory (a little), reading the manual
(doesn't take long) and experimenting (a bit).
....


--
PETER FOX Not the same since the bra business went bust
pe******@eminen t.demon.co.uk.n ot.this.bit.no. html
2 Tees Close, Witham, Essex.
Gravity beer in Essex <http://www.eminent.dem on.co.uk>
Aug 12 '05 #6
A good example for OO is the 'Person' class.

All Persons have name, address, telephone number etc. You create a
class that encapsulartes these variables, with getter and setter
methods for using them.

If you then needed to extend their functionality, for example to have
classes that dealt with Students and Lecturers, you would have half of
the functionality already built. The student and lecturer classes
would EXTEND or INHERIT (key words to learn about) all of the
functionality of the Person class, but you could add relevent
functionality for the student and lecturer classes
(getCouresework Results(), getAttendence() for student for example).

An exampe for PHP; you could create some sort of SQL writing class,
then create SUBCLASSES for Oracle, MySQL and Postregsql integration -
the SQL development would be inherited from the SQL writing class but
the bit that communicates with the db and executes the SQL would be
developed in the SUB CLASS (also known as CHILD CLASS).

The key strength is in maintainability . If you had just written the
SQL writing code and copy and pasted it into 3 functions for writing to
the various DBMS and you found an error, you would have to correc it in
3 places. If you had created a set of classes, then you would only
have to update it in one place.

Now in PHP with include files you *can* possibly achieve a similar
level of reusablity (I can't think why not but my gut instinct tells me
it must be flawed in some way), but OO is a nice and neat way of
achieving it.

The beauty of OO from a conceptual perspective is that you can model a
project in terms of things that can relate to the real world; persons,
chairs, products and so on. It can help in understanding how these
things interact and therfore in assists in planning the code.

Have a look at class diagrams and UML for some ways of modelling and
planning code - the bigger the project the more the benefit is from
approaching the development in a formal and structured way.

Hope this helps,

Rick
www.e-connected.com

Aug 12 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
9604
by: Fernando Rodriguez | last post by:
Hi, I need to traverse the methods defined in a class and its superclasses. This is the code I'm using: # An instance of class B should be able to check all the methods defined in B #and A, while an instance of class C should be able to check all methods #defined in C, B and A. #------------------------------------------------
18
6962
by: John M. Gabriele | last post by:
I've done some C++ and Java in the past, and have recently learned a fair amount of Python. One thing I still really don't get though is the difference between class methods and instance methods. I guess I'll try to narrow it down to a few specific questions, but any further input offered on the subject is greatly appreciated: 1. Are all of my class's methods supposed to take 'self' as their first arg? 2. Am I then supposed to call...
1
3347
by: Oplec | last post by:
Hi, I'm learning C++ as a hobby using The C++ Programming Language : Special Edition by Bjarne Stroustrup. I'm working on chpater 13 exercises that deal with templates. Exercise 13.9 asks for me to turn a previously made String class that deals with char's into a templated String class that uses the template parameter C instead of char. I thought it would be fairly simple to do this exercise, but I encoutered many errors for my...
13
2394
by: Bryan Parkoff | last post by:
I have created three classes according to my own design. First class is called CMain. It is the Top Class. Second class and third class are called CMemory and CMPU. They are the sub-classes. Two sub-classes have the relationship to communicate back and forth through this pointer. The pointer is responsible inside Top class for allocating and deallocating two sub-classes. CMemory class is responsible to allocate and deallocate memory...
9
4998
by: Banaticus Bart | last post by:
I wrote an abstract base class from which I've derived a few other classes. I'd like to create a base class array where each element is an instance of a derived object. I can create a base class pointer which points to an instance of a derived class, but when I pass that base class pointer into a function, it can't access the derived object's public functions. Although, the base class pointer does call the appropriate virtual function...
8
2858
by: Bryan Parkoff | last post by:
I find an interesting issue that one base class has only one copy for each derived class. It looks like that one base class will be copied into three base classes while derived class from base class is executed. It means that three derived classes are pointed to a separated copy of base class. I do not allow second and third copy of base class to be created, but it must remain only first copy of base class. It allows three derived...
21
4085
by: Jon Slaughter | last post by:
I have a class that is basicaly duplicated throughout several files with only members names changing according to the class name yet with virtually the exact same coding going on. e.g. class A { std::vector<B*> Bs; public:
5
3167
by: Andy | last post by:
Hi all, I have a site with the following architecture: Common.Web.dll - Contains a CommonPageBase class which inherits System.Web.UI.Page myadd.dll - Contains PageBase which inherits CommonPageBase - Contains myPage which inherits PageBase Each of these classes overrides OnInit and ties an event handler
3
3763
by: Hamilton Woods | last post by:
Diehards, I developed a template matrix class back around 1992 using Borland C++ 4.5 (ancestor of C++ Builder) and haven't touched it until a few days ago. I pulled it from the freezer and thawed it out. I built a console app using Microsoft Visual C++ 6 (VC++) and it worked great. Only one line in the header file had to be commented out. I built a console app using Borland C++ Builder 5. The linker complained of references to...
0
2840
by: emin.shopper | last post by:
I had a need recently to check if my subclasses properly implemented the desired interface and wished that I could use something like an abstract base class in python. After reading up on metaclass magic, I wrote the following module. It is mainly useful as a light weight tool to help programmers catch mistakes at definition time (e.g., forgetting to implement a method required by the given interface). This is handy when unit tests or...
0
10644
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10379
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10127
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9201
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7665
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6882
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5552
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4336
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3015
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.