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.428 Comments on “Eclipse – Formatter e Save Action

  1. Experience the tantalizing world of the finest snus varieties and flavors, carefully crafted to satisfy your cravings and elevate your senses to a whole new level!

  2. Genuinely when ѕomeone doesn’t Ьe aware of afterward іts up to othеr viewers that they wiⅼl assist, so heгe it takes ρlace.

    Have a lоok at my webpage … onlinebet

  3. Having read this I believed it was rather enlightening.
    I appreciate you spending some time and energy to put this informative
    article together. I once again find myself personally spending a significant amount of time both reading and commenting.
    But so what, it was still worth it!

  4. You actually make it seem so easy with your presentation but I find this
    topic to be really something which I think I would never understand.
    It seems too complex and extremely broad for me. I am looking forward for your next post, I will
    try to get the hang of it!

  5. Hi, i think that i noticed you visited my site so i
    came to return the want?.I’m trying to find things to improve my web site!I suppose its adequate to use some of your concepts!!

  6. Are you exhausted by the constant cycle of recruiting and training developers? If so, you might want to consider using https://iconicompany.com.

    Our website provides access to skilled developers for your business. Instead of hiring full-time employees, you can hire freelancers and eliminate the hassle of recruitment and training.

    By utilizing our service, companies can access a diverse range of proficient developers. This enables them to better navigate economic fluctuations and swiftly expand their workforce, while also gaining access to exceptional and in-demand skills.

  7. Have you ever considered about adding a little bit more
    than just your articles? I mean, what you say is valuable and all.
    However just imagine if you added some great visuals or video
    clips to give your posts more, “pop”! Your content
    is excellent but with pics and video clips, this website could definitely be one of the very best in its
    field. Wonderful blog!

    Feel free to visit my website: blank october calendar

  8. Having read this I thought it was extremely enlightening.
    I appreciate you finding the time and effort
    to put this article together. I once again find myself personally spending way too much time both reading and leaving
    comments. But so what, it was still worth it!

  9. Hi tһere would yoս mind stating ѡhich blog platform уou’re uѕing?
    I’m planning to start my own blog ѕoon Ƅut I’m haνing a difficult tіme selecting between BlogEngine/Wordpress/Β2evolution and Drupal.
    Тһe reason I ask is bеcause yoսr design and style seеms different tһеn most blogs and I’m looking for somethіng complеtely unique.
    P.S Apologies f᧐r being off-topic but I haⅾ to ask!

    Here is my web blog – casino

  10. Это немаленький ряды, в котором только и можно выискать не
    столько одежу для жен, парней равным образом ребят, девайсы и сумки,
    но также всё исполнение) обиталища: постельное белье,
    соусник, тикалки, украшающие
    темы а также много чего еще – на каталоге наличествую распределения
    вдоль всякой комнатке, поэтому найти
    почему-то, возьмите хоть, пользу кого
    кухни либо зли комнатной, баста легонько.

    Кардиганы, свитера также пуловеры,
    жилеты также майки для сильной половины человечества
    равно теть, гарус из британской шерсти, кашемира,
    шелка равно хлопока, гербарий трикотажа.
    Помимо одежды на лавке скоромиться всё ради под
    своей смоковницей: белье для постели,
    тикалы, предметы умения, прибабасы, товары в целях торжеств и
    прочее. в течение целостном, цена багажей нате портале колыхается от $десятого по $600,
    проглатывать наиболее всевозможная камзол – с
    нижнего белья ут крылатка, обстановка,
    сумочки а также т.д. В неразделимом, текущий
    зоомагазин для тех, кто именно оценивает несложность, довольство равно прекрасное
    закал. Этот английский оптика приготовлен лишьбы чтобы девушек.
    Сайт Dress-for-less, в соответствии с названием, может помочь накупить труду подешевле – магазуха скупает обломки багажей из коллекций в строях неодинаковых марок, равным образом торгует их хоть сниженным стоимостям.

    Also visit my web page брендовая одежда россия

  11. Hey there! This is kind of off topic bᥙt I need some advice
    fгom an established blog. Ӏs it verү difficult to set up your own blog?
    I’m not ѵery techincal but I ϲan figure tһings oսt pretty
    fаst. I’m thinking aƅoսt creating mу own but I’m not ѕure whеre to start.
    Do үou have any ideas or suggestions? Тhanks

    My homepage – casino

  12. Учитывать таковские выплаты лига бессчетно имел право – они мало-:
    неграмотный стеснены начистую раз-два нее
    работой. Плательщики УСН девать имеет основания учесть
    компенсации затрат исполнителю-физлицу, какой уплачивает талья возьми компетентный улов.
    Сотрудникам немало наложить запрет кооперировать практика
    в специальном порядке немного произведением девать трудовому пакту, выплаты
    завались каковому немерено довольно
    облагаться налогом держи
    профессиональный хабар (п.
    главный инцидент – самозанятый мастерит буква объединения
    точно по трудовому условию. Относительно налоговых обязательств сообразно подоходному налогу равно взносам
    во внебюджетные основной
    капитал, самозанятый рассматривается сходственно подрядчику
    (исполнителю) юридическому физиономии.
    Те протори, то что мало-: неграмотный вникают на отдаривание, выказываются частными затратами
    самозанятого особ. предварительно заключением
    контрактам нужно было провести диагностику регистрацию
    гражданина яко самозанятого. Иные издержки, примерно автотранспортные или для сожительство, не
    положено сообразиться близ расчете налога для проигрыш.
    В налоговой отчетности – в декларациях равным образом расчетах – действию
    от самозанятыми особь видимо-невидимо обособляются,
    их воссоздают буква составе общественных признаков, предустановленных регламентированными отчетными конфигурациями.
    При этом надлежит разнить требования, связанные небольшой предоставлением удостоверений (к примеру (сказать), счетов-фактур в рамках ответной налоговой испытания), равно требования, сплоченные всего наполнением отчетных конфигураций (по временам оригинатор запроса присылает ходячая монета информации).

    Stop by my web page https://grand-insur.com/prezident-naznachil-10-novyh-sudej-v-sudy-odessy/

  13. I’m more than happy to find this site. I want
    to to thank you for your time just for this fantastic
    read!! I definitely liked every bit of it and i also have you
    book marked to check out new information in your web site.

  14. Magnificent goods from you, man. I have take into account your stuff previous to and you are simply extremely fantastic.

    I really like what you’ve acquired right here, certainly like what
    you are saying and the way in which in which you assert it.
    You make it entertaining and you continue to care for to stay it smart.
    I can not wait to learn much more from you. That is actually a tremendous website.

  15. I simply could not depart your web site prior to suggesting that I actually enjoyed the standard information an individual supply to your
    visitors? Is going to be again ceaselessly
    in order to inspect new posts

  16. hi!,I love your writing very a lot! proportion we communicate extra approximately your
    article on AOL? I need a specialist on this space to resolve my problem.
    May be that’s you! Having a look ahead to look
    you.

  17. Hi there! I know this is kinda off topic but I’d figured I’d ask.
    Would you be interested in exchanging links or maybe guest
    authoring a blog article or vice-versa? My site goes over a lot of the same subjects
    as yours and I think we could greatly benefit from each other.

    If you’re interested feel free to shoot me
    an e-mail. I look forward to hearing from you! Fantastic blog by the way!

  18. Hello! Quick question that’s entirely off topic. Do you
    know how to make your site mobile friendly? My
    blog looks weird when browsing from my iphone4.
    I’m trying to find a theme or plugin that might
    be able to fix this problem. If you have any recommendations,
    please share. Thank you!

  19. Hello there! This post couldn’t be written any better!
    Going through this post reminds me of my previous roommate!
    He continually kept talking about this. I will send this post
    to him. Pretty sure he’ll have a very good read.

    Thanks for sharing!

  20. Sadisflix et le seul est l’unique Site de Streaming 100% Français et Gratuit qui propose
    une grande variété de Films et de Séries en qualité HD.
    Découvrez notre catalogue exclusif et profitez d’un divertissement illimité.
    Nous vous offrons une sélection de contenus adaptée à vos
    préférences et à vos envies, ainsi que des mises à jour régulières pour vous offrir toujours plus de
    choix. Rejoignez notre communauté et profitez de la meilleure expérience de streaming VF et
    VOSTFR, sans aucune limite

Deixe um comentário

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

*

Esse site utiliza o Akismet para reduzir spam. Aprenda como seus dados de comentários são processados.