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.
You could certainly see your skills within the article you write.
The world hopes for more passionate writers such as you who aren’t afraid to mention how they believe.
Always follow your heart.
up x
Hello, I desire to subscribe for this website to
obtain newest updates, therefore where can i do it please assist.
Hi there! Someone in my Facebook group shared this
site with us so I came to look it over. I’m definitely loving the information.
I’m bookmarking and will be tweeting this to my followers!
Superb blog and brilliant design and style.
Check out my blog post: OptiSlim Keto Gummies Review
fildena 50 online fildena 100 online india fildena 50 mg price in india
У какой фирмы покупать двери? http://wladimir.5nx.ru/viewtopic.php?f=5&t=17916&p=56537#p56537 цены на них будут намного ниже, чем в салонах.
This article will help the internet visitors for building up new webpage or even a blog
from start to end.
This is the perfect site for anyone who really wants to understand this topic.
You realize 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 subject that’s been written about for decades.
Excellent stuff, just great!
На сайте https://premium-sk.ru/ вы сможете бесплатно вызвать мастера для того, чтобы он выполнил замеры с последующим ремонтом квартиры любой площади. Кроме того, в компании оказывают и такие услуги, как строительство коттеджей. В ней трудятся исключительно проверенные и надежные прорабы, инженеры и технологи. На работы, материалы распространяются гарантии. Для того чтобы ознакомиться с примерами, изучите портфолио. За 9 лет работы на рынке удалось наладить сотрудничество с лучшими поставщиками материалов и предложить клиентам профессиональный сервис.
На сайте https://naturalstones-jewerly.com.ua/ вы сможете приобрести изысканные, роскошные изделия из натуральных камней. Они созданы искусными ювелирами, которые производят не только стильную, но и качественную продукцию. Она будет пользоваться спросом во все времена. Вы сможете передавать изделия по наследству, ведь они сохранят свой вид надолго. Среди огромного ассортимента вариантов вы точно выберете то, что вам понравится. Украшение отлично впишется в ваш повседневный образ, станет броским элементом.
I’ve been browsing online more than 3 hours
today, yet I never found any interesting article like yours.
It’s pretty worth enough for me. Personally,
if all website owners and bloggers made good content as you did, the net will be a lot more useful than ever before.
1xslots
Hey! Тhіs is my first visit to yoᥙr blog! We
аre a team of volunteers аnd starting a new project іn a community іn the same niche.
Уօur blog pгovided սs useful іnformation to work on.
You have ɗone ɑ marvellous job!
Аlso visit my homepage … sport betting, Lauri,
800mg motrin otc
When someone writes an post he/she retains the
thought of a user in his/her mind that how a user can know it.
Therefore that’s why this post is outstdanding. Thanks!
Here is my web blog – printable october calendar 2024
darknet market links safe best drug darknet [url=https://world-darkmarket.com/ ]darknet markets norge [/url]
hebergeur minecraft openmod gratuit hébergement de site web gratuit
What’s up, everything is going perfectly here and ofcourse every one is sharing facts,
that’s actually fine, keep up writing.
darknet markets norway 2023 tor link list 2023 [url=https://darkwebcypher.com/ ]cannabis dark web [/url]
This is really interesting, You’re a very skilled blogger.
I’ve joined your rss feed and look forward to seeking more of your wonderful
post. Also, I’ve shared your site in my social networks!
Hello! This is kind of off topic but I need
some guidance from an established blog. Is it very difficult to
set up your own blog? I’m not very techincal but I can figure things out pretty quick.
I’m thinking about setting up my own but I’m not sure where to
begin. Do you have any points or suggestions? Thank you
I’m supposed to take Lasix 250 at the same time every day.
Keep on writing, great job!
It’s frustrating that I have to jump through hoops just to buy Accutane without prescription.
great publish, very informative. I wonder why the opposite
experts of this sector don’t realize this. You must continue your writing.
I am sure, you’ve a great readers’ base already!
It’s hard to find knowledgeable people in this particular topic, however, you sound like you know what you’re talking about!
Thanks
Here is my web blog :: coloradocashbuyers
I blog quite often and I truly appreciate your content.
This great article has truly peaked my interest.
I will book mark your blog and keep checking for new details about once per week.
I subscribed to your RSS feed as well.
An interesting discussion is definitely worth comment.
I believe that you should publish more about this topic, it might not be a taboo subject but typically
folks don’t talk about these subjects. To the next! Best wishes!!
На сайте https://bigpicture.ru/ вы сможете ознакомиться с интересными и любопытными новостями, которые оформлены в форме картинок. Публикации посвящены таким темам, как культура, история, путешествия. На портале имеются и лонгриды, почитать которые захочется и вам. Есть материалы на тему фотографии, а также те, что касаются прошлых времен. О многих фактах вы даже и не догадывались. Имеются данные о животных, истории в картинках, которые точно не оставят вас равнодушным. Узнаете новости времен СССР.
A fascinating discussion is definitely worth comment.
I do think that you ought to publish more about this subject, it
might not be a taboo matter but generally people don’t talk about these issues.
To the next! Kind regards!!
WOW just what I was looking for. Came here by searching for https://daftar-rajacuan.powerappsportals.com/
riobet casino
abc slot gacor hari ini buktikan sekarang
https://www.project-seven.es/Tangsel/play-sbowin
Excellent article! We will be linking to this particularly
great article on our website. Keep up the great writing.
Wow! This blog looks just like my old one! It’s on a entirely different subject but it has pretty much the same page layout and design. Great choice of colors!
вывод из запоя https://vivod-zapoy-msk.ru/
Hey I am so grateful I found your webpage, I really found you by accident, while I was browsing on Yahoo for something else, Anyhow I am here now and would just like
to say kudos for a marvelous post and a all round interesting blog (I
also love the theme/design), I don’t have time to browse it all
at the minute but I have saved it and also included your RSS
feeds, so when I have time I will be back to read much more, Please do keep up the fantastic work.
I do not even know how I ended up here, but I thought this post was great.
I don’t know who you are but definitely you’re going
to a famous blogger if you aren’t already 😉 Cheers!
Τhis excellent website гeally һas all of the informatiοn and faсts I wanted
about this subject and didn’t knoѡ who to ask.
Смотрите на нашем сайте пасьянсы онлайн косынка паук коврик и другие игра в дурака. Ученые установили, что игра в пасьянсы может помочь познакомиться с историей, культурой и традициями разных стран и эпох. Какие пасьянсы связаны с конкретными историческими событиями и персонажами, и как они могут помочь расширить свои знания о мире?
best european online pharmacy generic pharmacy online top 10 pharmacies in india
Hello this is kind of 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 guidance from someone with experience.
Any help would be enormously appreciated!
I’ll immediately snatch your rss feed as I can’t find your email subscription hyperlink or e-newsletter service.
Do you have any? Kindly let me realize so that I could subscribe.
Thanks.
This article gives clear idea designed for the new viewers of blogging,
that truly how to do blogging and site-building.
Hello there! Do you know if they make any plugins
to assist with SEO? I’m trying to get my blog to rank for some targeted keywords but I’m not seeing
very good results. If you know of any please share.
Kudos!
ایران خودرو 4301
I’m not sure exactly why but this blog is loading incredibly slow for me.
Is anyone else having this problem or is it a problem on my end?
I’ll check back later and see if the problem still exists.
Thankfulness to my father who informed me about this
webpage, this web site is really remarkable.
У какой фирмы покупать двери? http://soc-life.com/forum/6-17638-1 цены на них будут намного ниже, чем в салонах.
vivat мебель официальный сайт https://vivatsklad.ru/