can I has fulltext autocompletion for Java # Eclipse? Let's demonstrate:
Final piece of code:
getVariants().add(new Variant(MediaType.TEXT_XML));
How do I code now:
getv[ctrl+space].a[Enter]new
V[ctrl+space, down arrow,
Enter]M[Ctrl+Space, Enter].text_x
Basically, Eclipse completes word "TEXT_XML" when I provide letters "TEXT_X".
How would I like to code:
getv[ctrl+space].a[Enter]new
V[ctrl+space, down arrow,
Enter]M[Ctrl+Space, Enter].xml
and Eclipse should realise I meant "TEXT_XML" (fulltext autocompletion).
As far as I'm aware, there is no way of enabling a full-text code completion in the Eclipse preferences view. This has been bugging me for a while, too. I did quite a bit of digging and I'm pretty certain there is no easy way of achieving this.
However,
there are two ways of implementing the desired, but I assume both of which are way to much work for fixing this little nuisance.
There is an Eclipse plug-in extension point for the JDT Java Completion Proposal Computer - reference page
A sample project which implements this extension point can be found in this repository.
This is fairly convenient, but still a lot of boilerplate and tedious coding.
You can change the findKeywords method in the internal org.eclipse.jdt.internal.codeassist.CompletionEngine class and compile your own JDT fork. But this is discouraged for so many reasons. First of all, this class is a 12000 line monster and hard to just jump in. And of course, if you'd only hack a kludge in, there is little chance of this becoming an official contribution, so you'd need to worry about every eclipse release.
Additionally, there might be a very chillaxed way in the future. Although this might exceed your requirements a bit.
Have a look at the Code Recommenders project. This blog has an outline of the project objectives
It doesn't mention full-text auto-completion specifically, but I'd assume its matching algorithms go even beyond that.
Edit: In the proper SO-spirit, I'll keep this answer up to date:
Apparently the feature is now implemented in the Code Recommenders plug-in. See this blog post and this forum thread. I'm quite surprised it only took 10 locs. To me the extension point appeared more complex.
If your MediaType class does not contain a large number of accessible fields/methods you could simply use
getv[ctrl+space].a[Enter]new V[ctrl+space, down arrow, Enter]M[Ctrl+Space, Enter].[Ctrl+Space, down arrow, Enter]
you may need to press the down arrow more than once, though to select the desired field.
Yes, you can using Templates. (Window -> Preferences -> Java -> Editor -> Templates)
The basic usage is you set the name to what you want to type and you set the pattern to what you want to appear.
In my testing I set the name to xml, the Context to Java, the Pattern to TEXT_XML and Automatically insert turned on. Then when I typed out your example I was able to follow a pattern like...
getv[ctrl+space].a[enter]new V[ctrl+space, down arrow, Enter]M[ctrl+Space, Enter].xml[ctrl+space]
and since Automatically insert was turned on poof TEXT_XML was inserted.
Templates have much more functionality than that and the one source I used for this answer was Effective Eclipse.
I hope this helps!
Related
When refactoring code (e.g.: Refactor -> Rename), IntelliJ IDEA 14.x also rewraps (reformats) my code to fit into the 80 column limit.
Example: here's the code before the refactoring:
Refactoring in progress:
... and the code is re-wrapped once I press Enter:
What's most annoying about that, even Java classes which aren't currently open in the editor (but are affected by the refactoring) are reformatted, increasing the chance that formatting changes get propagated into my VCS unnoticed.
What I want to achieve is:
keep the original print margin at 80 columns, but still
have IDEA preserve my original formatting when renaming variables/classes/methods.
How do I achieve this?
Since I don't use any automatic formatting and mostly wrap my long lines manually, I figured out another solution.
Under "File -> Settings -> Editor -> Code Style -> Java -> Wrapping and Braces", I've disabled automatic wrapping entirely (i.e. set everything to "Do not wrap" where appropriate, except for class, method and field annotations, which are set to "Wrap always" by default).
The downside of this approach is that now IDEA sometimes unwraps long lines during refactoring, but those are easier to spot.
If you are doing an actual "Refactoring -> Rename", for example with SHIFT + F6 you are editing every file that has a reference to that variable name whether or not they are currently open in the editor is irrelevant if you change something all the files that are affected are edited and any VCS will consider them changed.
The behavior of reformatting the entire file on refactoring is been in Idea a long time and all bugs that have been filed against that behavior have been setting in an unassigned state forever. Here is one example.
I doubt that this behavior is going to change, I for one hope it does not.
If you want ridiculously long variable names then you need to either turn off the right margin or make it ridiculously long as well. Or change whatever configuration is causing things to be formatted differently.
Personally I set all the relevant things to ALWAYS whatever so I do not have somethings formatted one way and somethings formatted a different way. Consistency is more important than anything else in a large code base.
The VCS tools in Idea are extremely powerful and unmatched in any other IDE. You can easily see what has changed and exclude them from any commits or fix them up how you want.
Idea has a format on commit checkbox for all the various version control systems it supports as well.
I aggressively use Eclipse formatter and clean-up for all my code. Every time I save my source, all my code is formatted nicely, indentation fixed, braces put in correct places and removed where unnecessary, imports are organized, variables declared final where they should be, and other fine little things happen.
It's very comfortable to user, but I'm just curious – are there any drawbacks? May be bad habits that I'll acquire unknowingly?
Reformatting can play havoc with diffs in version control.
If there are multiple developers then make sure formatting is done to a common standard. Agree on a standard, export the formatting rules from Eclipse and put the formatting rules into source control somewhere. Get all devs to check out the rules and apply them.
Better still, use a version control hook to automatically format all source to the standard rules as part of the commit. This way *you will never have to use Ctrl-Shift-f again!
In general, no, the default rules work well. Are you using default values? Are you the lone developer or walking into an existing team / project?
The format and cleanup rules can be altered, tailored, and saved right alongside your source code. In essence, what my format button does may not be the same as what your format button does if either of us moved from the default rules.
The only problem I've seen is on mutil-member teams, if you do not share the same formatting rules, the formatting can result in difficulty comparing changes before check-in. So, for example, if you have a clean check-out then make a small change to ten files then use the synchronize view to compare your changes before check-in, all the spacing changes can obstruct the actual changes you have made. This can, for example, make a code review more difficult.
When I receive code I have not seen before to refactor it into some sane state, I normally fix "cosmetic" things (like converting StringTokenizers to String#split(), replacing pre-1.2 collections by newer collections, making fields final, converting C-style arrays to Java-style arrays, ...) while reading the source code I have to get familiar with.
Are there many people using this strategy (maybe it is some kind of "best practice" I don't know?) or is this considered too dangerous, and not touching old code if it is not absolutely necessary is generally prefered? Or is it more common to combine the "cosmetic cleanup" step with the more invasive "general refactoring" step?
What are the common "low-hanging fruits" when doing "cosmetic clean-up" (vs. refactoring with more invasive changes)?
In my opinion, "cosmetic cleanup" is "general refactoring." You're just changing the code to make it more understandable without changing its behavior.
I always refactor by attacking the minor changes first. The more readable you can make the code quickly, the easier it will be to do the structural changes later - especially since it helps you look for repeated code, etc.
I typically start by looking at code that is used frequently and will need to be changed often, first. (This has the biggest impact in the least time...) Variable naming is probably the easiest and safest "low hanging fruit" to attack first, followed by framework updates (collection changes, updated methods, etc). Once those are done, breaking up large methods is usually my next step, followed by other typical refactorings.
There is no right or wrong answer here, as this depends largely on circumstances.
If the code is live, working, undocumented, and contains no testing infrastructure, then I wouldn't touch it. If someone comes back in the future and wants new features, I will try to work them into the existing code while changing as little as possible.
If the code is buggy, problematic, missing features, and was written by a programmer that no longer works with the company, then I would probably redesign and rewrite the whole thing. I could always still reference that programmer's code for a specific solution to a specific problem, but it would help me reorganize everything in my mind and in source. In this situation, the whole thing is probably poorly designed and it could use a complete re-think.
For everything in between, I would take the approach you outlined. I would start by cleaning up everything cosmetically so that I can see what's going on. Then I'd start working on whatever code stood out as needing the most work. I would add documentation as I understand how it works so that I will help remember what's going on.
Ultimately, remember that if you're going to be maintaining the code now, it should be up to your standards. Where it's not, you should take the time to bring it up to your standards - whatever that takes. This will save you a lot of time, effort, and frustration down the road.
The lowest-hanging cosmetic fruit is (in Eclipse, anyway) shift-control-F. Automatic formatting is your friend.
First thing I do is trying to hide most of the things to the outside world. If the code is crappy most of the time the guy that implemented it did not know much about data hiding and alike.
So my advice, first thing to do:
Turn as many members and methods as
private as you can without breaking the
compilation.
As a second step I try to identify the interfaces. I replace the concrete classes through the interfaces in all methods of related classes. This way you decouple the classes a bit.
Further refactoring can then be done more safely and locally.
You can buy a copy of Refactoring: Improving the Design of Existing Code from Martin Fowler, you'll find a lot of things you can do during your refactoring operation.
Plus you can use tools provided by your IDE and others code analyzers such as Findbugs or PMD to detect problems in your code.
Resources :
www.refactoring.com
wikipedia - List of tools for static code analysis in java
On the same topic :
How do you refactor a large messy codebase?
Code analyzers: PMD & FindBugs
By starting with "cosmetic cleanup" you get a good overview of how messy the code is and this combined with better readability is a good beginning.
I always (yeah, right... sometimes there's something called a deadline that mess with me) start with this approach and it has served me very well so far.
You're on the right track. By doing the small fixes you'll be more familiar with the code and the bigger fixes will be easier to do with all the detritus out of the way.
Run a tool like JDepend, CheckStyle or PMD on the source. They can automatically do loads of changes that are cosemetic but based on general refactoring rules.
I do not change old code except to reformat it using the IDE. There is too much risk of introducing a bug - or removing a bug that other code now depends upon! Or introducing a dependency that didn't exist such as using the heap instead of the stack.
Beyond the IDE reformat, I don't change code that the boss hasn't asked me to change. If something is egregious, I ask the boss if I can make changes and state a case of why this is good for the company.
If the boss asks me to fix a bug in the code, I make as few changes as possible. Say the bug is in a simple for loop. I'd refactor the loop into a new method. Then I'd write a test case for that method to demonstrate I have located the bug. Then I'd fix the new method. Then I'd make sure the test cases pass.
Yeah, I'm a contractor. Contracting gives you a different point of view. I recommend it.
There is one thing you should be aware of. The code you are starting with has been TESTED and approved, and your changes automatically means that that retesting must happen as you may have inadvertently broken some behaviour elsewhere.
Besides, everybody makes errors. Every non-trivial change you make (changing StringTokenizer to split is not an automatic feature in e.g. Eclipse, so you write it yourself) is an opportunity for errors to creep in. Do you get the exact behaviour right of a conditional, or did you by mere mistake forget a !?
Hence, your changes implies retesting. That work may be quite substantial and severely overwhelm the small changes you have done.
I don't normally bother going through old code looking for problems. However, if I'm reading it, as you appear to be doing, and it makes my brain glitch, I fix it.
Common low-hanging fruits for me tend to be more about renaming classes, methods, fields etc., and writing examples of behaviour (a.k.a. unit tests) when I can't be sure of what a class is doing by inspection - generally making the code more readable as I read it. None of these are what I'd call "invasive" but they're more than just cosmetic.
From experience it depends on two things: time and risk.
If you have plenty of time then you can do a lot more, if not then the scope of whatever changes you make is reduced accordingly. As much as I hate doing it I have had to create some horrible shameful hacks because I simply didn't have enough time to do it right...
If the code you are working on has lots of dependencies or is critical to the application then make as few changes as possible - you never know what your fix might break... :)
It sounds like you have a solid idea of what things should look like so I am not going to say what specific changes to make in what order 'cause that will vary from person to person. Just make small localized changes first, test, expand the scope of your changes, test. Expand. Test. Expand. Test. Until you either run out of time or there is no more room for improvement!
BTW When testing you are likely to see where things break most often - create test cases for them (JUnit or whatever).
EXCEPTION:
Two things that I always find myself doing are reformatting (CTRL+SHFT+F in Eclipse) and commenting code that is not obvious. After that I just hammer the most obvious nail first...
Is there a simpler way of reordering methods within a class source file in IntelliJ than cutting and pasting the code manually? Nowadays I often need this while refactoring legacy code, e.g. to move related methods close to each other in the source code.
In Eclipse AFAIK there is a view similar to the Structure view of IntelliJ, where I can drag and drop methods around. However, this does not work in IntelliJ and I couldn't find any hints from its help either.
I am using IntelliJ 9.0.2 to be specific.
You can select a method name and hit: Ctrl+Shift+Up or Ctrl+Shift+Down to move it up and down.
On OS X: Cmd+Shift+Up or Cmd+Shift+Down
Beyond this the Rearranger Plugin lets you move methods around quickly, and even define a standard ordering based on your coding convention.
IntelliJ has a built in system that allows you to specify how to order your methods. You need to go to Settings (Ctrl + Alt +S) -> Editor -> Code Style -> Java -> Arrangement (tab) and scroll down until you find the icons with methods. There you can manipulate the options to sort them by visibility, or alphabetically, or to keep related ones grouped together.
Here is a screenshot of my settings which will order methods automatically by visibility (public, protected, private) and alphabetically (a-z).
The blue highlights show the currently selected rules.
Not a perfect answer yet, due to a bug in IntelliJ.
Though IntelliJ offers this feature implicitly, but it needs to be enabled as well as fixed. The OP's suggested way is technically arranging methods in depth-first order. However, if you use Breadth-first ordering(which works properly), it should reduce the manual work of moving functions by a lot, by arranging all caller and callee methods together.
Issue Link: https://youtrack.jetbrains.com/issue/IDEA-149524. Please do vote for its resolution.
The appropriate action for this is Rearrange Code. This has no key assigned to it, but you can define your own using Preferences->Keymap.
With your cursor on the method definition line (you do not have to and press ctrl+shift+up or ctrl+shift+down, to move up or down respectively.
You can also to ctrl+shift+numberpad - to quickly collapse everything so you can focus on moving around (plain - works on my laptop as well, not sure why) and ctrl+shift+numberpad + to get back to see everything (ctrl-shift-equals works on my laptop as well).
Select a block of text (hit Ctrl-W a few times) and then use Ctrl-Shift-Up and Ctrl-Shift-Down to move it around.
There is an automated way, which you can later tweak
Code -> show reformat file dialog
and tick "rearrange code" box
I'm working on a utility that will be used to test the project I'm currently working on. What the utility will do is allow user to provide various inputs and it will sends out requests and provide the response as output.
However, at this point the exact format (which input is required and what is optional) has yet to be fleshed out. In addition, coding in Swing is somewhat repetitive since the overall work is simple though this should be the safest route to go as I have more or less full control and every component can be tweaked as I want. I'm considering using a configuration file that's in XML to describe the GUI (at least one part of it) and then coding the event handling part (in addition to validation, etc). The GUI itself shouldn't be too complicated. For each type of request to make there's a tab for the request and within each tab are various inputs.
There seems to be quite a few questions about this already but I'm not asking for a 3rd party library to do this. I'm looking to do this myself, since I don't think it'll be too overly complicated (hopefully). My main consideration for using this is re-usability (later on, for other projects) and for simplifying the GUI work. My question is: are there other pros/cons that I'm overlooking? Is it worth the (unknown) time to do this?
I've built GUI in VB.NET and with Flex3 before.
XML is so 2000. It's code, put it in real source files. If it really is so simple that it could be XML, all you are doing is removing the XML handling step and using a clearer syntax. If it turns out to be a little more complicated than you first expected, then you have the full power of your favourite programming language to hand.
In my experience, if your layout really is simple, something like the non-visual builders in FormLayout can lead to really concise code with a minimum of repetition.
If you have to specify the precise location of every control you might look at a declarative swing helper toolkit that can minimize boilerplate and simplify layout. Groovy supports this as does JavaFX, and both are simple library extensions to Java (give or take).
If the form is laid out in a pattern, using a definition file in a format like XML or YAML will work. I've done that and have even set up data bindings in that file so that you don't even have to deal with listeners or initial values...
If you are sure you want XML, I'd seriously consider YAML though, it's really close but instead of:
<outer>
<inner a=1> abc </inner>
</outer>
I think it's a lot more like:
outer
inner a=1
abc
(I may have that a bit wrong, but that's close I think. Anyway, you should never force anyone to type XML--if you are set on XML, provide a GUI with which to edit it!)