2014-12-05

Level Up - Android Studio: How to Boost Productivity By Auto-Generating Getters and Setters

A best practice in Java is to encapsulate field variables by making them private and creating a "getter" and "setter" for each of them, as needed. Doing this with many fields can be a lot of boilerplate code to write. But, thankfully, modern IDEs, like Android Studio provide ways to auto-generate code so that you don't have to manually write it.

For example, if you have a class like the following:

public class MyClass {
    private int mId;
    private String mName;
}

Instead of manually writing each accessor (getter) and mutator (setter), go to the menu and click Code->Generate.. (hotkey `alt+insert), then choose the "Getter and Setter" option.

Done. That was fast. And, it will be just as fast with 20+ fields also.

But, wait! By default, Android Studio will include that "m" prefix (stands for "member" variable) in each of the generated method names, so you'll have method names like "setmId" and "getmId". There is a quick permanent fix for this also!

Go to File->Settings->Code Style->Java->Code Generation, then type a single "m" into the "Field", "Name prefix" field. Hit apply, then you are gone. All future code generations will take those "m" prefixes for field into account. Here's a screenshot to what this sentence means visually.

So easy to save a lot of time with Android Studio

That's it for this post. There are lots of other useful code generators also. If you are doing mindless work, it's probably been automated (or should be). ;)

~ Danial Goodwin ~



No comments: