473,406 Members | 2,371 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

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 1612

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 interrelationships 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.CheckPermissions('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******@eminent.demon.co.uk.not.this.bit.no.html
2 Tees Close, Witham, Essex.
Gravity beer in Essex <http://www.eminent.demon.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 interrelationships 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.CheckPermissions('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($sql);
$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($query, 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('SELECT `'.$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('SELECT `'.$t.'`.`ID` FROM `'.$t.'` WHERE '.$f.' =
"'.$v.'";');
}

function tcount ($t, $w) {
return mysql_zz('SELECT (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($id, $min, $max);
if($id) {
return mysql_zz('SELECT `'.$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($id, 0, 255);
return mysql_zz('SELECT `'.$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('SELECT '.$word.'(ID) FROM `'.$t.'`;');
}

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

?>
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******@eminent.demon.co.uk.not.this.bit.no.html
2 Tees Close, Witham, Essex.
Gravity beer in Essex <http://www.eminent.demon.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
(getCoureseworkResults(), 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
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,...
18
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...
1
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...
13
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....
9
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...
8
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...
21
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...
5
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...
3
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...
0
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...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
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,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
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,...
0
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...

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.