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

Checking that an entered date is before the current date

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

Problem

I want to write a function which returns true if a selected date is smaller than the current date, else return false.

This function is working as expected but I want to know the best possible way to do this.

private boolean isValidDate() {

    if(yearyearCurr)
        {
            //selected year is greater date is greater
            return false;
        }else
        {
            //selected year is same as current year check month

            if(monthmonthCurr)
                {
                    //if selected month is greater date is greater
                    return false;
                }
                else
                {
                    // selected day of month is less than or equal to current date; date is valid 
                    if(day<=dayCurr)
                        return true;
                    else
                        return false;
                }
        }
}

Solution

Just wanted to chime in:

  • Nobody mentioned this, but isValidDate() to determine whether 1 date is earlier than another date is frankly terrible. Call it isEarlierDate()



  • Where are the variables? Are those variables all defined outside of this function. That does not look good.



-
If there is one thing you learn today it is that this

if(day<=dayCurr)
    return true;
else
    return false;


should always be written as

return day<=dayCurr


  • As per @Heslacher, write out your variable names



This is my over-commented counter-proposal:

function isEarlierDate(){

  return year < currentYear || //Last year is in the past
         year == currentYear && month < currentMonth || //This year, earlier month is in the past
         year == currentYear && month == currentMonth && day < currentDay || //..
         false; //This is clearly not an earlier date
}

Code Snippets

if(day<=dayCurr)
    return true;
else
    return false;
return day<=dayCurr
function isEarlierDate(){

  return year < currentYear || //Last year is in the past
         year == currentYear && month < currentMonth || //This year, earlier month is in the past
         year == currentYear && month == currentMonth && day < currentDay || //..
         false; //This is clearly not an earlier date
}

Context

StackExchange Code Review Q#71768, answer score: 6

Revisions (0)

No revisions yet.