• Post Reply Bookmark Topic Watch Topic
  • New Topic

Quick Coding Style Question  RSS feed

 
Russ Russell
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When writing a simple program that only uses one class, is it better to put all the working code in main(), or is it better to put all the working code in the constructor, and have main simply instantiate the class? Example:



Thank you,
-Russ
 
Stephan van Hulst
Saloon Keeper
Posts: 7993
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As always, it depends.

Can you say that whatever it is you do, is a part of the class? Does it make conceptual sense to put it in a constructor?

If what you do are actions you perform on an instance of the class, then it's better to put it in the main. If they are inherently operations that belong to a class, make them part of the class.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In general, a constructor gets an instance of the class ready to do whatever it's going to do. Actually "doing" something -- the "working code" -- should be deferred to a method executed after the instance is fully constructed.

So I'm inclined towards something like...
 
Russ Russell
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Marc. This answers my question. What you are suggesting sits better with me than the either of the two options I originally presented.

Thanks!
-Russ
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!