Re: Is creating anonymous objects bad practice?



On Fri, 28 Nov 2008, Lew wrote:

Arved Sandstrom wrote:
To put it very succinctly, people expect constructors to return an initialized object. And that's all a constructor should do. It will confuse other people reading your code if you start non-initialization in a constructor. In your above example a maintenance programmer would figure it out, but it's not always that obvious.

It's got nothing to do with what "people expect". Doing work with an incompletely-constructed object leads to bugs, that's why it's bad.

Hold on, hold on, the issue in this thread isn't about incompletely constructing objects, it's about the other fork of Arved's succinct putting - that constructors should not do anything else. Consider:

public class LogMessage {
public LogMessage(String msg) {
System.err.println(msg) ;
}
}

Which is used OP-style like this:

doSomething() ;
new LogMessage("did something") ;

There's no risk of incomplete construction here, but i think we'd all agree that this is bad style nonetheless.

tom

--
This is your life and it's ending one minute at a time.
.



Relevant Pages

  • Re: fread breaks file descriptors opened in "w" mode.
    ... Lénaïc Huard wrote: ... of that decorator should parse the file is possible (i.e. if it is a ... regular file opened for reading). ... those conditions are met when the constructor is invoked. ...
    (comp.lang.c)
  • How do you implement global data?
    ... I have some data that I need to have accessible to multiple classes. ... The data is initialized from the constructor of one class by reading a file. ... How would you setup shared data under these conditions? ...
    (comp.lang.java.programmer)
  • Re: Moving from Delphi to C++
    ... for reading, std::string has c_str, and for buffers, you can use a ... and std::string has a constructor which takes a char*. ...
    (borland.public.delphi.non-technical)
  • Re: How do you implement global data?
    ... data is initialized from the constructor of one class by reading a file. ... That same class has an editor that can modify that data. ...
    (comp.lang.java.programmer)
  • Re: MSIE 6.0 does not support protyping with objects created with document.createElement.
    ... The objects created from said constructor won't actually behave like links. ... Assigning to the href property, for instance, wouldn't change the property value for the element as properties inherited from the prototype chain are only used during reading. ... Moreover, all objects created from the myObj constructor function will share the same anchor element, which is surely not intended. ...
    (comp.lang.javascript)