0

I want to add debug message in Java code. I would like to change assert with modern approach

public void registerForRead(SSLChannel l) {
  debug("Error");
  boolean wasNotPresent = readListeners.add(l);
  assert wasNotPresent : "Already registered";
}

If I change the code this way would I preserve the logic?

public void registerForRead(SSLChannel l) {
  debug("Error");
  boolean wasNotPresent = readListeners.add(l);
  if (wasNotPresent) {
    debug("Already registered");
  }
}
2
  • 5
    "change assert to modern approach" - nothing modern about this. Asserts never have and never should be a substitute for logging and vice versa. Commented Jun 13, 2014 at 7:42
  • Better go with the second solutions, assert statements can be turned off by JVM arguments so you cannot relay on them. Use logging to write log files (always!), use if statements to do programming logic and use a debugger to debug. Commented Jun 13, 2014 at 8:15

2 Answers 2

1

assert statement asserts that certain expectations are always met, conflicting which causes AssertionError

So clearly logging isn't a substitute here

Sign up to request clarification or add additional context in comments.

3 Comments

Can you recommend me some better approach for debugging logic?
you can add debugging statement but assert should still preserved if it is coded to guard the fulfilled expectation during runtime
@PeterPenzov Assuming you are using an IDE for your work (e.g. NetBeans, eclipse), I would get to know the debugger...
0

With the information in the question I can only give a few recommendations to improve your logging:

  • Debug("Error"); is not very helpfull at all. You want to be able to activate the debug level and get a clear message of what when wrong and where.

  • Asserts only work if you execute the virtual machine with the -ea argument. (Enable asserts). In production you do not want to crash the app just for just in case check. In development you want to be aware of weird things that shouldn't happen.

  • There is something wrong but I can't see why nor any exception. Make sure you are not reinventing the error handling mechanism. Exceptions are designed for that.

  • Sometimes using the old System.out.println or the logging equivalent may be acceptable for development. However, if you find yourself doing it very frequently it is a symptom of development problems (a.k.a. as bad smell): use good logging traces, unitary tests, etc.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.