I want to ask you about model and ModelWrapper behavior. According to Wikipedia article about model component of MVVM:
Model refers either to a domain model, which represents real state
content (an object-oriented approach), or to the data access layer,
which represents content (a data-centric approach).
I was looking for ModelWrapper usage samples in mvvmFX documentation and examples, but I found only data access layer model sample. I need to use model classes with business logic. For example, changing class state in setter method (is the side effect usage a code smell here?):
public class ModelClass {
private int intField;
private String stringField;
public int getIntField() {
return intField;
}
public void setIntField(int intField) {
if (intField == 100) {
this.stringField = "";
}
this.intField = intField;
}
public String getStringField() {
return familyName;
}
public void setStringField(String stringField) {
this.stringField = stringField;
}
}
According to ModelWrapper documentation:
The user changes the values of the viewModel properties (via the UI). The state of the underlying model instance may not be changed at this point in time! When the user clicks an Apply button (and validation is successful) copy all values from the ViewModel fields into the model instance.
How to use such model classes, and not to implement the business logic twice (in the model class at the first time and in the ViewModel class at the second time)? Or maybe I have to move business-logic in other place?
The ModelWrapper is mainly intended for Java Bean classes without much logic. It's a helper to prevent users from having to write code to copy values from a model object to the ViewModel and back.
In you example when you invoke the commit method of the ModelWrapper it will copy all values from the viewModel properties to the model instance by invoking all registered setter methods. This is done in the order in which the property fields are registered. If you have registered the intField-Property first, the ModelWrapper will first invoke the setIntField method (which changes intField and stringField in the model instance) and then invoke the setStringField method which overwrites the stringField.
However, having to modify the order of field registration doesn't sound like a good idea and will most likely not scale for more complex model classes.
So in the end I think the ModelWrapper is not a good tool for your use-case. In many cases there is no general answer on how to connect the model classes with the viewModel. It highly depends on the intended behavior and the use-cases.
Regarding the question on the side-effect in the setter and if this is a code-smell: In my oppinion it's perfectly fine to modify the state of multiple internal fields with a single method. This is what OOP and information-hiding is all about. However, in Java there is the convention of getter and setter methods. If you name a method setIntField most Java developers will assume that this method only modifies intField and nothing more. So I would recommend to find a better name for such a method and keep getters and setters simple and straight forward.
Related
As much as I have studied about encapsulation it is about hiding data to prevent from manipulation. For that we declare the private variables so that couldn't be accessible from out of class. But we can implement or access them out of class using setter getter method. So if we have to implement it using setter getter method than any other person can implement it using setter getter method. . So how we are safe from manipulation??
Encapsulation isn't a security measure in that it prevents people from messing with your code. It's a security measure in the sense that people can't go directly in and change variables without going through your proper channels. Consider the following psuedocode.
class ProgressBar {
public int maximum;
public int current;
}
vs
class ProgressBar {
private int maximum;
private int current;
...
public set_current(int amount) {
if (amount <= this.maximum) this.current = amount;
}
}
In the top example, users could go in and mess with current and break the
progress bar. In the bottom example, your setter protects from that.
You need to look at this way,
your code <------ client code
Client code will be trying to access your code. With Encapsulation, your data will be safe from manipulation that can be done by the client code. It will help in specifying the accessibility limit.
To give an Example,
You are building a game and you wouldn't want someone to increase the health of your character (manipulate the fixed data)
public class GameCharacter {
public int Health{ get; }
public GameCharacter ()
{
Health = 100;
}
}
No one can change the Health!
The purpose of Encapsulation is two-fold:
Bundling related functionality together;
Controlling the access to fields and methods which participate in providing the functionality.
The goal of getters and setters is to ensure that actors outside the code (or class) have only one point of interaction with your fields, thus maintaining the invariants. This helps in:
Preventing modification of values in an illegal/unacceptable manner that can break the functionality.
Ex: Two external actors trying to modify your account balance at the same time;
Localizing an aspect of code that may change in future.
Ex: Easily allowing you to change the type of a status variable from boolean to enum in future because it is always accessed from getter in the class;
Implement business rules, if any, that are need to be exercised when changes are made to your fields.
Ex: Not allowing the Engine class to modify and set the speed of your Car class to a negative value, just because the car is going in reverse.
I have a number of different organisations, each of which is an instance of the Organisation class. This contains getters and setters for instance variables, the setters contain validation where appropriate. It also has a few other odds and ends - overwritten toString(), equals() and hashCode() for example.
I have OrganisationView extends JFrame which accepts an Organisation and displays it in the GUI, and includes listeners for the various functions.
I understand from this question how this should all fit together and work with OrganisationController. What I'm not clear on is how many, if any, instances of OrganisationController I need. Is it one per organisation, and storing the organisation it refers to as an instance variable? Because it seems easier just to declare OrganisationController as static and call its methods directly from OrganisationView giving OrganisationView a method something like:
private boolean deleteButtonPressed(){
return OrganisationController.deleteOrganisation(this.organisationDisplayed)
}
(and perhaps some other business logic, but that's by the by)
OrganisationView, by the way, is called each time that particular display is needed, and is passed the organisation to show.
My question is: If it is better to have a separate instance of OrganisationController for each Organisation then why? It seems like an unnecessary amount of objects differing only in one instance variable. Or are static controllers acceptable?
I would not make it static. Use a singular controller and separate your views into directories. Then you can organized each part accordingly. You don't want to statically call the controller from the view. You want each person who logs in to have their own instance. Its simply a matter of separating out your views, models etc into separate folders and directories. I'm actually working on a project right now where I do this. I prepend each section with a keyword so as to keep it separate.
You can use the Singleton pattern to make sure that you only create one Controller && also access your controller in a static way.
I suggest you go for the enum implementation of Singleton which would be something like this
public enum OrganisationController{
INSTANCE;
// you can have fields
private final example;
// and also methods
public boolean deleteOrganisation(Organization org){
// do whatever here
}
}
And you can invoke methods in a static-looking way
OrganisationController.INSTANCE.deleteOrganization(org);
I am creating an application and at the front I check if the user is an admin, user, moderator or superadmin. Based on this I create a different XML.
So what I currently do is to pass a string in the method argument that converts the object to XML to specify which mapping it should use. However passing those strings around isn't good. Are there any patterns to do this better?
I could bring the role check to the mapping class, and then change the mapping id to the same as the role of the current user. But I don't think security checks fits those classes.
Would you just create an enum to keep the roles and pass that instead of a string?
Or create different classes and use a factory to return the right object?
A Common Interface Approach
By implementing a common interface between all return objects, you can develop some loose coupling in your code. For example:
public interface XmlReturn
{
public void displayXML(); // Just an example method.
}
And a class that implements this interface:
public class AdminXmlReturn implements XmlReturn
{
public void displayXML() { // Some code here for the admin XML }
}
With this, you can generate some sort of factory that takes a discriminator:
public abstract class XmlFactory
{
public static XmlReturn getInstance(String type)
{
// Using string as an example type. Doesn't need to be.
if(type.equals("Admin")) {
return new AdminXmlReturn();
}
}
}
and by referring to the object by it's interface type, you can generate as many different XML files you want, without having to change any code. IE:
public void loadPage(String permission)
{
// permission can be any type. This is just an example.
XmlReturn xml = XmlFactory.getInstance(permission);
xml.displayXML();
// This method exists in all objects that implement XmlReturn
}
Advantages
This approach has the main advantage that you can add as many new XML files and permissions as you want, and you won't need to change the code that loads the XML. This "separation of concerns" will help you to make your program very manageable and extendable.
By porting your decision logic to a factory, you help make your code more readable, and allows other people to abstract away from the details of the inner workings of your program, if you intend on sharing your code.
You question is not very clear. Anyway, I try to give some option:
if you want to serialize to XML different kind of users, then I would suggest to model the different kind of users as a hierarchy of classes, and have a specialized toXML() serialization method in each class. By the way, JAXB can help you a lot, if this is what you want to do.
if you have a class XMLBuilder that writes some XML, and the way the XML is built depends on the kind of user, then I would suggest to model your different kind of users with a hierarchy of classes, and then use method overloading in XMLBuilder, i.e. have several build() methods each one taking as input a different subclass of your user-kind hierarchy.
I hope this helps.
In my project I have a small data structure Key.
public class Key implements Serializable {
private static final long serialVersionUID = 1L;
public String db;
public String ref;
public Object id;
protected Key() {
}
public Key(String db, String ref, Object id) {
this.db = db;
this.ref = ref;
this.id = id;
}
}
Yes this class is simple and every field is publicly accessible.
But someone has suggested I use POJO style classes instead but when I asked why they were unable to tell me.
In my opinion , calling getters and setters is slower than direct access to a field.
So why I must use POJO programming style?
Taken from Wikipedia:
POJO is an acronym for Plain Old Java Object. The name is used to
emphasize that a given object is an ordinary Java Object, not a
special object.
A POJO is usually simple so won't depend on other libraries, interfaces or annotations. This increases the chance that this can be reused in multiple project types (web, desktop, console etc).
As someone has already pointed out in the comments, your object is technically a POJO already however you have specifically asked about getters and setters which are more akin to JavaBeans.
There are a number of reasons I can think of for using getters and setters:
You might only want to get some of the values (I.E. read only values). With fields, clients can both get and set the values directly. Fields can be made read-only if they are marked as final although this doesn't always guarantee that they are immutable (see point 9).
Getter & setter methods allow you to change the underlying data type without breaking the public interface of your class which makes it (and your application) more robust and resilient to changes.
You might want to call some other code such as raising a notification when the value is obtained or changed. This is not possible with your current class.
You are exposing the implementation of your class which could be a security risk in some cases.
Java beans are designed around POJO's which means that if your class is not implemented as one it can't be used by certain tools and libraries that expect your class to adhere to these well established principles.
You can expose values that are not backed by a field I.E. calculated values such as getFullName() which is a concatenation of getFirstName() and getLastName() which are backed by fields.
You can add validation to your setter methods to ensure that the values being passed are correct. This ensures that your class is always in a valid state.
You can set a breakpoint in your getters and setters so that you can debug your code when the values are obtained or changed.
If the field is an object (I.E. not a primitive type) then the internal state of your class can be modified by other objects which can lead to bugs or security risks. You can protect against this scenario in your POJO's getter by returning a copy of the object so that clients can work with the data without affecting the state of your object. Note that having a final field does not always protect you against this sort of attack as clients can still make changes to the object being referenced (providing that object is itself mutable) you just cannot point the field at a different reference once it has been set.
Yes, accessing or setting the values via method calls may be slower than direct field access but the difference is barely noticeable and it certainly won't be the bottleneck in your program.
Whilst the advantages are clear this does not mean that getters and setters are a silver bullet. There are a number of 'gotchas' to consider when designing real world, robust scalable classes.
This answer to a very similar question looks at some considerations in detail when designing a class that has getters and setters. Although the suggestions may be more relevant depending on the type of class you are designing E.G. a class that forms part of an API in a large system as opposed to a simple data transfer object.
Also note that there may be certain scenarios where a class with direct field may be advantageous such as when speed is essential or memory is limited although this should only be considered after profiling your code and finding that it is actually a bottleneck.
Also be careful that you are not just wrapping all of your fields in getters and setters as this is really missing the point of encapsulation.
This answer provides a good summary of the reasons for choosing a POJO over a JavaBean style object with getters and setters.
Use private class variables and public getters and setters which will provide you Encapsulation.
Getters and setters, especially the simplest forms will just be inlined by the JIT compiler and thus remove the method call overhead. This sounds very much like premature optimisation. If you ever get a bottleneck, then profile and look where it occurs. I am fairly certain it'll be not in property accesses.
Get yourself the book Effective Java.
Item 14, in public classes use accessor methods not public fields.
In this Joshua Bloch says there is nothing inheriently wrong with public fields in package-private or nested classes but strongly advises against use public classes.
He goes into much more detail on the subject, it's a great book, suggest you get a copy.
Imagine if some other programmer is using your code. If you don't provide setter and getter methods then he can directly call your variable and it surely will affect to your code. And it may lead to security issues
So by providing POJO class you are forcing him to call on your methods rather than directly calling your Instance variables.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why use getters and setters?
I have read books on Java, saying that it is good to create setters and getters for variables such as x and y. For example:
public int getX(){
return x;
}
public void setX(int x){
this.x = x;
}
But what is the difference from that and
...(shape.x)... // Basically getX()
and
shape.x = 90; // Basically setX()
If setters and getters are better, what practical problems would arise?
Multiple reasons:
If you allow field access like
shape.x = 90
then you cannot add any logic in future to validate the data.
say if x cannot be less than 100 you cannot do it, however if you had setters like
public void setShapeValue(int shapeValue){
if(shapeValue < 100){
//do something here like throw exception.
}
}
You cannot add something like copy on write logic (see CopyOnWriteArrayList)
Another reason is for accessing fields outside your class you will have to mark them public, protected or default, and thus you loose control. When data is very much internal to the class breaking Encapsulation and in general OOPS methodology.
Though for constants like
public final String SOMETHING = "SOMETHING";
you will allow field access as they cannot be changed, for instance variable you will place them with getters, setters.
Another scenario is when you want your Class to be immutable, if you allow field access then you are breaking the immutability of your class since values can be changed. But if you carefully design your class with getters and no setters you keep the immutability intact.
Though in such cases you have to be careful in getter method to ensure you don't give out reference of objects(in case your class have object as instances).
We can use the private variables in any package using getters and setters.
Using getter and setter functions allow for constraints and encapsulation. Lets say x is the radius. shape.x = -10 would not make much sense. Also, if someone tries to set an illegal value, you can print an error, set a default value, or do nothing.
It is good practice to make member variables private so they cannot be modified directly by programs using them.
Mutator functions
Encapsulation
A lot of people have mentioned encapsulating the specifics of the implementation, which to me is the biggest reason to use getters and setters in a class. With this, you also get a lot of other benefits, including the ability to throw out and replace the implementation on a whim without needing to touch every piece of code that uses your class. In a small project, that's not a big benefit, but if your code ends up as a well-used (internal or public) library, it can be a huge benefit.
One specific example: complex numbers in mathematics. Some languages have them as a language or framework feature, others don't. I will use a mutable class as an example here, but it could just as easily be immutable.
A complex number can be written on the form a + bi with real and imaginary parts, lending itself well to [gs]etRealPart and [gs]etImaginaryPart.
However, in some cases it's easier to reason about complex numbers on polar form re^(iθ), giving [gs]etRadius (r) and [gs]etAngle (θ).
You can also expose methods like [gs]etComplexNumber(realPart, imaginaryPart) and [gs]etComplexNumber(radius, angle). Depending on the argument types these may or may not need different names, but then the class' consumer can use either as fits its needs.
The two forms are interchangeable; you can fairly easily convert from one to the other, so which form the class uses for internal storage is irrelevant to consumers of that class. However, consumers may use either form. If you choose the form a+bi for internal representation, and expose that using fields rather than getters and setters, not only do you force the class consumers to use that form, you also cannot later easily change your mind and replace the internal representation with re^(iθ) because that turns out to be easier to implement in your particular scenario. You're stuck with the public API you have defined, which mandates that specifically the real and imaginary parts are exposed using specific field names.
One of the best reasons I can think of for getters and setters is the permanence of a class's API. In languages like python you can access members by their name and switch them to methods later. Because functions behave differently than members in java once you access a property thats it. Restricting its scope later breaks the client.
By providing getters and setters a programmer has the flexibility to modify members and behavior freely as long as the adhere to the contract described by the public API.
Another good reason to user getter and setter can be understand by the following example
public class TestGetterSetter{
private String name ;
public void setName(String name){
this.name = name ;
}
public String getName(){
return this.name ;
}
}
The point of getters and setters is that only they are meant to be used to access the private variable, which they are getting or setting. This way you provide encapsulation and it will be much easier to refactor or modify your code later.
Imagine you use name instead of its getter. Then if you want to add something like a default (say the default name is 'Guest' if it wasn't set before), then you'll have to modify both the getter and the sayName function.
public class TestGetterSetter{
private String name ;
public void setName(String name){
this.name = name ;
}
public String getName(){
if (this.name == null ){
setName("Guest");
}
return this.name ;
}
}
There is no requirement for getters and setter to start with get and set - they are just normal member functions. However it's a convention to do that. (especially if you use Java Beans)
Let's say, hypothetically, you find a library that does a better job of what you have been doing in your own class (YourClass). The natural thing to do at this point is to make YourClass a wrapper interface to that library. It still has a concept of "X" which your client code needs to get or set. Naturally, at this point you pretty much have to write the accessor functions.
If you neglected to use accessor functions and let your client code access YourClass.x directly, you would now have to rewrite all of your client code that ever touched YourClass.x. But if you were using YourClass.getX() and YourClass.setX() from the beginning, you will only need to rewrite YourClass.
One of the key concepts of programming, and especially object oriented programming, is hiding implementation details so that they're not used directly by code in other classes or modules. This way, if you ever change the implementation details (as in the example above), the client code doesn't know the difference and doesn't have to be modified. For all your client code knows, "x" might be a variable, or it might be a value that is calculated on the fly.
This is an oversimplification and doesn't cover all the scenarios where hiding implementation is beneficial, but it is the most obvious example. The concept of hiding implementation details is pretty strongly tied to OOP now, but you can find discussions of it going back decades before OOP was dreamed up. It goes back to one of the core concepts of software development, which is to take a big nebulous problem, and divide it into small well-defined problems which can be solved easily. Accessor functions help keep your small sub-tasks separate and well-defined: The less your classes know about each other's internals, the better.
There are lots of reasons. Here are just a few.
Accessors, getters in particular, often appear in interfaces. You can't stipulate a member variable in an interface.
Once you expose this member variable, you can't change your mind about how it's implemented. For example, if you see a need later to switch to a pattern like aggregation, where you want the "x" property to actually come from some nested object, you end up having to copy that value and try to keep it in sync. Not good.
Most of the time you are much better off not exposing the setter. You can't do that with public fields like x.
Before get into the answer, we gotta know something prior...! "JavaBeans".
JavaBeans are java classes that have properties. For our purpose, think of properties as private instance variables. since they're private, the only way they can be accessed
from outside of their class is through 'methods'in the class.
The methods that change a propertiy's value are called setter methods, and the methods that retrieve a property's value are called getter methods.
I would say that neither the getters/setters nor the public members are good Object Oriented design. They both break OOP Encapsulation by exposing an objects data to the world that probably shouldn't be accessing the properties of the object in the first place.
This is done by applying the encapsulation principle of OOP.
A language mechanism for restricting access to some of the object's components.
This means, you must define the visibility for the attributes and methods of your classes. There are 3 common visibilities:
Private: Only the class can see and use the attributes/methods.
Protected: Only the class and its children can see and use the attributes/methods.
Public: Every class can see and use the attributes/methods.
When you declare private/protected attributes, you are encouraged to create methods to obtain the value (get) and change the value (set). One example about visibility is the [ArrayList][2] class: it has a size property to know the actual size of the inner array. Only the class must change its value, so the code is something like
public class ArrayList<E> {
private int size;
private Object[] array;
public getSize() {
return this.size;
}
public void add(E element) {
//logic to add the element in the array...
this.size++;
}
}
In this example, you can see that the size value can change only inside the class methods, and you can get the actual size by calling it in your code (not mutating it):
public void someMethod() {
List<String> ls = new ArrayList<String>();
//adding values
ls.add("Hello");
ls.add("World");
for(int i = 0; i < ls.size(); i++) {
System.out.println(ls.get(i));
}
}
Getters and setters encapsulate the fields of a class by making them accessible only through its public methods and keep the values themselves private. That is considered a good OO principle.
Granted, it often seems like redundant code if it does nothing more than setting or returning a value. However, setters also allow you to do input validation or cleanup. Having that in one place improves data integrity for your objects,
Because we are using Object oriented programming language.
Here we are using Data hiding and encapsulation.
The variable should not directly accessible from out side world (for achiving data hiding) so we will create it private so
shape.x
is not correct.
Getter and setter method are used to get and set the value of x which is the way to achive encapsulation.