I am writing a communication software that will talk to lab processes in the control department in my uni. The processes communicate over serial port and there will be a fair bit of bit checking/manipulation. I have written a helper class like the following:
public class Channel {
public enum Kind {DIGITAL_IN, DIGITAL_OUT, ANALOG_IN, ANALOG_OUT, COUNTER_IN};
private int resolution;
private int number;
private Kind kind;
public byte[] bits;
public Channel(Kind kind, int resolution, int number) throws Exception {
if (resolution % 8 != 0) {
throw new Exception("Resolution must be divisible by 8");
}
this.kind = kind;
this.resolution = resolution;
this.number = number;
this.bits = new byte[resolution/8];
}
public int getResolution() {
return resolution;
}
public int getNumber() {
return number;
}
public Kind getKind() {
return kind;
}
}
My question now is if it would be considered bad practice in this case to have my byte[] declared as public? In my LabProcessProtocol class I will access these channels bits and change them according to what I get from the process on the serial port.
I have a hunch that Java is all about being private and using getters and setters but I'm not sure. It seems so convoluted in this case.
Thanks in advance.
Well, there's no absolute prohibition against public fields. If you feel that is the best solution, then don't be ashamed, go ahead an do it.
That said, stop and think about what you want to accomplish. Making everything private is not a goal in itself - the idea is to establish invariants, to make the code easier to understand and to work with.
So consider what you want to do with the byte[]
- what operations will others want to perform on it? Consider having methods for these operations, that will be easier to understand and cleaner than exposing the field as public. Also, consider what operations you do not want to allow (that would be the part that establishes invariants). For example, direct field access would allow replacing the byte[]
with another one of different length - you probably want to prevent that.
Or maybe so much happens to this byte[]
that it deserves a (wrapping) class of its own? This all depends on how it is used.
In closing, there's no problem with starting with a simple public field. You can always refactor it later, once you have found a more appropriate solution.
Note: "You can always refactor it later" does not apply for classes which are part of a public API (i.e. you are writing a library to be used by other, outside projects). Design of public APIs (often just called "API design") is much harder than design of "internal" code, this is just one example. This probably does not apply in this case, I just wanted to point it out.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With