Any ways to improve the foll. code block :
public class MyUnits {
public static String MILLSECONDS = "milliseconds";
public static String SECONDS = "seconds";
public static String MINUTES = "minutes";
public static String HOURS = "hours";
public int quantity;
public String units;
public MyUnits(int quantity, String units) {
this.quantity = quantity;
开发者_StackOverflow this.units = units;
}
public String toString() {
return (quantity + " " + units);
}
// Test code
public static void main(String[] args) {
System.out.println(new MyUnits(1, MyUnits.MILLSECONDS));
System.out.println(new MyUnits(2, MyUnits.SECONDS));
System.out.println(new MyUnits(3, MyUnits.MINUTES));
System.out.println(new MyUnits(4, MyUnits.HOURS));
}
}
Any help will be appreciated.
The static ints should be final. The usual modifier for a "constant" in Java is
public static final <Type> <name> = <value>;
A bigger enhancement: exchange the static int with enum:
public enum Unit {MILLISECOND, SECOND, MINUTE, HOUR}
The new constructor signature would be:
public MyUnits(int quantity, Unit unit) { ... }
The non-static fields in MyUnit should be made private. Add getter/setter methods for access.
And finally (and for serious code only), I'd separate the test code from the class. Have a look at testing frameworks, like junit
and implement separate test classes.
Mark your
public static
variables asfinal
; better yet, use enums.Don't let instance variables (
quantity
,units
) bepublic
. Provide "getter" methods to read their values. Consider not providing "setter" methods to change their values. This makes your class immutable, which can make it easier to use (the state of an immutable object is much more predictable than that of a mutable object!)Be more specific about what the code is intended to do; then make it do that. (This also allows you to ask more specific questions, which would get you better answers.)
Add comments, especially javadoc comments.
use enum for the unit within your class.
public enum MyUnit {
MILLSECONDS(1, "milliseconds"), SECOND(2, "seconds"),
MINUTES(3,"minutes"), HOURS(4, "hours");
private MyUnit(int quantity, String units) {
this.quantity = quantity;
this.units = units;
}
private int quantity;
private String units;
public String toString() {
return (quantity + " " + units);
}
/*getters setters*/
}
and just call like that
MyUnit.HOURS.getUnits();
MyUnit.HOURS.getCuantity();
Add clone(), hashcode() and equals(), and implement Comparable, Serializable and Cloneable.
Remove the test code and move it to a test class. Use JUnit for testing.
Write a function public Date addToDate(Date date)
.
精彩评论