Java-Gaming.org    
Featured games (79)
games approved by the League of Dukes
Games in Showcase (477)
Games in Android Showcase (107)
games submitted by our members
Games in WIP (534)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  "Dead Objects"?  (Read 2310 times)
0 Members and 1 Guest are viewing this topic.
Offline span123

Senior Newbie





« Posted 2012-10-30 16:55:41 »

Hi,
I have a little question and I hope its in the right section but well here it comes  Wink
today in class our professor "collected the homework" (what was a programm that takes decimal numbers and converts them to binary numbers). Well not very difficult but he told me i created a "dead object" by writing:
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
public class Converter {
 
  public Converter() {
    //do the algorithm etc..
 }  
 
  public void otherFUnctions() {
    //..
 }
 
  public static void main(String[] args) {
    [b]new Converter();[/b]
  }
}

He told me this is a bad behaviour of writing code and my algorithm should better be in the main method, than instantiating a dead object. He also didnt want to explain that to me and just said you'll learn more about that when you learned how stacks are built.
I wonder now why this is so bad because i always see alot of ppl starting their code like this (even example code in books I've read is like that).
Since my prof didnt had the time or smth else  Grin to explain that to me.
So I wanted to ask you guys, maybe someone can explain it
thx
Offline princec

JGO Kernel


Medals: 342
Projects: 3
Exp: 16 years


Eh? Who? What? ... Me?


« Reply #1 - Posted 2012-10-30 17:07:03 »

Short answer, this is perfectly legal code.

Long answer, this is perfectly legal code, though in general it is regarded as bad form to do heavy lifting in constructors, though IMHO it's a matter of taste rather than any real practical consideration in performance or correctness in any current JVM.

Cas Smiley

Offline span123

Senior Newbie





« Reply #2 - Posted 2012-10-30 17:12:36 »

hmm ok thanks for the fast answer, but what do you mean by heavy lifting? You mean its bad to do the calculations etc in the constructor?
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline actual

JGO Coder


Medals: 23



« Reply #3 - Posted 2012-10-30 17:43:51 »

Looking at the code it could also be that he is calling it a "dead object" is because the algorithm is small and simple enough to just be put directly into the main method, instead of creating and instantiating an object to do the work. For instance if I were writing a code example that took a sentence and printed out every other word I might do it like this:

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
class EveryOtherWord {

   public static void main(String[] args) {
      String sentence = "This is a test sentence that will be used to print every other word.";
      String[] words = sentence.split("\\s+");

      for (int i = 0; i < words.length; i++) {
         if  (i % 2 == 0) System.out.println(words[i]);
      }
   }


Note, I did not need to create an instance of the class EveryOtherWord. I simply put the algorithm directly into the main method. The class only exists as a place to hold the main method.

Only your professor knows what he really meant by "dead object" though.
Offline Danny02
« Reply #4 - Posted 2012-10-30 18:16:42 »

I think the problem your prof has is the fact that you do the hole algorithm in the constructor only, and after the algorithm is finished you don't use the object in any way. So there is really no point in creating the object in the first place.
If you on the other hand would store the result of the algorithm in a field of the object one could justify that the algorithm is done in the constructure.
Something like:
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
class CoolAlgorithm
{
   final int result;

   CoolAlgorithm(int input)
   {
      result = /*do something*/input;
   }
...
   static main(String ... args)
   {
      CoolAlgorithm algo = new CoolAlgorithm(46);
      System.out.println("Result: " + algo.result);
   }
}
Offline ClickerMonkey

JGO Coder


Medals: 20


Game Engineer


« Reply #5 - Posted 2012-10-30 18:22:54 »

My strategy: If the algorithm is more than 10 lines of code move it out into a method called run or something.

1  
2  
3  
Converter conv = new Converter();
conv.setInput( 45 );
conv.run();


As soon as you need to write methods or have class level variables, it's annoying adding static to the beginning of everything =P

In the end, your teacher is expressing his personal preferences, there's absolutely nothing wrong with what you did. And I say that not because I do it as well.. but there is no worthwhile argument to be had about the impact this method has on memory and performance.

Offline sproingie

JGO Kernel


Medals: 201



« Reply #6 - Posted 2012-10-31 19:02:50 »

A constructor should construct an object and do nothing more.  It shouldn't have any side effects other than setting fields on the new object, calling only "pure" (no side effects) code for things like validation.  There are legit reasons to break out algorithms into distinct objects though.  If you follow these conventions, you'll find you can plug your "computational objects" into a whole lot of useful libraries like java.util.concurrent and guava:

  • If you just want side effects: implement java.lang.Runnable

  • If you want to return a value: implement java.util.concurrent.Callable

  • If you take an argument each call and return a value: use Guava and implement com.google.common.base.Function
Offline Danny02
« Reply #7 - Posted 2012-10-31 20:37:34 »

the thing with the pure constructor is two sided sword in my opinion.
Some times you need to do some unsafe things to initialize an object, so some suggest to add an initialize() method to the class. The problem with this is that you get uninitialized objects, a thing which is error prone.
After that one could come up with the idea to build a factory which creates and initialize the object, but then one just could have done it in the constructor anyways.

PS: throwing exceptions in a constructor is a hole other thing, which depends on the failure handling one is using
Offline sproingie

JGO Kernel


Medals: 201



« Reply #8 - Posted 2012-11-01 00:23:39 »

Obviously, it's not a hard and fast rule about what must not go into a constructor, but it should be a general principle that a method should just do what it says on the tin, and for constructors, that's "construct an instance".  I actually don't believe in requiring an explicit .initialize() method to make an object ready, because a constructor should never ever return a "broken" object.  But if I really can't do without separate initialization, then I wrap it up in a factory of some sort or a builder where I defer the final .build() call.

In Scala, I avoid a lot of these hoops by simply using "lazy val".  Alas were it so elegant in Java...
Offline KittenKoder

Senior Member


Medals: 7



« Reply #9 - Posted 2012-11-01 11:42:00 »

Actually, a "dead object" is one that is not assigned to anything. By leaving the pointer hanging like that you run the risk of the garbage collector deleting it before it can finish what it's doing. You need to assign it to something that holds the object until the program exits or you are finished with the object. Look into information on object scopes and lifespans for a more in depth understanding of the idea. It's bad form to leave a pointer hanging, even for one shot objects, and why there are a lot of good uses for static methods instead.

If you're going to create an entire object for something like a simple math algorithm, you may want to make a static class and use static methods in place. Not sure exactly what your object is doing, but it's an option.

I am no one else.
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline Orangy Tang

JGO Kernel


Medals: 56
Projects: 11


Monkey for a head


« Reply #10 - Posted 2012-11-01 12:17:47 »

By leaving the pointer hanging like that you run the risk of the garbage collector deleting it before it can finish what it's doing.

Eh? That is not how the GC works.

[ TriangularPixels.com - Play Growth Spurt, Rescue Squad and Snowman Village ] [ Rebirth - game resource library ]
Offline DrHalfway
« Reply #11 - Posted 2012-11-01 12:27:43 »

I always thought GC only collects objects which go out of scope?

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
public void someFunction() {
     Object someObject = new Object();

     // once function returns someObject is collected
}

public Object someFunction() {
     Object someObject = new Object();

     // scope of someObject is passed onto callee of someFunction(), its not collected
    return someObject;
}


Am I missing something here?

Offline Danny02
« Reply #12 - Posted 2012-11-01 13:09:11 »

it's simple, the gc collects every object which reference is not stored anymore.

So in the example this thread started with the gc can collect the "dead object" right after creation, but this doesn't matter, because the code in the constructor is run anyway
Offline KittenKoder

Senior Member


Medals: 7



« Reply #13 - Posted 2012-11-01 13:12:35 »

By leaving the pointer hanging like that you run the risk of the garbage collector deleting it before it can finish what it's doing.

Eh? That is not how the GC works.

I explained it poorly, I'm not very good with explaining things, sadly.


I am no one else.
Offline Orangy Tang

JGO Kernel


Medals: 56
Projects: 11


Monkey for a head


« Reply #14 - Posted 2012-11-01 14:24:28 »

By leaving the pointer hanging like that you run the risk of the garbage collector deleting it before it can finish what it's doing.

Eh? That is not how the GC works.

I explained it poorly, I'm not very good with explaining things, sadly.

Please show an example of where a 'dead' object could be GC'd before "it can finish what it's doing". Because I think you're misunderstanding (or at the very least giving the OP very confusing and wrong advice).

[ TriangularPixels.com - Play Growth Spurt, Rescue Squad and Snowman Village ] [ Rebirth - game resource library ]
Offline Cero
« Reply #15 - Posted 2012-11-01 14:54:59 »

When I learned java it took a while to grasp the truth that everything in Java is a pointer and that a line like
1  
String str = new String("data")

actually creates 2 things, one pointer and one actual data. And they are not at the same "location".
Especially if you start with C++ it gets confusing.

I mean the actual object is just floating around SOMEWHERE, and only through pointers can you access it. its creepy.

Kinda like a helium balloon with strings... the balloon itself is unreachable (its too high up and you cant pull on the strings Grin), and if you cut all strings, you will lose it forever.

Offline theagentd
« Reply #16 - Posted 2012-11-01 17:32:11 »

Kinda like a helium balloon with strings... the balloon itself is unreachable (its too high up and you cant pull on the strings Grin), and if you cut all strings, you will lose it forever.
Nominated for the Best Explanation of the GC Ever award.  Grin

Myomyomyo.
Offline sproingie

JGO Kernel


Medals: 201



« Reply #17 - Posted 2012-11-01 17:52:28 »

I've found with C++, you end up having to use pointers so often anyway that there's little to confuse by the time you get to Java.  And in fact life gets a lot simpler since you don't have to worry about auto_ptr, shared_ptr, charm_ptr, strange_ptr, polka_dot_ptr, etc...
Offline Cero
« Reply #18 - Posted 2012-11-01 18:51:48 »

I've found with C++, you end up having to use pointers so often anyway that there's little to confuse by the time you get to Java.  And in fact life gets a lot simpler since you don't have to worry about auto_ptr, shared_ptr, charm_ptr, strange_ptr, polka_dot_ptr, etc...

Yeah I would agree, its a mess.
But that doesnt change the fact that a little weird and unintuitive with Java, because then you cant even explain it with the simple box analogy, because all boxes in java are empty with a note "your princess is in another castle, go look @<address>"

Offline sproingie

JGO Kernel


Medals: 201



« Reply #19 - Posted 2012-11-01 19:01:51 »

I think the postal analogy works, which is how I learned it in C: You have a bunch of P.O. boxes, each one has an address.  If you pass around an address to someone else, you might give them an address card, you're certainly not going to hand them the whole box.

Now substitute "reference" for address, and you've got java objects (and confused C++ programmers who expect entirely different semantics from what they call "references")
Offline masteryoom

JGO Coder


Medals: 5
Projects: 2


If you look closely, you might see it turning...


« Reply #20 - Posted 2012-11-04 04:08:21 »

My strategy: If the algorithm is more than 10 lines of code move it out into a method called run or something.

1  
2  
3  
Converter conv = new Converter();
conv.setInput( 45 );
conv.run();


As soon as you need to write methods or have class level variables, it's annoying adding static to the beginning of everything =P
My strategy: If the compiler doesn't like it in the main method, do it in an object instead.  Grin

Smiley
Pages: [1]
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

pw (35 views)
2014-07-24 01:59:36

Riven (33 views)
2014-07-23 21:16:32

Riven (21 views)
2014-07-23 21:07:15

Riven (24 views)
2014-07-23 20:56:16

ctomni231 (55 views)
2014-07-18 06:55:21

Zero Volt (47 views)
2014-07-17 23:47:54

danieldean (38 views)
2014-07-17 23:41:23

MustardPeter (43 views)
2014-07-16 23:30:00

Cero (59 views)
2014-07-16 00:42:17

Riven (56 views)
2014-07-14 18:02:53
HotSpot Options
by dleskov
2014-07-08 03:59:08

Java and Game Development Tutorials
by SwordsMiner
2014-06-14 00:58:24

Java and Game Development Tutorials
by SwordsMiner
2014-06-14 00:47:22

How do I start Java Game Development?
by ra4king
2014-05-17 11:13:37

HotSpot Options
by Roquen
2014-05-15 09:59:54

HotSpot Options
by Roquen
2014-05-06 15:03:10

Escape Analysis
by Roquen
2014-04-29 22:16:43

Experimental Toys
by Roquen
2014-04-28 13:24:22
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!