Skip to main content
2 of 4
added 315 characters in body
candied_orange
  • 114.6k
  • 27
  • 222
  • 352

Don't overflow the heap and you should be fine. If you obeyed the principle that constructors should not do real work then object creation is about as expensive as pointer addition.

Even if it wasn't, worrying about it is likely premature optimization. If you must speculate, speculate that code is fast but hard for humans to read until proven otherwise. In over 20 years the only good performance optimizations I made without hard data were the kind big O notation teaches you. This isn't one of those.

Now that isn't to say there isn't an issue here. What you're looking at is objects being used as functions. This isn't tragic but it's not a helpful design. If you're looking at code like

result = new Employee().getIDBySSN(ssn);

then you might as well be looking at

result = Employee.getIDBySSN(ssn);

Because you're just as concretely bound to one implementation of getIDBySSN(). Maybe you don't care about that. If you don't then everything is fine. If you're thinking the static method looks better, maybe because it's more familiar, well then fine. I don't think it's any better. What I think is better is this:

result = employee.getIDBySNN(ssn);

Why? Because now I don't know exactly which implementation I'm using. That means other implementations can be substituted in here. It also means you have to do more work because now something else (preferably another class) has to figure out which implementation to use here and hand that to you.

This is called separating construction from behavior. It's very powerful. It will preserve the ability to use polymorphism. But it's not cheap. It's up to you if it's worth caring about. The best rule of thumb for if this is OK I've found is how stable the concrete thing is that your binding yourself to. I've never regretted using String or ArrayList this way. However, other things, especially from my own code base, have made me wish I had a time machine so I could go back and yell at myself.

Other than that, no, I make nameless temporary objects (the fancy term for this) all the time. It's just part of the cost of doing business.

candied_orange
  • 114.6k
  • 27
  • 222
  • 352