"Dead Objects"?

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:


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 ;D to explain that to me.
So I wanted to ask you guys, maybe someone can explain it
thx

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 :slight_smile:

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?

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:


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.

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:


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);
   }
}

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

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.

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

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

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…

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.

Eh? That is not how the GC works.

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



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?

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

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).

When I learned java it took a while to grasp the truth that everything in Java is a pointer and that a line like

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 ;D), and if you cut all strings, you will lose it forever.

Nominated for the Best Explanation of the GC Ever award. ;D

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 @”

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”)