Okaaaaaaay....
I am migrating from PHP to C#, I used PHP because it was sooo easy to use and to understand, though I have always had a problem when it comes to understanding objects & classes, not how they are created but really, what their purpose is, I created many applications with PHP and found that I could create them using functions, and to my own detriment, I avoided classes because I couldnt really get on with them, Now I am migrating to C# for a number of reasons, mainly because if I want to get anywhere as a developer I MUST learn to use objects in there correct manner.
Also I know I am making references to PHP type syntax, but as I am moving to C#, if there are any crossovers, I hope you will forgive them!
I can understand that objects are very good for code reuse, but thats why i used functions, if I needed to describe a product, I created a function that would do this, then loop for each product in the DB, so If I have to create an object that holds a method to do this exact same job, why use the object instead of the method/function on its own.
I suppose these are a bit confusing to read, I am having difficulty articulating what I mean!
I know an object can be used to do what you need it to do, and I have tried reading through tutorials, in order to try to understand this, but I will try to put my point across and please let me know what I am confusing and where I am going wrong!
say I have the object cupOfCoffee, this can hold the values, milk(bool), coffeeType(string example: "instant"), sugar(int), container(string, example: "cup" or "mug")
would then if I was making an application that made multiple instances cupOfCoffee , if I used functions only would I get into trouble because to create multiple instances using functions I would have to store each cupOfCoffee instance either in an array, flat file or DB with a reference (so that they could be referenced individually), whereas using the cupOfCoffee Object, I could have multiple instances:
(psuedocode)
*****************************
jim = new cupOfCoffee;
sarah = new cupOfCoffee;
// now I have jim.cupOfCoffee, sarah.cupOfCoffee
//now I want to make it how they like it:
jim.cupOfCoffee.milk = true;
jim.cupOfCoffee.sugar = 0;
jim.cupOfCoffee.coffeeType = "Fresh";
jim.cupOfCoffee.container = "mug";
sarah.cupOfCoffee.milk = true;
sarah.cupOfCoffee.sugar = 2;
sarah.cupOfCoffee.coffeeType = "instant";
sarah.cupOfCoffee.container = "cup";
*****************************
Now, If was to do the same with Functions I would have something like:
*****************************
functon cupOfCoffee($name, $milk, $sugar, $type, $container)
{
$name = new array(); // I klnow this a PHP method, but I am just learining and this what I know!
$name[milk] = milk;
$name[sugar] = sugar;
$name[type] = type;
$name[container] = container;
$return name();
}
//now lets make the coffee:
$JimCoffee = cupOfCoffee("jim", 1, 0, "Fresh", "Mug") ;
$sarahCoffee = cupOfCoffee("sarah", 1, 2, "Instant", "Cup");
print_r (JimCoffee);
print_r(sarahCoffee);
*****************************
Both methods will return a value of jim/sarah, and the details holding their preferences of coffee, with the C# example they would be held in an object, in the PHP function they would be held in an array.
So what is the difference?
Why would holding the details in an object be better than holding the same details in an array? I'm sorry but I just cannot seem to get past the idea that you can get to the same result, I suppose the question is not why is it better, but why is it preferable to use and OOP than functions?
Or am I completley wrong in what I think?
Loading
Sam HobbsPosted Jul 15, 2010, 7:58 PM
You say "function" a lot; is the function you showed a sample PHP function?
I can tell you a little history that might help. PHP (at least the original PHP) is like C; they look alike and the runtime functions for PHP were similar to the C runtime functions. In the past, the C language had "struct" types and structures only had plain data such as integers and they could have other structures; C structures cannot have functions. Then someone began to make macros that allowed use of C in a more object-oriented way. So the predecessor to C++ was C macros.
So objects such as classes in C# and C++ can have both data and functions (C# can also have properties, which are like a combination data item and function, but for now that is just confusing).
I think that what you are calling an array is not a traditional array. A traditional array has subscripts that are numbers and only numbers. If the items that you are calling arrays allow data in the square brackets to have non-numeric values then they are not actually arrays. In other languages they would be called a dictionary or a map.
You said "or at least referenced (....) an object can be called anywhere" and I don't understand; I think your thoughts were distracted when you wrote that.
You also said "array only holds data" but I don't know if that is true; you know better tahn I do. The important thing is that in C# and most other languages, you must define what an object is and objects must have all that you say it does; nothing less and nothing more.
James CrawfordPosted Jul 18, 2010, 9:47 AM
It has been a great help, the examples and tutorials that I have come across in the past all seem to insiuate that you have a small working knowledge of what classes and objects are, I think I have been looking for the wrong answer, or at least the wrong question has been giving me the wrong answer, what I suppose I should have been asking all along is, What are objects AND in what context do they fit into an application?
Both of your answers have helped me to discover this, and the post I made about variables and functions, was me trying to show that I understand their context, (or at least I am begininng to..)
Well Rome wasnt built in a day and I do need to work on this a lot more before I am able to create that 'next operating system ' hehehe
All the best
Jimmy
theLizardPosted Jul 17, 2010, 6:32 PM
Don't worry about me and Sam we are not really arguing, we are just a couple of old farts having our independent say about our interpretation of what things are, Sam takes a more by the book method I have a more simplistic view of things that is I do not particularly care about the technical reasons why you should or should not do things in a particular way I do things in ways that get results and some times that means doing a lot more work to start with but you end up with a shorter development time.
In my view, all objects are is a means to reuse code in one or more applications, if the object is generic in nature then you can have a single object that does not or is not dependent on the known or unknown. The best way for me to illustrate this is to give an example of a function (method) in a c++ component i have written that looks at the controls on a windows form (text, combo, date time edit type controls) and associate a single control on a form to its corresponding database field. (this is only one of a number of functions needed to do the job)
int __fastcall TLizardAgent::SetEditOrdinals(TWinControl *p)
{
int ordinal;
UnicodeString name1, name2;
int type;
int j;
fieldCount = 0;
//compare the edit controls on the TWinControl's ClassName, if they match one of these
//cast the control to one of the TLizard controls like this c = static_cast
//once cast to the edit control we can get the exended properties and set their values
//from the info in the database. Remember, these were obtained with a call to
//agent->getColDef(db, "what table", "");
//type: is an enum
//name1: is the FieldName property of the control
//name2: is the field name extracted from the database and placed in Fields[n].field
for(int i =0; i
{
type = coNone;
if(p->Controls[i]->ClassName() == "TLizardComboBox")
{
c = static_cast
name2 = c->FieldName;
type = coCombo;
}
if(p->Controls[i]->ClassName() == "TLizardEdit")
{
e = static_cast
name2 = e->FieldName;
type = coEdit;
}
if(p->Controls[i]->ClassName() == "TLizardDateTimePicker")
{
dt = static_cast
name2 = dt->FieldName;
type = coDateTime;
}
switch(type)
{
case coCombo:
case coEdit:
case coDateTime:
for(j = 0; j< (int)Fields.size()-1; j++)
{
name1 = Fields[j]->Field.LowerCase();
if(name1 == name2.LowerCase())
{
ordinal = Fields[j]->OrdinalPosition;
fieldCount++;
break;
}
}
switch(type)
{
case coCombo:
c->DbOrdinal = ordinal;
Fields[j]->Lookup = c->Lookup;
Fields[j]->LookupTable = c->LookupTable;
Fields[j]->LookUpIdentName = c->LookUpIdentName;
break;
case coEdit:
e->DbOrdinal = ordinal;
break;
case coDateTime:
dt->DbOrdinal = ordinal;
break;
}
break;
}
}
return(fieldCount-1);
}
//---------------------------------------------------------------------------
Now this function (method) does not do a great deal but what it does is crucial to how the the component works, the TLizardAgent (the object) here could never know and would not know in advance how many controls on a form there are, it does not need to know yet by placing this one object on a form we can assign values to the controls, create the sql statments of an Insert or update, set focus to the next control in rank order on keydown (VK_RETURN) to do what this does the old way, you would need create the methodes on every single windows form, explicitly map the controls on the form to a database field, create the sql statements using the field names and parameter bind the values form the controls on the form, this is an enormous amount of work especially if you have 5, 10, 20 odd forms.
All I am trying to do here with this example is to show what can be achieved with classes (objects if you like) by careful design you can create generic tools to shorten any development time.
This example function can also be done in C#..
Sam HobbsPosted Jul 17, 2010, 2:13 PM
In C++ and in C# there is a "this". The this is a pointer (C++) or reference (C#) to the object. The only difference between a static and a non-static function is that a static function does not have the this pointer or reference. For C++, when a non-static function of a class is called, there is always at least one parameter; the this pointer. You don't see the this pointer as a parameter; it is hidden or at least it is passed automatically. A static function can do everything a non-static function can do except a static function needs to get the this pointer or reference somehow other than the normal way that member functions do. The reason static functions are needed is when a function is called from some other software such as Windows that calls functions that could be written in various languages. Static data items are items that get allocated once only when the program begins execution and that one allocation is always used.
So technically, there is only one copy of the code for every function, regardless of whether it is a static or non-static function. The only difference is that a static function gets called without knowing where the non-staic mebers are at; it needs to be told where "this" is if it needs to access non-static members of the class.
James CrawfordPosted Jul 17, 2010, 1:30 PM
Right from what I have been reading up on and have been trying to find out more about objects nad their context in the part they play in applications, so this is the conclusion I have come to.
A class is the basis of outr code, we create a class to perform a specific function (in the english context, not a programmatic context, i refer to the the purpose of the class)
An object is a reference to, or in its simplest form, a temporary copy of the class, this is why you can have static and non-static members, or functions, which allow is to perform static (class) functions, or non-static(member) functions calling a static(or class) function means that the class, in its original format runs the function, when calling a non-static(or member) function, you are calling the functions, through the object, and in effect, calling the temporary copy of the class function, that is stored within the object (the temporay copy of the class)
this also applys (in its own way) to members (or the variables) of the class, a non-static variable can only be changed through the object because the object is the temporary copy of the class, and the assigning of value applys ONLY to the object in which the member has been changed,
so for instance:
class Demo
{
public int userID;
public static string clubTitle;
}
we can change the value of userID only if we have created an object first but I am going to create two to illustrate my reasoning
Demo myDemo = new Demo;
Demo myNewDemo = new Demo;
So to change the value of userID in myDemo, we would use
myDemo.userID = 1;
however, because myNewDemo.userID has yet to be assigned a value it reamins null.
but with static variables, these can uniformly change the value in all objects, without the need for changing each individual value (as you would have to do with non-static), but to do this we have to go through the class , and not an object:
Demo.clubTitle = "My C# Sharp class";
this would mean now both myDemo.clubTitle AND myNewDemo.clubTitle would both be 'My C# Sharp class'
now this is where I begin to get a little confused, going back to functions again, is it the same reasoning that I use with static and non-static variables, the same reason that you can only call non-static(member) functions through an object, and static(or Class) functions through the Class?
The reason I am using this method to explain is because it makes sense to me, I was sick of looking up 'what is an object' and reading 'An object can be anything you like, a person or a tree, or a dog', I understood that concept but was unable to see how it fitted into a programming environment, because I always saw functions as doing exactly that job that they were describing, I couldnt see how objects and classes were referencing in weach other, and in what context an object fitted into a class, if how I have described using variables and functions is correct, then it has finaly sunk in after reading and trying to understand for soooo long!
James CrawfordPosted Jul 17, 2010, 7:57 AM
And the cupofCoffee example was just that, and example, its not going to be the pivitol snippet of code that creates the next operating system and dont really understand the argument about it, its not like there is going to be intellectual property rights stamped all over it.
All Sam did was take a reference that I understood and change it slightly so that I could understand what I was asking, I am sorry that I did not mention yours but it seemed overly complex (at the time that is, now I undeerstand objects a little better I can see what you were writing), All of us have said that there are similarities within these two languages, lets face it PHP, C++ & C# wouldnt have spread so far as they have today if they didnt have the flexibility to provide what a developer wants, and this is going to be an OOP approach with simplistic intuative methods, and all three can do this (well maybe not C++ as much, but that is another argument!)
On top of this, when I look back at most of the PHP apps that I have written I can see now how easily they can be converted into object based apps, as the functions I wrote were to seperate as much code as possible so that I could (if needed) change the internal workings of the functions without having to completley re-write the rest of the program.
Example:
I wrote a shopping cart, on the web page were 'markers' that told the server where and when to put the main items of the cart (by this I mean the basket, the products, the owners name and address, contact details, the members details, drill down links, even admin duties), I used the markers to call each function , this meant that templates for the shopping cart could be made using these markers to place what you wanted wherever on the page, you could go into each seperate function and change what you liked, because each 'marker' was a distinct and seperate job to every other one, and each function did not depend on any others.
All along I have be programming in a simplistic OOP method, without actually using classes.
theLizard and Sam, thank you both for helping me out, you both did in different ways, just please dont argue over simple misunderstandings, or differences of opinion, thats the beauty of programming, there is no single correct answer, if you asked 100 students to write a contact form, you would get 100 answers, and if you you got 2 that where the same i would take a look at both their work
and please call me Jimmy, I much prefer that!
Jimmy
Sam HobbsPosted Jul 17, 2010, 2:43 AM
Younger developers often criticize older languages in ways that are not true. It is just not true that all old programs were filled with gotos, except that assembly language was used much more in the past and it is certainly true that the machine language for most processors require branching for conditional instructions.
theLizardPosted Jul 16, 2010, 10:42 PM
True, C structs maybe different to c++ or c# but fundamentally they are the same, whether they just contain int's or other data type structures or classes as is the case in the latter.
structural or procedural programming had goto's and labels for a reason, they were used to branch of to another section of the program if a condition called for it to do so but yes I would agree with you that using goto's was not good for a number of reasons.
Event driven languages are way better than the old procedural languages, but you could argue that goto's were the predecessor of event's.
Sam HobbsPosted Jul 16, 2010, 9:07 PM
Yes, C still has structs, but C structs are not the same thing as C++ structs, and the differences are highly relevant here. It is not true that "structs have their use in C, C#, C++ in the same manner as classes do". C does not do classes and C++ structs are the same as C++ classes so that is enough to make it clear that structs in C are different from structs in C++.
It is not true that old programs used a lot of gotos. Many of them did but it was not necessary. Software designers have understood the value and use of logically structuring programs without gotos for nearly half a century. I have never used a goto in programs I write since 1975 at the latest. I think the Pascal language does not have a goto statement; part of the design of the Pascal language was to show the use of structured programming, which is explicitly "goto-less".
theLizardPosted Jul 16, 2010, 8:11 PM
Quote:
Thanks Sam, that has helped a great deal, I can see where your misunderstanding of PHP arrays comes from, as in PHP the numeric elements in an array can also be strings (I suppose that I should have used each element name within a quote, sorry about that), PHP arrays are very very flexible, and can also be multi-dimensional, that is, an array can hold and array as the value of one of its elements, each of those elements can also hold arrays too, this (within PHP at least is a very nice tool), PHP can create arrays wherer the element is either numeric or string, but string named arrays can also be referenced by their position within the array, this does sound confusing, but once you begin to see how they work, it begins to come naturally.
End Quote:
What you describe here regarding arrays is NO different to C# or C++ array declarations, use and manipulation. It is also good of Sam to use some one else's example turn it into a console example then call the solution or example his, this is what Sam does frequently.
Quote by Sam:
You said "or at least referenced (....) an object can be called anywhere" and I don't understand; I think your thoughts were distracted when you wrote that.
End Quote:
I Understand clearly. an object CAN be called from anywhere in your application, it is or should be easy to understand since this is OOP programing, in C# you do not need to worry about including the header files of your class object (as is the case in C++) to begin using the object you simply declare the object of type cupOfCoffee aCup = new cupOfCoffe() where you want to use it in your application, it is that simple.
Quote by Sam:
You say "function" a lot; is the function you showed a sample PHP function?
End Quote:
A function is a function in any language, I have not learned PHP nor do I want to but I recognized the example you gave as a function without any worries at all. if you have been around programming for as long as Sam says he has then Sam would know this.
Quote by Sam:
I can tell you a little history that might help. PHP (at least the original PHP) is like C; they look alike and the runtime functions for PHP were similar to the C runtime functions. In the past, the C language had "struct" types and structures only had plain data such as integers and they could have other structures; C structures cannot have functions. Then someone began to make macros that allowed use of C in a more object-oriented way. So the predecessor to C++ was C macros.
End Quote:
PHP is influenced by C++ and you can find similarities in almost any programming language if you want to.
Sam makes it sound as if structs have been relegated to the past, C# has structs, C STILL has structs, c++ has structs, even PHP can utilize C type structs (see this article), Pearl uses hash tables as structs.
structs have their use in C, C#, C++ in the same manner as classes do, the trick is to know when to use a struct and when to use a class. A class can have structs and similarly a strcut can have classes as their members.
The old traditional way of programming required you to write your program in sequential steps with a hell of a lot of branching using goto and the like OOP is like having multiple programs which are autonomous in that they do not care where in a program they are called from, you can create a win form and a single class with methods (functions) then declare the class in your win main() by inserting two or three lines of code and run the application, hell a class can even have a constructor method that creates a new win form adds controls to the form and execute the form and control methods and fire events so that when you call the class from your win main() the associated form of the class pops up
Component programmers know this because, simplistically, when you place a component (they come from the tool pallet) your are actually placing an autonomous program with a symbiotic relationship on your form meaning that if you drop a component (object) on a host form, it will run the instructions (methods / function) when called for. You just provide the parameter data as is required by the component.
Sam HobbsPosted Jul 16, 2010, 12:57 PM
For what it is worth, I think that that PHP code is a lot like JavaScript. JavaScript uses functions like that for providing a somewhat object-oriented feature.
I think I have no problem understanding arrays that are actually dictionaries; I just was not sure that that is what was happening in the code you had.
James CrawfordPosted Jul 16, 2010, 7:08 AM
function cupOfCoffee($name, $milk, $sugar, $type, $container)
{
$name = array(); // I klnow this a PHP method, but I am just learining and this what I know!
$name['milk'] = $milk;
$name['sugar'] = $sugar;
$name['type'] = $type;
$name['container'] = $container;
return $name;
}
//now lets make the coffee:
$JimCoffee = cupOfCoffee("jim", 1, 0, "Fresh", "Mug") ;
$sarahCoffee = cupOfCoffee("sarah", 1, 2, "Instant", "Cup");
//this dumps the contents of the arrays to the web page
print_r ($JimCoffee);
print_r($sarahCoffee);
?>
James CrawfordPosted Jul 16, 2010, 6:33 AM
Yes, that function was a PHP function, in the same manner as C# you can pass parameters to a method, each line within that function assigned the value of the named parameter, to the value of the element it was being assinged, though that was a bad example, as each time you called the function, it would just write over the previous values within the array, this is where multi-duimensional arrays come in handy, it could be written so that each element would be an array holding the data for each cup of coffee.
I think want my biggest problem is, is that I have used PHP for so long, I am finding hard to 'break the PHP habit' - lolz, it can be worse than giving up smoking hahaha,
And you are right I am worrying a lot over a simple thing, I have a number of books that I have bought from Amazon, including C# step by step, as the version I was able to view in the O'Reilly website seemed to have a lot to offer, I am also finding it difficult to rememebr to declare each variable type as in PHP you dont have to do this, in the same way that C# automatically works out:
var myName = "Jimmy";
PHP does the exact same thing with all strings, if it is an int, string, double, bool, or even floating point, it automatically assigns the var type to the variable. (this is I find where the major differences between a scripted language, and a compiled language start to come to light) Within C# this is very bad practise, within PHP it is standard, though you would normally provide a comment to remind what the variable is for.
It is things like this that make the big differences, not the similarities (as there are a goodly number of similarities) as most languages will have callable functions, loops, branching and IF this do this, if not do that.
I am beginning to get my head around C# as a programming language and find that it is becomming more and more easier to use, I think what my main problem is is learning to think in C#, not in PHP and then convert the PHP into C#!
Thanks for your help again Sam, it has managed to help me understand a bit more, and oh yes, I ran your console app on VS 2010, once I was able to see the flow of data, and how this can be used, as well as how the cupOfCoffee object interprets what it is being sent, then I was able to understand a bit more.
Jimmy
Sam HobbsPosted Jul 15, 2010, 8:43 PM
The following is a sample C# console program that is an implementation of your pseudocode, except I added the method "Show" to show a method in the class.
theLizardPosted Jul 15, 2010, 7:15 PM
Simplistically a cup of coffee is an object in the real world and in the virtual world. your PHP function
functon cupOfCoffee(name, milk, sugar, type, container)
{
name = new array(); // I klnow this a PHP method, but I am just learining and this what I know!
name[milk] = milk;
name[sugar] = sugar;
name[type] = type;
name[container] = container;
return name();
}
can be written as a class
public class cupOfCoffee
{
//members
string who;
bool milk;
int sugar;
string type;
string container;
public cupOfCoffee(wantMilk, qtySugar, whatType, typeContainer, whoFor) //constructor
{
milk = wantMilk;
sugar = qtySugar;
type = whatType;
container = typeContainer;
}
public bool WantMilk //do this for all members
{
get{return milk};
set{milk = value};
}
public string aMethod(string whatever)
{
//do whatever
}
}
Then when you want to instantiate the class you could do something like
cupOfCoffee[] name = new cupOfCoffee[10]; //this tells the system to create an array of cupOfCoffee having 10 elements
to access an element of cupOfCoffee ---> name[index].WantMilk = true;
---> name[index].QtySugar = 2; etc.
to resize the array ---> Aray.Resize(ref name, name.Length() +1);
to access the new index -- name[name.Length()-1] = new cupOfCoffe(true, 2, "fresh", "Mug", "Jim");
for single objects --> JimsCoffee = new cupOfCoffe(true, 2, "fresh", "Mug", "Mary");
to get the details for Mary from the array
for(int i = 0; i < name.Length(), i++)
{
if(name[i]who == "Mary")
{
//do what ever...
}
}
I think you are probably scaring yourself for no reason about classes they are very easy to handle.
Hop this helps you.
James CrawfordPosted Jul 15, 2010, 3:45 PM
an array is basically a variable that stores values within itself, an object can do the same thing (or references the said data), however, an object can include functions that can manipulate the data, whereas an array cannot, on top of this, a function (at least in PHP) has to be included in every page, or at least referenced (in the same way that classic asp uses 'includes') an object can be called anywhere within the application (at at least within the scope of the application page - in the same way include is used, 'using' allows us to call them in the same way.
So, array only holds data, an object can hold the data (or at least references the data), any data referenced within the object can be manipulated using functions (or methods) within the scope of the object...
is this right?
Jimmy
Sam HobbsPosted Jul 15, 2010, 2:43 PM
Using the function cupOfCoffee, is it possible for the program somepalce else to create an item in the array (without using the cupOfCoffee function) that does not have the same properties that the cupOfCoffee function creates? If so then that is the major problem with doing that. In object-oriented languagtes such as C# you must define what a cupOfCoffee is and then every cupOfCoffee object has the members that you specify.