Journal FortKnox's Journal: Object Oriented Programming 101: intro 17
Due to a lack of understanding of OOP by gmhowell in his <A HREF="http://slashdot.org/~gmhowell/journal/18764">journal</A>, I'm gonna write a beginners lessons in OOP. It isn't something for someone that doesn't know how to code, but someone that is comfy with procedural coding, and wants to understand OOP. BTW - I'm terrible with HTML, so sorry about the HREF tag that isn't a hyperlink. I'm putting this entire entry into the 'code' format so it'll be easier to read.
Lesson 1:
OK, allow me to throw stuff into the water and get your feet wet in OOP.
I'll use pseudo code that looks an aweful lot like Java, to help you out.
Lets say you want to create a 'TV' in code. We'll do it in procedural type first.
We'll need a picture, volume, and channels.
So we make a structure:
structure TV
{
Display picture;
int volume;
int channel;
}
So, to change the channel, you'll need a function to do that:
void changeChannel( Structure TV, int newChannel )
{
TV.channel = newChannel;
}
What OOP does is wrap all this stuff up together (variables AND functions). This gives us an advantage. We don't need to put the structure into the function, because the variables and the function belong to the same structure. So, we make a new special structure called a 'class'.
class TV
{
int channel;
int volume;
Display picture;
void changeChannel( int newChannel )
{
channel = newChannel;
}
}
And, to use this new class, you create an object like so:
void main()
{
TV tvObject = new TV(); //just allocating mem
tvObject.changeChannel( 2 );
}
Voila!
Lesson 1:
OK, allow me to throw stuff into the water and get your feet wet in OOP.
I'll use pseudo code that looks an aweful lot like Java, to help you out.
Lets say you want to create a 'TV' in code. We'll do it in procedural type first.
We'll need a picture, volume, and channels.
So we make a structure:
structure TV
{
Display picture;
int volume;
int channel;
}
So, to change the channel, you'll need a function to do that:
void changeChannel( Structure TV, int newChannel )
{
TV.channel = newChannel;
}
What OOP does is wrap all this stuff up together (variables AND functions). This gives us an advantage. We don't need to put the structure into the function, because the variables and the function belong to the same structure. So, we make a new special structure called a 'class'.
class TV
{
int channel;
int volume;
Display picture;
void changeChannel( int newChannel )
{
channel = newChannel;
}
}
And, to use this new class, you create an object like so:
void main()
{
TV tvObject = new TV();
tvObject.changeChannel( 2 );
}
Voila!
Thats great, BUT! a little puzzle... (Score:2)
But I had a question at my review session this weekend- here's the set up:
Class Person (Name, SSN, and get and set methods)
Class Student extends Person (School name, gpa)
CLass HSstudent extends Student (graduation date)
Class College Student extends Student (Credits, Major)
Every class has a "read" function that will read in from the command line values for its internal data types.
You are writing a program that will take in data on students. Everyone is either A Highschool student or a College student.
The input MUSt be taken in this order: Then if the word "University" or "College" is somewhere in the School string, ask for otherwise assume they are a HS student and ask for What is the most OO way of implementing this?
What is the best way of doing this?
Instantiating a Student, calling Student1.read();
then query the SchoolName value to decide HS or College, then query those additional fields, then construct a CollegeStudent with ALL of the values?
Have a ReadWhatsLeft() method in HS and College student to figure out what internal variables have already been initialized?
Or have 6! (6 factorial) constructors for College Student, where whatever values aren't passed in on the parameter list query the user and are asked for on the command line?
Any takers?
Re:Thats great, BUT! a little puzzle... (Score:2)
This is just an intro on what classes are. Next lesson is encapsulation, then inheritance, then polymorphism.
Then I'll get into Java, and talk about syntax, constructors, copy constructors, etc etc etc... you're like 10 lessons ahead
Re:Thats great, BUT! a little puzzle... (Score:1)
As far as the "read" method: I think the answer you are looking for is actually found in the Static Factory pattern.
I speak java so this is how I would solve it:
First, you would make the Person structure an Interface.
For your static factory, you make a class called
Registrar in package Education (or whatever)
that has methods like
Registrar.getCollegeStudent(arg1, arg2, art_etc)
or
Registrar.getHSStudent(arg1, arg2, arg_etc)
and of course
Registrar.defaultStudent()
and let's not forget
Registrar.getSomeStudent(person)
which in all cases return instances of Person.
Furthermore, instead of making the other data fields simple String data types, you make them their own data object classes, perhaps
RegistrationInfo {
List classes;
Major major;
int classesCount(){
return List.size();
}
String getMajor(){
return major.getName();
}
}
(hmmm...maybe I'm making it too complicated here....)
Then, when the new Student is initialized, if some fields are not provided by the "client" (this might be an automated process as well, don't forget) then you make those fields Null Objects. For example
class NullRegistrationInfo extends RegistrationInfo {
int getClassesCount {
return 0;
}
String getMajor() {
return "Not signed up for any classes.";
}
}
Finally, you could always throw an Exception from the static constructor if the client doesn't provide the right number of arguments.
I am not an professional java programmer, just working my way up to that point...so if anyone wants to critique my answer please go crazy!
Re:Thats great, BUT! a little puzzle... (Score:2)
That's my leaning- get the data from the user, assume they are baboons banging on the keyboard, and massage. Only after it has been inspected will I fold the data into my data structures.
But I'm interested in this Static Factory pattern- but I don't entirely understand.
Is the static factory (our Registrar class) an extension of the User Interface idea?
For example, the Registrar class has a "getDataFromUser()" method that gets the data, and based upon what is or isn't null then calls getCollegeStudent( p1, p2, p3, p4)?
AFter that, I like how they are all "held" as Students- thats nice and OO.
Re:Thats great, BUT! a little puzzle... (Score:1)
For example, the Registrar class has a "getDataFromUser()" method that gets the data, and based upon what is or isn't null then calls getCollegeStudent( p1, p2, p3, p4)?
(All this following assumes we're talking about java. I don't know much about C++ except that it's hard
The static factory is like a function that returns whatever object you want to create. That way you can throw exceptions -IllegalArgumentException - or whatever when the user doesn't provide enough info. You can't throw exceptions from class constructors (in java). So yeah it is like the UI concept. However ideally you still want to have a layer of abstraction that checks the user input before it even gets to the Static Factory.
The static factory examines the arguments passed to it (be they strings, a Person object, or nothing for a default) and "builds" the corresponding correct object. The object returned always has the same type (a common interface or superclass) regardless of the parameters, so, in java, you sometimes have to cast it back up to the expected class (someone want to correct me on this one?).
You can also have static factories accept type codes instead of parameters, for example,
Person hsStudent = Registrar.getStudent(Education.HIGH_SCHOOL)
or
Person clgStudent = Registrar.getStudent(Education.COLLEGE)
I should say that I haven't created commercial APIs, I've just used the Java class libraries, so somebody else will have to pick up from here.
Re:Thats great, BUT! a little puzzle... (Score:2)
Super-dupe. I didn't realize that about exceptions not allowed in constructors... very sneaky- I like it a lot.
Yes, you have to cast UP, but not down(towards Object)- that's implicit. like when you grab stuff from vectors- you cast.
When using pointers in C, you do more casting than an anxious fisherman.
But Why? (Score:1)
Of course, anybody who has waded through pages of spaghetti code knows the advantages of oop over procedural code intuitively.
Still, you might want to take a look at this guy's [slashdot.org] site [geocities.com] and all the arguments he makes against OOP. I would be interested to hear your reaction.
Re:But Why? (Score:1)
cool, keep 'em coming (Score:2)
I've done some OO programming, mainly in school, but when I need to turn out code, I end up going procedural, cause OO just seems like such overkill for most of what I'd want to do. I could use a refresher
Just wanted to mention ObjC (Score:1)
Re:Just wanted to mention ObjC (Score:2)
I love Objective C, but I don't know if it's features far outweigh Java. Java is almost better supported and about as fast. It's got broader support and , unless your using OS X w/NS classes, Java has a better native API. Things like Apache XML support, web services support, development enviornments... etc.
Also, I just hate header files. Java is nice that way.
It's probably the language that should of been, especially over C++.
From Lesson One (Score:1)
Re:From Lesson One (Score:1)
import java.util.*;
Class TvDemo {
Class Tv {
}
public static void main(String args[]){
boolean keepAddingTVs;
List tvroom;
List tvroom = new ArrayList();
keepAddingTVs = true
while(keepAddingTVs){
tvroom.add(new TV());
keepAddingTVs = AskUser_KeepAddingTVs();
}
System.out.println("Wow, you have " + tvroom.size() + " tvs in your tv room.");
}
}
By using Lists, Vectors and similar data structures you can avoid having to clutter your code with confusing names like tv1, tv2 ad nauseum. I don't think procedural languages have List strucutres, do they? If they do, it is in the form of arrays which typcially have to be statically dimensioned at coding. Someone correct me if I'm wrong.
Re:From Lesson One (Score:1)
Re:From Lesson One (Score:2)