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.

32.428 Comments on “Eclipse – Formatter e Save Action

  1. And also, it’s easy to replace images to keep them on motif with the room’s ever-changing layout. This home design pattern is all about using items in brand-new, interesting and also unusual means. If you have a matching bedroom collection, think of relocating some of the items to the visitor area, dining room, or entrance. This look embraces organic products such as wool, cotton, silk, rattan and also clay in earth tones and warm neutrals. The days of using one metal finish everywhere in the house are gone. Rather, it’s currently really common to blend and also match steel coatings– not only in the kitchen and bathroom– yet throughout the home on surface areas like doorknobs, drape rods, lights, hinges, as well as much more.

    Choose top quality throws, paddings, and carpets that match the area. The very best means to make a place show up even more extravagant is to utilize tones that enhance each other. Choosing 2 shades as well as their differing tones will certainly guarantee this. For dependable color use, adhere to shades of black, white, or gray. This year is about making your residence really feel even more like your individual design with top notch items. The focus of this trend gets on top quality, much like our equipment.
    Contemporary Art Gallery Living Area
    Prior to signing up with GH in 2020, she was the digital editor at Elle Style. In her existing role, she discovers every little thing from style patterns as well as home trips to lifestyle product suggestions, including writing her regular monthly column, “What’s in My Cart.” This New York City apartment, crafted by Kati Curtis Layout, includes a tray ceiling that magnificently highlights the Sputnik world chandelier and also includes depth to the format. What’s more, the mix of light and dark hues produce a striking 3D effect. The luxe appearance isn’t concerning glam, glossy, mirrored, or glitzy spaces.

    What color of furniture is in for 2023? As we have actually talked about, natural materials such as wood, as well as natural, grounding color combinations with a concentrate on green, brownish and also cream tones will certainly be prominent throughout 2023, helping to establish a relaxing, and tranquil ambience.

    Similar to our very own individualities and quirks, work with awkward living-room designs and also not against them, to develop an unique room that doesn’t look like everyone else’s blueprint develop. And also if you’re looking to market your residential property, make your niche suggestions and recesses really shine by making them a statement attribute in your front room. These living room design concepts make sure to influence, and even if you do not replicate the room like-for-like, there’s something you can select as well as play regarding with as component of your next job. One easy method to change the appearance of your living-room is to go about enhancing it with interesting textiles through colorful vintage carpetings, area rugs, toss cushions, pillows, and also much more. As well as there’s no need to invest thousands of dollars on nice-looking textiles. Comb flea markets as well as vintage shops as well as see if you can resource an antique Turkish carpet cost a bargain or previously owned vintage carpets that are still in excellent condition.
    See All Exterior As Well As Garden Furnishings
    The use of a mural likewise broadens the room as it stops an expanse of the white wall making the room really feel blocky. If you want living space concepts that are instantaneously going to add something various to your area, choosing a couple of shades to repeat together is a terrific location to begin. Include texture underfoot, whilst zoning a seating area or relaxation edge with one of the very best carpet layouts that unites your scheme with an accent color. As revealed right here, try layering a smaller sized patterned design over a bigger all-natural distinctive carpet for an included layer of tactility. Add a sense of simple dramatization with a range of lighting fixtures and also candles that provide a space differing tones of light for the utmost in lavish living-room design concepts.

    Not just does this woven setup add some personality to this large area, but the variety of reflective rooms additionally helps bounce the light around ideal. ” Although recessed illumination is definitely not going anywhere, I assume that lights– even equally as ornamental pieces a lot more so than for illumination– will certainly be included right into property spaces,” she says. This area not just fills up on sofas at flooring degree but the interior designer has born in mind the upper quarters of the room also.

    Remember 80s decorating? Iconic 1980s interior designs and home accessories loveproperty.com – lovePROPERTY Remember 80s decorating? Iconic 1980s interior designs and home accessories loveproperty.com.

    A gleaming surface or a massive size can offer a high-style focus in the area. Select elevated drapes that are more comprehensive than your window to attain a lavish appearance. Mint & pink– For a suppressed combination with a calming result, pink and mint eco-friendly are ideal. Marian Parsons is the woman behind the well-known blog site and also social media brand Miss Mustard Seed. Marian and also her family members remain in the middle of a full renovation of their recently-purchased house as well as selected to mount glamorous brass hardware from Grandeur Hardware. A space by Timothy Corrigan blends materials like metal, timber, and also velour.
    Like Style & Interior Design? Follow Us
    Otherwise, it may make your living-room appearance chaotic, which totally defeats the function of developing a luxurious living-room interior decoration. For instance, you can integrate the soft qualities of velvet furniture with the grainy natural structure of a wood coffee table. By playing appearances off of each other, you’ll function to produce a sensation of deepness in your interior decoration that stimulates a brilliantly edited, varied mix. For example, modern minimalist design commonly integrates tidy lines, neutrals, and also black components; while maximalist design prefers split appearances, color, and also classic items. Nonetheless, we see both design perspectives accepting the use of all-natural materials, such as timber, stone, woollen, linen, and rattan, as well as numerous other trends on this listing. Before we enter the interior design patterns for 2023, as constantly, I recommend embellishing your home in a way that makes you feel excellent.

  2. Wonderful blog! Do you have any tips and hints for aspiring writers?
    I’m planning to start my own blog soon but I’m a little lost on everything.
    Would you suggest starting with a free platform
    like WordPress or go for a paid option? There are so many
    choices out there that I’m completely overwhelmed ..
    Any ideas? Cheers!

  3. The other day, while I was at work, my sister stole
    my iPad and tested to see if it can survive a 25 foot drop,
    just so she can be a youtube sensation. My apple ipad is
    now destroyed and she has 83 views. I know this is
    entirely off topic but I had to share it with someone!

  4. На сайте https://mihub.ru/ вы сможете ознакомиться с новостями, посвященными таким популярным брендам, как Redmi, Xiaomi, MIUI. Здесь регулярно выкладывают анонсы, обзоры, а также инновационные технологии, различные обновления. При необходимости вы сможете сравнить те гаджеты, которые вызвали у вас интерес. Это позволит лучше понять функциональные особенности и многое другое. Все новости сопровождаются интересной, красочной картинкой, которая позволит в полной мере понять данную тему.

  5. Heya i’m for the first time here. I came across this board and I to find It really helpful & it helped me out much.
    I’m hoping to present something again and help others such as you helped me.

  6. Heya i am for the primary time here. I found this board and
    I in finding It truly helpful & it helped me out much.
    I hope to give something back and aid others
    such as you aided me.

  7. Hey there! I know this is kinda off topic but I was wondering which blog platform are you
    using for this website? I’m getting tired
    of WordPress because I’ve had problems with
    hackers and I’m looking at alternatives for another platform.
    I would be fantastic if you could point me in the direction of a good platform.

  8. We’re a group of volunteers and starting a
    brand new scheme in our community. Your web site offered us with
    valuable info to work on. You’ve done an impressive task and our
    whole neighborhood can be grateful to you.

  9. Hey I know this is off topic but I was wondering if you knew of
    any widgets I could add to my blog that automatically tweet my newest
    twitter updates. I’ve been looking for a plug-in like this for quite some time
    and was hoping maybe you would have some experience with something like this.
    Please let me know if you run into anything. I truly enjoy reading your
    blog and I look forward to your new updates.

  10. You really make it seem so easy with your presentation but I find this topic to be really something
    which I think I would never understand. It seems too complex and very broad
    for me. I am looking forward for your next post, I will try to
    get the hang of it!

  11. Excellent beat ! I would like to apprentice while you amend your web site, how could i subscribe for a blog
    web site? The account helped me a acceptable deal. I had
    been a little bit acquainted of this your broadcast offered bright clear idea

  12. I pay a quick visit every day a few web sites and blogs to read articles or reviews, however this blog provides feature based content.

  13. Great blog here! Also your website a lot up very fast!
    What host are you the use of? Can I get your associate
    hyperlink to your host? I desire my website loaded up
    as quickly as yours lol

  14. Have you ever thought about including a little bit more than just your
    articles? I mean, what you say is valuable and all.
    However think about if you added some great graphics or videos
    to give your posts more, “pop”! Your content is excellent but
    with pics and clips, this site could certainly be one of the
    greatest in its field. Good blog!

  15. Its like you read my mind! You appear to know a lot about this,
    like you wrote the book in it or something. I think that you can do with some pics to drive the
    message home a little bit, but instead of that, this is excellent blog.

    A great read. I’ll certainly be back.

    my site jdb

  16. You actually make it seem really easy with your presentation but
    I to find this topic to be actually something that I believe I’d by no means understand.
    It sort of feels too complex and very broad for me.
    I am looking ahead in your next put up, I’ll attempt to get the dangle of it!

  17. For latest news you have to visit world-wide-web and on the web I found this website as
    a most excellent site for most up-to-date updates.

  18. Thanks , I have recently been looking for info approximately this topic for a long time and yours
    is the best I have came upon so far. However, what concerning the bottom line?
    Are you certain in regards to the supply?

  19. Good day! I know this is kind of off topic but I was wondering if you knew where I could get a captcha
    plugin for my comment form? I’m using the same blog platform as yours and I’m having trouble
    finding one? Thanks a lot!

  20. I would like to thank you for the efforts you’ve put in writing this site.
    I am hoping to check out the same high-grade content from you in the future as well.
    In truth, your creative writing abilities has encouraged me to
    get my very own blog now 😉

Deixe um comentário

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *

*

Esse site utiliza o Akismet para reduzir spam. Aprenda como seus dados de comentários são processados.