HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Creating date strings and setting dates

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
creatingdatesdatesettingandstrings

Problem

I've created a Java class, Date, in which I basically create date strings and set dates. Is there anything I can do besides adding comments to improve/shorten my code?

I've tested all of my methods to see if they work correctly, and they all work as planned. I haven't done tests that force the IllegalArgumentsException to be thrown yet though.

I've tried changing the instantiated boolean variable shortDisplay have a default value of true, which has made my program work correctly as far as I know.

I'm assuming when you declare a boolean instance variable, you need to also declare what its default value should be, otherwise issues arise. If anyone could comment on why that is, that would be great.

Date.java

```
public class Date {
private int year;
private int month;
private int day;
private boolean shortDisplay = true;

public Date() {
setDate(2000, 01, 01);
}

public Date(int yy, int mm, int dd) {
setDate(yy, mm, dd);
}

public Date(int yy, int mm) {
setDate(yy, mm);
}

public Date(int yy) {
setDate(yy);
}

public Date(Date otherDate) {
setDate(otherDate);
}

public Date(String dateStr) {
setDate(dateStr);
}

public void setDate(int yy, int mm, int dd) {
setYear(yy);
setMonth(mm);
setDay(dd);
}

public void setDate(int yy, int mm) {
setYear(yy);
setMonth(mm);
setDay(1);
}

public void setDate(int yy) {
setYear(yy);
setMonth(1);
setDay(1);
}

public void setDate(Date otherDate) {
int yy = getYear();
int mm = getMonth();
int dd = getDay();
setYear(yy);
setMonth(mm);
setDay(dd);
}

public void setDate(String dateStr) {
int length = dateStr.length();
int indexCount = 0;
if (length >= 0) { // basically checking to see if the date even exists
if (dateStr.in

Solution


  • Your class does not handle months with less than 31 days, in-real-life-speaking your unit test for adding five days to 28th April is already wrong



  • stringMonth can be left as a private static final array, so that you are not re-creating it every time monthString() is called



  • equals() implementation does not check for null/class type, and by right you should have a corresponding hashCode() implementation too



  • before() can probably be better implemented as compareTo() if you can consider letting your class implement Comparable



  • There are better ways of formatting the String representation in toString() and parsing a String date in setDate(String dateStr)



  • Some Javadocs will be helpful too, especially to indicate the format that you are using in toString() ("MM/DD/YY")



  • Consider a proper testing framework such as JUnit or TestNG?

Context

StackExchange Code Review Q#47316, answer score: 5

Revisions (0)

No revisions yet.