M
M
muzclubs2016-10-30 12:00:37
Java
muzclubs, 2016-10-30 12:00:37

What is the correct way to use operator brackets?

Good afternoon!
I always used operator brackets when working with loops, an if block, regardless of whether several statements were nested inside or not. The programming teacher says that the operator bracket should only be used when there are several operators inside, otherwise it should be written in this form:

if() k=321;
else z = 256;

I've always done this before:
if(){
k=321;
}else{
z = 256;
}

It seems to me that in the latter version, the readability of the code becomes much better.
Can you please tell me which style to follow?

Answer the question

In order to leave comments, you need to log in

7 answer(s)
T
trevoga_su, 2016-10-30
@muzclubs

The programming teacher says that the operator bracket should only be used when there are several operators inside, otherwise it should be written in this form
tell him he's a theoretician.
When you need to add the second condition, the brackets will definitely be needed. This time.
Second, readability is better.
Thirdly, the possibility of errors is excluded.
The presence of brackets does not affect anything, there are no minuses. Only pluses.

P
protven, 2016-10-30
@protven

It's best to use vendor-recommended coding rules
www.oracle.com/technetwork/java/javase/documentati...

A
Alexander Sinitsyn, 2016-10-30
@a_u_sinitsin

The Yii2 documentation recommends

if() k = 321;
else z = 256;

but not
if() 
  k = 321;
else 
  z = 256;

I write myself
if(){

  k = 321;
} else {

  z = 256;
}

It may be overkill, but it's easier for me. An empty line is more striking, you can see where it started, where it ended.

A
aol-nnov, 2016-10-30
@aol-nnov

in descending order of priority:
in my humble opinion, if curly braces can be supplied, they should be.
// and don't forget about code formatting!!1

A
Argumentus, 2016-10-30
@Argumentus

We are required to use this code at work:
if(){
k=321;
}else{
z = 256;
}

M
muzclubs, 2016-10-30
@muzclubs

Thank you all very much for your replies.
Then I will not exclude the use of brackets when working with blocks that have only one operator inside. If the teacher swears, then I will give him a link to the repository.

M
murlogen, 2016-10-30
@murlogen

You are right in an unexpected place.
Your version is potentially less problematic when debugging (when you constantly comment on pieces of code and uncomment them back).
The instructor's option is "kinda easy to read" but may cause unexpected syntax shifts.
I hope you have indents.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question