I have an object
class that tells me what type of data has changed.
object Part {
const val CONTRAST = 0x00000001
const val SATURATION = 0x00000010
const val PIXELATION = 0x00000100
const val SHARPNESS = 0x00001000
const val BRIGHTNESS = 0x00010000
const val ALL = 0x11111111
}
In my usage method I check what Part
of data has changed. And, update only matched data.
fun applyUpdate(flag: Int, percentage: Int) {
if (flag and Part.CONTRAST == flag) {
applyContrastUpdate(percentage)
}
if (flag and Part.SATURATION == flag) {
applySaturationUpdate(percentage)
}
.
.
}
// applyUpdate(Part.CONTRAST, 60) --> only contrast is updated.
// applyUpdate(Part.SATURATION, 30) --> only saturation is updated.
// applyUpdate{Part.ALL, 0}. --> all values are updated.
What I understand is that 0x0001 and 0x0001 = 0x0001
= CONTRAST.
But, if I define a new Part
say DISTORTION = 0x0011
, then changes in distortion will also change CONTRAST.
e.g. 0x0011 and 0x0001 = 0x0001
= CONTRAST
With this code, I can define upto 8 Part
s. Placing 1
's properly. Right? If I had 36 Part
s, how can I keep this functionality working?
EnumSets are probably less error-prone than bit flags. It's a matter of opinion, but I think the syntax is easier to work with for bit flags. Bit flags like this can be used for optimization. In Android, the designers were very enum-averse, so enums are not used in platform code.
If you do go with flags:
You can have up to 31 flags, not 8. Or 63 flags if you use Long
instead of Int
. (Not 32 and 64, because the very first bit is used for sign.) You've defined your constants using hexadecimal, not binary, and only using one possible value of each hexadecimal digit, so you've only used a quarter of your available bits.
You can define them using doubling values in each digit, up to 8:
object Part {
const val CONTRAST = 0x00000001
const val SATURATION = 0x00000002
const val PIXELATION = 0x00000004
const val SHARPNESS = 0x00000008
const val BRIGHTNESS = 0x00000010
const val SOMETHING = 0x00000020
const val ALL = 0x0000003F
}
When you check flag and Part.CONTRAST == flag
, you are checking if the flag has only CONTRAST
turned on. If you want to check if the flag merely contains CONTRAST
, you would check flag and Part.CONTRAST == Part.CONTRAST
, or to put it more succinctly: flag and Part.CONTRAST != 0
.
User contributions licensed under CC BY-SA 3.0