Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code style: "hiding" data types (Java)

I'm working on a set of classes to represent musical notes, bars, rhythms and so on. Naturally, I'll have to deal with time signatures that are best represented by a fraction (like 4/4, 3/4 and so on).

I'm wondering what is better style. Having a constructor for a Bar contain a Fraction-object or just two ints as a time signature.

public Bar(Fraction timeSignature) {
    this.timeSignature = timeSignature;
}

or:

public Bar (int num, int den) {
    timeSignature = new Fraction(num, den);
}

I mean… i could have both but which one should I go for in my application? Is there a "better" style?

Thank you for your thoughts!

like image 683
Macks Avatar asked Apr 22 '26 05:04

Macks


2 Answers

Personally, I'd go w/ the first approach. If you know you need/want a Fraction object, why have the Bar not just take that? The person invoking the Bar class will need to understand the Fraction either way (to pass you the ints), so it's just cleaner.

like image 74
Michael Avatar answered Apr 24 '26 17:04

Michael


I'd use the first one and provide a factory method in the fraction class to be able to call something like:

new Bar(Fraction.of(4, 4));

best of both world ;-)

like image 29
assylias Avatar answered Apr 24 '26 18:04

assylias



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!