Reputation: 1678
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");
}
}
Upvotes: 0
Views: 311
Reputation: 11655
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.
Upvotes: 0
Reputation: 240900
assert statement asserts that certain expectations are always met, conflicting which causes AssertionError
So clearly logging isn't a substitute here
Upvotes: 1