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.
This OLG.ca Player Agreement – Terms and Situations of Use for OLG.ca contains the terms and circumstances that govern the uuse of
OLG’s OLG.ca online gaming platform.
my blog … 온라인바카라
deep web drug markets https://cypher-online-drugs.com/ dark web market list
It’s a pity you don’t have a donate button! I’d without a doubt donate to this excellent blog!
I suppose for now i’ll settle for bookmarking and adding your RSS feed to my Google account.
I look forward to brand new updates and will talk about this blog with my Facebook group.
Talk soon!
deep dark web https://heinekendrugsmarketplace.com/ blackweb official website
darknet market list https://worldmarketplacee.com/ darknet drugs
how to access dark web https://darkweb-world.com/ tor dark web
dark web access https://cypheronionmarket.com/ deep web sites
darknet links https://world-drugs-online.com/ darkmarket list
darknet links https://worldmarket-linkk.com/ dark web access
deep dark web https://cypher-darknet.com/ how to get on dark web
Excellent blog here! Also your website loads up fast!
What web host are you using? Can I get your affiliate link to
your host? I wish my website loaded up as fast as yours lol
dark web market list https://darkwebworldmarket.com/ dark net
Obviously, we do not advocate for mess, however you can’t leave your
workplace vacant, either.
darknet links https://world-dark-market.com/ dark web drug marketplace
I was suggested this blog by my cousin. I’m not sure whether
this post is written by him as nobody else know such detailed
about my difficulty. You’re wonderful! Thanks!
darkmarket https://heinekendrugsmarketplace.com/ darknet sites
darkmarket url https://cypher-darknet.com/ darknet sites
dark market 2023 https://world-darkmarketplace.com/ tor markets links
of course like your web site but you have to test the
spelling on quite a few of your posts. Many of them
are rife with spelling problems and I to find it very bothersome to inform the
truth however I’ll certainly come again again.
darknet drug store https://darkweb-cypher.com/ dark market
darknet drug store https://darkmarketworld.com/ deep web drug markets
I’m gone to convey my little brother, that he should also pay a quick
visit this webpage on regular basis to get updated from most recent news update.
My blog post – Lady and Tramp coloring pages
вывод из запоя на дому недорого https://vivod-iz-zapoev.ru/
dark web drug marketplace https://dark-market-world.com/ dark web link
tor dark web https://heinekendrugsmarket.com/ darknet market links
I’ve been exploring for a little for any high-quality articles or weblog posts on this kind of
area . Exploring in Yahoo I eventually stumbled upon this site.
Studying this information So i am satisfied to show that I’ve a very excellent uncanny feeling I discovered just what I needed.
I so much certainly will make sure to don?t forget this
web site and provides it a look regularly.
how to get on dark web https://world-drugs-online.com/ bitcoin dark web
dark market url https://worldmarketplacee.com/ dark web links
Processing aluminum gray 5-forty ton forklift shipped grey, closed,
chilly ash admixture quench agency rapid cooling, screen, then after melted.Are handled comparatively clean completely,
residual aluminum content of 2% -5%.Matching mud bag,
free of mud.Appropriate for giant-scale aluminum plant to give attention to.This text is supplied by the manufacturers of ball mill worth — Henan Xingbang Heavy Trade Co.,
Ltd. Xingbang Heavy Industries is committed jaw crusher to the
research and development of the grey aluminum manufacturing course of and aluminum grey
tools, now the market aluminum ash dealing with system, aluminum gray aluminum ash separation therapy cell crusher
station and without separation of the cold aluminum gray and then through
the ball mill, drum machine, roll display machine screening, crucible melting.
5, alicey599 within the case of coarse grain dimension of the mineral disseminated, the re-election can get a better
separation indexes.Can produce a rough concentrate
or mixed concentrates, can also get the ultimate concentrate.This text is supplied by the Henan Xingbang Heavy
Industries Co., LtdThe contents of xxx is: ultrafine mill worth you will have
to consider its configuration, as well as manufacturers.Ultrafine mill is outfitted with a hammer crusher, bucket elevator, storage silo, feeder
micro-grinding the host variable frequency analysis machine, soundproof room, double rotary kiln supplier cyclone powder collector,
pulse mud system.
Here is my web-site – http://crmkt.com/domain/cougarslut.com
dark net https://cypherdrugsmarketplace.com/ dark web links
Property Democrat Leader Phil GiaQuinta operates for Fort
Wayne Cityy Utilities.
Also visit my web-site: homepage
dark web access https://world-darknet.com/ tor markets links
Hi colleagues, nice article and fastidious urging commented here, I am genuinely enjoying by these.
motilium canada otc
deep web search https://worldmarket-linkk.com/ dark web search engine
darknet drug market https://worldmarket-darknet.com/ deep web markets
how to access dark web https://cypher-market-onion.com/ tor dark web
dark market list https://world-darkmarket.com/ dark web sites links
dark market https://world-onlinedrugs.com/ how to get on dark web
An impressive share, I just given this onto a colleague who was doing a little analysis on this. And he in fact bought me breakfast because I found it for him.. smile. So let me reword that: Thnx for the treat! But yeah Thnkx for spending the time to discuss this, I feel strongly about it and love reading more on this topic. If possible, as you become expertise, would you mind updating your blog with more details? It is highly helpful for me. Big thumb up for this blog post!
tor market https://cypherdrugsmarketplace.com/ the dark internet
deep web drug markets https://worldmarket-darknet.com/ darkweb marketplace
Это могут быть равным образом уникальные запчасти, а также комплектующие через опробованных изготовителей, да их связывает одно –
высокое качество продукции,
что и приспосабливается в ФОРРИНГС близ ремонте
автомобиль. При надобности новая смена частей, покупателям предоставляются оригинальные комплектующие Шкода.
же обосновывается данное огромным счетом авто
на магистралях, как негусто Шкода попадается а также
в России, да биш наиболее мировыми моделями значится Octavia, Superb, Yeti
и Fabia. Авто Шкода сегодняшний день позволительно без колебаний отсрочить к идеалу экономичности
(а) также практичности. Skoda – данное чешская сигнет авто, возлюбленная на сегодняшний момент живете развивается и принадлежать ко одной из самых
участившихся сверху территории Европы.
Сервисный власти Skoda обдувает быстротечное, чего становой хребет лучшее отсеивание каждых неисправностей, в таком случае буква сервисе трубят
поднаторевшие искусники. на правах (а) также каждая иная сигнет, Skoda обладает предопределенными минусами, а также узлами, коие больше ломаются.
Сервисный средина ФОРРИНГС делает отличное предложение
полный комплекс услуг немерено обслуживанию
автомобилей ауди. же 10 лет сверху базаре услуг и еще отзывы наших клиентов позволяют
нам делать вывод об высоком качестве проводимых во
автосалоне ФОРРИНГС занятий.
Feel free to surf to my site – https://remont-skoda-1.ru/
darknet drugs https://heineken-darkweb-drugstore.com/ dark web link
deep web drug links https://world-onlinedrugs.com/ darknet drug links
tor markets links https://dark-market-world.com/ blackweb
dark market url https://world-darkmarket.com/ darkmarket list
Hmm is anyone else having problems with the pictures on this
blog loading? I’m trying to find out if its a problem on my end or if it’s the blog.
Any feed-back would be greatly appreciated.
best darknet markets https://world-darkweb.com/ darkmarket link
deep web links https://heinekenoniondarkweb.com/ dark market list