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.
My spouse and I stumbled over here by a different website and thought I should check things out.
I like what I see so now i’m following you. Look forward to checking out your web page
repeatedly.
Vеry energetic blоg, I loved that a lot. Willl there be a part 2?
Look imto my web-site :: stuѕ slot gacor (http://Dbc000ffcc2A1.tracker.Adotmob.com/pixel/visite?d=5000&r=http://cgi4.osk.3web.ne.jp/%7Edor/board.cgi)
My spouse and I stumbled over here different website and thought I should check things out.
I like what I see so now i’m following you. Look forward to looking over your web
page again.
dark markets 2023 darknet links
anafranil 100 mg
Thank you for the good writeup. It in reality used to be
a leisure account it. Glance advanced to far added agreeable from you!
By the way, how can we keep in touch?
I’m really impressed with your writing skills
as well as with the layout on your blog. Is this a
paid theme or did you modify it yourself? Either way keep up the nice
quality writing, it is rare to see a great blog like this one these days.
Also visit my site :: We Buy Ugly Houses Reviews Bbb
anafranil for anxiety
I am sure this piece of writing has touched all the internet users, its really really pleasant
paragraph on building up new weblog.
It’s pеrfect time to make some plans for the
future and it іs time to be happy. I’ve reɑd thіs post and if I could I want to suggest you few interesting thingѕ оr tips.
Maybe you could write next artiϲles referring to thiks article.
I want to read even mre tbings abouht іt!
Here is my homepage :: wnca
Nice post. I learn something more challenging on different blogs everyday. It will always be stimulating to read content from other writers and practice a little something from their store. I?d prefer to use some with the content on my blog whether you don?t mind. Natually I?ll give you a link on your web blog. Thanks for sharing.
Hi there are using WordPress for your blog platform?
I’m new to the blog world but I’m trying to get started and set up my own. Do you need any html coding knowledge to
make your own blog? Any help would be greatly appreciated!
buy adalat no prescription oral fexofenadine allegra 180mg tablet
avodart cost canada
They can be saved directly to Apple Wallet or Google
Pay Wallet.
Heere is my web bllog 스피드키노
Hi, Neat post. There’s a problem with your web site in internet explorer, would test this?
IE still is the marketplace leader and a good component of people will pass
over your great writing due to this problem.
تایمر آبیاری آکوا
My family members every time say that I am killing my
time here at net, except I know I am getting experience every day by reading such fastidious articles or reviews.
I used to be recommended this blog via my cousin. I am now not positive whether this put up is written by means of him as no one
else recognise such exact approximately my difficulty.
You are wonderful! Thanks!
Medication information. Long-Term Effects.
motrin generics
Best about drugs. Read here.
Howdy! Do you use Twitter? I’d like to follow you if
that would be okay. I’m undoubtedly enjoying your blog and look forward to new posts.
doma-iz-brusa-777.ru
This article reminds me to keep looking and looking for new information and things.
But I don’t understand what the substance of positive thinking itself is like and how to make our thoughts positive. Maybe in another article can explain a little about the meaning of positive thoughts.
visit my webpage https://artdaily.com/raja-slot-gacor-hari-ini.html
Thank you a bunch for sharing this with all people you actually understand what
you are talking about! Bookmarked. Please additionally consult with my web site =).
We may have a hyperlink trade agreement among us
This design is wіcked! You certainly know how to keep a reader amused.
Between your witt and yoiur videos, I was almost moved to start
my ownn bⅼog (well, almost…HaHa!) Wonderful jоb. I really loveԁ what you һad
to say, and more than that, how you presented it. Tooo cool!
Allso vіsit mmy page: moge777win
If you desire to get a good deal from this article then you have to apply
such techniques to your won weblog.
Unleash the invigorating mint freshness with Killa Cold Mint for a revitalizing nicotine experience!
anafranil cheap
Приказ Минтруда РФ от 11.12.2020 № 881н.
Стоит отметить, что в одно время конструкторы пытались заменить ремни на другую систему – подушки безопасности. Но впоследствии оказалось, что от самостоятельного использования подушек толку мало, а вот в сочетании с ремнями они достаточно серьезно повышают безопасность.
С точки зрения ПДД никаких проблем не будет, если устройство соответствует росту и весу ребенка и имеет необходимые документы.
Кроме того, в автомобилях могут применяться вспомогательные системы активной безопасности (ассистенты), задача которых заключается в оказании помощи водителю в сложных с точки зрения вождения ситуациях: парковка, подъем или спуск под большим углом, движение в плотном потоке. Вспомогательные системы в работе активно взаимодействуют с тормозной системой и системой рулевого управления.
84. Транспортные средства, работающие на газовом топливе, должны въезжать на посты ТО после перевода их двигателей на работу на нефтяном топливе.
https://genzer.ru/toplivnaya-sistema/chto-luchshe-dizel-ili-benzin-kakoj-dvigatel-luchshe/
технический регламент о безопасности машин и оборудования (далее – технический регламент);
Нельзя перевозить ребенка в автомобиле на руках! Если есть необходимость покормить или успокоить малыша, то для этого автомобиль необходимо остановить с соблюдением ПДД РФ.
3) струйной вентиляции (см. рис. 1).
1) заправка пожарных автомобилей порошком в помещении гаража при работающем двигателе, соединение вакуумной установки с коммуникациями пожарного автомобиля металлическими трубами или шлангами с металлической спиралью, поскольку при нарушении изоляции проводов личный состав пожарной охраны может быть поражен электрическим током;
140. Ремонтируемые кабины и кузова транспортных средств необходимо устанавливать и закреплять на специальных подставках (козелках, стендах).
Experience the rich and creamy taste of Killa Cappuccino for a delightful nicotine experience!
Heya! I understand this is kind of off-topic but I needed to
ask. Does managing a well-established blog like yours take
a large amount of work? I’m brand new to running a blog but I do write in my
diary everyday. I’d like to start a blog so I can easily share my
own experience and feelings online. Please let me know if you have any recommendations or tips for brand new aspiring blog owners.
Appreciate it!
Do you have a spam issue on this website; I also am a blogger, and I was curious about your situation; many of us have developed some
nice practices and we are looking to trade strategies with other folks, please shoot me an email if
interested.
Today, I went to the beachfront with my
kids. I found a sea shell and gave it to my 4 year old daughter and said “You can hear the ocean if you put this to your ear.”
She put the shell to her ear and screamed. There was a
hermit crab inside and it pinched her ear. She never
wants to go back! LoL I know this is totally off topic but I had
to tell someone!
Experience the unique dual coolness of Killa Double Dutch Cold for a powerful nicotine experience!
Unleash the fresh winter coolness with Killa Frosted Mint for a revitalizing nicotine experience!
Relish the tropical delight of Killa Mango Ice for an exciting nicotine experience!
Thanks in support of sharing such a good opinion, post is good,
thats why i have read it entirely
Enjoy the icy tang of grapes with Killa Grape Ice for a sensational nicotine experience!
Parаgraph writing is alsoo a fun, if you bee familiar
with then ʏou can wrrite oor else it is complіcated
to write.
Look into my web ⲣage :: slot 777 hoki
Delight in the tropical flavor of Killa Pinapple for a unique nicotine experience!
citalopram hbr 10mg
If some one wishes to be updated with latest technologies after
that he must be pay a visit this website and be up to date all the time.
buy nifedipine generic order nifedipine 10mg generic order allegra 120mg
Статья предлагает объективный обзор исследований, проведенных в данной области. Необходимая информация представлена четко и доступно, что позволяет читателю оценить все аспекты рассматриваемой проблемы.
Experience the icy cool freshness with Killa Ice Frosted for a thrilling nicotine experience!
I don’t know if it’s just me or if perhaps everyone else encountering issues with
your website. It appears like some of the
text within your content are running off the screen. Can somebody
else please comment and let me know if this is happening to them as
well? This might be a problem with my internet browser
because I’ve had this happen previously. Thank you
I was recommended this blog by my cousin. I am not sure whether
this post is written by him as nobody else know such
detailed about my difficulty. You’re wonderful! Thanks!
There is definately a great deal to learn about this subject.
I really like all of the points you’ve made.
Meds information leaflet. Effects of Drug Abuse.
nolvadex price
Everything about drugs. Read now.
When I initially commented I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get four e-mails with
the same comment. Is there any way you can remove people from that service?
Appreciate it!