Formatting javadoc in Enums - intellij-idea

I'm looking for a way to set up code formatting to keep javadoc in enums in separate blocks. Right now wrapping of enum members works as intended, but for some reason javadoc comments start/end on the same line as the members
I'd keep getting this:
public enum FormatTest {
FOO, /**
* some description
*/BAR, BAZ;
}
but I want it to look something like this:
public enum FormatTest {
FOO,
/**
* docs either like this
*/
BAR,
/** or like this */
BAZ;
}
It works perfectly well for class members strangely enough...

try changing the Code Style settings.
In IntelliJ, go to: Settings -> Code Style -> Java -> Wrapping and Braces tab.
Scroll down untill you see Enum constants, and change the value to: Wrap always.
See screenshot

Related

How to prevent adding extra empty lines before documented items during code formatting in IDEA/Kotlin?

I am using IntelliJ IDEA for Kotlin and have a nice enum with documented items:
enum class TestEnum {
/** A comment for the item #1. */
ITEM1,
/** A comment for the item #2. */
ITEM2,
/** A comment for the item #3. */
ITEM3
}
It look nice and pretty. But when I use automatic code formatting it make it like this:
enum class TestEnum {
/** A comment for item #1. */
ITEM1,
/** A comment for item #2. */
ITEM2,
/** A comment for item #3. */
ITEM3
}
It an an adds empty line before every comment. If there are a lot of items and especially if it's a nested enum it's starting to look ugly and hard to read. The same this happens with documented properties or methods.
Is there any setting to prevent that?
This behavior was implemented recently in the Kotlin plugin 1.3.70. I created a request to disable it: https://youtrack.jetbrains.com/issue/KT-37420. Please follow this issue for updates.
The workaround is to use an older version of Kotlin plugin (1.3.61).

In Kotlin documentation (KDoc), is it possible to link to a specific overloaded method?

Consider the class comment of this Kotlin class:
/**
* This class has two methods, one that takes one parameters ([foo]),
* and another one that takes two parameters ([foo]).
**/
class Clazz {
/* Foo with one. */
fun foo(a: Int) { }
/* Foo with two. */
fun foo(a: Int, b: Int) { }
}
I'd like the second link to point to the 2nd function ( the one with the two parameters ).
Is this possible in the Kotlin documentation language?
Just found this answer:
Note that KDoc does not have any syntax for resolving overloaded members in links. Since the Kotlin documentation generation tool puts the documentation for all overloads of a function on the same page, identifying a specific overloaded function is not required for the link to work.
From https://kotlinlang.org/docs/reference/kotlin-doc.html
... but I don't really understand the reasoning.
Sounds like this makes sense in the context where docs are read separately from code, but most of the time when I read or use comments it's in the IDE UI.

Intellij - indentation when copying multiple lines

I have a class Foo
public class Foo {
String property1;
int property2;
Object property3;
List<String> property4;
}
Now I would like to copy the names of the properties to class Bar.
public class Bar {
property1
property2
property3
property4
}
Obviously, this code does not compile, but the goal is to call a template to generate some code. When copying valid Java code, there is no problem. Unfortunately, probably because this code does not compile, when copying the selected properties from Foo in a Java source File, the indentation of class Bar is not like this, but:
public class Bar {
property1
property2
property3
property4
}
Is there a way to get those properties in one column in a Java File?
I'm assuming the templates you want to call simply insert the type before a field.
In that case you could:
use F2 to navigate through each error
fill in the type
ctrl+shift+enter ("Complete current statement" action) to add the missing semicolon and properly indent the line
Or you could also:
select the copied property names
unindent them all the way (now they are aligned)
reindent them
I found a solution, which seems to be an improvement over the current way.
It is possible to do a "Paste Simple" in Intellij using Ctrl+Alt+Shift+V. This way, Intellij does no-auto formatting. So when the cursor is at the start of the line, a block is inserted.
After that, it is possible to call the templates and only when having valid Java Code, I can call Ctrl+Alt+L to reformat the code.

OOP - When to Use Properties vs When to Use Return Values

I am designing a process that should be run daily at work, and I've written a class to do the work. It looks something like this:
class LeadReport {
public $posts = array();
public $fields = array();
protected _getPost() {
// get posts of a certain type
// set them to the property $this->posts
}
protected _getFields() {
// use $this->posts to get fields
// set $this->fields
}
protected _writeCsv() {
// use the properties to write a csv
}
protected _sendMail() {
// attach a csv and send it
}
public function main() {
$this->out('Lead Report');
$this->out("Getting Yesterday's Posts...");
$this->_getPosts();
$this->out("Done.");
$this->out("Next, Parsing the Fields...");
$this->_getFields();
$this->out("Done.");
$this->out("Next, Writing the CSVs...");
$this->_writeCsv();
$this->out("Done.");
$this->out("Finally, Sending Mail");
$this->_sendMail();
$this->out('Bye!');
}
}
After showing this code to one of my colleagues, he commented that the _get() methods should have return values, and that the _write() and _sendMail() methods should use those values as parameters.
So, two questions:
1) Which is "correct" in this case (properties or return values)?
2) Is there a general rule or principle that governs when to use properties over when to use return values in object oriented programming?
I think maybe the source of your question comes from the fact that you are not entirely convinced that using properties is better than having public fields. For example here, common practice says that should not have posts and fields as public. You should use the getField method or a Field protected property to regulate access to those fields. Having a protected getField and a public fields doesn't really make sense.
In this case your colleague may be pointing at two things. The fact that you need to use Properties and not public fields and also the fact that it is probably better to pass the post into the method and not have the method access a property if you can. That way you don't have to set a property before calling the method. Think of it as a way of documenting what the method needs for it to operate. In this way another developer doesn't need to know which properties need to be set for the method to work. Everything the method needs should be passed in.
Regarding why we need properties in the first place? why shouldn't you use public fields. Isn't it more convenient? It sure is. The reason we use properties and not public fields is that just like most other concepts in OOP, you want your object to hide its details from the outside world and just project well defined interfaces of its state. Why? Ultimately to hide implementation details and keep internal change to ripple out(Encapsulation). Also, accessing properties has the added benefit of debugging. You can simply set a breakpoint in a property to see when a variable is changed or simply do a check if the variable is of certain value. Instead of littering your code with said check all over the place. There are many more goodies that come with this, returning readonly values, access control, etc.
To sum up, fields are though of as internal state. Properties(actual get/set methods) are though of as methods that interact with internal state. Having an outside object interact with interfaces is smiley face. Having outside class interact with internal state directly is frowny face.

Best practice: ordering of public/protected/private within the class definition?

I am starting a new project from the ground up and want it to be clean / have good coding standards. In what order do the seasoned developers on here like to lay things out within a class?
A : 1) public methods 2) private methods 3) public vars 4) private vars
B : 1) public vars 2) private vars 3) public methods 4) private methods
C : 1) public vars 2) public methods 3) private methods 4)private vars
I generally like to put public static vars at the top, but then would a public static method be listed ahead of your constructor, or should the constructor always be listed first? That sort of thing...
I know it's finnicky but I just wondered: what are best practices for this?
PS: no I don't use Cc#. I know. I'm a luddite.
In Clean Code, Robert C. Martin advises coders to always put member variables at the top of the class (constants first, then private members) and methods should be ordered in such a way so that they read like a story that doesn't cause the reader to need to jump around the code too much. This is a more sensible way to organize code rather than by access modifier.
The best practice is to be consistent.
Personally, I prefer putting public methods first, followed by protected methods, following by private methods. Member data should in general always be private or protected, unless you have a good reason for it not to be so.
My rationale for putting public methods at the top is that it defines the interface for your class, so anyone perusing your header file should be able to see this information immediately.
In general, private and protected members are less important to most people looking at the header file, unless they are considering modifying the internals of the class. Keeping them "out of the way" ensures this information is maintained only on a need to know basis, one of the more important aspects of encapsulation.
Personally I like to have public at top, protected and then private. The reason for this is that when somebody cracks open the header he/she sees what he/she can access first, then more details as he/she scrolls down.
One should not have to look at the implementation details of a class in order to use it, then the class design is not done well.
I think I have a different philosophy on this than most. I prefer to group related items together. I can't stand having to jump around to work with a class. The code should flow and using a rather artificial ordering based on accessibility (public, private, protected etc. ) or instance versus static or member versus property versus function doesn't help keep a nice flow. So if I nave a public method Method that is implemented by private helper methods HelperMethodA, HelperMethodB etc. then rather than have these method far apart from each other in the file, I will keep them close to each other. Similarly, if i have an instance method that is implemented by a static method, I will group these together too.
So my classes often look like this:
class MyClass {
public string Method(int a) {
return HelperMethodA(a) + HelperMethodB(this.SomeStringMember);
}
string HelperMethodA(int a) { // returns some string }
string HelperMethodB(string s) { // returns some string }
public bool Equals(MyClass other) { return MyClass.Equals(this, other); }
public static bool Equals(MyClass left, MyClass right) { // return some bool }
public double SomeCalculation(double x, double y) {
if(x < 0) throw new ArgumentOutOfRangeException("x");
return DoSomeCalculation(x, y);
}
const double aConstant;
const double anotherConstant;
double DoSomeCalculation(double x, double y) {
return Math.Pow(aConstant, x) * Math.Sin(y)
+ this.SomeDoubleMember * anotherConstant;
}
}
This would be my ordering
Static Variables
Static Methods
Public Variables
Protected Variables
Private Variables
Constructors
Public Methods
Protected Methods
Private Methods
I use the following rules:
static before anything
variables before constructors before methods (i consider
constructors to be in the category of
methods)
public before protected before private
The idea is that you define the object (the data), before the behaviours (methods). Statics need to be separated because they aren't really part of the object, nor it's behaviour.
I used to care a lot. Over the last several years using modern IDEs pretty much everything is only 1 or 2 keystrokes away, I've let my standards relax substantially. Now, I start with statics, member variables, then constructors after that I don't worry about it much.
In C# I do let Resharper organize things automatically.
I generally agree with the public, protected, private order as well as the static data, member data, member functions order.
Though I sometimes group like members (getters & setters) I generally prefer listing members within a group ALPHABETICALLY so that they can be located more easily.
I also like lining up the data/functions vertically. I tab/space over to the right enough so that all names are aligned in the same column.
To each his own, and as Elzo says, modern IDEs have made it easier to find members and their modifiers in an easy way with colored icons in drop-down menus and such.
My take is that it is more important for the programmer to know what the class was designed for, and how it can be expected to behave.
So, if it is a Singleton, I put the semantics (static getInstance() class) first.
If it is a concrete factory, I put the getNew() function and the register / initialize functions first.
... and so on. When I say first, I mean soon after the c'tors and d'tor - since they are the default way of instantiating any class.
The functions that follow are then in:
logical call-order (e.g. initialize(), preProcess(), process(), postProcess() ), or
related functions together (like accessors, utilities, manipulators etc),
depending on if the class was meant primarily to be a data-store with some functions, or function provider with a few data members.
Some editors, like Eclipse and its offspring, allow you to reorder in the outline view the the vars and the methods, alphabetically or as in page.
The sequence of public followed by protected and private is more readable to me, It's better to describe the class logic in comments at top of the header file simply and function call orders to understand what a class dose and algorithms used inside.
I am using Qt c++ for a while and see some new sort of keywords like signal and slot I prefer to keep ordering like above and share my idea with you here.
#ifndef TEMPLATE_H
#define TEMPLATE_H
class ClassName
{
Q_OBJECT
Q_PROPERTY(qreal startValue READ startValue WRITE setStartValue)
Q_ENUMS(MyEnum)
public:
enum MyEnum {
Hello = 0x0,
World = 0x1
};
// constructors
explicit ClassName(QObject *parent = Q_NULLPTR);
~ClassName();
// getter and setters of member variables
// public functions (normal & virtual) -> orderby logic
public slots:
signals:
protected:
// protected functions it's rule followed like public functions
private slots:
private:
// methods
// members
};
#endif // TEMPLATE_H