For example, if I use an enum, which all values are manually defined individually, for example:
public enum MyNum{
Zero(0),
One(1),
Two(2);
private final int value;
MyNum(int value){
this.value=value;
}
public int getValue(){
return value;
}
}
public class Test{
public static MyNum getUnknownMyNum(){
return MyNum.Two;
}
public static void main(String[] args){
MyNum n1=MyNum.One;
MyNum n2=MyNum.Two;
System.out.println(n1==getUnknownMyNum());
System.out.println(n2==getUnknownMyNum());
}
}
and don't use the feature of bitwise operation, eg:
MyNum n=MyNum.Zero | MyNum.One;
,is it violating open-closed principle? Because I think at this case, adding a new enum (eg:Three(3)) needs to edit MyNum.java.
If all enum value are assigned manually, and I don't need bitwise operation when using that enum, it means each value is independent to each other, which is different from
public enum MyNum{
Zero,
One,
Two
}
that calculates each value from zero, and hence we can replace the following enum :
public enum MyNum{
Zero(0),
One(1),
Two(2);
private final int value;
MyNum(int value){
this.value=value;
}
public int getValue(){
return value;
}
}
into individual classes:
public interface MyNum{
}
public class Zero implements MyNum{
public static final Zero MyNum=new Zero();
public static final int value=0;
}
public class One implements MyNum{
public static final One MyNum=new One();
public static final int value=1;
}
public class Two implements MyNum{
public static final Two MyNum=new Two();
public static final int value=2;
}
public class Test{
public static MyNum getUnknownMyNum(){
return Two.MyNum;
}
public static void main(String[] args){
MyNum n1=One.MyNum;
MyNum n2=Two.MyNum;
System.out.println(n1==getUnknownMyNum());
System.out.println(n2==getUnknownMyNum());
}
}
which replaces the one using enums into the version that use an interface with classes. And this time we don't need to edit the MyNum.java in order to add a new enum "Three", but creating a new class Three.java:
public class Three implements MyNum{
public static final Three MyNum=new Three();
public static final int value=3;
}
which fits open closed principle, is it true?
Note: for c++ enums for example,
enum class MyNum{
Zero,
One,
Two
}
enum class MyNum{
Zero,
One=2,
Two
}
they doesn't consider as "all values are manually defined individually" because some values needs to calculate from previous value