It’s really useful to describe the enum syntax in Java when you want to express Value Object. This article just show how we could describe value object better using enum syntax. and You should know this article is included my personal opinions that might be not true. so I want to you who become more strictly than before when you are reading this.
What is the Value Object ?
Firstly, Let’s try to get the concept of Value Object briefly. Value Object is usually mentioned in Programming language (especially Java).
It means the object what only has ‘status’ without behavior. and We usually abbreviate it as VO. so I will mentions it as VO at now.
in other words, VO would be usually just data class that has only value(= variables) without any doing something(= function).
if you should use enum syntax, then the Enum object will be the one to describe some data like Database. but The difference between Enum and Database is Enum data object is only stored in memory located programming language regions.
- Value Object
- The thing only has variables without function.
- expressing data object in programming language.
Let’s try to express VO without enum syntax.
You can express VO using class keyword. because Enum is implemented from class. Let’s try to describe ‘Season’ object simply using class.
1 | class Season { |
This Season class only has data without any function as you learned the above.
but You could see the disadvantage of the above source code. String type can take any word that you don’t want. it means this season class can take the string value that doesn’t associated with Season. If we can make it more strictly, then the source code is better.
1 |
|
Let’s do refactoring.
You can change this code better using enum keyword.
1 |
|
The source code using enum is more simple than the class one and the readability is also better.
and one of the features of enum is that same data object is become same instance. so if you need to express like this data type then it’s really good choice that using enum for that.
- The advantage that you express VO with enum
- Improving readability
- Only input the data you want
- same data is same instance (singleton)
enum with multiple fields
you also add new fields in enum object if you want. Let’s suppose for understanding this case. we need two fields that one is the korean word and the other is english code that represent the season. let’s follow up the below code.
1 |
|
lastly, i would like to say the advantage of enum keyword one more. let’s think the situation that some concepts could express various ways. sometimes we should it parse to another type one. but this coding style is not good. because you should add new function to parse whenever you add new variables that are same concepts. and You could not keep the consistency.
1 | class Parser { |
if you use enum, it will be better.
1 |
|