What if my class has only private fields which injected by the container? Is it good or bad? In that case, I have to use DI framework in testing (and maybe that's not bad) but on the other hand, no setters, no unnecessary code. Is that bad practice or not?
Setter methods are way of achieving abstraction which is one the most important principle of OOP. Ideally the code should not be dependent on container. I think setter methods will provide standard way of using DI and in addition good code readability. I always consider setter DI a good practice unless my class instantiation is dependent on some other dependency (for which i will use constructor based DI).
I think you should not depend on container for performing DI.
Hope this helps.
strong text**First, what are the alternatives to DI via setter methods? Martin Fowler distinguishes three ways: **interface, setter and constructor injection. So none of these ways is good or bad by definition, it's how you use them and what suits your system best. If you want your fields immutable during after object creation, use constructor injection with private fields.
Nonetheless Setter injection is the most common way of DI and several frameworks rely on it. If you're unsure go with this way. You'll also find lots of information about it.
If your question targets the use of setters at all, the question is if your class is a data structure (see Martin's Clean Code ch. 6 for detailed information). In other words, if your class has no other purpose than holding some data and you can make your fields public(*). If it holds business logic, use private fields and getters/setters.
(*) personally I disagree with that, but that's only me. :-)
Related
Java Beans, as far as I know, should always:
Have only an empty constructor
Have only fields, and getter/setter methods for these fields.
However, I am wondering what the convention is for Java beans to implement interfaces like Comparable? I could leave the java bean pure, meaning absolutely no behaviour, only data, and write a custom comparator-class. Implementing comparable is easier though.
Are there any conventions when it comes to implementing simple common interfaces like Comparable to Java Beans? I cannot find any consequences myself, but it feels like I might breaking some rules, and that there might be something I haven't thought of.
IMHO this question is mostly not about conventions but about the needs.
You are right that separation of bean stuff from any business logic is a good style. I'd add here that this typically a good practice because relationship between your beans and comparators are many-to-many, i.e.
You will probably hold several comparators for one bean class and use them in different contexts
Sometimes you can re-use one comparator for several different classes or make hierarchy of comparators.
However you are right that writing comparison logic into class itself is less verbose and in some cases preferable. The choice completely depends on the author taste and requirements of the application he/she is working on.
I've just discovered that reading and writing any private field of any object could be done without any accessor, but using reflection.
So, my question is: in the case of an application which uses no third technology (e.g. EL) but JAVA, if I need a POJO that contains let say 20 fields, is it more interesting to implement 40 accessors, or to use reflection to access them? I guess some pros and cons, but any experience or feedback would be great :)
You can, but it wouldn't be very maintainable, so: don't do it. The advantages of using getter/setter to access members is, that you are able to hide the accessor, initialize lazy and you will be able to refactor easily (e.g. with IDEA or Eclipse).
You can access object fields and methods using reflection, but you should not.
This article lists at least 2 measurable reasons why not:
Performance. Accessing object methods/fields using reflection is slower than accessing via accessors.
Security restrictions
And the greatest drawback is non-maintainability, quoting from the article below:
A more serious drawback for many applications is that using reflection
can obscure what's actually going on inside your code. Programmers
expect to see the logic of a program in the source code, and
techniques such as reflection that bypass the source code can create
maintenance problems.
It's generally better to access your fields through getters, even if you're using reflection to figure out what fields are available. You can just as easily figure out what getters are available via reflection and call those getter methods. This allows you to:
1) Dynamically figure out what data is available.
2) Explicitly state which fields should be made available and which fields should be private.
3) Explicitly override a getter's behavior to suit your needs.
In most normal cases, reflection is used for figuring out what data is available on an object. You should not use reflection as a general replacement for getters and setters. Otherwise, your code will become truly unmaintainable.
Reflection is only good for specific use cases where one needs to do magic on objects without being able to assume a lot about their structure. Specifically, if your JVM uses a SecurityManager, it might very well prevent code to set privates through reflection.
You could look at this other question for more information about the security manager.
I've always known Singletons to be "bad", but only now that I've made the move to Java from C++ have I decided to find a way around them. From a bit of reading, I've found that either Factories or Dependency Injection could possibly do the job, but I'd like some confirmation on this.
As an example, I was about to write a AnimationCache singleton that would store a Map<String, Animation>. Different classes should be able to have access to this class (basically) anywhere so that they can easily and efficiently load Animations. A very brief example of what the equivalent code would look like using DI would be great.
Also, is Guice a good framework for DI with non-web apps? I have used Spring for web development, but I'm not so sure that'd work for games.
Spring and Guice will do fine. I personnally prefer Guice for pure dependency injection, but Spring offers much more.
The code would just look like this:
public class AnimationCacheClient {
private AnimationCache cache;
#Autowired // for Spring, or
#Inject // for Guice (but I think Spring also supports it now)
public AnimationCacheClient(AnimationCache cache) {
this.cache = cache;
}
// ...
}
I personnally prefer constructor injection, but you might also use setter injection or field injection.
Note that the purpose of DI is not to have "easy singletons", though. Its main purpose is to make the code (of AnimationCacheClient, here) easily unit-estable, by being able to inject mock dependencies (here, a mock AnimationCache instance).
Using Spring, DI is very simple. Using the #Autowired annotation, you don't even need additional xml to wire things up or a setter method. A member in the class that needs access to the one that has been your singleton before will do.
Here is a good example: http://www.developer.com/java/other/article.php/3756831/Java-Tip-Simplify-Spring-Apps-with-Autowired.htm
I recently 'withnessed' this thread on Singleton and how bad it might be (or not) and what you can do to bypass it. Well worth the read.
I'm developing plugins in Eclipse which mandates the use of singleton pattern for the Plugin class in order to access the runtime plugin. The class holds references to objects such as Configuration and Resources.
In Eclipse 3.0 plug-in runtime objects
are not globally managed and so are
not generically accessible. Rather,
each plug-in is free to declare API
which exposes the plug-in runtime
object (e.g., MyPlugin.getInstance()
In order for the other components of my system to access these objects, I have to do the following:
MyPlugin.getInstance().getConfig().getValue(MyPlugin.CONFIGKEY_SOMEPARAMETER);
, which is overly verbose IMO.
Since MyPlugin provides global access, wouldn't it be easier for me to just provide global access to the objects it manages as well?
MyConfig.getValue(MyPlugin.CONFIGKEY_SOMEPARAMETER);
Any thoughts?
(I'm actually asking because I was reading about the whole "Global variable access and singletons are evil" debates)
Any thoughts?
Yes, for the current use-case you are examining, you could marginally simplify your example code by using statics.
But think of the potential disadvantages of using statics:
What if in a future version of Eclipse Plugin objects are globally managed?
What if you want to reuse your configuration classes in a related Plugin?
What if you want to use a mock version of your configuration class for unit testing?
Also, you can make the code less verbose by refactoring; e.g.
... = MyPlugin.getInstance().getConfig().getValue(MyPlugin.CONFIGKEY_P1);
... = MyPlugin.getInstance().getConfig().getValue(MyPlugin.CONFIGKEY_P2);
becomes
MyConfig config = MyPlugin.getInstance().getConfig();
... = config.getValue(MyPlugin.CONFIGKEY_P1);
... = config.getValue(MyPlugin.CONFIGKEY_P2);
You suggest that
MyPlugin.getInstance().getConfig().getValue(MyPlugin.CONFIGKEY_SOMEPARAMETER);
is too verbose and
MyConfig.getValue(MyPlugin.CONFIGKEY_SOMEPARAMETER);
might be better. By that logic, wouldn't:
getMyConfigValue(MyPlugin.CONFIGKEY_SOMEPARAMETER):
be better yet (Maybe not shorter, but simpler)? I'm suggesting you write a local helper method.
This gives you the advantage of readability without bypassing concepts that were crafted by people who have been through the effort of fixing code that was done the easy/short/simple way.
Generally globals are pretty nasty in any situation. Singletons are also an iffy concept, but they beat the hell out of public statics in a class.
Consider how you will mock out such a class. Mocking out public statics is amazingly annoying. Mocking out singletons is hard (You have to override your getter in every method that uses it). Dependency Injection is the next level, but it can be a touch call between DI and a few simple singletons.
This question already has answers here:
Why use getters and setters/accessors?
(37 answers)
Closed 7 years ago.
I have seen member variables given a private modifier and then using getter/setter methods just to set and get the values of the variable (in the name of standardization).
Why not then make the variable public itself (Other than cases like spring framework which depends on getter/setters for IOC etc). It serves the purpose.
In C# I have seen getter/setter with Capitalization of the member variable. Why not make the variable public itself?
In order to get a stable API from the first shot. The Java gurus thought that if later on, you might want to have some extra logic when setting/getting an instance member, you don't want to break existing API by replacing public fields with public methods. This is the main reason in Java.
In the case of C#, public properties are used instead of public fields because of binary interface compatibility. Someone asked a similar question right here, on SO.
So, it's all about encapsulating some logic while still preserving interface for... future proofing.
Even back in 2003 it was known that getter and setter methods are evil.
Because interfaces only allow for specifying methods, not variables. Interfaces are the building stones of API's.
Hence, to access a field through an interface, you need to have the getter and setter.
This is done so you can change the getter or setter implementation in your public API after you release it. Using public fields, you wouldn't be able to check values for validity.
Encapsulation
You also mentioned C# properties. These are really just getters/setters under the hood, but with a more concise syntax.
It's part of encapsulation: abstracting a class's interface (the "getters" and "setters") from its implementation (using an instance variable). While you might decide to implement the behaviour through direct access to an instance variable today, you might want to do it differently tomorrow. Say you need to retrieve the value over the network instead of storing it locally—if you have encapsulated the behaviour, that's a trivial change. If other objects are relying on direct access to an instance variable, though, you're stuck.
The most and foremost use for getters and setters in Java is to annoy the developers. The second most important use is to clutter the code with useless noise. Additionally, it forces you to use a different name for the same thing, depending on where you are (inside or outside the class). Not to forget the added ambiguity (do you call the getter inside the class or do you use the field directly?) Next, they are used to allow access to private data but that's just a minor side effect ;)
In other programming languages, the compiler will generate them for you (unless, of course, you provide your own implementations). In Delphi, for example, you have read and write modifiers for fields (just like private, static or final in Java). The define if you'll have a getter or setter generated for you.
Unlike the Delphi guys, the Java guys wanted everything to be explicit. "If it's not in the source, it's not there". So the only solution was to force people to write all the getters and setters manually. Even worse, people have to use a different name for the same thing.
Getters and setters may very well be the greatest lie ever told. They are considered a sign of good design, while the opposite is true. New programmers should be taught proper encapsulation, not to write dumb data carrier classes that contain nothing but getters and setters.
(The idea that you need getters and setters to future-proof your code if you want to change the implementation later on is an obvious case of YAGNI. But that is really beside the point.)
The most common reason is a poor understanding of encapsulation. When the developer believes that encapsulating stuff really just means getters & setters rather than encapsulating behavour.
The valid reasons for having getters/setters are:
1) You are making a generic¹ object such as JComponent. By using a getter/setter rather than direct access to the variable means that you can do some pre-processing on said variable first (such as validate it is with a set range) or change the underlying implementation (switching from an int to a BigInteger without changing the public API).
2) Your DI framework does not support ctor injection. By having just a setter you can ensure that the variable is only set once.
3) (Ties in with #1) To allow tools to interact with your object. By using such a simple convention then GUI tools can easily get all the settings for a given component. An example of this would be the UI builder in NetBeans.
¹ Of the not-Generic type. Bad word to use I know, please suggest an alternative.
Having a setter allows you
perform validation
to fire a property changed event if the new value is different from the previous value
In the case in question there is no need for getter and setter if the value is simply read or written.
Well,
OOP. ;)
Or to be a little more precise:
Getters and Setters are used to provide a defined interface to a classes
properties. Check the OOP link, it describes the concepts more in detail...
K
You'd need encapsulate those attributes if there are constraints for example or to make general validity checks or post events on changes or whatever. The basic use is hiding the attribute from the "outer world".
Some Java frameworks require them (JavaBeans I think).
-- Edit
Some posters are trying to say this is about encapsulation. It isn't.
Encapsulation is about hiding the implementation details of your object, and exposing only relevant functions.
Providing a get/set that does nothing but set a value does not accomplish this at all, and the only reason for them is:
Perform some additional validation before set/get
Get the variable from somewhere else
Integrate with frameworks (EJB)
There are several reasons:
Some Java APIs rely on them (e.g. Servlet API);
making non-final variable public is considered to be a bad style;
further code support: if sometime in future you`ll need to perform some actions before each access/mutation (get/set) of the variable, you will have less problems with it.
In C# constructions like
public int Age
{
get
{
return (int)(today() - m_BirthDate);
}
}
are are just syntactic sugar.
property idea is core in OOP (Object oriented programming). But problem is that Java introduce them not in core of language (syntax / JVM), but (probably few years later??? historics of Java say better) as convention: pair of consistent getters/setter is property in bean, concept of property is in libraries, not in core.
This generate problem in few libraries, framework. Is single getter a read only property or not? That is the question. I.e.in JPA entities if You want implement classic method (algorithm) beggining with "get" like getCurrentTine() is the best mark by #Transient to disable interpretation like property having value.
In other words, I like very much property concept in C# designed 10 years later and better. BTW C# property has getter/setter too, but sometimes/partially hidden, visible at low level debugging. Free from question "why getter" etc ...
In Java world is interesting to read about Groovy concept of property (hidden getter/setter in different way than C#) http://www.groovy-lang.org/objectorientation.html#_fields_and_properties
EDIT: from real life, every java object has getClass() method, tools from java.beans.BeanInfo package report this as property "class", but this not true. It isn't property (readonly property) in full sense. I imagine properties like C# (with his internal hidden name get_Something1) hasn't conflict with "functional" GetSomething2()