• Post Reply Bookmark Topic Watch Topic
  • New Topic

Writing a Fraction Class - Simplifying help  RSS feed

 
Joseph Ibrahim
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

So for my Project this week we have to write a class for Fractions (constructing, doing basic math with it, etc).
Anyways, I was able to write it rather easily, however my teacher mentioned that it's possible to write most of the methods in this class in only one line of code and with a lot of code reuse... and I was wondering how exactly I would go about doing that?

Here are the two most complicated methods (imo):

Now the way I've done it does in fact work, and produce the desired result, I was just wondering how I could simplify it. Specifically, he made us write a reciprocal method in our code, and I was wondering how I could rewrite the divide method to just return this fraction multiply by the reciprocal of the other Fraction?

Any help would be much appreciated,
Joseph

(Side note: I plan to replace all the calls of numer / denom with the getNumr / getDenom methods he gave us, I just haven't gotten around to it yet)
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 37462
537
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Joseph,
There's a concept called "chaining" you can use. It works when method calls return the object. For example StringBuilder append methods return StringBuilder objects. This lets us write code like:


Reduce looks like a candidate for that behavior. With that knowledge, you should be able to see how to merge the last two lines of each method. You could merge all three lines that way although I personally don't find it clearer because the line is so long.
 
Campbell Ritchie
Marshal
Posts: 56518
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why use get methods when you can use the fields directly, even when they areprivate? Is there a simpler form at all?
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!