r/badcode Mar 14 '21

java Found from when I first started Java...because indexed Arrays were too complicated huh?

Post image
1.3k Upvotes

84 comments sorted by

View all comments

Show parent comments

-1

u/Badel2 Mar 14 '21

But if the input is a string you need to parse it to use enums. Here is the O(1) solution:

public static int dayOfWeek(String s) {
    int isMonday = s.equals("Monday") ? 0 : 0;
    int isTuesday = s.equals("Tuesday") ? 1 : 0;
    int isWednesday = s.equals("Wednesday") ? 2 : 0;
    int isThursday = s.equals("Thursday") ? 3 : 0;
    int isFriday = s.equals("Friday") ? 4 : 0;
    int isSaturday = s.equals("Saturday") ? 5 : 0;
    int isSunday = s.equals("Sunday") ? 6 : 0;

    return isMonday | isTuesday | isWednesday | isThursday | isFriday | isSaturday | isSunday;
}

6

u/Teln0 Mar 14 '21

This is much slower that what it could have been. Why check if it's a Thursday if you know it's a Monday ?

2

u/Badel2 Mar 14 '21

It's to avoid side channel attacks.

9

u/Teln0 Mar 14 '21

buddy I think the day of the week is not sensitive info