From what I understand, getters and setters are recommended for use for ALL variables and situations.
However I have a situation here where it seems they are just making the code long and awkward so I want to know can I leave them out in this situation or is that bad practise…
I have the following class –
public class Conversation {
class Message
{
private int id;
private int senderId;
private Timestamp timeSent;
private String text;
}
private int conversationId;
private int userIdA;
private int userIdB;
private ArrayList<Message> messages = new ArrayList<Message>();
...
... (Getters and setters for members of Conversation)
...
}
So I am using getters and setters for the Conversation member variables. However I don’t want to use them for inner class, Message, variables. It is just adding about 30 lines to the code of filler and makes it look much more awkward. So is it bad practise to leave them out here? I will also never be editing the Message variables, they will be set with a call to the constructor Message(…, …, …, …) and after that they will just be read. So I definitely reckon it’s fine to leave out the getters, but what about the setters?
If
Messagewere private, I would say no problem at all with using the fields directly; it’s just an internal-details struct, and there are no encapsulation issues (since the outer class can see all of the inner class’ private variables, anyway).But,
Messageis package-private: anyone in that package can also see its fields. This is a gray area, because it’s not quite the published API, but it’s still reasonable, depending on how big the package is, that you’ll want encapsulation down the line. For instance, if it’s a big package and some other class starts depending onMessage(and if none do, you may as well make itprivate), then you risk encapsulation problems if you want to changeMessage‘s internals down the line. So, it’s a judgement call.If
Messagewere public, I would definitely say to provide getters.Btw, if you’re using
Messagejust as a POD here, you should make itstatic— good habit to get into. Generally speaking,staticis better than not.