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.
http://nagaevo.ekafe.ru/viewtopic.php?f=86&t=1737
I think this is one of the most important information for me.
And i’m glad reading your article. But wanna remark on few general things, The site style is wonderful, the
articles is really nice : D. Good job, cheers
I just couldn’t leave your web site prior to suggesting that I actually enjoyed the standard information an individual
provide to your guests? Is gonna be again often to check out new posts
Nice post. I learn something totally new and challenging on blogs I stumbleupon every day.
It’s always interesting to read through articles from other authors and use
a little something from other sites.
Hey there, You have done an incredible job. I will definitely
digg it and personally suggest to my friends.
I’m confident they will be benefited from this website.
Very nice article. I absolutely appreciate this
site. Stick with it!
darkmarket link dark website
This is the perfect web site for everyone who hopes to understand this topic.
You know a whole lot its almost tough to argue with
you (not that I personally would want to…HaHa).
You definitely put a new spin on a topic that’s been written about
for years. Wonderful stuff, just excellent!
Thank you for the auspicious writeup. It in fact was a amusement account it.
Look advanced to far added agreeable from you! By the
way, how can we communicate?
Here is my web-site; sell my home fast for cash
http://edu.bestbb.ru/viewtopic.php?id=170
Everything is ѵery open with a really clear description of the issues.
It was definitely informаtive. Your site is extremely helpful.Thank
you for sharing!
Lookk into my blog … australian
http://mypenza.ru/forum/index.php?showtopic=53357
This paragrapһ is in fact a nice one it helps new web users,
ԝho are wisһing for blogging.
Feel free to visit my web page; slot gacor hari ini
Hey there would you mind sharing which blog platform you’re using?
I’m looking to start my own blog soon but I’m having a tough time deciding
between BlogEngine/Wordpress/B2evolution and Drupal.
The reason I ask is because your layout seems different then most
blogs and I’m looking for something unique. P.S
Apologies for getting off-topic but I had to ask!
Applicants can apply onn the internet loans anytime, even throughout weekends.
My page – 무직자대출
Thanks for any other informative blog. The place else could I am
getting that type of info written in such an ideal method?
I have a challenge that I’m just now running on, and I
have been on the look out for such info.
http://forum.supernova.ws/viewtopic.php?f=58&t=3541
My programmer is trying to persuade me to move to .net from PHP.
I have always disliked the idea because of the expenses.
But he’s tryiong none the less. I’ve been using Movable-type
on numerous websites for about a year and am anxious about switching to another platform.
I have heard great things about blogengine.net.
Is there a way I can import all my wordpress posts into it?
Any kind of help would be greatly appreciated!
Look at my site – Derma Advanced Skin Cream
dark websites onion market
Someone essentially assist to make significantly articles I’d
state. That is the very first time I frequented your web page and
to this point? I amazed with the analysis you made to create this particular post
extraordinary. Excellent task!
We are a group of volunteers and starting
a new scheme in our community. Your site offered us with valuable info to
work on. You have done a formidable job and our whole community will be grateful to you.
Hey there, You have done a great job. I will definitely
digg it and personally suggest to my friends. I am confident they’ll be
benefited from this site.
prograf 1 mg
http://гуманитарныйлицей.рф/forum/messages/forum1/topic41/message122/?result=new
That is a good tip particularly to those new to the blogosphere.
Short but very accurate info… Thank you for sharing this one.
A must read post!
darknet market lists darknet markets 2023
dark markets 2023 dark web access
blackweb dark web market
Hello everyone, it’s my first visit at this web page,
and piece of writing is genuinely fruitful in support of me, keep up posting these articles or
reviews.
http://izumrudnoeozero.listbb.ru/viewtopic.php?f=8&t=194
Hey there! Would you mind if I share your blog with my
myspace group? There’s a lot of folks that I think
would really enjoy your content. Please let me know. Thanks
Thanks a lot for sharing this with all of us you actually understand what you are speaking approximately!
Bookmarked. Please also visit my website =). We may
have a link alternate arrangement among us!
Also visit my web blog; Mozz Guard Bug Zapper
What’s up to every single one, it’s genuinely a pleasant for me to go to
see this web site, it includes important Information.
dark websites dark markets
Hi there this is somewhat of off topic but I was wondering if
blogs use WYSIWYG editors or if you have to manually code with
HTML. I’m starting a blog soon but have no coding knowledge so
I wanted to get advice from someone with experience. Any help would be greatly
appreciated!
where to buy atarax
http://m9-com.ru/forums/viewtopic.php?f=3&t=9726
Hello There.Ӏ found yоur blоg uѕing msn. This is an extremely well written article.
I’lⅼ be sure to bookmark іt and com bacк to read more of your
useful іnformation. Thanks foг the post. I will definitеly return.
Here is myy page … slot onlijne (penzu.com)
Hi there it’s me, I am also visiting this site daily, this website is truly fastidious and the users are truly sharing nice thoughts.
Pills information leaflet. What side effects can this medication cause?
avodart pills
Actual trends of drug. Get information now.
celebrex 200 mg capsule
Even after four years of stringent controls on immigration imposed underneath former President Donald J.
Trump, the general share of Individuals born in different countries
isn’t solely rising, however coming near ranges final seen within the
late 19th century. 1960s and approaching the record 14.Eight p.c seen in 1890,
shortly before giant numbers of Europeans started disembarking from vessels
at Ellis Island. In 2021, the speed of inhabitants progress fell
to an unprecedented 0.1 %. Immigration, even at diminished levels, is for the first time making up a majority of population progress.
Thanks a lot for helping us with N-400, N336 application process
and patiently answering all our questions time
and once more. In 2021, that determine was 148,000, or one-tenth the achieve that was regular a decade ago, and smaller than worldwide migration for the first time
ever. The most recent report, from the Census Bureau’s population estimates program, confirmed a internet gain of 244,000 new residents from immigration in 2021 – a far
cry from the middle of the earlier decade, when the bureau
recurrently attributed annual good points of a million or extra to immigration.
Hello I am so delighted I found your website, I really found you
by error, while I was researching on Askjeeve for something else,
Anyways I am here now and would just like to say thanks a lot for a fantastic post
and a all round entertaining blog (I also love the theme/design), I don’t have time to read
it all at the moment but I have saved it and
also added in your RSS feeds, so when I have time I will be back to read much more, Please
do keep up the awesome work.
Review my web blog – bang4d
Hello, its nice article about media print, we all be
familiar with media is a great source of data.
how to get seroquel
Wonderful goods from you, man. I have understand your stuff previous to
and you’re just too great. I really like what you’ve acquired here, certainly like what you’re saying and the way in which
you say it. You make it entertaining and you still take care of
to keep it sensible. I cant wait to read far more from you.
This is really a tremendous web site.
my site; jon4d
anafranil uk
Right away I am going to do my breakfast,
when having my breakfast coming over again to read additional news.
Hey there! I’m at work surfing around your blog from my new apple iphone!
Just wanted to say I love reading your blog and look forward to all your posts!
Carry on the fantastic work!
Fantastic website you have here but I was wanting to know if you knew of any community forums that cover
the same topics talked about in this article?
I’d really like to be a part of group where I can get feed-back from other
knowledgeable individuals that share the same interest. If you have any suggestions, please
let me know. Thanks a lot!