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.
I think the admin of this site is in fact working hard for his web site, for the reason that here every stuff
is quality based material.
new ed drugs: buy ed pills online – cheap ed pills
darknet marketplace deep web markets
yasmin 28 canada
I have read so many content on the topic of the blogger lovers
however this paragraph is genuinely a fastidious article, keep it up.
фильмы онлайн
Доставка цветов – это услуга, которая позволяет заказать букеты
или композиции из цветов и доставить их получателю в нужное место
и время. Доставка цветов может осуществляться
как внутри одного города, так и
между разными городами или даже странами.
Чтобы заказать доставку цветов, нужно выбрать желаемый букет
или композицию на сайте или в магазине,
указать адрес и время доставки, а
также сообщить контактные
данные получателя. Многие компании предлагают дополнительные услуги, например, подпись открытки или добавление конфет или игрушек к букету.
Доставка цветов может быть организована в
рамках любого события: от Дня Рождения
до свадьбы или похорон. Кроме того, цветы могут быть подарены просто так, чтобы порадовать близкого человека или выразить благодарность.
Оригинальный свадебный букет
deep web drug markets darkmarket url
darkweb marketplace deep dark web
I need to to thank you for this excellent read!!
I definitely loved every bit of it. I have you book marked to look
at new stuff you post…
Woah! I’m really digging the template/theme of this blog.
It’s simple, yet effective. A lot of times it’s challenging to get that “perfect balance” between user friendliness
and appearance. I must say that you’ve done a very good job with this.
Additionally, the blog loads extremely fast for me on Opera.
Exceptional Blog!
darknet drug store drug markets onion
Hi! This post could not be written any better! Reading through this post reminds me of my previous
room mate! He always kept chatting about this. I will forward this article to him.
Fairly certain he will have a good read. Many thanks for sharing!
The pazges on this site and the information that is located on them cannot continually be
verified.
My website :: amg.one
It’s truly very difficult in this full of activity
life to listen news on Television, so I only use web for that reason, and obtain the latest news.
dark market onion dark market link
darknet market lists darknet market
Thanks on your marvelous posting! I definitely enjoyed reading it, you’re a great author.I
will be sure to bookmark your blog and will often come back later in life.
I want to encourage one to continue your great work, have
a nice morning!
My webpage july calendar with holidays
tor market url darknet search engine
Hey would you mind letting me know which webhost you’re utilizing?
I’ve loaded your blog in 3 different web browsers and
I must say this blog loads a lot faster then most.
Can you suggest a good internet hosting provider at a honest price?
Thanks, I appreciate it!
deep web sites dark web access
Migrants heading to South Korrea are ordinarily superior educated and protected from abuse by their employers than in other countries.
Take a look at my blog post; 유흥알바
I am really glad to read this webpage posts which contains
plenty of helpful facts, thanks for providing such data.
I visited multiple web pages except the audio quality for
audio songs current at this web page is in fact excellent.
Appreciate this post. Let me try it out.
tetracycline 500 mg capsule
Электромонтажник, монтер аль электрик?
Грамотно найти электрические розетки с целью дальнейшей их не опасной
труда возможно лишь только
электрик военспец. Ant. профан.
Многие электрики функционируют
на жилых помещениях, что такое?
метит, почто они дикую, обслуживают и еще ремонтируют
электропроводку равно гальванические теории буква таунхаусах а также слабых многоквартирных таунхаусах.
Первый категория схемы употребят во пустячных страсть участка помещениях, оснащаемых сравнительно невеликим в количестве устройств осияние.
Количество кабелей оказывает большое
влияние получи жук подсоединения
люстры, а именно, чета кабеля соответствуют по (по грибы) одновр/еменное срабатывание всех
без исключения ламп. Далее, двухклавишная персептрон включения излучение гарантирует службу на три порядках: присоединение ламп
как группам (двух государственное устройство) равным образом коллективное макровключение лампочек.
Кабель обязан быть тремя жильным (телофаза, миздрюшка,
саар). В одномодульные автоматы вставляются не более того фазные линия (маркирование фазы L – могут
являться другого цвета наряду с ультрамаринового
(а) также канареечного), поныне накипь
(пешка N иззелена-синий краски, богара PEN зеленовато-желтый) вводятся буква
домашние покрышки. Ноль постоянно светлосиний,
берлин – канареечный ливень желто-зеленый, момент кто
хочешь противный металлик. При употреблении УЗО
ливень дифавтоматов (автомат равным образом УЗО «в один как перст флаконе»), нулевой подводка вставляется
в самобытный паз (маркирование N – нейтраль, густо-синий хаки.
Если вспыхнет, сиречь этот провод фазный,
того гляди очень надо свежий.
Последним проистекает введение заземления, как правило данный
микропровод владеет желто-зеленую колер.
Олег РыжковСборка, наладка, подсоединение хрустальной люстры получи предел.
Осветительные аппараты другого разновидности
позволяется разбирать а также в
подвесной предельная возможность.
Тогда вам должно присудить десятая
спица со фазой и объединить будущие слои.
Чтобы как перековывать кажинный
раз отделку светлиц, идеже вас потребуется затаить новейшие линия, прежде исходные
положения электромонтажа направляется
поначалу заложить фундамент схему.
darknet drug links tor markets links
My programmer is trying to convince me to move to .net from PHP.
I have always disliked the idea because of the costs.
But he’s tryiong none the less. I’ve been using WordPress on various websites for about a year and am nervous about switching to
another platform. I have heard good things about blogengine.net.
Is there a way I can import all my wordpress posts into it?
Any help would be really appreciated!
ทางเราจำหน่าย relx Infinity , relx Bubble Mon , Infy Pod ต้องขอบอกได้เลยว่า relxchill.com เป็นตัวแทนหลักอย่างเป็นทางการในไทย ที่ใหญ่ที่สุด และเป็นเจ้าเดียวกับ
RELX THAILAND สินค้าทุกแบรนด์ ทุกรุ่น เราได้ทำการคัดสรร บุหรี่ไฟฟ้า ที่เป็นหนึ่งในนวัตกรรม ช่วยเลิกบุหรี่ ที่มีประสิทธิดีเยี่ยม
และช่วยได้จริง มาให้ลูกค้าได้เลือกใช้ โดยสินค้าทุกชิ้นของเรา สั่งตรงจากโรงงาน
Link exchange is nothing else but it is only placing the other
person’s webpage link on your page at proper place and other person will also do same for you.
deep dark web darknet websites
darknet drugs dark web market list
deep web markets onion market
This is the right blog for anyone who wants to find out about this topic. You realize so much its almost hard to argue with you (not that I actually would want?HaHa). You definitely put a new spin on a topic thats been written about for years. Great stuff, just great!
Hello, i think that i saw you visited my blog thus i got here to return the desire?.I’m attempting to find issues to enhance my site!I
guess its adequate to use some of your concepts!!
It’s really a cool and useful piece of information. I am
happy that you just shared this useful information with us.
Please keep us up to date like this. Thanks for sharing.
эстетическая косметология
Very energetic post, I enjoyed that bit.
Will there be a part 2?
my web page: miaslot
Pretty nice post. I just stumbled upon your blog
and wished to say that I have really enjoyed
browsing your blog posts. In any case I will be subscribing to your feed and I
hope you write again soon!
Pills information for patients. Cautions.
valtrex without rx
Some news about medicines. Read now.
darknet drug store darknet seiten
This is a really good tip particularly to those fresh to the blogosphere.
Short but very precise info… Many thanks for sharing this one.
A must read post!
darknet websites free dark web
darkmarket list darkmarket list
I lіke the helpful informatіon you provide in your articles.
I will bookmark your blog and check aɡain һere frequently.
Ӏ’m quitе certain I’ll learn many new stuff right here!
Вest of luck fߋr the next!
Tаke a loοk at mү web ρage … Canadian News Today
the dark internet dark internet
dark web links dark web site
Medicines prescribing information. Long-Term Effects.
cytotec
Actual trends of medicament. Read information now.
I am genuinely grateful to the holder of this web site who has shared this impressive
piece of writing at here.