Commenting methods in java
- The basics of TOGAF certification and some ways to prepare TOGAF offers architects a chance to learn the principles behind implementing an enterprise-grade software architecture, including.
- Haskell vs. PureScript: The difference is complexity Haskell and PureScript each provide their own unique development advantages, so how should developers choose between these two .
- A quick intro to the MACH architecture strategy While not particularly prescriptive, alignment with a MACH architecture strategy can help software teams ensure application .
- Postman API platform will use Akita to tame rogue endpoints Akita’s discovery and observability will feed undocumented APIs into Postman’s design and testing framework to bring them into .
- How to make use of specification-based test techniques Specification-based techniques can play a role in efficient test coverage. Choosing the right techniques can ensure thorough .
- GitHub Copilot Chat aims to replace Googling for devs GitHub’s public beta of Copilot Chat rolls out GPT-4 integration that embeds a chat assistant into Visual Studio, but concerns .
- Navigate multi-cloud billing challenges Keeping track of cloud bills from multiple clouds or accounts can be complex. Learn how to identify multi-cloud billing .
- 5 Google Cloud cost optimization best practices Cost is always a top priority for enterprises. For those considering Google Cloud, or current users, discover these optimization .
- How to create and manage Amazon EBS snapshots via AWS CLI EBS snapshots are an essential part of any data backup and recovery strategy in EC2-based deployments. Become familiar with how .
- BrightTALK @ Black Hat USA 2022 BrightTALK’s virtual experience at Black Hat 2022 included live-streamed conversations with experts and researchers about the .
- The latest from Black Hat USA 2023 Use this guide to Black Hat USA 2023 to keep up on breaking news and trending topics and to read expert insights on one of the .
- API keys: Weaknesses and security best practices API keys are not a replacement for API security. They only offer a first step in authentication — and they require additional .
- AWS Control Tower aims to simplify multi-account management Many organizations struggle to manage their vast collection of AWS accounts, but Control Tower can help. The service automates .
- Break down the Amazon EKS pricing model There are several important variables within the Amazon EKS pricing model. Dig into the numbers to ensure you deploy the service .
- Compare EKS vs. self-managed Kubernetes on AWS AWS users face a choice when deploying Kubernetes: run it themselves on EC2 or let Amazon do the heavy lifting with EKS. See .
Комментарии в Java: не всё так просто
Комментарии — казалось бы, что может быть проще, и чего тут целую статью писать. Но тут не всё так просто. Как говорил мой начальник, код писать может каждый, а вот хороший комментарий написать сложно. Большинство курсов по изучению языка начинаются с традиционного Hello World. Даже в Oracle Tutorials в разделе «Getting Started» мы начинаем с The «Hello World!» Application. И с самых первых строк кода мы видим их — Java комментарии. Их важность также подчёркивается тем, что в таком важном документе, как «Java Code Convention» комментариям отводится отдельный раздел: Comments. Как гласит документация, комментарии в Java делятся на два типа:
- комментарий реализации (или комментарий кода);
- документирующий комментарий.
Комментарии кода используются для описания отдельных строк/блоков, а комментарии для документирования используются, чтобы описать спецификацию кода (его интерфейс), не зависящую от его реализации. Java комментарии игнорируются компилятором, т.к. они несут смысл для разработчика, а не для пользователя. Поэтому можно уменьшить размер компилируемых классов.
Комментарии Java кода
// Строчный комментарий System.out.println("Hello, World!");
/* * Блочный комментарий */ System.out.println("Hello");
Понятно, что нет абсолютной истины, и иногда комментарии необходимы. Но всегда есть варианты, и с излишними комментариями нужно бороться. В этой же главе упоминаются необычные комментарии, TODO:
// TODO: Добавить World System.out.println("Hello, ");
Смысл в них в том, что они могут особым образом обрабатываться в IDE. Например, в IDEA они собираются на отдельной вкладке, где их можно посмотреть:
И небольшой puzzler с комментарием: Строка «http://google.com» является корректной строчкой внутри метода, т.к. http здесь — это на самом деле метка, а дальше — комментарий. Зачастую многие комментарии могут стать из комментариев кода комментарием для документирования, о которых поговорим далее.
Комментарии для документирования
Комментарии для документации описывают общедоступный API. API — это програмный интерфейс приложения, то есть те классы и методы, которые доступны другим разработчикам для выполнения каких-либо действий. Если кратко, то данные комментарии должны пояснять, зачем создан тот или иной класс и пакет и что делает тот или иной метод. Так же можно при необходимости описывать поля класса. Именно то, что оформлено в качестве JavaDoc мы и видим в подсказках наших IDE. Например:
То, как правильно оформлять JavaDoc опять же смотрим в Java Code Convention: Code Convention. Они чем-то похожи на блочные комментарии, но вместо одного астериска (не Астерикса)) используется два. Пример JavaDoc был приведён выше. Описывать все возможности нет смысла, так как об этом уже написано в официальной документации Oracle. Поэтому всё необходимое смотрим в официальной документации по JavaDoc, раздел «Tag Descriptions». У Oracle есть даже отдельный tutorial на эту тему: How to Write Doc Comments for the Javadoc Tool. Подсказки в IDE — хорошо, но на самом деле они не просто так doc. На основе этих JavaDoc комментариев генерируется документация. Для этого есть специальная утилита javadoc. Как мы видим, в том Tutorial об этом и говорится. Описание того, как ей пользоваться, есть на официальном сайте Oracle для JavaDoc. Чтобы увидеть воочию, как это выглядит, можно создать в каталоге подкаталог с названием пакета, например: test. В нём создать простенький класс с комментариями. Например:
package test; /** * This is a JavaDoc class comment */ public class JavaDocTest < /** * This is a JavaDoc public field comment */ public static final String HELLO_MESSAGE = "Hello, World!"; public static void main(String. args) < JavaDocTest.greetings(); >/** * This is a JavaDoc public method comment */ public static void greetings() < System.out.println(HELLO_MESSAGE); >>
После этого можно выполнить следующую команду из каталога, который содержит наш каталог с пакетом: javadoc -d ./test test После этого мы увидим процесс генерации документации.
И после можем открыть index.html, чтобы увидеть сгенерированный документ. Вы часто сможете увидеть, когда выставляют документацию по API. Например, Spring Framework API.
Заключение
Как мы видим, казалось бы, такая простая штука как комментарии на деле оказывается куда сложнее. Поэтому, если комментариям выделить некоторое время и за ними следить, ваш код будет лучше и вы как программист будете ценнее. #Viacheslav
The best way to comment code in Java
What’s the best way to comment code in Java, is there a way to generate the function name and the parameters automatically in Eclipse ? For example I’m writting those comments manually :
//// Some comments about the function // // the user ID // The user password // public Connect(int id, String password)
10 Answers 10
Javadocs can easily be generated in Eclipse. You can type /** and it will autocomplete. You can also configure your code templates to automatically generate javadocs.
Edited the answer. Changed the link, didn’t mean to link to the generator tool but to javadoc documentation in general.
Select the method for which you want comments and press SHIFT , ALT and J together.
Take the time to learn about JavaDoc as well it’s a very rich area for documenting your code.
By convention this is the way to do it:
/** Some comments about the function * * @param id the user ID * @param username The user password * */ public Connect(int id, String password)
If your method returns anything, you would add a `@return’ followed by an explanation.
You IDE and the standard JavaDoc tool will be able to parse this.
what a bad example, your first line is not formatted, you don’t end the comments with «.», you once start with lower case, then you start with UPPERCASE
I personally prefer to use JAutodoc plugin for commenting. Take a look at it. Its good.
Yes, but auto-generated javadoc comments are useless. It is better to use CTRL+ALT+J to add the comment skeletons . and then immediately add the actual comment.
There seems to be some confusion on this thread. The key sequence I use to generate javadoc comments is SHIFT + ALT + J not CTRL ?
The best way is to use JavaDoc and eclipse has built in code templates for doing just that.
If you want to have the format you’ve shown here, then you can write your own templates. The templates functionality will allow you to insert variables, of which one will be the method name.
I’d say that the best way to comment code in java is to provide meaningful names for your methods and variables names 🙂
The best way is to use Javadoc comment format, not the one you shown in the question.
In Eclipse, put your cursor on the method name and press Ctrl + Alt + J . It will generate you a Javadoc comment with all parameters listed.
You can also control the way Javadoc comment is generated in Window -> Preferences -> Java -> Code Style -> Code Templates -> Comments
You need to press CTRL + ALT + J in same time having the cursor on the declaration row.
Please don’t link to LMGT or suggest to other users RTFM, it’s just plain rude and not constructive. meta.stackexchange.com/questions/15650/…
I would suggest to go with the shift+alt+j for Eclipse, and write the description of the function so that other developer can understand what the function can do and also this auto commenting functionality will provide the @param and @return attributes so that you can specify what should be needed and what should be expected in order to execute the function.
/** * @param msg * will return the converted message from the byte[] msg * @return */
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.21.43541
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.