简体   繁体   中英

Replacing System.err.println in quick debug of short code examples

I have to write short code samples for which using an IDE is overkill; I use Gedit. For debugging purposes, I've been using a quick method dbgm . Some Google search has thrown up similar suggestions:

import java.util.Scanner;

public class Tyle {

public Tyle() {
}

/**
* @param debugmessage
* This method takes any debugmessage and prints the string version
* to System.err.println
*/
private static void dbgm(Object debugmessage) {
    System.err.println(debugmessage.toString());
}

/**
* @param number
*/
public static int cube(int i) {
    int cube;
    cube=i*i*i;
    dbgm(cube); //debug message
    return cube;
}

public static void main(String [] args){
    System.out.print("Enter number: ");
    Scanner s = new Scanner(System.in);
    int inp = s.nextInt();
    Tyle.cube(inp);
    s.close();
}
}

This has its merits, I can search for dbgm , and leave any bona fide System.out.println() calls alone.

But I am not at all sure if using a method like this is good practice, especially when in debug mode. I have been thinking of using something akin to generics, where I provide a type rather than just specify Object (it feels risky) and depend on toString() .

I can use assert in this simplistic example, but there can be much more complex situations during user studies. Such as if number is based on user input. There can also be situations where I am trying to just quickly check that some parameters are giving expected values.

Is there a way to safely write a variant of the dbgm method where I can get the appropriate descriptor, specifically if for example its a custom object? I want to keep reusing the solution to this in a sort of 'production' environment.

Is there a right way?

If the code samples you are writing consists of a single java files, I'll recommend not using a dbmg method, just using System.our/System.err print methods explicitly. Using a custom logging abstraction will probably complicate the sample code with unnecessary details.

However, if:

  • Others are going to use your code sample in other projects.
  • You code sample will eventually end up in production.
  • You code sample is bundled in a project (using multiple files and dependency management).

Then don't reinvent the wheel, use a Logging framework.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM