Search code examples
javadatedayofweek

Modelling multiple days of the week


This is the second time i've come accross a one-many relationship between object and weekday and I'm not sure if i'm modelling it in the best way:

@Entity
MyObject {
    private int id;
    private String foo;
    private boolean monday;
    private boolean tuesday;
    private boolean wednesday;
    private boolean thursday;
    private boolean friday;
    private boolean saturday;
    private boolean sunday;
}

Has anyone come across a better way of doing this?

My requirement is to retrieve all instances of MyObject from the db that match the current day of the week, i.e. no need to check multiple days for example mon=1 && tues=1


Solution

  • When modeling a finite number of items in a set, it is usually best to use an enum.

    public enum DayOfWeek {
        Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
    }
    

    You might use this in your class like so:

    class YourClass {
        private Set<DayOfWeek> activeDays;
    
        public void addActiveDay(DayOfWeek day){
            activeDays.add(day);
        }
    }
    ...
    
    yourclass.addActiveDay(DayOfWeek.Friday);