This question already has answers here:
Get and Set methods in Java. How do they work?
(5 answers)
Closed 7 years ago.
Can somebody tell me or show me something that would make me understand the get and set methods completely? I know some of it already but it still confuses me.
I am trying to learn the MVC Design Pattern but I find it hard because I haven't completely understand this. I thought it was easy but it's not really that easy. Well, at least for me.
Your own example would be appreciated. Thank you in advance guys :)
The Model, View, Controller design pattern is a useful way of decoupling the various components of an GUI driven application. It improves cohesion, which essentially emphasises the responsibility of discrete elements of your software and helps avoid unnecessary overlapping of functionality.
The Model stores what is referred to as 'business logic'. This means it houses all of the data which is core to your application.
The View is what handles the graphical interface. Everything responsible for managing how your graphics are rendered is defined here.
Finally, the Controller handles events. This includes asynchronous events such as whenever a key has been pressed, or the mouse has been moved, or the user has touched their screen. It receives these events and decides what to do with them.
So, how they come together is as follows; the Model defines what needs to be drawn. Any graphics the View needs to render is therefore housed in the Model. This means that any modifications to the Model's data will in turn effect what is drawn on the screen; however, the Model is only really defining what elements need to be drawn, it has no clue how to draw them; just how to manage them and manipulate them. It's the View which can take these elements and in turn use them within a graphical context. The controller on the other hand, handles events and in turn manipulates the contents of the Model. It does this by using a defined set of rules on how each input event will affect certain parts of the Model.
So, in this regard, the Model, View, Controller can be looked at like this:
final Model m = new Model();
final View v = new View(m);
final Controller c = new Controller(m);
Both the Controller and View need access to the Model in order to manage and render the application respectively, but the Model doesn't care about either of them. This is because the Model defines the core data dependencies of your application, which should be transferrable, and work independently of whether it's a component of a GUI or not.
In terms of getter and setter methods, all these do are provide access to a member variable sitting inside a class. So if we were to look inside the View, we would see something like this:
public final class View {
/* Member Variables. */
private final Model mModel;
public View(final Model pModel) {
/* Initialize Member Variables. */
this.mModel = pModel;
}
public final Model getModel() {
return this.mModel;
}
}
The method getModel() is referred to as a getter method; it's sole responsibility is to return a variable; in this case it returns the View's mModel variable. What's useful about getter and setter methods is that you can control access to that variable; the method can be declared public, protected and private for example, which all change just who else inside your application can get access to the Model. The same goes for a setter method, whose only responsibility should be to change the value of a specific variable belonging to the owning Object.
I know this should be a comment, but I currently don't have the reputation required to post a comment.
First of all, could you please provide more information about what specifically you'd like to know? Are you confused about how getters and setters work in general? Are you confused about how the work in an MVC pattern? (getters and setters work the same way in MVC as they do in other design patterns).
If the link posted in the comment above doesn't solve your answer, then hopefully I can help. Getters and setters (getVarName and setVarName) are used to provide additional functionality (like ensuring that a value fits a desired range, etc) and also to provide encapsulation of your code. Besides the additional functionality (like validation), encapsulation also helps avoid errors like accidentally changing the value of a class's variable when you don't mean to. Take a Customer class for example:
public class Customer {
private int empNo;
private int deptNo;
//additional class variables
public Customer() {
//default constructor }
public Customer (int emp, int dept) {
empNo = emp;
deptNo = dept;
}
public int getEmpNo() {
return empNo;
}
public void setEmpNo(int emp) {
empNo = emp;
}
//other methods
}
Let's say that all employee numbers must be 5 digits long and not start with a 0. If we don't use a setter, then there's no way to check if the number given is a valid number (or that it was even given). For that, we could write a simple validation requirement in our setEmpNo method.
public void setEmpNo(int emp) {
if(emp >= 10000 && emp <= 99999) {
empNo = emp;
}
//code to handle invalid numbers
}
Encapsulation also helps us avoid certain errors, like changing the value of empNo when we mean to just check the value in a condition, etc. For instance, if we don't use getters and setters and just have a public empNo, the following typo would change the value of the employee's employee number:
if(employee1.empNo = 12345) { //checking if this is employee 12345 would use ==
//perform action for specified employee
}
However, if we use getters and setters, we'd still run into a problem because we're not checking if the desired employee's employee number is 12345, but that employee's number would NOT be permanently changed to 12345 and would still retain his/her correct employee number. Does this make sense?
It looks like someone already posted a pretty good answer about MVC, so I won't repeat any info on that. One thing I will point out is that MVC is usually (if not always) used for server-based apps. If you have an app that contains a website that users interact with and a database, then there's a good chance you'll use some variant of the MVC pattern. However, you're not going to use MVC for something like a Hello World app.
I hope my answer isn't too basic. It's hard to judge a user's knowledge level without getting additional info. If you'd like me to clarify or give further explanation on anything I've posted, let me know.
Best of luck going forward.
Getter and setter methods used when we define instance variables private so from outside class we can't access private instance variables directly which is useful for encapsulation(hiding data from outside world). So for accessing private variables we required some methods which is basically getter and setter.
public class Employee
{
private int empNum;
public Employee(int empNum) {
this.empNum = empNum;
}
public int getEmpNum() {
return empNum;
}
public void setEmpNum(int empNum) {
this.empNum = empNum;
}
}
for more reasons why we use getter/setter read this answer
There is no direct relation between MVC and getter/setter methods.
MVC is basically design patter for software development where we divide task between different modules(model, view and controller)
model -> Data layer
view -> Representational layer
controller -> Controller layer between model and view
So when you create model class in mvc you define multiple instance variables(attributes) for model but from controller you don't want to access that variables directly so in that case you should use getter setter methods.
Actually getter/setter concept in not limited to just mvc it is use as a codding standard and for abstraction purposes.
Related
This question already has answers here:
Are getters and setters poor design? Contradictory advice seen [duplicate]
(16 answers)
Closed 9 years ago.
I have been going through clean code book which states that the class should not expose the internal state of its data and only should be exposing the behavior. In case of a very simpl and dumb java bean exposing the internal state which getter's and setters, is it not worth just removing them and make the private members public? Or just treat the class as a data structure?
I don't think so. It depends of the lifetime of your Object and its "exposure" (external modification).
If you're only using it as a data structure, exposing fields in secure way (final) sounds enough:
public class Person {
public final String firstName;
public final String lastName;
public Person(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
}
The term POJO was intended to distinguish classes from JavaBeans or any other convention. As such a POJO is by definition NOT required to do anything.
I have been going through clean code book which states that the class should not expose the internal state of its data and only should be exposing the behavior.
This is called encapsulation and a good principle.
In case of a very simpl and dumb java bean exposing the internal state which getter's and setters, is it not worth just removing them and make the private members public?
That is an alternative approach. Some projects may forbid this approach while others may encourage it. Personally, I would favour this approach for classes which are encapsulated in some way already e.g. they are package local.
There is a view that some day in some way your class might have additional requirements and changing the "API" will be impossible. This goes against the YAGNI principle and very rarely proves to be the case and when it does has a much lower cost than adding lots of methods which don't do anything.
However, this is not always the case and if you don't use accessor methods you should consider what the impact will be on the project if you have to change it later. Using accessor methods every where means you never need to worry about this.
In summary, if you are pretty sure accessor methods are pointless and it won't be a problem to add them later, I would say you should use your judgement. However if you are not sure if it could be a problem in the future or you don't want to have to worry about it, use accessor methods.
The definition of POJO doesn't mandate getter/setter.
Experimentally, I am not using getter and setter in my current project.
The approach I am taking is this one:
unless necessary, don't provide getter/setter.
So far, I didn't find a case where I really needed get/set.
Some friend told me: "having get/set is helpful if in the future you need xyz"; my reply has been: when -in the future- I need to do so, I will provide the getter and setter; I don't want to anticipate anything.
The objection about incapsulation, that some may raise, is not really a valid one: providing getter and setter breaks incapsulation in the same manner, plus you have additional lines of (useless) code. Bugs may also lay in getter and setters.
This is an example of one of a non-trivial domain class:
public class SSHKey implements IsSerializable {
public Long id;
public Long userId;
public String type;
public String bits;
public String fingerprint;
public String comment;
#SuppressWarnings("unused")
private SSHKey() { // required by gwt-rpc
}
public SSHKey(String text) throws InvalidSSHKeyException {
Ensure.that(text != null, new InvalidSSHKeyException("Invalid Key"));
text = text.trim();
String[] parts = text.split(" ", 3);
Ensure.that(parts.length >= 2,
new InvalidSSHKeyException("Invalid Key"));
type = getType(parts);
Ensure.that(type.equals("ssh-rsa") || type.equals("ssh-dss"),
new InvalidSSHKeyException(
"Key must start with 'ssh-rsa' or 'ssh-dss'"));
bits = getBits(parts);
comment = getComment(parts);
}
private String getBits(String[] parts) {
return parts[1];
}
private String getComment(String[] parts) {
if (parts.length == 3)
return parts[2];
return type + " " + bits.substring(0, min(15, bits.length())) + "...";
}
private String getType(String[] parts) {
return parts[0];
}
}
The constructor takes the responsibility to validate and prepare the data to be manageable. Thus this logic doesn't need to be in a setter/getter.
If I was shown object with public members some years ago, I would probably not like them; maybe I am doing something wrong now, but I am experimenting and so far it is ok.
Also, you need to consider if your class is designed to be extended or not (so, foresee the future is part of the requirements), and if you want your object to be immutable. Those things you can only do with get/set.
If your object must be immutable, and you can avoid the empty constructor, you can just add 'final' to the member instances, btw.
Unfortunately I had to add IsSerializable (similar to java.io.Serializable) and an empty constructor since this is required by gwt. So, you could tell me then "you see? you need the getter an setter"; well not so sure.
There are some jdbc frameworks which promote the use of public fields btw, like http://iciql.com
This doesn't imply that this project is correct, but that some people are thinking about it.
I suppose that the need of getter/setter is mostly cultural.
The issue with making the members accessible is that you no longer control them from inside the class.
Let's say that you make Car.speed accessible. Now, everywhere in you program there can be some reference to it. Now, if you want to make sure that speed is never set a negative value (or to make the change synchronized because you need to make it thread safe), you have to either:
in all the points where speed is accessible, rewrite the program to add the control. And hope that everybody that changes the program in the future remembers to do so.
make the member private again, create the getter and setter methods, and rewrite the program to use them.
Better get used to write getter and setter from the beginning. Nowadays, most IDEs do it automatically for you, anyway.
The canonical answer to this is: You don't know whether your simple data structure will stay so simple in the future. It might evolve more than you expect now. It might be also possible, that anytime soon you want some "value changed" observer in that bean. With getter and setter methods you can do this very simply later without changing you existing codebase.
Another pro point for getter/setter is: If in Rome, do like the Romans... Which means in this case: Many generic frameworks expect getter/setter. If you don't want to rule all these usefulls frameworks out right from the start then do you and your colleagues a favour and simply implement standard getter/and setters.
Only if you expose a class in a library that's used beyond your control.
If you do release such a library, the Uniform Access Principle dictates that you should use getters and setters in order to be able to change the underlying implementation later without requiring clients to change their code. Java doesn't give you other mechanisms to do this.
If you use this class in your own system, there's no need: your IDE can easily encapsulate a public field and update all its usages in one safe step. In this case, brevity wins, and you lose nothing for the time where you need encapsulation.
I think it's a good idea to use getters and setters, unless you have very specific speed/memory/efficiency requirements or very simple objects.
A good example is a Point, where it is probably both nicer and more efficient to expose it's .x and .y variables.
That said, it will actually not be a big effort to change the visibility of a few member variables and introduce getters and setters even for a large codebase, if you suddenly require some logic in a setter.
JavaBeans require getters and setters. POJOs do not, anyway this has its benefits
The objetive of the getters and setters is to achieve encapsulation, which manages the internal state of object. This allows you to add or change business rules in your application after the application has been implemented only change the getter or setter code, example, if you have a text field that only allows for more than 3 characters can check before assigning it to an attribute and throw an exception, other reason for not doing this is if it's possible you'll want to change the implementation or change variable names or something like. This cannot be enforced if the field is publicly accessible and modifyable
anyway you can use your IDE to generate setters and getters.
If you are developing a simple application can be recommended, if your application is complex and must give maintenance is not recommend.
for the data-type objects, like POJO / PODS / JavaBean, at python you have only public members
you can set those and get those easily, without generating boilerplate setter and getter code(in java these boilerplate code usually(98%) exposes the inner private tag as noted in the question)
and at python in the case you would need to interact with a getter, then you just define extra code only for that purpose
clean and effective at the language level
at java they chose the IDE development instead of changing base java, see JavaBean e.g. how old that is and java 1.0.2 is how old...
JDK 1.0 (January 23, 1996)
The EJB specification was originally developed in 1997 by IBM and later adopted by Sun Microsystems (EJB 1.0 and 1.1) in 1999
so just live with it, use the setter getter because those are enforced by java surroundings
That's the true what #Peter Lawrey explains about encapsulation.
Only one note: it's more important, when you are working with complex objects (for example in the domain model in a ORM project), when you have attributes that aren't simple Java types. For example:
public class Father {
private List childs = new ArrayList();
public Father() {
// ...
}
private List getChilds() {
return this.childs;
}
public void setChilds(List newChilds) {
this.childs = newChilds;
}
}
public class Child {
private String name;
// ...
private String getName() {
return this.name;
}
public void setName(String newName) {
this.name = newName;
}
}
If you expose one attribute (like the childs attribute in the Father class) as a public, you won't be able to identify what part of your code are setting or changing one property of your exposed attribute (in the case, for example, adding new Child to a Father or even changing the name of a existing Child). In the example, only a Father object can retrieve the childs content and all the rest of the classes can change it, using its setter.
This question already has answers here:
Difference between abstraction and encapsulation?
(40 answers)
Closed 7 years ago.
I have been trying to understand the concept of encapsulation and abstraction for quite sometime through many links and youtube videos but still have some confusion related to the concept of encapsulation.
According to the understanding I have related to the concept of Abstraction and Encapsulation is :
Abstraction is showing only what is necessary
Encapsulation says hide complexity
For Eg :
If we have customer application to add a customer and his related details like address by getting a database connection.
In this scenario what I understood about abstraction is showing only addCustomer() method in our class and rest of the operation that we perform when add method is called like getDBConnection() and addCustomerAddress() is hidden inside it.
**
public void addCustomerDetails(){
getDBConnection();
addCustomer();
addCustomerAddress();
}
**
So here whoever is using our class just need to call addCustomerDetails()(i.e.Abstraction) and need not be worried about how db connection is made and how those operations are performed i.e.(Hiding details or Encapsulation)
So far everything is good but somewhere I read another definition related to encapsulation as in :
Data Encapsulation is the process of combining data and functions into a single unit called class.
It can be achieved through keeping data members as private and functions public so that nobody can access it directly.
Kindly tell me what is the correct definition of Encapsulation and how?
Thanks.
Think of encapsulation this way, then it can actually connects your 1st definition of encapsulation to your 2nd definition.
Encapsulation = "combining data and functions into a single unit called class" (your 2nd definition)
Each private data member in a class cannot be accessed from outside of the class. So, it's effectively hidden. Only methods/functions that are within the class can access them. From outside the class, in order to manipulate the private data member in the class, you can only do so by calling public method/functions that are defined within the same class.
The idea of encapsulation can be initially thought as protecting your class' fields.
What I usually think about Encapsulation is that you don't provide public access to entities outside your class (that is external classes) and if you wish so, you do that using public methods (usually getters and setters).
So let's take an example:
private String field1;
This field can be only accessed from methods within this class and nothing else; neither read nor write access for external classes.
If you wish to give read access, you implement a getter for that field:
public String GetField1() { return this.field1 }
Now, here is the good practice with encapsulation, if you want now to give write access you will do the following:
public void SetField1(string value)
{
if(some_logic_here}
{
// If and only if true, then set
this.field1 = value
}
}
So your class' attributes won't get random values, but will pass through some checks, to ensure that the data are valid and appropriate for what the field represent.
So to summarise about Encapsulation:
Does expose only the necessary parts of the class.
Does hide the unnecessary parts of the class from external entities.
I want to save and load objects to a database without using a ORM (like Hibernate).
Lets say i have the following class:
public class Person {
private int age;
public void birthday(){
age++;
}
}
This class doesn't provide a get-method, so the internal state (age) is encapsulated.
If i want to save the object i need a getter method to do the following:
insert into TABLE_PERSON (id, age) vales (1, person.getAge());
The otherway round i need a setter-method to load the object:
int age = "Select age FROM Person";
person.setAge(age);
But i dont want to break the encapsulation (by implementating additional setter- and getter-methods) just to save and load objects.
Is there any possibility to do this? Maybe some kind of pattern (memento?) or best practise?
Thank you in advance!
You mentioned Memento. There's a variant called Snapshot documented by Grand. Here's the UML class diagram:
Person would be the Originator in the pattern.
You could dump the Memento instance to a binary object in the database.
Note that Memento is an inner class of Originator. The createMemento/setMemento are a kind of single get/set which might be breaking encapsulation if you're a purist. However, the packet of information (the Memento) used on the call is an interface with no methods, so encapsulation of Originator's state is guaranteed. This might even work with an ORM if you map it properly.
Of course, this seems a lot of work just to avoid a get/set. Your Person/age example is not quite realistic (not a great model of a Person). It's quite normal to expose a person's age or date of birth, and exposing that property to persist the object would be OK. Encapsulation doesn't mean don't reveal anything. It means don't expose too much detail.
For example, let's not use age but rather Person.birthday. That could be stored internally as a String in YYYY-MM-DD format or using a Date object. Such detail would not be exposed (it would be encapsulated). This is also done so that you can change it and not affect clients of your class. Anything you hide can be changed without negatively affecting clients.
By exposing a person's birthday, you say "I'm taking the risk that Person will always have a birthday." That part is exposed and thus will be hard to change without breaking clients.
Edit after comments
Public methods (e.g., save and load) in Person can take care of the save/load database operation. They will have access to private fields (age) and can get the job done. You said you're not using an ORM, so then you just do it yourself.
Allen Holub wrote a few articles on exactly that subject. He proposes a Builder and something he calls Reverse Builder pattern.
The way it would work in your case a Person would be responsible for generating a representation of itself. That is to say you define an PersonImporter and PersonExporter interfaces to move data into and out of the Person object. These classes are basically part of the Person design. So:
interface PersonImporter {
public int getAge();
public String getId();
}
interface PersonExporter {
public void setDetails(String id, int age);
}
class Person {
private int age;
private String id;
public Person(PersonImporter importer) {
age = importer.getAge();
id = importer.getId();
}
public void export(PersonExporter exporter) {
exporter.setDetails(id, age);
}
}
This doesn't eliminate getters and setters completely it is controlling it using interfaces.
Holub's Article
This is what I think, may not be perfect.
Encapsulation is done for data hiding. Perhaps, you just don't want someone to set a wrong value to the age attribute.
Maybe you can introduces a wrapper class, which is used by external code and only that class is allowed to use your Person class.
If you create a file with public wrapper class lets say PersonWrapper, that provides getter and setter for age. But these getter and setter can have your desired logic of validations such as what values can be set for age, who can etc. Within the same file, Person class may be defined as private but with plain getter and setters for age param. Your PersonWrapper should only use Person class getter and setter on some predefined conditions.
In this way you may be able to have a better encapsulation.
one way here is the use of mapper classes. Create a PersonMAP that map the class to table and and encapsulate all database operations in that class.
I really don't see how using getters/setters is breaking encapsulation. Getters and setters respect encapsulation. In fact, they're a means to achieving it.
I'm currently working on a Java trading card game, similar to the old Pokémon one. What I now want to do is to define all the cards in some way, but because there's a lot of fields that need to be initialized, I'm thinking of alternative ways, because a constructor will be very long and hardly readable for each card. I also have to initialize the attacks which means I have to basically create an anonymous inner class (is the term correct?) every time, like so:
/**
* Base set Abra 43/102
*/
public final class Abra extends Pokemon
{
public Abra()
{
super(
new ImageIcon("img/scans/base-set/43-abra.jpg"),
"Abra",
"Base Set Abra",
null,
Type.PSYCHIC,
Type.PSYCHIC,
Type.NONE,
30,
0
);
attack1 = new Attack("Psyshock", Type.NORMAL)
{
/**
* 10 damage. Flip a coin. If heads, the Defending Pokémon is now Paralyzed.
*/
public void doAttack()
{
damageApplyWeaknessAndResistance(10);
if (gui.frames.CoinFlipDialog.showCoinFlipFrame() == CoinFlip.COIN_HEADS)
{
Game.getOpponentPlayer().getActivePokemon().status = Status.Paralyzed;
}
}
};
attack2 = null;
}
}
So my second option is to make a hierarchy with interfaces and abstract classes, meaning that the values will not be stored in fields, but rather just returned by methods when needed:
public interface Card extends Cloneable, MouseListener, MouseMotionListener
{
public String getFullName();
public ImageIcon getSmallIcon();
public ImageIcon getFullIcon();
}
public interface Pokemon extends Card
{
public String getName();
public int getHPLeft();
public int getMaxHP();
public Type getType();
public Type getWeakness();
public Type getResistance();
public int getRetreatCost();
public Attack getAttack1();
public Attack getAttack2();
}
public class Abra extends AbstractPokemon
{
#Override
public Attack getAttack1()
{
return new Abra.PsyShock();
}
#Override
public Attack getAttack2()
{
return null;
}
#Override
public int getMaxHP()
{
return 30;
}
#Override
public String getName()
{
return "Base Set Abra";
} //etc...
So my question is: Is any of these methods preferred or is there even any better way?
I recommend using the Builder pattern. Click here for an explanation.
It comes recommended by Josh Bloch: it's Item 2 in his book Effective Java 2nd Edition.
I'd take the following approach:
Have a class that can act as a wrapper for any particular card. Find a way to export the data for each card into a file or database, and load the cards from the files/database when the program launches. The wrapper should be able to import all card-specific data... the wrapper will have all card-handling functions available, and some functions may not be applicable to all cards.
The alternative would be to have a card interface, and you design a custom cards using the interface, one new class for every card.
Depending on how expandable / flexible you want your engine to be, decide on an approach to take. I'd personally recommend using a wrapper class, and linking your engine to a database or flatfile.
I would recommend using parametric polymorphism, with one card behaving according to how it has been configured. Not only would you reduce the number of classes (and by extension, complexity), but you would also be able to configure cards by passing their characteristics (wrapped in a structure, say, XML) to the constructor. You could also use this parametric polymorphism concept on the "attack" classes.
Gotta love those -1s without justification. I know it's an unusual viewpoint, but I've been at this for decades and sometimes I don't think the typical way is the best way. If you really think it's wrong, why not say why? Meh.
I am not the one who neg-scored you, but my take on why I would do so is as follows.
While your idea of using a hashtable to store internal data is feasible, it is not the best approach for what the original poster intends. His application (or game) involves a lot of operations based on the attributes of the card in the play; it is not only about saving the attributes to and reading them from a database. In such a case, having typed attributes with proper meaning will make it easier to perform the game logic. Remember that OOD/OOP is about proper encapsulation and having a cohesive and meaningful structure.
I would definitely take a data driven approach. Each card is going to share a certain set of attributes. You definitely don't want to implement a new builder or java class for each of your cards, especially if there could be hundreds of them. You will want your data in some format you can read and parse to create your deck so you can add, remove, and modify cards without having to modify java code. Something human readable/editable like xml would probably work very well.
The difficulty will be when it comes to special attacks or other items that require special code to handle. In that case, you could use an embedded scripting engine like jython or even the built in javascript support in java 1.6. This way you can modify your card library easily. The biggest difficulty now would be testing your special attack scripts.
Why not just put all the info about a single entity in a hash table and wrap that in a class?
You still get encapsulation and all the nice advantages, but you can also easily write code to bind your data to a GUI or database without resorting to reflection.
You CAN still write setters and getters where they are needed to interact with other code, but in an app like you are talking about most of the fields are pure data that is never specifically manipulated (most code accessing fields is general copy and paste, not really specific to any field).
You can also use a single method like set("Name", "Abra"); or name=get("Name"); to access any field in the hash without writing dozens of setters and getters...
I came to this conclusion after writing hundreds of properties type screens where the data was simply being pulled from a DB, presented on a screen, modified, then sent back to the DB. These days my goal is that when I'm doing this I should be able to add a new control to the process without a single line of code--just metadata modification.
Bindings to the screen and database and even validations can all be set up as metadata then, and everything becomes much easier...
(Easier assuming you are as adverse to copy and paste as I am anyway...)
For the use in a Servlet based application I've written a class to store a view name and objects to be rendered. Actually it is more a data structure than a class in the sense of OOP. I wonder if I should expose the members or if should use getters.
public class Result {
private final int status;
private final String view;
private final Map<String, Object> model = new HashMap<String, Object>();
public Result(final int status, final String view) {
this.status = status;
this.view = view;
}
public Result put(final String modelName, final Object modelObject) {
model.put(modelName, modelObject);
return this;
}
}
Should I add getStatus(), getView() and getModel() or should I change the member visibility to "public"? At the moment I don't know any scenario where it would be useful to have a method to access a member. "Result" is an immutable datastructure and no computations are needed when members are accessed. Would you add getters for the unlikely event that the implementation changes?
Addendum
I read a section related to my question in Robert C. Martins excellent book Clean Code (page 99):
Hybrids
This confusion [about objects and data structures] sometimes lead to
unfortunate hybrid structures that are
half object and half data structure.
They have functions that do
significant things, and they also have
either public variables or public
accessors and mutators that, for all
intents and purposes, make the private
variable public, tempting other
external functions to use those
variables the way a procedural program
would use a data structure.
Such hybrids make it hard to add new
functions but also make it hard to add
new data structures. They are the
worst of both worlds. Avoid creating
them. They are indicative of muddled
design whose authors are unsure of -
or worse, ignorant of - whether they
need protection from functions or
types.
For a data-holder class creating getters or not is a matter of taste. Based on your description you can make the visibility public or package on status and view, but I would add a getter for retrieving a model by name. Although the map is final, its contents is not.
Edit
I meant something like:
public Object get(final String modelName) {
return model.get(modelName);
}
There is no reason to make the model map visible. (I would name the map "models" and use setModel(name, model) and getModel(name) as accessors.)
I can't make concrete recommendations as it would depend on how you're going to be using that class. However...
I often create "lightweight" objects intended as data structures to transport some immutable data. Like you, I make the members public final and initialize them in the constructor.
The risks associated with accessible, mutable data members aren't there when they're final; all you're losing is the ability to meaningfully subclass the class. Also, you can't attach functionality to data access. But for a lightweight data transfer object, chances are you won't be doing that anyway.
You say:
At the moment I don't know any
scenario where it would be useful to
have a method to access a member.
That's precisely why I'd advocate accessing the data via getters. At the moment you're using the object to store corresponding objects in your model. However your model may well change in the future, and yet you may want to display the data in the view in the same fashion.
Given that, and the headache in testing the view component of an MVC, I would always implement the getter/setter mechanism.