Eclipse – Formatter e Save Action

Depois de ter falado sobre Code Templates para comentários no código, vou neste post falar sobre a formatação e como otimizar isso para lhe ajudar e não atrapalhar.

Muitos desenvolvedores tem problemas com o famoso Ctrl+Shift+F, que promete formatar seu código e muitas vezes acaba é deixando ele mais confuso.

Bem, o nosso padrão de código(se é que posso chamar assim) é muito diferente(ou um pouco depende) dos códigos dos gringos, ou seja, o Eclipse formata no padrão deles pode dizer assim ;).

Para resolver esse “problema” o desenvolvedor tem que fazer uma configuração simples, mas um pouco chata(considerada por alguns) mas no pior caso será feita apenas uma única vez ;).
Vá em Windows –> Preferences –> Java –> Code Style –> Formatter.

Vamos agora criar um novo profiler, clique em New e digite um nome para o seu novo profile.



Pronto, agora vamos personalizar, clique em editar.



Vou tentar falar um pouco sobre cada aba de opção.

Indentation
Nesta aba você vai selecionar a indentação em si e o tamanho dela, normalmente o tamanho da tab é 4.

Braces
Nesta aba você vai personalizar a posição das chaves(“{” , “}”).

White Space
Está é interessante, pois você poderá personalizar até os espaços em branco entre cada variável, método e assinaturas de todo tipo de objeto, desde strings até arrays e várias outras.

Blank Lines
Nesta aba você irá definir as quebras de linhas(linhas em branco) entres métodos, variáveis, pacotes e etc. Aqui você irá definir por exemplo que o espaço de linha entre a declaração de um package para um import seja de 2 linhas por exemplo.

New Lines
Nesta aba você define como um método vazio deverá ficar, se você deseja inserir uma nova linha neste método, definir também como um array declarado deverá ser exibido e identado, assim como uma annotation.

Control Statements
Esse é bem interessante mesmo, pois aqui você irá definir como seus else, IF, catch, while etc devem ser identados.

Line Wrapping
Neste você define o tamanho Maximo da coluna que uma linha pode comportar, como deve ser a identação de uma assinatura de um método, métodos declarados, enum, variáveis declaradas e etc.

Comments
Isso é referente a identação do Java Doc, blocos de comentários normais(//, /**/), qual o formato das tags HTML, espaço entre os textos do comentário e se desejar remover qualquer linha em branco que esteja no comentário.

Todas essa opções podem já serem visualizadas no código de exemplo ao lado de cada uma, facilitando assim a personalização.
Então supondo que você já criou e personalizou seu profile vamos agora tentar otimizar isso.

Para se utilizar do profile basta você executar o atalho dentro do código, que é o Ctrl + Shitf + F, pronto ele aplica a sua configuração personalizada.
Mas supondo que você criou um profile e quer sempre executar ele, fica meio chato você ficar sempre digitando o Ctrl+Shit+F correto ? Que tal otimizar isso ?

Save Actions
Vá em Windows –> Preferences –> Java –> Editor –> Save Actions.


Para ativar(caso não esteja) basta selecionar a opção “Perform the selected actions on save”.

Agora podemos adicionar uma formatação automática, selecione o Format source code e clique em Formatter.



Verifique se o seu profile está selecionado como profile ativo(Active Profile), clique em Ok e pronto, na próxima vez que você salvar(Ctrl + S) qualquer arquivo .java(classe) ele irá aplicar a(s) sua(s) configuração(ões) automaticamente.

Para definir como padrão para todos os integrantes da equipe, basta seguir os passos abaixo.

Vá em Windows –> Preferences –> Java –> Code Style –> Formatter –> Edit –> Export –> Salve seu profile.

Agora cada desenvolvedor irá poder importar toda a configuração de formatação de código, ou você mesmo poderá levar para onde quiser a sua formatação.

Simples não ?

Ações adicionais do Save Action

Se você quiser personalizar ainda mais a sua formatação é possível ainda inserir algumas formatações adicionais. Na tela de Save Actions temos o Configure onde você poderá definir mais configurações que serão executadas ao salvar qualquer classe Java.


Vou tentar explicar um pouco cada uma delas:

Code Style
Responsável em adicionar ou criar blocos fechados({, }) no bloco de IF/while/for/do.Definir se você quer parênteses em condições por exemplo:
(((i > 0) && (i < 10)) || (i == 50)) ou sem (i > 0 && i < 10 || i == 50).
Se quer adicionar o modificador final em todas os parâmetros onde seja necessário, e quais tipos de parâmetros(private, parameter, local variables).

Member Accesses
Usar o “this” em todos as variáveis e métodos locais ou somente onde for necessário. Como devem ser declarados os métodos e variáveis etc.

Unnecessary Code
Como o nome mesmo já diz, remove trechos de códigos desnecessários, como imports de classes que não existem dentre outras configurações.

Missing Code
Adiciona automaticamente as tags “@Override” e “@Deprecated” nos métodos.

Code Organizing
Organiza a ordem do métodos.

Bem essa são as formas simples de como otimizar o código, seja pela formatação dele ou até por simples comentários, mas essa é a intenção, não perder tempo com coisas simples e repetitivas ;).

Abraços e espero ter contribuído com este artigo para agilizar o processo de desenvolvimento.

32.352 Comments on “Eclipse – Formatter e Save Action

  1. На сайте https://theserials.online/ имеются интересные, увлекательные сериалы различного жанра. Все фильмы в отличном качестве и с хорошим звуком. А самое главное, что варианты представлены в огромном многообразии, что позволит выбрать решение на любой вкус. Просматривать сериалы можно на любом устройстве, в том числе, на компьютере, мобильном телефоне и где бы вы ни находились. Найдите такой сериал, который соответствует вашим предпочтениям. Есть фильмы прошлых лет, а также новинки, которые точно понравятся каждому киноману.

  2. hello there and thank you for your information – I have
    definitely picked up anything new from right here.
    I did however expertise several technical points using this site, since
    I experienced to reload the website lots of times previous to
    I could get it to load properly. I had been wondering if
    your web host is OK? Not that I’m complaining, but slow loading
    instances times will often affect your placement in google
    and can damage your quality score if advertising and marketing with Adwords.
    Anyway I’m adding this RSS to my email and could look out for much more
    of your respective interesting content. Make sure you update this
    again very soon.

  3. Magnificent goods from you, man. I have be aware your stuff prior to and you’re just too excellent.

    I actually like what you have received here, really like what you’re stating and the way
    in which in which you say it. You make it enjoyable and you still care for to
    keep it wise. I can’t wait to read far more from you.
    That is actually a great website.

  4. Online casinos have grown to be increasingly popular
    over the years, and Singapore is not any exception. With the rise
    of technology, online casinos have grown to be more accessible than ever before.
    Now you can enjoy your favorite casino games from the comfortable surroundings of your own home, without having
    to happen to be a physical casino.

    Online casinos provide a wide variety of games, including slots, table games,
    and live dealer games. You can choose from hundreds of different
    games, each using its own unique features and bonuses. Whether
    you are a seasoned gambler or perhaps a beginner, there’s something
    for everybody at an online casino.

    One of the biggest advantages of playing at an online casino is convenience.
    It is possible to play your favorite games once you want,
    without having to be worried about opening hours or dress codes.

    All you need is really a computer or mobile
    device and an internet connection.

    Another advantage of playing at an online casino may be the bonuses
    and promotions that are available. Many online casinos offer welcome bonuses to new players, together with ongoing promotions and
    loyalty programs for regular players. These bonuses
    will let you increase your likelihood of winning and make your gaming experience even more enjoyable.

    Online casinos also provide a higher payout percentage than physical casinos.
    This means that you have a better chance of winning once you play at
    an online casino. Additionally, online casinos have lower overhead costs than physical casinos, which means they can afford
    to offer higher payouts to their players.

    With regards to safety and security, online casinos are just as safe as physical
    casinos. Reputable online casinos use advanced encryption technology to safeguard their players’ personal and financial information.
    In addition they undergo regular audits by independent third-party companies to ensure that
    their games are fair and unbiased.

    If you are not used to online gambling, it
    is important to select a reputable online casino.
    Look for an online casino that’s licensed and regulated by way of a
    reputable authority, including the Malta Gaming Authority or the UK Gambling
    Commission. It’s also advisable to read reviews from other players to get
    an idea of their experiences with the casino.

    In conclusion, online casinos provide a convenient and enjoyable solution to gamble from the comfort of your own home.
    With a huge selection of different games to select from and
    generous bonuses and promotions available, there has never been an improved time
    to try your luck at an online casino in Singapore. Remember
    to choose a reputable casino and gamble responsibly. Good luck!

    Also visit my website singapore online casino

  5. Hmm is anyone else encountering problems with the pictures on this blog loading?
    I’m trying to determine if its a problem on my end or if
    it’s the blog. Any feed-back would be greatly appreciated.

  6. Gamma казино Gama Casino предлагает огромный выбор игр для всех любителей азарта. У нас вы найдете множество игровых автоматов, включая разнообразные слоты с разными темами и функциями. Также в нашем казино доступны классические настольные игры, такие как покер, блэкджек и рулетка. Все игры представлены от ведущих разработчиков, их качество и честность гарантированы.

  7. This design is steller! You certainly know how to keep
    a reader amused. Between your wit and your videos,
    I was almost moved to start my own blog (well, almost…HaHa!) Great job.
    I really enjoyed what you had to say, and more than that, how
    you presented it. Too cool!

  8. I do not even know the way I ended up here, however I assumed this
    put up was once good. I don’t know who you are however
    certainly you are going to a famous blogger if you happen to aren’t already.
    Cheers!

  9. Terrific article! This is the type of information that should be shared across the internet.
    Shame on Google for not positioning this put up upper!
    Come on over and consult with my website . Thanks =)

  10. Hmm it appears like your blog ate my first comment (it was super long)
    so I guess I’ll just sum it up what I had written and say, I’m thoroughly enjoying your blog.
    I as well am an aspiring blog blogger but I’m still new to everything.
    Do you have any recommendations for inexperienced
    blog writers? I’d definitely appreciate it.

  11. It is appropriate time to make some plans for the future and
    it’s time to be happy. I’ve read this post and if I could
    I desire to suggest you few interesting things or advice.
    Perhaps you could write next articles referring to this article.
    I want to read more things about it!

    Here is my web-site; Hoteldaebudo

  12. Excellent pieces. Keep writing such kind of information on your site.
    Im really impressed by your blog.
    Hello there, You have done an excellent job. I’ll definitely digg it and personally recommend to my friends.
    I am sure they will be benefited from this site.

Deixe um comentário

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *

*

Este site utiliza o Akismet para reduzir spam. Saiba como seus dados em comentários são processados.