Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

DiceGame Code - which is better?

 
Stephen Foy
Ranch Hand
Posts: 143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
They are quite alike, but i believe one is better writte.
Which should i use, and can i improve on it?

code 1



code 2:

[/size]
 
Stephen Foy
Ranch Hand
Posts: 143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Anything please??
 
Junilu Lacar
Bartender
Posts: 7466
50
Android Eclipse IDE IntelliJ IDE Java Linux Mac Scala Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Stephen,

Honestly, your code still needs a bit of work to make it clearer and easier to follow. As I mentioned in another thread, you should write code in such a way that it reads the way it is intended to work. Each method should have a single responsibility and consistent level of abstraction and detail. Assign methods names that reflect what they actually do. Your rollDice() method does not actually just roll the dice; it does almost everything.

My first-cut implementation of rollDice() would probably be something like:



But then again, this code is very procedural. If I really wanted OO code, I might try something like:



Notice that these first methods do not have much detail but they give you a high-level view of what happens in the program. If you need more detail, you would drill down to other methods. Those methods would have a lower level of abstraction and more detail. The trick is getting the right balance of detail and abstraction.
 
Stephen Foy
Ranch Hand
Posts: 143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks im gonna give it another bash, i think my problem is we havnt started OO programming yet, the ways i ave used are the ways we have been shown so far. Only been in java for 2-3 months. My problem is, linking methods, like you have there methods called in other methods.

How?

Thanks for the advice.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic