IDEA's choice for new method/variables
I personally like to put all my class variables at the end of the class. I then like to put my methods in order of visibility with public being at the top. I put constructors and static methods above all non-static methods. When I allow intellij to create methods and variables it puts them in different places.
Is it reasonable to ask idea to put new variables with all the others?
Is it reasonable to ask idea to put methods in a specific order?
I don't really mind moving them, but it would be nice.
Please sign in to leave a comment.
Charles, it is a long standing wish to be able to define, where to put
methods, fields. Either Jetbrains do not know how to solve it or they do
not care how structured their own classes are...
Tom
Thomas Singer wrote:
... or the current placement suits their code style. I must say that
putting class variables at the end of the class seems a tad odd, but
whatever floats your boat ;)
Ciao,
Gordon
--
Gordon Tyler (Software Developer)
Quest Software <http://java.quest.com/>
260 King Street East, Toronto, Ontario M5A 4L5, Canada
Voice: 416-643-4846 | Fax: 416-594-1919
Well, our file structure is relatively fine grained (at least more
grained than IDEA supports it):
- constants
- static fields
- non-private static methods (as long as there are no instance methods)
- fields
- constructors
- implemented/overridden methods
- non-private instance methods ("accessing", "actions")
- private methods ("utils")
- inner classes
Tom
The reason I put class variables at the end is because I just don't care about them. I never directly access them. I try to always use get and set methods. The variables are always private and even if I'm in a private method I use the get methods.
Would a plugin that rearranges items according to your rules suffice? At least until IDEA adds the functionality you need?
-Dave
I think it would. I really need to learn the api but I'm just not sure it's worth the effort until they get it officially released.
I think I could whip out a plugin to do the rearranging, but would like to first determine what flexibility people need. Thomas mentioned the following items:
(though I'd like an example of what a non-private static method with "no instance method" means.)
There would be a list in the configuration dialog where these items could be moved up/down to specify the order.
Are these item categories sufficient?
Or perhaps something more generic: suppose there were two ordered lists, one to order outer level classes based on their public/private/package protection level; another to order class contents. Entries in each list could be added, removed or reordered with other entries.
The class content items would be fields, methods or inner classes with specific attributes:
You'd be able to leave any of those attributes unspecified also, or be able to negate them.
Taking Thomas's spec as an example, the class contents ordered list might be:
All items are to be retained in relative order. So "all constructors" gathers all the constructor methods together but leaves them in the same original overall order as the user had them.
Likewise, anything not covered by a rule would follow at the end of the file in original order. So you could just specify a list of "public static final fields" and it would only move the constants to the front of the class.
Keep comments and trailing blank lines together with the original object.
Does this sound like it will meet the need? Can you think of anything else -- other selection criteria, maybe?
Hi Dave,
such a plugin would be very helpfull. I prefer to keep getter/setter methods separated from other methods, so an option to treat methods beginning with set/get/is different than other methods would be nice (so there would be three kind of methods: constructor/getter and setter/normal.
Good point! I assume most folks want to keep the getter/setter pair together. Or does anybody want all the getters first, then the setters? (Would anybody admit it? :)
Or perhaps somebody wants the getter/setter together with the field declaration?
Isn't this a bit extreme? Just curious: what is the benefit of an object accessing its private fields via getters?
Vlad
P.S. Personally, I see a couple of benefits for directly accessing and modifying private fields:
1) Slightly better performance (no overhead associated with method calls), without sacrificing good design practices or readability.
2) Very easy to spot field usages (because fields are highlighted by IDEA + I can do a Ctrl-Shift-F7 on a particular field and see right away both its read and write usages.)
Vlad,
By the way, the JVM optimizes out the method calls -- accessor methods are inlined and are as fast as accessing the private variable.
Still, I refer to my own private variables directly from within the class. (It's my right, may as well exercise it!)
-Dave
For me it doesn't matter, whether it's done by IDEA or a plugin. But I
do not have the time to develop one.
Tom
Yes, we keep the getters and setters together. Years ago they were
separated and searching one was a nightmare.
Tom
I think, it's a matter of taste. I prefer to access private variables
directly, but I also see, that - especially for setters or lazy getters,
sometimes it is very handy to have a method you can set a breapoint in...
Tom
I think the philosophical argument about using getters within a class has to do with having only one way of retreiving a value.
That way you "guarantee" that an external caller and an internal caller will always get the same thing.... I have seen this when for example someone does some level of formatting in a getter and then bugs appear because the getter does not return the same value as the directly calling the private member.
Florian
In my jsp/servlet application I do not use getters and setters.
Ok 90% of you just quit reading :)
On the applet/application side, which is most of my work.
It is probably not worth getting into too big of a discussion about it. This is also IMHO a style issue. I have a certain style of design that works for me and fits into the weird way my brain works. I'll try to explain the benefits I see in it. Most of these only concern the getters, I'm not as disciplined about setters.
The ease of maintinence and reduction of nullpointers in larger applications is a major benefit. If you have only senior level programmers then you probably don't run into this as much, but it still makes modifications easier IMHO.
It also takes some of the "procedural" aspects out of the code. The getters can be called anytime and will take care of any initialization that needs to be done. It really removes me from having to think about what has already happened (or not happened) in the application. The need to put lots of initialization in a constructor is gone, and the need to make sure that the connectToDatabase() method is called before I access the connection variable is removed. I just call getConnnection() and if the connection has timed out or has not been established it will take care of it for me.
It also adds flexability. If I decide that a variable should not be modified I have a single place to clone it and it becomes read only. I also try to not pass around my concrete classes. My getter can return the interface type.
There are downsides to it. I have to think about every getter, what needs to happen before I return a reference to the variable ect. It also takes some time setting up the getters and setters although idea helps with that :)
I hope this explains why I do it, I'm definatly not saying everyone should, just that this is a reasonable design strategy.
IMHO, it's not a style issue :)
As Florian said, always accessing through getters and setters assures the
same resulat always. Also, if the class is subclassed, the subclass can
modify the behaviour of the property, which it can become more difficult if
direct access is done.
The other day, I needed to transform access to an object into a cache. I
jus't subclassed and overrode the getters:
getPropertyX() {
if (! loaded) load();
return x;
}
Much easier if there's a guarantee that access id done through the getters.
That said, in 99% of cases I myself use direct access to properties.
Carlos
I think what you just described IS a style, not a coding style but a design style.
This is one of those subjects that can cause lots of unuseful dialog. It's up there with where to put curley braces, and the correct pronunciation of char, and linux :)
vlad wrote:
Doing something because you perceive in your mind that it would be faster is not
a good reason. That type of action is really "premature optimization" in that
respect.
However, that said, I happen to access my members directly internal to a class,
but if I expose a member to any other class
even a subclassI always use agetter method to do that. Here are the reasons for it:
1) Refactoring tools take care of my code, but any member exposed outside of one
class is part of its interface.
2) Any code that is already written, packaged, and distributed that expects a
certain interface will break if the name changes.
All my fields are private, to guarantee that they will never be part of the
interface. If you never dynamically load and run code, you don't have to
be as diligent about it, but as soon as you do then variable name changes can
break an implementation.
+999999 premature optimization may be the root of all evil. Definatly the source of a lot of bad code.
How do you make sure that each field is initialized properly? How do you make sure it only gets initialized when used?
charles decroes wrote:
I develop using COP (Component Oriented Programming), using a component
framework like Apache Avalon. As such, the component has a definite
lifecycle. I can guarantee that my component will be initialized the
same way every time.
Now, for classes that are not components (like my simple JavaBean value
classes), I provide legal default values in the constructor.
As a general rule, I don't add lazy initialization unless I really need
to. In most cases, I get along just fine without it.
Thanks to all who replied to my question (accessing private fields directly vs. via getters). For the record, I agree with most of the arguments brought forward to support the use of getters in a situation or another - I was just curious if you are absolutely "religious" about the internal usage of getters (and why) or you apply this policy on a case-by-case basis.
Personally, I still prefer the later approach, although I must admit that the "philosophical argument" presented by Florian is very compelling per se.
A couple of remarks regarding the "optimization" issue:
1) Dave wrote:
"The JVM optimizes out the method calls -- accessor methods are inlined and are as fast as accessing the private variable."
Question: doesn't the inlining optimization require the accessor method (or the whole class) to be declared final? Otherwise, how can the JVM ensure virtual method behavior for overriding accessors? (see e.g. Carlo's reply)
2) Berin wrote:
"Doing something because you perceive in your mind that it would be faster is not a good reason. That type of action is really "premature optimization" in that respect."
I would qualify the phrase to say that doing something just because it would be faster (or is perceived to be faster) is not a good reason - and "premature optimization".
I completely agree with this. But while optimizations should not be done for the sake of attempting to optimize every little thing - an attempt which in fact is likely to fail and even make more harm than good - I can still be reasonably careful to opt for implementation choices that do not incur additional cost without any real benefit. Rather than regarding these choices as (premature) optimizations, I regard them as natural choices. (Example: I am careful from the beginning not to call methods without side-effects in loop test conditions. Is this a premature optimization, or just a good programming practice? I would say the latter.)
In the particular case of private fields, there may well be certain benefits in accessing them via getters. But that was exactly the whole purpose of my question: discussing and weighting out the possible benefits.
And I would say that this discussion was indeed beneficial. Unlike Charles, I believe that we can all learn from design style discussions, provided they are carried out with rational arguments - as they are on this thread and on the vast majority of IDEA forum threads.
Friendly,
Vlad
Hi Vlad,
You asked,
Question: doesn't the inlining optimization require the accessor method (or the whole class) to be declared final? Otherwise, how can the JVM ensure virtual method behavior for overriding accessors?
I asked this at JavaOne a couple years ago. Cliff (Sun's JIT compiler guru) said that the VM treats an accessor method of a class as final if no subclasses are (class)loaded. If one ever is loaded, though, the JIT compiler discards the old code and has to recompile the calls to the accessor method. So the VM knows that it is a final method, even though you didn't say so.
Those Sun compiler guys are smart! (The garbage collection guys are no slouches either..)
-Dave
Dave,
thanks for the Java optimization insight, it is really interesting. If I understand correctly, this requires JVM to keep track of all classes with optimized accessors. Do I also understand correctly that the compiler removes away the accessor inlining optimization even if a newly loaded subclass does not override the superclass accessor? And one more thing: do you know what are the conditions that an accessor must meet in order to be optimized? In other words: how does the compiler recognize that a certain method is an (optimizable) accessor?
It would be great if you could point me to an article or Web resource that discusses these technical issues in more detail.
Thanks,
Vlad
P.S. Sorry for "hijacking" the initial thread topic. I think that a rearranging plugin would be great and I am very much looking forward to it.
Hi Vlad,
My understanding is that every method, not just accessors, is considered "final until proven otherwise." The JVM knows whether a class has any subclasses, or whether a method has been overridden by a subclass. Loading a new subclass doesn't invalidate the optimization unless the method of the superclass is overridden. They is discard the relevant compiled code (in this case for all the classes that reference the class with the new subclass), and let the JIT compiler recompile whenever it would next be directed to do so (which is different between client and server VM's). I'm sure there's more to it than that if an existing thread has made or is making a call to the old (inlined) method, but they handle that somehow.
Potentially, all methods could be inlined. How aggressive they decide to be depends on the VM, and probably changes from release to release. I was pretty amazed at the JavaOne session at the amount of loop unrolling, peephole and other optimizations they will perform, especially in the server VM.
I found several whitepapers and other stuff (searched Google for Hotspot Virtual Machine, and Cliff Click); here are two that seemed interesting:
Hope that helps.
I'll get busy on that plugin!
-Dave
vlad wrote:
That is what I was saying. So we are in agreement.
:) Many of our choices can be attributed to programming practice, optimization,
style, and preference. My only comment was if your whole reason for making a
decision is only optimization--wait until you have impirical data to prove you
need that optimization. You might throw a TODO in there just to flag it to
check later, but that is your choice.
I agree.
Looks like no one else is using Jalopy - a very good free java code formatter. Even the development seems stopped since last November. It has pretty much all the functionalities you can think of. It can be easily configured, integrated with ant and several popular IDEs. I've configured two external tools in IDEA to help me to format a single file or a group of files based on my code style. They work pretty well.
http://jalopy.sourceforge.net
http://jalopy.sourceforge.net/download.html
I've uploaded version 0.1 of the Rearranger plugin, which does what I think most people on this topic wanted.
The plugin performs two rearrangement tasks:
Reordering is based on the configuration supplied by the user. (By default, no rearrangement takes place.) The user creates a list of entries, specifying various attributes of the fields, methods, and classes. These attributes include all the standard Java modifiers (public, private, protected, final, static, etc.) as well as some other criteria (method is constructor, getter/setter, etc.)
The plugin moves objects to the front of the file or class declaration in the order they appear in the list. So, for example, you could specify a list like:
and all public static void fields would be moved to the front of each class definition, followed by constructors and accessor/mutator methods. Everything else follows these, in the same relative order as in the original file.
See http://www.intellij.org/twiki/bin/view/Main/RearrangerPlugin for more detail and to obtain the plugin.
Please let me know if there are bugs or additional features you'd like. One thing I know does not work: detecting if a method is overridden or not. (It's not obvious how to do this in Psi, but I'm sure it's easy)
-Dave
Very cool - will take a look at it. What EAP build is required?
Tom
I built it with 944 but I think it would work with builds back to the early 900's. The Psi specific code only needs to identify classes and class members, and that part of Psi hasn't changed for a long time. It wouldn't work with the current release builds only because of the change in the way documents are committed, but that could be added. (I keep hoping IntelliJ will release a new one before I have to retrofit anything else!)
-Dave