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

Avoid redundant code in this simple method

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

Problem

I am wondering what would be an efficient way to simplify this very simple PHP method and I really lack inspiration:

public function formatToFullDate($countryCode, $hideTime = false)
{
    $format = '';
    if($hideTime === true)
    {
        switch($countryCode)
        {
            case 'us':
            case 'ca':
                $format = '%A %e %B %Y';
                break;
            case 'de':
                $format = '%A, den %e. %B %Y';
            break;
            default:
                $format = '%A %e %B %Y';
        }
    }
    else
    {
        switch($countryCode)
        {
            case 'us':
            case 'ca':
                $format = '%A %e %B %Y - %I:%M %P';
                break;
            case 'de':
                $format = '%A, den %e. %B %Y - %H:%M';
            break;
            default:
                $format = '%A %e %B %Y - %H:%M';
        }
    }

    return gmstrftime($format, $this->getTimestamp());
}

Solution

There is still some redundant code in there(' - %H:%M' and '%A %e %B %Y'). You could put these in variabels, but i like it so more. Sory for my bad English.

public function formatToFullDate($countryCode, $hideTime = false)
{
    $format = '';
    $time_format = '';
    switch($countryCode)
    {
        case 'us':
        case 'ca':
            $time_format = ' - %I:%M %P';
            $date_format = '%A %e %B %Y';
            break;
        case 'de':
            $time_format = ' - %H:%M';
            $date_format = '%A, den %e. %B %Y';
        break;
        default:
            $date_format = '%A %e %B %Y';
            $time_format = ' - %H:%M';
    }
    if($hideTime)$time_format = '';

    return gmstrftime($date_format.$time_format, $this->getTimestamp());
}

Code Snippets

public function formatToFullDate($countryCode, $hideTime = false)
{
    $format = '';
    $time_format = '';
    switch($countryCode)
    {
        case 'us':
        case 'ca':
            $time_format = ' - %I:%M %P';
            $date_format = '%A %e %B %Y';
            break;
        case 'de':
            $time_format = ' - %H:%M';
            $date_format = '%A, den %e. %B %Y';
        break;
        default:
            $date_format = '%A %e %B %Y';
            $time_format = ' - %H:%M';
    }
    if($hideTime)$time_format = '';

    return gmstrftime($date_format.$time_format, $this->getTimestamp());
}

Context

StackExchange Code Review Q#24495, answer score: 8

Revisions (0)

No revisions yet.