So-called “Hungarian Notation” is a naming convention which is very popular in Java world (and in general). It’s characterized by fields’ and properties’ names starting with a lower-case letter “m”:
Now, you might find yourself in a situation when you have a project that uses Hungarian Notation, but needs to be refactored to so-called “Camel Case” notation. One common example in Android world are projects that migrate from Java to Kotlin. Since Kotlin has an official style guide and Hungarian Notation isn’t there, you’ll need to get rid of this notation if the original Java project uses it. That’s a lot of monotonic, annoying and tedious work which can drive you crazy.
Luckily, you don’t really need to do all this work manually. In this article, I’ll share with you a little script that I wrote to perform this refactoring automatically.
Script to Refactor from Hungarian Notation to Camel Case
You can grab the script from this gist. It’s written in Java and requires Java 9 (or later) to be compiled and executed.
To run the script, paste the code from the above gist into a file called
HungarianRemover.java and then execute the following commands:
This command will generate HungarianRemover.class file in the same path.
Then, if you want refactor all the files in the current working directory (recursively), execute this class without any arguments:
Alternatively, you can specify the target directory for refactoring as a command line argument:
java HungarianRemover /path/to/target/dir/
If everything goes well, you’ll see an output similar to this:
Target directory: /path/to/target/dir/ Done Lines changed: 4862 Identifiers changed: 7231
At this point, you should ensure that there are no compilation errors in your project and then test your application thoroughly. I tested this script on multiple projects and haven’t encountered special issues, but there is still a chance that the automatic refactoring changed the behavior in subtle ways.
That’s it. If everything went well, you’ve just removed Hungarian Notation from your files automatically and spared yourself a hell lot of time and headache. If you experience any problems with the script, please let me know by leaving a comment under the gist.
As you might know, Hungarian Notation is one of the most controversial and flammable topics in software. Some developers like it, while others hate it with passion, so you might wonder what I think about it. Well, I worked in many projects that used Hungarian Notation, as well as many projects that didn’t. To be honest, I don’t think it makes much difference. Therefore, in this post, I decided to avoid the discussion of Hungarian Notation’s utility. Please, resist the urge to turn the comments section into a war zone 😉
I should also mention that I took the initial idea from this blog post.
As usual, thanks for reading and don’t forget to subscribe for notifications about new posts if you liked this article.