Search code examples
javatypesenumstype-safety

Differences between type-safety and value-safety


I've been reading Head First Object-Oriented Analysis and Design book and I'm trying to learn oop.

in one of the pages of this book, I've read these lines:

we’ve made the application less fragile along the way. It’s not going to break so easily now, because we’ve added both type safety and value safety with these enums.

and also:

So you can’t misspell or mistype an enum without getting a compiler error. It’s a great way to get not only type safety, but value safety; you can a void getting bad data for anything that has a standard range or set of legal values.

I've read this answer and I got confused because I thing the answer is something that we can assume that as value-safety.

now my question is What is the difference between type-safety and value-safety? and how can Enum bring us type-safety and value-safety? please give me some example about type-safety scenario and value-safety scenario in enums.

Thanks. sorry for my bad English.


Solution

  • Assume we are holding a convention for superheroes. While they register we ask them whether they belong to MARVEL or DC.

    Type-safety is simply the check on what kind of value a user is allowed to enter. For a method like this:

    void register(String name, String affiliation);
    

    A user can enter only Strings, not integer, not Lists, not Files.

    But, a user can still enter any String, which may or may not be a valid action comic group or we don't want that group to register. Values like 'abcd', 'dummy', 'action_labs' will still be valid string but we don't want Action Labs buddies to register. Type-safety : true, Value-safety : false. Moreover, Marvel or DC superheroes don't know whether to put 'marvel' or 'Marvel' or accidentally 'malver' or 'marvl' etc. It would be so hard to find how many sups are with marvel even if we go with equalsIgnoreCase().

    With value-safety we define an enum:

    enum ComicGroup{
        MARVEL, DC
    }
    

    and modify the method:

    void register(String name, ComicGroup affiliation);
    

    The user does now has only two options ComicGroup.MARVEL or ComicGroup.DC. We can be 100% sure that our values will always either be those. Type-safety : true, Value-safety: true.