简体   繁体   中英

Understanding when to use Object as return type

Please consider the following piece of code. I am trying to understand the need of Object return type. May be I haven't understood properly when should we actually be using return type as Object in a method, I was going through the following code and as you can see, the AdNewCpp method is called inside doGet method and the return type of AdNewCpp method has been defined as Object . I am wondering if there can be something else that can be used in place of Object as the return type?

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.setContentType("text/html;charset=UTF-8");
        // Allocate a output writer to write the response message into the network socket
        PrintWriter out = response.getWriter();

        // Use ResourceBundle to keep localized string in "LocalStrings_xx.properties"

        // Write the response message, in an HTML page
        try {
            out.println("<!DOCTYPE html");  // HTML 5
            out.println("<html><head>");
            out.println("<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>");

            out.println(AddNewCpp("cpp test - new"));

            out.println("<head><title>Test API</title></head>");
            out.println("<body>");
            out.println("<h3>TestAPI</h3>");

            // Tabulate the request information 
            out.println("</body></html>");
        }   
        finally {
            out.close();  // Always close the output writer
        }
    }

    public static Object AddNewCpp(String cppDesc) throws IOException {
        String accessKey = "DNN7ACCESSKEYEXAMPLE";
        String secretKey = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY";
        String uRLCppList = "http://something.com/abc";
        String method = "POST";
        java.util.Date currentTime = new java.util.Date();
        SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");

        // Give it to me in GMT time.
        sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
        String dateTimeString = sdf.format(currentTime);

        String signature = generateSignature(method, secretKey, dateTimeString);
        String authorization = accessKey + ":" + signature;
        Map<String, String> params = new HashMap<String, String>();
        params.put("cppListDesc", cppDesc);

        String[] result = sendHttpRequest(uRLCppList, "POST", params, dateTimeString, authorization);

        return result;
    }

You can return String [] as you are actually returning the String Array from your AddNewCpp method

public static String[] addNewCpp(String cppDesc) throws IOException{
                               /\    
                               ||
            //Method Name Should be in camelCase(good Practice)
 String[] result = sendHttpRequest(uRLCppList, "POST", params, dateTimeString, authorization);
 return result;
}

Well, you are returning a String array in any case, at least here, so you could replace the Object with String[] , which wouldn't change much, especially as the out.println will not present a very readable result anyway.

You are using an Object as a return code if you know of no more specific types to use. But of course, this means, that the method using that return code has to be prepared to cope with anything. In your example, this is done by implicitly calling toString() (by out.println ), which every Object has. In many other cases, you would have to do many instanceof checks to see, what the Object actually is.

Personally, I would try to avoid it, as it makes code inherently surprising: Just be reading the method signature you do not know what to expect as result, you would have to read the method itself or worse, the documentation.

In this example, I don't see why AddNewCpp would not return a String[]. The direct use of the Object class is also less need since Java has generics.

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