22

I'm taking another crack at learning Java with the aim of getting a job. As I write code, I sometimes find it quite difficult to navigate my code using the formatting I often see in tutorials. Something I've found that helps me is dividing up chunks of codes with long commented dashed lines (example below).

It really helps but I'm concerned that this is generally against professional best practices or not. I find it visually appealing but will companies or other coders?

//package declaration
package word_builder; // declares the package to be used in testPackage

//----------------------------------------------------------------------------------------------------------------------
//imports
import java.util.Scanner;
//----------------------------------------------------------------------------------------------------------------------
public class rootSuffixCombine{ // creates the rootSuffix class to contain rootSuffix method
//----------------------------------------------------------------------------------------------------------------------
//methods
        public static void rootSuffix(){   // method for combining just a root and a suffix
//----------------------------------------------------------------------------------------------------------------------
            // initial prompt and scanner creation
            System.out.println("Do you want to make a word?");
            Scanner partTaker = new Scanner(System.in);
            String answer = partTaker.nextLine();
//----------------------------------------------------------------------------------------------------------------------
//variable initialization to start loops
            int x = 1;
            int y = 1;
//----------------------------------------------------------------------------------------------------------------------
// outer while loop for taking user input to either continue with program or end it
            while (x == 1){
//----------------------------------------------------------------------------------------------------------------------
// affirmative case (continues program, prints results, then asks if you want to make another)
                if (answer.equalsIgnoreCase("yes")){ // sets answer and ignores case
//----------------------------------------------------------------------------------------------------------------------

                    System.out.print("please input \"root\": ");  // takes the root
                    String root = partTaker.nextLine();
                    System.out.print("please input \"suffix\": ");  // takes the suffix
                    String suffix = partTaker.nextLine();
//----------------------------------------------------------------------------------------------------------------------
// main output
                    System.out.println("The word you created is: " + "\"" + root.concat(suffix) + "\"");
//----------------------------------------------------------------------------------------------------------------------
//resets loop in case user wants to make another word
                    y = 1;
//----------------------------------------------------------------------------------------------------------------------
                    // second while loop for creating more words
                    while (y == 1){
//----------------------------------------------------------------------------------------------------------------------
// prompts for second word
                        System.out.println("Do you want to make another word?");
                        answer = partTaker.nextLine();
//----------------------------------------------------------------------------------------------------------------------
//affirmative case
                        if (answer.equalsIgnoreCase("yes")) {
//ends second loop
                            y = 0;}
//----------------------------------------------------------------------------------------------------------------------
// negative case
                        else if (answer.equalsIgnoreCase("no")) {  //ignores case
// closes second loop
                            break;}
//----------------------------------------------------------------------------------------------------------------------
//handling non-standard answers
                         else{
                            System.out.println("sorry, i dont understand");
//resets loop
                            x = 1;
                            y = 1;}}}
// end of second loop
//----------------------------------------------------------------------------------------------------------------------
// negative case (main loop)
                else if (answer.equalsIgnoreCase("no")) {
                    System.out.println("OK, shutting down.");
                    break;} //ends loop
//----------------------------------------------------------------------------------------------------------------------
// catches non-standard response and repeats initial question until "yes" or "no" is given
                else{
                    System.out.println("I dont understand, try again.");
                    answer = partTaker.nextLine();}}}
//----------------------------------------------------------------------------------------------------------------------
// main, which runs the method(S)
    public static void main(String[] args){
        rootSuffix();}}
//----------------------------------------------------------------------------------------------------------------------
//END

with a semi-long page of code, does this come off as messy?

0

9 Answers 9

92

What you're doing here isn't commenting the code, it's writing documentation with some code snippets in it.

If this was part of a tutorial course to help me understand some new tech stack step by step, yeah that level of commenting can be helpful if it's non-trivial syntax; although generally this would be presented more in a written format with alternating text and code blocks, as opposed to comments in a code file. Regardless of the specific format, this kind of ratio between explanation and actual code would make sense in a tutorial. I'm still not a fan of the horizontal separators but that may be more of a subjective opinion.

For professional real world codebases? This would be a slog to write, a slog to read, and an even bigger slog to have to update and maintain. It explains trivial syntax that a developer should be able to naturally read from the code syntax alone (if they were unable to, I would question their ability as a developer).

Don't take that statement as being harsh on you, you're a learner and not a professionally hired software developer. It's okay for you to use a crutch that helps you while you get familiar with things.

But based on past experience (those of others and my own) I would suggest holding back on suggesting different ways of doing things until you feel comfortable and experienced both in the language and general development methodology. How you think about things is unlikely to be indicative of how an experienced engineer thinks about things.


While this is not the main question, I would be remiss if I didn't point out that your overall logical design is messy, to say the least. Nested while loops are a very complex thing, and variable names like x, y and rootSuffix do not in any way reveal their purpose in the code.

It appears to me like you're trying to cover for bad variable/method naming and an overall unreadable coding style, thereby misdirecting yourself into coming up with some third-party commenting style as opposed to focusing on actually writing more readable code in the first place.

You're clearly putting effort in trying to learn this new thing, which is good, but you've dedicated your effort in an inefficient manner. Don't take this answer as a negative comment on your effort, only on the direction of your effort.

Remove all comments, and look at your code. Rewrite the code, without adding comments, until you feel that it reads easier. Then ask someone else to read it and see if they intuitively understand it or not (that's not just a beginner thing, even senior developers need code reviews in order to have their code checked for readability).

When you get to that later stage, there is a code review StackExchange for that very purpose.

8
  • 11
    This was a wholesome answer. I'm glad to see members that have the sensibility and sensitivity to actively encourage and guide people when learning new things. I think it's a very important thing in a community.
    – dani-vta
    Commented Jun 12 at 15:06
  • 15
    And for a little humor, the only true measure of code quality is WTFs per minute. Commented Jun 12 at 18:51
  • 3
    @TheDarkCanuck: My intuition here is that this paradigm suffers from forgetting the simplicity of examples. Yeah, example code is inherently simple because no one wants to study to be able to understand an example in a blog post; but it's not a realistic rendition of real life complexity. The assertion that you can explain code structure prosaically, which is what literate programming is built on, is easily countered by every developer's experience of trying to explain things to people that make logical sense in their brain but require a roundabout way to express in natural language.
    – Flater
    Commented Jun 13 at 0:50
  • 8
    @TheDarkCanuck The similarities are only superficial. The whole idea of literate programming is to describe the ideas and concepts and NOT technical details in prose. There's literally not a single comment in the whole program that describes a higher level concept or the thought process behind the algorithm. I'd go so far as to say this is about as contrary to literate programming as possible.
    – Voo
    Commented Jun 13 at 9:21
  • 4
    I use x, y, and z for coordinates (and i, j, and k) for loop counters. IMHO all variable names should be meaningful, and these are no exception. There is a message intended to the reader "There is nothing subtle here; these are just coordinates or loop counters." Commented Jun 13 at 18:58
34

There is a proper place for commenting this heavily: when you're writing code that nobody will ever be an expert on and is in an unfamiliar language, or otherwise can't be understood within a reasonable amount of time.

The product I work on has about twenty-five million lines of code. Of that, about ten lines are in x86-32 assembler, and about twenty are in ARM64 assembler. Those are the only assembler code in the product. Both pieces of assembler are about creating error conditions (different ones for those two platforms) that can't be straightforwardly generated from the high level languages used in the product. This is used to test error handlers.

I wrote the x86 assembler, but I haven't needed to change it for about fifteen years. I modified the ARM64 assembler from an example last year, and have not touched it since. I won't be around forever, and nobody else in my team writes assembler. So commenting in great detail is a good idea.

4
  • 7
    I'm not sure why this answer was down-voted. Consider reading some assembly code first, and then reread this answer. On that note, I've often wondered if commenting every line started with less expressive languages, and then it carried over to higher level languages. Commented Jun 13 at 0:50
  • 1
    Note the voter, but I think "code that nobody will ever be an expert on" could use a little clearification. It might need a "and isnt understandable as is"
    – Martijn
    Commented Jun 13 at 13:35
  • 10
    @GregBurghardt My personal guess is that the habit actually comes from code written didactically in classes. It's entirely appropriate for a professor to add a comment that says something like "A for loop can repeat the same code multiple times" in an introductory Comp Sci course. The problem is that the students get in the habit of writing the same kind of comments. It is possible that assembly embedded in some other code (e.g. C/C++) should get similar levels of comments, since the assembly version of a for loop is not going to look like a for loop to most coders.
    – mdfst13
    Commented Jun 13 at 13:57
  • 7
    As someone who has dealt with assembly many times... I am of the opinion that assembly code needs heavy handed commentary With pseudo code that explains how it works and a lengthy explanation before hand that explains the what/why of the assembly code. Because assembly is not human readable. As hard as the code I wrote 3 years ago is to understand (don't know what that imbecile was thinking). The assembly I wrote 3 weeks ago is impenetrable without good comments.
    – Questor
    Commented Jun 13 at 22:26
28

There were several answers speaking to commenting in general. However, you question specifically asks about the dashes pattern.

Dashes are loud. They interrupt any flow you might have had while reading the code Sometimes this is desirable, sometimes it is undesirable. As you get better at reading code, there will be less and less desire to break things up.

They are useful at times. I have worked on several source code files where I found it useful to use a big line of dashes, or two, or three. They corresponded to big semantic changes in the code which wasn't immediately obvious when quickly skimming through a few thousand lines of code with the mouse-wheel. 19 dash-lines out of 80 lines of code is probably more disruptive than you really want.

In the end, I think it's reasonable to treat big lines of dashes LIKE USING ALL CAPS IN AN EMAIL. IT HAS ITS PLACE BUT YOU DON'T WANT TO USE IT ALL THE TIME. Use it sparingly, when it really matters.

1
  • Ah ok, thank you for mostly addressing the dashes aspect. this was literally my first program (and thus my first time using most of the syntax and what not) the "comments" were just there to help me remember vocab more than anything. My fault for choosing a bad example but everybody really focused on the comments instead of the actual dashes. Can’t say I didn’t learn a lot of important hints regardless. Commented Jun 14 at 0:25
11

Step 0 - intro

Comments in code are (generally) a code smell (=small red flag). If you need comments to explain you did something wrong, code needs to read like a story. The same goes for needing dashed lines to seperate code visually.

The entry functions (eg where your code 'starts') should contain very little code and a lot of descriptive functions. Only 'deeper' functions should have the details.

The fact that you needed dashes to get your code 'more' easy to understand is a variant of this code smell.. After step 2 things become more clear, lets work our way to that:


Step 1 - Assessment

I have copied your code and added my own comments what I think as a senior developer. Please read through this first before reading the rest of my answer :) Please read all my added comments.

//package declaration
//## Duh, this is always on top, why does this have docs?
package word_builder; // declares the package to be used in testPackage
//##                      ^^^--- if a name requires a comment, its a bad name

//----------------------------------------------------------------------------------------------------------------------
//## this line above is a waste of space
//imports
import java.util.Scanner;
//----------------------------------------------------------------------------------------------------------------------
//## this line above is a waste of space
public class rootSuffixCombine{ // creates the rootSuffix class to contain rootSuffix method
//                                  ^-- If you dont know what a class declaration is, please quit
//----------------------------------------------------------------------------------------------------------------------
//## this line above is a waste of space
//methods
        public static void rootSuffix(){   // method for combining just a root and a suffix
//                                             ^-- If you dont know what a method is, please quit
//----------------------------------------------------------------------------------------------------------------------
//## this line above is a waste of space
            // initial prompt and scanner creation
            //## Yes, I can see that? Why did you make my read that line?
            System.out.println("Do you want to make a word?");
            Scanner partTaker = new Scanner(System.in);
            String answer = partTaker.nextLine();
//----------------------------------------------------------------------------------------------------------------------
//## this line above is a waste of space
//variable initialization to start loops
//## Yes, I can see that? Why did you make my read that line? 
            int x = 1;
            int y = 1;
//----------------------------------------------------------------------------------------------------------------------
//## this line above is a waste of space
// outer while loop for taking user input to either continue with program or end it
            while (x == 1){
//----------------------------------------------------------------------------------------------------------------------
//## this line above is a waste of space
// affirmative case (continues program, prints results, then asks if you want to make another)
                if (answer.equalsIgnoreCase("yes")){ // sets answer and ignores case
//----------------------------------------------------------------------------------------------------------------------
//## this line above is a waste of space

                    System.out.print("please input \"root\": ");  // takes the root
//##                                                                  ^^-- Yes, I can see that? Why did you make my read that line? 
//##                                                                  ^^-- also: No it doesnt, it prints
                    String root = partTaker.nextLine();
                    System.out.print("please input \"suffix\": ");  // takes the suffix
//##                                                                   ^^-- Yes, I can see that? Why did you make my read that line? 
//##                                                                   ^^-- also: No it doesnt, it prints                    String suffix = partTaker.nextLine();
//----------------------------------------------------------------------------------------------------------------------
//## this line above is a waste of space
// main output
                    System.out.println("The word you created is: " + "\"" + root.concat(suffix) + "\"");
//----------------------------------------------------------------------------------------------------------------------
//## this line above is a waste of space
//resets loop in case user wants to make another word

// ##############################
// ##############################
// ## I HAVE NOW SPEND ALL MY FOCUS TRYING TO UNDERSTAND, from now on my review would be less proper.
// ##############################
// ##############################
                    y = 1;
//----------------------------------------------------------------------------------------------------------------------
//## this line above is a waste of space
                    // second while loop for creating more words
                    while (y == 1){
//----------------------------------------------------------------------------------------------------------------------
//## this line above is a waste of space
// prompts for second word
                        System.out.println("Do you want to make another word?");
                        answer = partTaker.nextLine();
//----------------------------------------------------------------------------------------------------------------------
//## this line above is a waste of space
//affirmative case
                        if (answer.equalsIgnoreCase("yes")) {
//ends second loop
                            y = 0;}
//----------------------------------------------------------------------------------------------------------------------
//## this line above is a waste of space
// negative case
                        else if (answer.equalsIgnoreCase("no")) {  //ignores case
// closes second loop
                            break;}
//----------------------------------------------------------------------------------------------------------------------
//## this line above is a waste of space
//handling non-standard answers
                         else{
                            System.out.println("sorry, i dont understand");
//resets loop
                            x = 1;
                            y = 1;}}}
// end of second loop
//----------------------------------------------------------------------------------------------------------------------
//## this line above is a waste of space
// negative case (main loop)
                else if (answer.equalsIgnoreCase("no")) {
                    System.out.println("OK, shutting down.");
                    break;} //ends loop
//----------------------------------------------------------------------------------------------------------------------
//## this line above is a waste of space
// catches non-standard response and repeats initial question until "yes" or "no" is given
                else{
                    System.out.println("I dont understand, try again.");
                    answer = partTaker.nextLine();}}}
//----------------------------------------------------------------------------------------------------------------------
//## this line above is a waste of space
// main, which runs the method(S)
    public static void main(String[] args){
        rootSuffix();}}
//----------------------------------------------------------------------------------------------------------------------
//## this line above is a waste of space
//END

If you read all my comments (until I didnt wanted to add anymore), you have read a lot, but didnt really get any wiser and it probally was a chore (at least I hope so, I'm trying to prove a point). You just wasted a lot of mental compute and you havent even got to the detail of the code yet.

Note: This is how your comments feel to us (more experienced users)


Step 2 - Remove clogging

Often less is more in coding. You dont always want a lot of info, you want to understand the code quickly. Now the same code, no comments:

package word_builder;

import java.util.Scanner;

public class rootSuffixCombine
{
    public static void rootSuffix(){
        System.out.println("Do you want to make a word?");
        Scanner partTaker = new Scanner(System.in);
        String answer = partTaker.nextLine();
        int x = 1;
        int y = 1;
        while (x == 1){
            if (answer.equalsIgnoreCase("yes")) {
                System.out.print("please input \"root\": ");
                String root = partTaker.nextLine();
                System.out.print("please input \"suffix\": ");
                System.out.println("The word you created is: " + "\"" + root.concat(suffix) + "\"");
                y = 1;
                while (y == 1){
                    System.out.println("Do you want to make another word?");
                    answer = partTaker.nextLine();
                    if (answer.equalsIgnoreCase("yes")) {
                        y = 0;
                    }
                    else if (answer.equalsIgnoreCase("no")) {
                        break;
                    }
                     else{
                        System.out.println("sorry, i dont understand");
                        x = 1;
                        y = 1;
                    }
                }
            }
            else if (answer.equalsIgnoreCase("no")) {
                System.out.println("OK, shutting down.");
                break;
            }
            else{
                System.out.println("I dont understand, try again.");
                answer = partTaker.nextLine();
            }
        }
    }

    public static void main(String[] args){
        rootSuffix();
    }
}

This is a lot smaller! A lot less data to parse, now I actually see what is going on. And now I can see what the real issue is: Code format/styling/single responsibility!
You correctly identified an issue, but solved it incorrectly. What I mean is that your code is not very easy to read. You applied the comments-solution to remedy that, but that wasnt the correct solution.


Step 3 - Move code to dedicated methods

Apply Single responsibility. Well, a part of it. A function should only have one task. Thats a bit of a broad description, but another aproach is "one reason for change". Or a rule I like to use is: Describe what this is doing and if you say 'AND', its wrong.

Also, you are repeating yourself! Everything exists twice?! You added code to prevent issues, but that created a mayor factor for issues: Duplicate code. The follow code does (about) the same as yours!

package word_builder;

import java.util.Scanner;

public class rootSuffixCombine
{
    public static void rootSuffix(){
        Scanner partTaker = new Scanner(System.in);

        while(askIfWantsWord(partTaker)){
            askWord(partTaker)
        }
    }

    private Boolean askIfWantsWord(Scanner partTaker){
        System.out.println("Do you want to make a word?");
        String answer = partTaker.nextLine();

        while(true){
            if (answer.equalsIgnoreCase("yes")) {
                return true;
            else if (answer.equalsIgnoreCase("no")) {
                System.out.println("OK, shutting down.");
                return false;
            }
            else{
                System.out.println("I dont understand, try again.");
                answer = partTaker.nextLine();
            }
        }
    }

    private Boolean askWord(Scanner partTaker){
        System.out.print("please input \"root\": ");
        String root = partTaker.nextLine();
        System.out.print("please input \"suffix\": ");
        System.out.println("The word you created is: " + "\"" + root.concat(suffix) + "\"");
    }

    public static void main(String[] args){
        rootSuffix();
    }
}

Please note that I'm not a Java programmer, I might be off a bit.

The mayor improvement is the rootSuffix method. Its short and super easy to understand. You dont know HOW it works, but you do instantly know what is going on. In 2sec you understand what this does, instead of 2minutes of your code. I dont care about the details at first. I only want details if I care. If I want to know how we ask for a word I only need to check that code then.


Step 4 - Distill more repeated code

There is still a lot of duplicate code: The print-question+partTaker. Distill that into an own method and turn the if/elseif/else into a case:

package word_builder;

import java.util.Scanner;

public class rootSuffixCombine
{
    public static void rootSuffix(){
        Scanner partTaker = new Scanner(System.in);

        while(askIfWantsWord(partTaker)){
            askWord(partTaker)
        }
    }

    private Boolean askIfWantsWord(Scanner partTaker){
        String answer = getAnswerForQuestion("Do you want to make a word?");

        while(true){
            switch (answer.toLowerCase()) {
                case "yes" -> return true;
                case "no" -> return false;
                default -> answer = getAnswerForQuestion("I dont understand, do you want to make a word?");
            };
        }
    }

    private Boolean askWord(Scanner partTaker){
        String root = getAnswerForQuestion("please input \"root\": ");
        String suffix = getAnswerForQuestion("please input \"suffix\": ");

        System.out.println("The word you created is: " + "\"" + root.concat(suffix) + "\"");
    }

    private String getAnswerForQuestion(String question){
        System.out.print(question);
        
        return partTaker.nextLine();
    }

    public static void main(String[] args){
        rootSuffix();
    }
}

This last version reads a lot easier. Each function is easily understandable. You dont need comments because the code now speaks for itself. You dont need to always know the details, only when you care.
Bonus: This now has an easy way to add 'y/n' als legit answer too


Note: The steps above are done a bit...crude, I could've done a better job naming and thinking about it (but its just a quick review for now). I've tried to show an example, but the actual theory generally is a bit more nuanced. You should consider this as a introduction.

This final result might be a bit intimidating, but that is mostly (likely) because this is new to you. This way of programming becomes normal very easily with some practice and from that point on this will read a lot faster than any comment could.

3
  • 3
    i really appreciate this, but my question was mostly about the dashes. the "comments" were just reminders for myself since at the time that was literally my first time typing anything in java, so the vocab, syntax...etc was all completely new to me. still, i learned a lot of tangential stuff from this answer and will take it to heart. Commented Jun 14 at 0:32
  • 1
    @KanagawaPunk I think the beginning of this answer addresses your question and I'm glad you got more from this answer. As a pro of over 25 years, I can tell you that your original code is completely unreadable (sorry). If I was doing a code review, I'd search-and-replace out all the horizontal line comments (maybe all the comments) before going further. The code in step 4, is approximately what I would pass at code review and it contains exactly zero lines of comments. Commented Jun 14 at 19:47
  • @KanagawaPunk I've rephrazed it a bit to focus it a tiny bit more towards your question :) I answered a bit more broadly, but the conclusion is the same for both aproaches
    – Martijn
    Commented Jun 15 at 11:10
9

So, first, I'd agree with others that your example is totally over the top... comments that just re-state what's already obvious (e.g. that class MyClass creates a class called MyClass), and you have so many of those visual dividers that it just becomes clutter, making things harder to read. Bad comments are much worse than not having comments at all.

However, tone it down a bit, and this kind of visual separation can be useful. It's generally better to avoid large methods that do many things, but when it happens anyway, providing some visual structure can make it more manageable. Since any IDE will render comments in a different colour, having a blank line and a single short comment at the top of a block of code can help the eye spot the logical sections.

That said, in your example, I can't see any comments that I'd bother to keep, except maybe the "catches non-standard response" one.

5
  • 5
    "Since any IDE will render comments in a different colour, having a blank line and a single short comment at the top of a block of code can help the eye spot the logical sections." So would whitespace, and that would be easier to write, maintain, and navigate by cursor.
    – Flater
    Commented Jun 13 at 4:26
  • 1
    @Flater "So would whitespace" - well, yes, that's why I explicitly said "a blank line and a short comment". Providing visual cues - including both whitespace and comments - is a useful technique for improving code readability, even if the question is a terrible example of how to do that correctly. Commented Jun 14 at 0:31
  • As an example, I typically separate sections of code in my file with 5 lines. In order: a blank line, a comment line with no text, a comment line with the section title, a comment line with no text, and another blank line. This is lightweight to maintain, and pops out sufficiently in the file outline in the IDE to quickly jump from section to section. Commented Jun 15 at 10:36
  • @MatthieuM. That's a bit too much whitespace for my taste - in general I wouldn't want more than one blank line and one comment - but not unreasonable. Commented Jun 16 at 20:41
  • @SimonGeard: I think it depends what you're commenting for. As I mentioned I use those 5 lines as "section separators", and my files typically have only one such separator (between the public section first, and the implementation section second), so 5 lines is fine... and really helps pinpointing it in the outline. For doc comments on methods, I don't "waste" lines. Commented Jun 17 at 7:48
5

Specific to using lines of dashes to offset sections: this is not inherently bad, if used appropriately, and actually it used to be quite common...but modern programming tools and styles mean there are fewer times when it is appropriate.

For example, it used to be not unusual to come across a file that had a large section of constants being declared in one place, offset with some marker like dashes so that you could quickly scroll past the boring section and find the next interesting section. (It might also be marked with something like # START XYZ CONSTANTS and end with # END XYZ CONSTANTS so you could use find-replace to go past.)

Or any other long section that was internally cohesive but distinct from the surrounding code.

But it would be rare to find those situations in modern production code. A section of constants would be externalized into a separate file and a chunk of discrete code would be moved into its own block that can be collapsed by a modern IDE, so there simply wouldn't be a need for comments that separated these sections.

4

Should you do this in a professional context? No.

But it's interesting to think about why you think this is more appealing.

I suspect the reason you are doing this is because you are new to coding and you haven't trained your eyes to look for visual landmarks in the language. So you've constructed one that you put in manually.

I noticed out of the 11 / 19 or so places you've opted to put this line there is a brace nearby: enter image description here

Give each brace its own line and it becomes more obvious. This is called the "allman" style. Some people like this for precisely the reason you added those dashes. My recommendation for you is to use the elements of the language itself as visual landmarks instead of adding things in via comments. But really, this will happen naturally over time anyway so don't worry about it too much.

In the short term, try removing dashed lines for all places where that same "division" could be demarcated by a brace and see how that works for a while. enter image description here

Looking at the remaining 5 or so places where you've opted to put a separation line. 2 are marking out the imports and the last 3 are actually places where there are no natural separation built into the language. In both cases you can opt to use a newline to separate those chunks. Instead of this: enter image description here

The newline itself is the demarcator: enter image description here

1
  • 1
    Some great suggestions here. Regarding newlines, an analogy that's often in my head is how we break down long pieces of text into paragraphs.
    – IMSoP
    Commented Jun 15 at 13:03
3

Others have given lots of good advice. Here's a few more points, which I hope may prove helpful on your journey.

  1. Learn to use language features. It seems to me that you have the abstraction of an Answer. I would make it into a class of its own (in Java, everything is a class), hide the implementation details (case insensitive string, etc), and have two methods isYes() and isValid(). IsYes should be called only if you have tested isValid(). What else can you encapsulate?

  2. I don't trust code unless I can see it. If I write a method that is long enough to occupy more than one page, I try to split it into smaller functions, so I can read and test each sub-function, and can try to convince myself that the whole will work if the parts do. If I can't understand it without comments, then it is too complicated to understand with (possibly lying) comments.

  3. Comments should never answer the questions "what/how?": they should answer "why?", e.g. "why would I want to use the Answer class", "why would I call isYes()?". If you need to explain what your code does, or how it does it, rewrite the code. I try to write strategic comments, which go at the head of a class or method.

  4. Comments often lie. If you write some code such as x = x/3, then a comment "divide x by 3", you need to change the comment if you ever change the code. Often people forget, and we have a lying comment.

  5. Avoid naked floats, double, strings, ints (except for the odd loop counter). Instead encapsulate them, and put any constraints and assumptions into the class.

  6. Try to find examples of Java code written by masters: I learned a lot from reading Robert Martin, Martin Fowler, and Kent Beck. (Be careful, though, as some of them have rewritten their books in other programming languages). If you can lay hands on Martin Fowler's refactoring (First edition, I think the new addition uses Javascript rather than Java), you will find the book organized around Code Smells (i.e. bad stuff) and how to make the code less smelly.

  7. I assume that you have done some research and convinced yourself that Java is what you need for the job market. (Disclaimer: I learned Java during the 1990s, when it was the Next Big Thing, and used it for about 20 years; in the past 8 years I have done everything using other languages).

  8. Are you using a decent IDE? I recommend getting used to Eclipse, and learn how to write JUnit tests.

4
  • 2
    Why -1 though? Would certainly help to know which item is "wrong" in someones opinion ..
    – Kromster
    Commented Jun 13 at 13:12
  • 3
    While this answer is correct, I dont think its a fit for this TS. (i.e. beginner) These are correct answers, but for a intermediate+ level
    – Martijn
    Commented Jun 13 at 13:41
  • 1
    thanks for all the tips and resources! it was a bad decision to use that code as my example since it was literally my first time typing anything in java, so i "commented" to remind me of basic things and vocab.it was simply the first one i could find that had the dashes in it. Commented Jun 14 at 0:39
  • 1
    @KanagawaPunk Good luck on your journey. Please remember that there are plenty of people who will help if you have questions. Commented Jun 14 at 1:20
2

In almost all cases, using long lines of dashes to break up code is not helpful. Most IDEs have features that help you collapse code when you need to, a simple double line break would have achieved the same aim and been less invasive.

  • I find a simple blank line between conceptual block of logic is enough to make the reader understand the transition between concepts. You might put a single line comment as a header to that region of code if it is needed.

I would like to address this comment though:

I sometimes find it quite difficult to navigate my code using the formatting I often see in tutorials

This is a red flag, it suggests that either the tutorials you are reading are using bad conventions or you do not yet know how to read the code at all. If your issue is that you cannot read the code, then the first time you can do whatever you need to make your code understandable to you, but the goal for you is to learn how to read code and understand the logic.

If instead by tutorials you simply mean code examples that you found online, perhaps you should stick to formal tutorials or curated lessons that do have a lot more documentation within the code, you need to learn good habits by immersing yourself within good code examples.

Not the answer you're looking for? Browse other questions tagged or ask your own question.