Applying Google Code Style to your Java Projects

 


Over the years I have seen how some projects upload their code with indentation or without indentation.

I learned working with teams that apply good practices, that it is good to use a style guide for the source code.

One of them and widely used in other companies, is the google java format which follows google Java style guide. This post will explain how to use it and make sure no one else uploads its code without format.


Pre-requisites

- You need to download the Google Style  and save it in a location on your PC.

- IntelliJ IDEA

- Any project using maven 

IntelliJ IDEA

The first step is add it file in IntelliJ IDEA - Preferences - Editor - Code Style - Import Scheme


You need to import the scheme and ready.

Maven Plugin

In the project where you need to apply it code style you need to add the fmt-maven-plugin (available in GitHub) in your pom.xml. 

 


We are configuring the plugin to apply Google format to src/main/java (our principal source code) and src/test/java (our tests cases).

Note: The plugin changed of groupId and will be soon in maven central. In the meantime, we are going to use the old groupId.


Pre-commit with Git

To make sure our format is always applied, we add a hook on the pre-commit in Git. Then when you execute a git commit -m "commit code changes", this guarantees  that the format is applied before.

vi .git/hooks/pre-commit
#! /bin/bash
mvn com.coveo:fmt-maven-plugin:format
git add -u

Don't forget to give execute permission:  chmod a+x .git/hooks/pre-commit



Test

Apply a commit and check your code before doing a push and you will see the final result.



Looks your entity:



Ready. No more code without format or indentation in your git repo.

Enjoy


Joe




Share:

0 comentarios:

Publicar un comentario