Eliminate Boilerplate with Android Code Generation

Harshith Shetty
2 min readMar 30, 2021

--

Are you and your team wasting time on creating the same boring boilerplate components manually for new features?

Tired of creating setup component files like fragment, layouts, views, viewmodel, repositories , doa, network , test files etc repeatedly in their specific directories, adhering to specific app architecture, and glue code for binding?

Answer: Generate It!

Creating a generator one time for components will let you and your team members save time, enforce standards and be consistent throughout projects.

Also, there is a simple way to do it. Let’s start!

Steps

$ npm i -g hygen
  • Go to your android project root directory and create initialize hygen
$ hygen init self
  • Create a new generator (Ex: Fragment)
hygen generator new --name fragment

A new _templates folder will be created in your root directory which will have all your project code generators. Add it to version control to share it with all team members.

  • Add a template file in the created generator to describe destination and contents for the file generation. You can have 1 to N templates for a generator. (“/_templates/fragment/new/FragmentTemplate.ejs.t”)
  • We are creating two parameters: module and name to keep it dynamic
  • Run generator with parameters we want.
hygen fragment new --name UserList --module user

Done. This creates a Fragment UserListFragment in user module.

Conclusion

Now you nor anyone else working on project will need to create this component manually.

This was a small walkthrough of the flow to create a generator and 1 template file. We can use this to create N number of files and injections like proguard mapping for dao,network models etc.

This is not limited to android, understanding it will help you to create it for any platform like backend, web, ios, flutter etc.

You can save hours of time wasted on manally creating/copy pasting code and teaching/knowledge sharing the structure of your project and keeping it consistent across team. Also adding/changing standards will not need much meetings and screen sharing!

Cheers!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Harshith Shetty
Harshith Shetty

Written by Harshith Shetty

Mobile App Architect @Shaadi.com

No responses yet

Write a response