r/javahelp • pro barista • Mar 19 '13

Some tips when asking for help

I see a lot of folks asking for help in this sub as well as /r/java. Allow me to give a few words of friendly advice.

Use a concise, descriptive title. What if I titled this post omg u guise! read this! would you read it? Me neither.

Indent all of your code to properly format it. To trigger "code mode", every line must be indented a minimum of 4 spaces. Each level of further nesting should be 2 additional spaces.

This line is indented 4 spaces.
  This line is 6.
    Here is 8.
  Six again.
Now 4.

public class ThisEnsures {
  private final String yourCode = "Looks like this.";
}

If it seems tedious to type 4 spaces at the front of every line, type all of your code into a code editor like eclipse, highlight it and hit tab until you get the 4 spaces you need.

I strongly recommend using 2 spaces additional indent for each level of nesting, but that's a style thing. At least make it readable for us to help you.

Use descriptive variable names. You should be doing this anyway as a matter of writing self-documenting code. But especially if you're posting here for help, your code should be easy to read. This includes your main class name, even if it's the only class in your code sample.

Include all relevant code. It's very difficult to help you if you post something like: Hey guys, I need help with this code snippet, can anyone find the bug?

String foo() {
  funiculate(bar);
  String desc = "I don't even.";
  for (int i = bar; i< 2*bar; i--) { System.out.println(desc); }
}

Where on earth are all these things being referred to defined?

Don't put all your code in your main() method. I see lots of beginners do this, but you should get out of that habit. Also, don't just create a bunch of static methods and variables and have main() call those either.

Instead, take advantage of all that OO has to offer by creating an instance of your application, configure it with IO stuff, and then run it.

public class ExampleApp implements Runnable {
  private final Scanner in;
  private final PrintStream out;
  private final PrintStream err;

  public ExampleApp(InputStream in, PrintStream out, PrintStream err) {
    this.in = new Scanner(in);
    this.out = out;
    this.err = err;
  }

  @Override
  public void run() {
    // write code for your app here
  }

  public static void main(String[] args) {
    new ExampleApp(System.in, System.out, System.err).run();
  }
}

Never, ever repeat code. If in the implementation of your run() method you notice that you are typing the same three lines of code over and over again, make a new private method and call it instead of typing that code over and over again. If that code doesn't require access to any instance state, make it static.

This is a great idea because it allows you to write short, easily understandable methods and give them (and their parameters) good descriptive names. Easy to understand, self-documenting code. This will also help you avoid bugs.

When you get a handful of methods that all seem to be operating on some subset of state, consider encapsulating that state with those methods into a new class. This is great practice for doing real programming, and helps you structure your thinking by clumping problems into high level chunks.

For example, in the example app above, I would consider letting the ExampleApp class create a class that handles all interaction with the user (maybe called UserInterface) and another class that does the actual business logic of whatever problem you're trying to solve, and then coordinate interaction between the two. This way, the flow of data between the user and the code that does the crunching is all encapsulated by the application class, and the code that does the crunching is separate from the code that does the interaction with the user.

Write unit tests before asking for help. If you have a bug, and you've written a lot of small, easy to understand methods, try writing JUnit tests for all those methods that exercise them in basic ways. Use a mocking framework like Mockito or EasyMock (I prefer Mockito) to configure your classes if needed.

You'll be surprised how often you don't need to post your question in the first place.

Good luck!

16 Upvotes

4 comments sorted by

1

u/i_post_things Mar 19 '13

Most exceptions will produce a stack trace. This will contain line numbers (far off to the right) containing all the lines down to the exact method that threw the exception. This will usually give you a start as to where the exception was caused, but it might not tell you exactly why it was caused. A stack trace will often give you a good idea of where to start backtracking from.

Here is an example of a stack trace which shows you from top to bottom. In Eclipse, you can generally click on the line number, and it will automatically take you to the code.

Generally, you don't want to catch NullPointerExceptions, but at times, it may be helpful to temporarily wrap the entirety of the code in a try/catch, and print out the stack trace along with some variable information in the catch portion.

2

u/severoon pro barista Mar 19 '13

If you want to do yourself a favor when it comes to exception handling, validate data when it first arrives in the system and log or otherwise alert the user to invalid data right then. There's nothing worse than storing invalid data in the database only to cause an exception at some random point later, removed in time and space from the actual source of the problem.

Also, learn how to properly use exceptions. They should only be used for exceptional conditions. Only throw unchecked exceptions when the only remedy is a code change, otherwise checked exception.

2

u/blazedaces Mar 19 '13

To add a bit to your post, almost all these things can be easily done with a proper IDE like eclipse (but nearly all of them can refactor):

Badly named variable? No problem, select it and type alt+shift+r (or right click -> refactor -> rename). It will automatically rename the variable everywhere it is referenced (even other classes).

Repeated code? No problem, select it and type alt+shift+m (or right click -> refactor -> extract method). If your code repeats exactly it will replace all instances with that method.

Feel creating JUnit tests too much work? Install moreunit, a plugin that creates and jumps to tests at the click of a button. It will even ask you what mocking framework you may want to use and plop it in for you!

Make your IDE work for you. Programming can be fast and easy.

1

u/[deleted] Mar 20 '13

If it seems tedious to type 4 spaces at the front of every line, type all of your code into a code editor like eclipse, highlight it and hit tab until you get the 4 spaces you need.

Much easier is to just use the RES built in feature, highlight the code you want indented and click the 'Code' link above the input box