PMD rule Accessor Method Generation - pmd

Can anyone explain bit in detail about this rule. Rule:AccessorMethodGeneration Priority:3 Avoid autogenerated methods to access private fields and methods of inner / outer classes with concrete examples for both fields and methods?

The PMD documentation provides a summary of the AccessorMethodGeneration rule, with my emphasis added:
When accessing a private field / method from another class, the Java
compiler will generate a accessor methods with package-private
visibility. This adds overhead, and to the dex method count on
Android. This situation can be avoided by changing the visibility of
the field / method from private to package-private.
So PMD is advising you that if you make such members and methods package-private instead of private you will avoid the overhead of having to access them through compiler generated accessor methods. (I'm not an Android developer so I can't comment on the "dex method count" issue.)
This is the code example PMD provides with respect to private members:
public class OuterClass {
private int counter;
/* package */ int id;
public class InnerClass {
InnerClass() {
OuterClass.this.counter++; // wrong accessor method will be generated
}
public int getOuterClassId() {
return OuterClass.this.id; // id is package-private, no accessor method needed
}
}
}
And here is an SO example where the compiler will auto-generate code to access private methods. Note the poster's comment (with my emphasis added):
The compiler takes the inner classes and turns them into top-level
classes. Since private methods are only available to the inner class
the compiler has to add new "synthetic" methods that have package
level access so that the top-level classes have access to it.
In summary, PMD is flagging code where you can make performance improvements (which I would think would usually be very minor) in some scenarios by modifying the access on private members and private methods.
One other point worth noting is that there are some PMD bug reports on AccessorMethodGeneration not working properly (e.g. https://github.com/pmd/pmd/issues/274 and https://github.com/pmd/pmd/issues/342). So if you can't understand why PMD is flagging your code with a AccessorMethodGeneration warning, check the bug reports.

Related

Private methods in amongst Public methods

Suffering insomnia at 5am & so reading Clean Code (by Robert Martin). This book is often seen as a Bible for coding structure and so I was interested to see he suggests the 'Newspaper' analogy when it comes to ordering methods/functions within classes. The book suggests you order functions by first public method, then related private methods, then second public method, then related private methods (and so on). So a class structure might look like this:
public func openAccount() {
completeNameDetails()
completeAddressDetails()
}
private func completeNameDetails() {
...
}
private func completeAddressDetails() {
...
}
public func closeAccount() {
deleteNameDetails()
deleteAddressDetails()
}
private func deleteNameDetails() {
...
}
private func deleteAddressDetails() {
...
}
From hunting stackoverflow this morning, it seems there is strong support for this method:
Best practice: ordering of public/protected/private within the class definition?
The issue I have with this suggestion, however, is the public methods of the class are scattered throughout the class. Would it not be better to have all the public methods at the top of the class and then the privates below it. Certainly this view also has a strong support from this community:
Order of items in classes: Fields, Properties, Constructors, Methods
So in summary, should public methods all be grouped together above private methods or should public methods be followed by their respective private methods (meaning public and private methods are mixed)?
I too have read Clean Code and the value in reading the book is indeed immense. There are however edge cases with which I do not agree. The step down function method as described by Mr Martin is one of them.
Ideally, a class should only have 1 to 3 public methods, otherwise it is very likely doing too much. I prefer my public methods to be grouped together. When you do have very small classes, what Mr Martin suggests can work nicely, but in the realistic software world, you will have classes with more than one or two public methods.
To myself, when I look at a class, the public methods tells me the functionality should I wish to consume them. It is fair that a good IDE will still tell you when consuming, but if I do want to look into the class, it is just easier to read and grog it. Good IDE will let you navigate the lower level private functions easy enough.
Another disagreement I have with clean code is the "I" prefix for interfaces. I prefer my interfaces to be prefixed with an "I". This is however a separate discussion.
The most important takeaway is to be consistent. The strategy that you choose to name matters a lot less as apposed to consistency. If you use different strategies to your team, it will be hard for everyone to understand. As a team, choose a strategy and stick to it.

Annotations containing lambda expressions in Java 8

I am experimenting with static fields in annotations and I am stumbling upon something I do not understand.
I use the following code:
#a
public class myAnnotMinimal {
public static void main(String[] args) {
System.out.println(myAnnotMinimal.class.getAnnotations().length);
}
}
#Retention(RetentionPolicy.RUNTIME)
#interface a {
Consumer<Integer> f1 = a -> {return;}; // -> 0
//Consumer<Integer> f2 = new B(); //-> 1
//Consumer<Integer> f3 = C::eat; //-> 1
//int f4 = 5; //->1
//Supplier<Integer> f5 = ()->5; //->1
}
class B implements Consumer<Integer> {
#Override
public void accept(Integer t) {
}
}
class C{
public static void eat(Integer t){
}
}
Now, when running this I would expect '1' to be printed, however, the output I get is '0'. When I remove the f1 field and uncomment the other (f2-f5) fields the output is '1'. To me this pretty much looks like a bug. Is there something I am missing? I use jdk1.8.0_66 on linux.
Since this looks like a bug in the JDK I filed a bug report. By now the bug report has been accepted. See http://bugs.java.com/bugdatabase/view_bug.do?bug_id=8147585 .
This is a bug in the JRE’s annotation processing or, more precisely, its code hasn’t updated properly to accommodate the new language features, though it’s understandable that such usage hasn’t been considered.
Annotations are not supposed to provide utility methods and the ability to declare constants, i.e. fields that are implicitly public static final, should not be abused to add functions which carry code.
The reason for the bug is that certain Java language constructs produce synthetic methods behind the scenes. Field initializers may add code to a static method <clinit> at bytecode level, which is known and ignored by Reflection, thus creates no problems. That’s why Consumer<Integer> f2 = new B(); works (as it would do before Java 8), the creation happens inside this class initialization method. Note that int f4 = 5; creates a compile-time constant which does not need initialization code at all.
However, lambda expressions are compiled into synthetic methods which apparently are not ignored by the runtime Annotation implementation, despite being private, but checked for conformance with the standard annotation methods.
That’s why Supplier<Integer> f5 = ()->5; creates no problems, the synthetic method incidentally conforms to the annotation method pattern, as it has no parameters and returns a value. In contrast, Consumer<Integer> f1 = i->System.out.println(i); is compiled into a synthetic method having one parameter and void return type. This seems to cause the Annotation processing facility to reject that annotation as invalid (without reporting it).
In contrast, most method references do not need a synthetic helper method as they direct to the target method, thus Consumer<Integer> f3 = C::eat; creates no problems. You can verify this pattern by changing the declaration of f1 to Consumer<Integer> f1 = System.out::println;, while being semantically equivalent, the problem disappears, as now there’s no offending synthetic method in the annotation class file.
While this is indeed a bug, as, when when the Java language accepts lambda expression inside annotation fields, the JRE implementation should catch up to handle that scenario, I strongly discourage you from adding code to annotation types that way. Saving a single utility class is not worth that code smell. Also keep in mind that this creates additional runtime overhead compared to ordinary utility methods.

Protected Access Level in Swift

How can I make protected (like in ruby) variable or function in Swift? I know Swift has only 3 levels but nonetheless is it possible?
Access Levels
Swift provides three different access levels for entities within your
code. These access levels are relative to the source file in which an
entity is defined, and also relative to the module that source file
belongs to.
Public access enables entities to be used within any source file from
their defining module, and also in a source file from another module
that imports the defining module. You typically use public access when
specifying the public interface to a framework.
Internal access
enables entities to be used within any source file from their defining
module, but not in any source file outside of that module. You
typically use internal access when defining an app’s or a framework’s
internal structure.
Private access restricts the use of an entity to
its own defining source file. Use private access to hide the
implementation details of a specific piece of functionality.
Public
access is the highest (least restrictive) access level and private
access is the lowest (or most restrictive) access level
Currently I see only one solution - write parent class with private modifier and children class in single file but it's kind of painful.
Swift prefers to not use protected. You can read the reasons here Access Control and protected
In contrast, protected conflates access with inheritance, adding an entirely new control axis to reason about. It doesn’t actually offer any real protection, since a subclass can always expose “protected” API through a new public method or property. It doesn’t offer additional optimization opportunities either, since new overrides can come from anywhere. And it’s unnecessarily restrictive — it allows subclasses, but not any of the subclass’s helpers, to access something.
In Ruby's point of view, it may be important. However in Swift, neither it is useless, nor it is a matter of the language.
Swift language is primarily based on modules when it comes to access levels. It even has public private(set) variables, which is much needed in Objective-C (causes boilerplate).
There's no equivalent to protected in Swift where only subclasses have access to the method. Personally, I don't miss it.
In Swift (as Objective-C) there is far less emphasis on subclassing than other languages. If you find you have a set of methods that you want to be protected, it is probably better to factor them out as a delegate.
Swift 3.0 not cantains protected modifier. In our sdk we use internal(set) modifier that approve set operation only in sdk project.
private var _authorized : Bool = false
public internal(set) var authorized : Bool
{
get
{
return _authorized;
}
set
{
_authorized = newValue
}
}

What is the point declaring variables at the end of class?

I saw multiple examples in MSDN that uses to declare the internal fields at the end of the class. What is the point?
I find this a little embarrassing, because each time Visual Studio adds a method it adds it to the end of the class, so there is need every time to move it...
class A
{
public A(){}
// Methods, Properties, etc ...
private string name;
}
class A
{
private string name;
public A(){}
// Methods, Properties, etc ...
}
In C++, it makes sense to put the public interface of the class at the top, so that any user of the class can open up your header file and quickly see what's available. By implication, protected and private members are put at the bottom.
In C# and Java, where interface and implementation are completely intertwined, people would probably not open your class's source code to see what's available. Instead they would rely on code completion or generated documentation. In that case, the ordering of the class members is irrelevant.
If it's obvious the variable has been declared, and the code is by way of an example, then arguably this gets you to the bit being demonstrated quicker - that's all I can think of.
Add-ins like ReSharper will allow you to standardise and automatically apply this layout at the touch of a key combination, by the way, if it is what you want.
Many programmers strive for self-documenting code that helps clients to understand it. In C++ class declaration, they would go from most important (i.e. what is probably most frequently inspected) to least important:
class Class {
public:
// First what interest all clients.
static Class FromFoobar(float foobar); // Named constructors in client code
// often document best
Class(); // "Unnamed" constructors.
/* public methods */
protected:
// This is only of interest to those who specialize
// your class.
private:
// Of interest to your class.
};
Building on that, if you use Qt, the following ordering might be interesting:
class SomeQtClass : public QObject {
public:
signals: // what clients can couple on
public slots: // what clients can couple to
protected:
protected slots:
};
Then the same down for protected and private slots. There is no specific reason why I prefer signals over slots; maybe because signals are always public, but I guess the ordering of them would depend on the situation, anyhow, I keep it consistent.
Another bit I like is to use the access-specifiers to visually seperate behaviour from data (following the importance ordering, behaviour first, data last, because behaviour is the top-interest for the class implementor):
class Class {
private:
void foobar() ;
private:
float frob_;
int glob_;
};
Keeping the last rule helps to prevent visual scattering of class components (we all know how some legacy classes look like over time, when variables and functions are mixed up, not?).
I don't think there is any valid reason for this. If you run Code Analysis on a class declared like this you'll get an error as private fields should be declared on top of classes (and below constants).

GWT Dynamic loading using GWT.create() with String literals instead of Class literals

GWT.create() is the reflection equivalent in GWT,
But it take only class literals, not fully qualified String for the Class name.
How do i dynamically create classes with Strings using GWT.create()?
Its not possible according to many GWT forum posts but how is it being done in frameworks like Rocket-GWT (http://code.google.com/p/rocket-gwt/wiki/Ioc) and Gwittir (http://code.google.com/p/gwittir/wiki/Introspection)
It is possible, albeit tricky. Here are the gory details:
If you only think as GWT as a straight Java to JS, it would not work. However, if you consider Generators - Special classes with your GWT compiler Compiles and Executes during compilation, it is possible. Thus, you can generate java source while even compiling.
I had this need today - Our system deals with Dynamic resources off a Service, ending into a String and a need for a class. Here is the solutuion I've came up with - btw, it works under hosted, IE and Firefox.
Create a GWT Module declaring:
A source path
A Generator (which should be kept OUTSIDE the package of the GWT Module source path)
An interface replacement (it will inject the Generated class instead of the interface)
Inside that package, create a Marker interface (i call that Constructable). The Generator will lookup for that Marker
Create a base abstract class to hold that factory. I do this in order to ease on the generated source code
Declare that module inheriting on your Application.gwt.xml
Some notes:
Key to understanding is around the concept of generators;
In order to ease, the Abstract base class came in handy.
Also, understand that there is name mandling into the generated .js source and even the generated Java source
Remember the Generator outputs java files
GWT.create needs some reference to the .class file. Your generator output might do that, as long as it is referenced somehow from your application (check Application.gwt.xml inherits your module, which also replaces an interface with the generator your Application.gwt.xml declares)
Wrap the GWT.create call inside a factory method/singleton, and also under GWT.isClient()
It is a very good idea to also wrap your code-class-loading-calls around a GWT.runAsync, as it might need to trigger a module load. This is VERY important.
I hope to post the source code soon. Cross your fingers. :)
Brian,
The problem is GWT.create doen't know how to pick up the right implementation for your abstract class
I had the similar problem with the new GWT MVP coding style
( see GWT MVP documentation )
When I called:
ClientFactory clientFactory = GWT.create(ClientFactory.class);
I was getting the same error:
Deferred binding result type 'com.test.mywebapp.client.ClientFactory' should not be abstract
All I had to do was to go add the following lines to my MyWebapp.gwt.xml file:
<!-- Use ClientFactoryImpl by default -->
<replace-with class="com.test.mywebapp.client.ClientFactoryImpl">
<when-type-is class="com.test.mywebapp.client.ClientFactory"/>
</replace-with>
Then it works like a charm
I ran into this today and figured out a solution. The questioner is essentially wanting to write a method such as:
public <T extends MyInterface> T create(Class<T> clz) {
return (T)GWT.create(clz);
}
Here MyInterface is simply a marker interface to define the range of classes I want to be able to dynamically generate. If you try to code the above, you will get an error. The trick is to define an "instantiator" such as:
public interface Instantiator {
public <T extends MyInterface> T create(Class<T> clz);
}
Now define a GWT deferred binding generator that returns an instance of the above. In the generator, query the TypeOracle to get all types of MyInterface and generate implementations for them just as you would for any other type:
e.g:
public class InstantiatorGenerator extends Generator {
public String generate(...) {
TypeOracle typeOracle = context.getTypeOracle();
JClassType myTYpe= typeOracle.findType(MyInterface.class.getName());
JClassType[] types = typeOracle.getTypes();
List<JClassType> myInterfaceTypes = Collections.createArrayList();
// Collect all my interface types.
for (JClassType type : types) {
if (type.isInterface() != null && type.isAssignableTo(myType)
&& type.equals(myType) == false) {
myInterfaceTypes.add(type);
}
for (JClassType nestedType : type.getNestedTypes()) {
if (nestedType.isInterface() != null && nestedType.isAssignableTo(myType)
&& nestedType.equals(myTYpe) == false) {
myInterfaceTypes.add(nestedType);
}
}
}
for (JClassType jClassType : myInterfaceTypes) {
MyInterfaceGenerator generator = new MyInterfaceGenerator();
generator.generate(logger, context, jClassType.getQualifiedSourceName());
}
}
// Other instantiator generation code for if () else if () .. constructs as
// explained below.
}
The MyIntefaceGenerator class is just like any other deferred binding generator. Except you call it directly within the above generator instead of via GWT.create. Once the generation of all known sub-types of MyInterface is done (when generating sub-types of MyInterface in the generator, make sure to make the classname have a unique pattern, such as MyInterface.class.getName() + "_MySpecialImpl"), simply create the Instantiator by again iterating through all known subtypes of MyInterface and creating a bunch of
if (clz.getName().equals(MySpecialDerivativeOfMyInterface)) { return (T) new MySpecialDerivativeOfMyInterface_MySpecialImpl();}
style of code. Lastly throw an exception so you can return a value in all cases.
Now where you'd call GWT.create(clz); instead do the following:
private static final Instantiator instantiator = GWT.create(Instantiator.class);
...
return instantiator.create(clz);
Also note that in your GWT module xml, you'll only define a generator for Instantiator, not for MyInterface generators:
<generate-with class="package.rebind.InstantiatorGenerator">
<when-type-assignable class="package.impl.Instantiator" />
</generate-with>
Bingo!
What exactly is the question - i am guessing you wish to pass parameters in addition to the class literal to a generator.
As you probably already know the class literal passed to GWT.create() is mostly a selector so that GWT can pick and execute a generator which in the end spits out a class. The easist way to pass a parameter to the generator is to use annotations in an interface and pass the interface.class to GWT.create(). Note of course the interface/class must extend the class literal passed into GWT.create().
class Selector{
}
#Annotation("string parameter...")
class WithParameter extends Selector{}
Selector instance = GWT.create( WithParameter.class )
Everything is possible..although may be difficult or even useless. As Jan has mentioned you should use a generator to do that. Basically you can create your interface the generator code which takes that interface and compile at creation time and gives you back the instance. An example could be:
//A marker interface
public interface Instantiable {
}
//What you will put in GWT.create
public interface ReflectionService {
public Instantiable newInstance(String className);
}
//gwt.xml, basically when GWT.create finds reflectionservice, use reflection generator
<generate-with class="...ReflectionGenerator" >
<when-type-assignable class="...ReflectionService" />
</generate-with>
//In not a client package
public class ReflectionGenerator extends Generator{
...
}
//A class you may instantiate
public class foo implements Instantiable{
}
//And in this way
ReflectionService service = GWT.create(ReflectionService.class);
service.newInstance("foo");
All you need to know is how to do the generator. I may tell you that at the end what you do in the generator is to create Java code in this fashion:
if ("clase1".equals(className)) return new clase1();
else if ("clase2".equals(className)) return new clase2();
...
At the final I thought, common I can do that by hand in a kind of InstanceFactory...
Best Regards
I was able to do what I think you're trying to do which is load a class and bind it to an event dynamically; I used a Generator to dynamically link the class to the event. I don't recommend it but here's an example if it helps:
http://francisshanahan.com/index.php/2010/a-simple-gwt-generator-example/
Not having looked through the code of rocket/gwittir (which you ought to do if you want to find out how they did it, it is opensource after all), i can only guess that they employ deferred binding in such a way that during compile time, they work out all calls to reflection, and statically generate all the code required to implement those call. So during run-time, you cant do different ones.
What you're trying to do is not possible in GWT.
While GWT does a good job of emulating Java at compile time the runtime is of course completely different. Most reflection is unsupported and it is not possible to generate or dynamically load classes at runtime.
I had a brief look into code for Gwittir and I think they are doing their "reflection stuff" at compile time. Here: http://code.google.com/p/gwittir/source/browse/trunk/gwittir-core/src/main/java/com/totsp/gwittir/rebind/beans/IntrospectorGenerator.java
You might be able to avoid the whole issue by doing it on the server side. Say with a service
witch takes String and returns some sort of a serializable super type.
On the server side you can do
return (MySerializableType)Class.forName("className").newInstance();
Depending on your circumstances it might not be a big performance bottleneck.