Object Oriented Programming... In Java!

A place to discuss the implementation and style of computer programs.

Moderators: phlip, Moderators General, Prelates

shinigami
Posts: 1
Joined: Tue May 18, 2010 4:55 am UTC

Object Oriented Programming... In Java!

Postby shinigami » Tue May 18, 2010 5:23 am UTC

Ok, so I'm trying to get a clear picture of just exactly how to make my code properly 'object oriented'. I'm studying this in uni, almost failed my first assessment because it wasn't OO enough (although the code did what it was supposed to do).

From what I gather so far (and I'm posting here to see if i'm wrong), Object Oriented Programming really is just the simplifying of your code into things analogous to real world objects. The internet and my textbook (Intro to Java programming, Liang) are rather vague about these concepts.

So, does anyone on this forum know of any good OOP resources I should read?

I think my problem was not using enough 'classes' in my last project. Stuffing most of my features into just a few classes. And too much code sitting in the main, when I could have just given it its own class. The way i'm going to go in the next one currently will be to split off everything into it's own class, and try and keep as little in the main as possible.

User avatar
Aaeriele
Posts: 2127
Joined: Tue Feb 23, 2010 3:30 am UTC
Location: San Francisco, CA

Re: Object Oriented Programming... In Java!

Postby Aaeriele » Tue May 18, 2010 8:32 am UTC

shinigami wrote:I think my problem was not using enough 'classes' in my last project. Stuffing most of my features into just a few classes. And too much code sitting in the main, when I could have just given it its own class. The way i'm going to go in the next one currently will be to split off everything into it's own class, and try and keep as little in the main as possible.


This is probably it. Though honestly, there's a broad area which is "too much" or "too little" breakdown into classes.
Vaniver wrote:Harvard is a hedge fund that runs the most prestigious dating agency in the world, and incidentally employs famous scientists to do research.

afuzzyduck wrote:ITS MEANT TO BE FLUTTERSHY BUT I JUST SEE AAERIELE! CURSE YOU FORA!

User avatar
Jplus
Posts: 1721
Joined: Wed Apr 21, 2010 12:29 pm UTC
Location: Netherlands

Re: Object Oriented Programming... In Java!

Postby Jplus » Tue May 18, 2010 9:22 am UTC

Read Design Patterns: Elements of Reusable Object-Oriented Software by the Gang of Four. It's a classic, and by far the best explanation of the key ideas behind OOP that I know of. The examples are written in C++ and Smalltalk, but that won't be a problem because it only hinges on the concepts.
"There are only two hard problems in computer science: cache coherence, naming things, and off-by-one errors." (Phil Karlton and Leon Bambrick)

coding and xkcd combined

(Julian/Julian's)

dosboot
Posts: 143
Joined: Sun Jul 01, 2007 5:26 am UTC

Re: Object Oriented Programming... In Java!

Postby dosboot » Tue May 18, 2010 9:23 am UTC

Object Orientation means put 'related' state 'together'. State is variables, together means in an object, related is as dictated by the program but creatively interpreted by the programmer. That's 90% of the story. The other 10% says to look for where inheritance can be used to get modularity. The third and final take home point about OO is that due to historical reasons it has a reputation for being postured as a more useful and/or more essential paradigm than perhaps it should be.

I just told you the pure distilled essence, but real wisdom is reading what everyone else can read and understanding what everyone else doesn't. With enough experience in OO languages you'll understand points 1 and 2. With enough experience in functional languages (or maybe yet other languages..) you'll have your own informed opinion on point 3. Experience comes from writing programs yourself for self edification. Writing fuels a desire to read blogs, articles, mailing lists, wikis, (and stack overflow, and video presentations, and academic papers..)

So to answer your question directly, web > books for resources (books are good too, but the web is bigger than libraries and easier to comb). The best links are the ones you find yourself. Beyond the obvious Google + Wikipedia combo, there's also reddit (and subreddits for specific languages) for finding links.

User avatar
Jplus
Posts: 1721
Joined: Wed Apr 21, 2010 12:29 pm UTC
Location: Netherlands

Re: Object Oriented Programming... In Java!

Postby Jplus » Tue May 18, 2010 11:13 am UTC

dosboot wrote:The third and final take home point about OO is that due to historical reasons it has a reputation for being postured as a more useful and/or more essential paradigm than perhaps it should be.

(...) With enough experience in functional languages (or maybe yet other languages..) you'll have your own informed opinion on point 3.

This is very true. Another paradigm that, like functional programming, is at least as valuable as OOP, is generic programming. It is, among other languages of course, realised through typeclasses in Haskell, templates in C++ and (somewhat limited) generics in Java.
In fact, the most practical way to organise your program is usually not by sticking to one paradigm, but letting the use of such concepts depend on what you need on a case-by-case basis.

However, this very interesting lesson doesn't fully apply to Java, because it more or less enforces OOP. In fact some of the more prominent OOP patterns are built-in. If you wanted to use a more cross-paradigm style of programming in a Java-like language you could use Scala or Groovy. That's probably still not an option because your course uses Java, and your teachers have a point that OOP is often the best way to go in Java.
I still think Design Patterns by the Gang of Four would be a good introduction. To get a firm grasp of the basic idea of OOP, it actually suffices to read the first two chapters in a library or so (you don't really need the actual design patterns, and if you do you can easily look them up on the internet).
"There are only two hard problems in computer science: cache coherence, naming things, and off-by-one errors." (Phil Karlton and Leon Bambrick)

coding and xkcd combined

(Julian/Julian's)

0xBADFEED
Posts: 687
Joined: Mon May 05, 2008 2:14 am UTC

Re: Object Oriented Programming... In Java!

Postby 0xBADFEED » Tue May 18, 2010 2:37 pm UTC

Jplus wrote:Read Design Patterns: Elements of Reusable Object-Oriented Software by the Gang of Four. It's a classic, and by far the best explanation of the key ideas behind OOP that I know of. The examples are written in C++ and Smalltalk, but that won't be a problem because it only hinges on the concepts.

Don't bother reading this book at this time. You won't get much out of it. If you haven't personally encountered the design problems they describe in the book you're unlikely to see why the patterns they present are effective solutions. You'll just blindly apply the patterns (most likely incorrectly) or forget all about them.

I don't know of any material that really does an effective job teaching how to think in OO. It's not something you can just teach, each design situation is too ad-hoc and more often than not there are multiple good solutions and no best solution. Sure, you can read about guiding principles and tips but those don't teach you how to do OO decomposition of some problem domain (which is what you're really asking about). It's akin to trying to learn how to ride a bike by reading about cycling and physics.

The only thing that works is practice. Write a bunch of non-trivial programs. Try to identify weak spots in your designs. Try to add new features, was it easy or hard? How can you make your designs more modular to accommodate changes? How can you simplify your designs without sacrificing flexibility or capability? Actually solving these problems is the only way to get a real handle on it. Once you've written 5-10K lines of code you'll probably start to get a real handle on it. Once you've written 50-100K lines of code you'll probably have a good feel for what works.

That said, you should also read books, blogs, whatever about software design. But practicing and experimenting are far more important than what supplementary material you read.

User avatar
Jplus
Posts: 1721
Joined: Wed Apr 21, 2010 12:29 pm UTC
Location: Netherlands

Re: Object Oriented Programming... In Java!

Postby Jplus » Tue May 18, 2010 5:29 pm UTC

0xBADFEED wrote:
Jplus wrote:Read Design Patterns: Elements of Reusable Object-Oriented Software by the Gang of Four. It's a classic, and by far the best explanation of the key ideas behind OOP that I know of. The examples are written in C++ and Smalltalk, but that won't be a problem because it only hinges on the concepts.

Don't bother reading this book at this time. You won't get much out of it. If you haven't personally encountered the design problems they describe in the book you're unlikely to see why the patterns they present are effective solutions. You'll just blindly apply the patterns (most likely incorrectly) or forget all about them.

Usually I agree to 0xBADFEED or I am convinced by his arguments, but this time I think he's wrong. The book starts with an elaborate case study, about the design of a (hypothetical) word processor. Along the way they discuss how certain design patterns come into play, but more importantly they show you what OOP is really about. That's also the reason I recommended only the first two chapters of the book.

Of course you have to practice and of course knowing a bunch of design patterns won't help you in the start, but the part of the book that I recommend is not an enumeration of patterns. It's more like learning to read musical notation and mapping the tones to the piano keys before learning to play the piano. (So, helpful even though you still need practice after that).
"There are only two hard problems in computer science: cache coherence, naming things, and off-by-one errors." (Phil Karlton and Leon Bambrick)

coding and xkcd combined

(Julian/Julian's)

User avatar
Berengal
Superabacus Mystic of the First Rank
Posts: 2707
Joined: Thu May 24, 2007 5:51 am UTC
Location: Bergen, Norway
Contact:

Re: Object Oriented Programming... In Java!

Postby Berengal » Tue May 18, 2010 8:03 pm UTC

The ironic thing about this is that OP was probably implementing some relatively easy algorithm, which is usually best not done with any OOP at all.

Where OOP shines is in modeling complex interactions between wildly different "objects". Note that the objects don't have to correspond to anything in the real world at all; if you can put a noun to it you can make it an object (but that doesn't mean you should make every noun an object). Programming is inherently mathematical, and mathematics has little to do with the real world as such, especially in what constitutes an object. Ignoring that will just lead to headaches and confusion.

Grokking OO is hard and knowing when something is an object and when not and when it wasn't but now is and when it used to be but isn't anymore and when two classes are really the same and when something shares a common supertype and when they don't etc. etc. etc. can only come through experience. OOP is like chess; easy to learn, but really hard to master, and that's perhaps my main gripe with OOP, or at least where it stems from. It offers a seemingly easy alternative to other ways of programming, but it really isn't. Many who try it, however, think they're really good just because they know all the rules, but they frequently mess up and produce bad code. They read things like Design Patterns but they don't really understand it, so they become cargo-cultists, spreading their misinformed ideas about programming to others and in general making people miserable.

Don't become a cargo-cultist. Learn the rules, learn why the rules are the way they are and then finally grok when to break them.

I wouldn't recommend Design Patterns at this stage, because you need to know how to program before you can learn how to program in OOP. The first two chapters could be some nice food for thought though.
It is practically impossible to teach good programming to students who are motivated by money: As potential programmers they are mentally mutilated beyond hope of regeneration.

User avatar
evilbeanfiend
Posts: 2650
Joined: Tue Mar 13, 2007 7:05 am UTC
Location: the old world

Re: Object Oriented Programming... In Java!

Postby evilbeanfiend » Tue May 18, 2010 9:36 pm UTC

on why the OP failed, it sounds like their classes had to many responsibilities
in ur beanz makin u eveel

0rm
Posts: 81
Joined: Wed Feb 17, 2010 2:30 pm UTC

Re: Object Oriented Programming... In Java!

Postby 0rm » Sun May 23, 2010 6:02 pm UTC

evilbeanfiend wrote:on why the OP failed, it sounds like their classes had to many responsibilities


Not necessarily. One of the most well designed classes I have come across was a wrapper around GLSL (OpenGL's shader language) functionality. It simply allowed you to feed it two source files, call acoupla methods, and you then had a compiled (depending on whether or not it was valid glsl source code) shader to work with. This all took place in one class. It is one of the best examples of a well encapsulated class I have seen. So it doesn't matter how many responsbilities a class has, it just matters on how well it is encapsulated. Of course I managed to bastardize it with my own way of loading the source with a custom markup. I made a separate class to do that dirty work. I'm not going to paste the shader classes code here, but you can find it in "Beginning OpenGL Game Programming".

However, I willl provide another example. I am exposing my game engine to a scripting language, AngelScript, and I found myself copypasting alot of code for each class I had to expose. Most specifically, pointers that the exposed classes required to tdo their work. Instead of constantly copypasting those pointers, I made a C struct and a C method to handle the class setup for me.

Code: Select all

typedef struct {
    int ref_count;
    string name;
    asIScriptEngine*  engine;
    asIScriptContext* ctx;
    asIScriptModule*  module;
    asIObjectType*    otype;
} ScriptCore;
// stick one of these in a class, then in the classes constructor, call this method... this is the C++ side that I deal with, so the end user doesn't worry about this.
extern "C" void SCOBJ_INIT(ScriptCore* sc, const string& n) // SCripted OBJect INIT
{
    sc->ref_count=1;
    sc->name=n;
    sc->engine=SApplication::engine; // static... get over it...
    sc->ctx=APP_PTR()->engine->CreateContext();
    sc->module=sc->engine->GetModule("Game");
    sc->otype=sc->engine->GetObjectTypeById(sc->module->GetTypeIdByDecl(sc->name.c_str()));
}


You can equate a C struct to a class in java with all public members and no methods. Try it sometime, they're handier than verbose classes... for some things, not all things. If you're filling up a class with a bunch of getters and setters and you are simply using it to bundle up data into one place, consider making those properties public rather than using a verbose method

Code: Select all

foo.x;
// as opposed to
foo.getX();

Here's another example that I used recently for a project (in Java, a Wario Ware type of game):

Code: Select all

public class GameState {
   public GameState(){
      tries_left=5; // think of these as lives.
      games_completed=success_streak=highest_streak=0;
      succeeded_previous_game=true;
      first_game=true; // set to false after first game. used to increase time in the global game object so the player can read the instructions.
   }
   public int tries_left;
   public int games_completed;
   public int success_streak;
   public int highest_streak;
   public boolean succeeded_previous_game;
   public boolean first_game;
}

Then any class that needs to access game state data can simply grab a reference from the global game object and do what it needs to do, instead of passing all these values as arguments to a function or method.

Hpe you were able to learn from my mistakes 8)
They say it's unhackable; I think it can be hacked.
They say it's fast; I think it could be faster.
They say it's the best; I think it can be done better.

User avatar
Pesto
Posts: 737
Joined: Wed Sep 05, 2007 5:33 pm UTC
Location: Berkeley, CA

Re: Object Oriented Programming... In Java!

Postby Pesto » Sun May 23, 2010 10:23 pm UTC

Jplus wrote:Usually I agree to 0xBADFEED or I am convinced by his arguments, but this time I think he's wrong. The book starts with an elaborate case study, about the design of a (hypothetical) word processor.

I'm reading GoF right now, and I skipped right past the case study. It seemed to be very GUI centric, which I have very little experience in. I skipped straight to the catalog of patterns, and I'm finding that much more useful. Each small example applies specifically to the pattern at hand.

Then again, I'm fairly comfortable starting out in theory world (where eveything is either a sphere or a cube and friction doesn't exist) and being able to apply what I've learned in the real world.

User avatar
BobTheElder
Posts: 86
Joined: Wed Feb 17, 2010 11:30 pm UTC
Location: England, near Bournemouth

Re: Object Oriented Programming... In Java!

Postby BobTheElder » Mon May 24, 2010 9:44 am UTC

evilbeanfiend wrote:on why the OP failed, it sounds like their classes had to many responsibilities


The single responsibility principle is used in responsibility driven design methodologies like the Responsibility-driven design (RDD) and the Use Case / Responsibility Driven Analysis and Design (URDAD).
Rawr

User avatar
Jplus
Posts: 1721
Joined: Wed Apr 21, 2010 12:29 pm UTC
Location: Netherlands

Re: Object Oriented Programming... In Java!

Postby Jplus » Tue May 25, 2010 5:24 pm UTC

Pesto wrote:I'm reading GoF right now, and I skipped right past the case study. It seemed to be very GUI centric, which I have very little experience in.

It's not as GUI-centric as it seems. I had no GUI experience at all when I read it, but I had not a signle problem grasping the concepts that they explained because they don't depend in any way on the GUI elements of the examples. Also, not all examples are GUI-ish.
I would still recommend that you read it, because it provides a really nice overview of the ideas that all those design patterns have in common.
"There are only two hard problems in computer science: cache coherence, naming things, and off-by-one errors." (Phil Karlton and Leon Bambrick)

coding and xkcd combined

(Julian/Julian's)


Return to “Coding”

Who is online

Users browsing this forum: No registered users and 30 guests