Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly organize structure of two enums with relationship many-to-many between them in terms of application's architecture and classes?

I have enum CarBrand:

public enum CarBrand {
    BMW, MERCEDES, VOLKSWAGEN, AUDI, FORD, OPEL
}

and enum CarBodyType:

public enum CarBodyType {
    SEDAN, MINIVAN, VAN
}

Relationship between them is many to many. I.e. a car brand can have several variants of type of car body, and a car body type has several brands.

How to define such entity–relationship model in my code with these enums?

Maybe I need make field in each enum as a set parameterized by another enum?

public enum CarBrand {
    BMW, MERCEDES, VOLKSWAGEN, AUDI, FORD, OPEL;

    private Set<CarBodyType> bodyTypes;         

    public Set<CarBodyType> getBodyTypes() {
       return bodyTypes;
    }

    public void setBodyTypes(Set<CarBodyType> bodyTypes) {
       this.bodyTypes = bodyTypes;
    }
}

and

public enum CarBodyType {
    SEDAN, MINIVAN, VAN;

    private Set<CarBrand> brands;

    // getter and setter
}

Is this a good solution? Or would it be better to implement such relationships via a third junction entity? If so, what should it be? How should this entity be designed and what fields should it contain?

like image 370
François Esthète Avatar asked Dec 15 '12 01:12

François Esthète


1 Answers

It is almost certainly not true that a body-type "has a" brand. It is most likely not true that a brand "has a" body type. What you most likely want to model is a separate set of the intersection of each brand's permissible body types.

That is you most likely want a Vehicle which has a body-type and a brand:

public class Vehicle 
{
    private CarBrand brand;
    private CarBodyType body;
    ...
}

and create Vehicles each of which model one combination.

In response to the comment

For example what about this case? If Book and Author are enums.

I don't think the book/author example works for enums (and maybe your use of enums is at the heart of the problem). The number of books and authors is open-ended; you wouldn't model either books or authors using a closed-set enum. Further more, it is true that every book has one or more authors, while every author is only an author in the context of having written one or more books (otherwise they are simply a person aspiring to be an author).

In relational modelling of books and authors you would have a Book table, an Author table and a separate relation table of BookAuthor which was a conjunction of foreign keys to the Book and Author tables. In object terms change the word "table" to "object", though in an object model you would probably replace the BookAuthor "table" with a set of authors in each book and/or a set of books in each author.

like image 94
Lawrence Dol Avatar answered Nov 20 '22 00:11

Lawrence Dol