Difference between revisions of "Java Class Template"

From AgileApps Support Wiki
imported>Aeric
imported>Aeric
 
(13 intermediate revisions by the same user not shown)
Line 1: Line 1:
Use this class as a template for a class that accesses record data and uses it to perform some operation.
Use this class as a template for a class that accesses record data and uses it to perform some operation. (The class is intentionally overly-complete. It's a lot easier to remove something you don't need than it is to look up the syntax for things you do need--or to know that syntax even exists.)
 
:<syntaxhighlight lang="java" enclose="div">
:<syntaxhighlight lang="java" enclose="div">
package com.platform.yourCompany.yourApplication;
package com.platform.yourCompany.yourApplication;
Line 22: Line 23:
   //  When showMessage() is called multiple times, the strings are concatenated.  
   //  When showMessage() is called multiple times, the strings are concatenated.  
   //  One long string is then displayed when the code returns to the platform.
   //  One long string is then displayed when the code returns to the platform.
   //  We add an HTML linebreak (<br>) to separate them.
   //  We add an HTML linebreak (<br>) to separate them. Log messages, on the
  //  other hand, use a Java "\n" (newline) character.
   public void show(String msg) throws Exception { Functions.showMessage(msg+"<br>"); }
   public void show(String msg) throws Exception { Functions.showMessage(msg+"<br>"); }
   public void log(String msg) throws Exception { Logger.info(msg, "YourClass"); }
   public void log(String msg) throws Exception { Logger.info(msg, "YourClass"); }
   public void debug(String msg) throws Exception { show(msg); log(msg); }
   public void debug(String msg) throws Exception { show(msg); log(msg); }


  /**
    * CALLED FROM THE PLATFORM (hence the Parameters argument)
    */
   public void doSomething(Parameters p) throws Exception
   public void doSomething(Parameters p) throws Exception
   {
   {
       try {
       try {
         debug("Started");
         //Record incoming parameters in the log
        //log( "Method params:\n"+ p.toString().replace(",","\n") );
 
         String objectID = p.get("object_id");
         String objectID = p.get("object_id");
         String recordID = p.get("id");   
         String recordID = p.get("id");   
Line 45: Line 52:
             // Display message to user, add an entry to debug log, and
             // Display message to user, add an entry to debug log, and
             // roll back the current transaction (no changes are committed).
             // roll back the current transaction (no changes are committed).
             String msg = "Error <doing something> in methodName()";
             String msg = "Error <doing something>:\n"+ r.getMessage();
             Functions.throwError(msg + "\n" + r.getMessage() );       
             Functions.throwError(msg);       
         }   
         }   
         debug("Success");
         debug("Success");
       } catch (Exception e) {
       } catch (Exception e) {
         log( "methodName(): "+e.getClass().getName() );   
         String msg = e.getMessage() + "\n methodName(): "+e.getClass().getName();
         Functions.throwError(e.getMessage());
        log(msg);   
         Functions.throwError(msg);
       }
       }
   }
   }


  /**
    * CALLED INTERNALLY(a utility function of some sort)
    */
  public String getSomeValue(String x) throws Exception
  {
      try {
        ...
      } catch (Exception e) {
        String msg = e.getMessage() + "\n methodName(): "+e.getClass().getName();
        Functions.throwError(msg);
      }
  }
  /**
    * UNIT TEST. (Note the @TestMethod pragma)
    */
   @TestMethod
   @TestMethod
   public void test1_DescribeTheTestHere() throws Exception
   public void test1_DescribeTheTestHere() throws Exception
   {
   {
      // Unit Test
       String expect = "some result";         
       String expect = "some result";         
       String actual = methodThatReturnsSomeResult();
       String actual = methodThatReturnsSomeResult();
Line 69: Line 92:
{{Best|
{{Best|
# Wrap code in a <tt>try..catch</tt> block, to guard against unexpected exceptions. (If not caught, they are simply ignored, and the method fails silently.)  
# Wrap code in a <tt>try..catch</tt> block, to guard against unexpected exceptions. (If not caught, they are simply ignored, and the method fails silently.)  
# When you detect an error, put a detailed message into the [[Debug Log]]. Then call [[Functions.throwError]] to generate an exception, display a message for the user, and roll back the current transaction.}}  
# When you detect an error, put a detailed message into the [[Debug Log]]. Then call [[Functions.throwError]] to generate an exception, display a message for the user, and roll back the current transaction.}}
 
Additional Notes:
:* '''Incoming Parameters'''
:: A Java method is always invoked in the context of some record. The method signature is therefore required to have take a [[Parameters Class|Parameters]] argument, which contains the record fields, along with additional parameters.
:: ''Learn more:''
:::* [[Standard Object Fields]]
:::* [[Standard Parameters]]
:* '''Object names and IDs'''
::* Most APIs take either object name or object ID. (Only a few require object ID.)
::* For most operations you'll know which object you're operating on, so you'll specify the object name in a string.
::* But the object ID is also available in the incoming Parameters, when you need it.

Latest revision as of 01:44, 7 February 2015

Use this class as a template for a class that accesses record data and uses it to perform some operation. (The class is intentionally overly-complete. It's a lot easier to remove something you don't need than it is to look up the syntax for things you do need--or to know that syntax even exists.)

<syntaxhighlight lang="java" enclose="div">

package com.platform.yourCompany.yourApplication;

// Basic imports import com.platform.api.*; import java.util.*;

// Reference static functions without having to specify the Functions class. // So Functions.throwError() can be written as throwError(). // (Code is shorter that way, but it's less obvious where things are defined.) import static com.platform.api.Functions.*;

// These are needed for advanced operations. //import com.platform.beans.*; //import static com.platform.api.CONSTANTS.*;

public class YourClass {

  // Convenience methods to display a message to the user or add it the debug log.
  // Note:
  //   When showMessage() is called multiple times, the strings are concatenated. 
  //   One long string is then displayed when the code returns to the platform.
  //   We add an HTML linebreak (
) to separate them. Log messages, on the // other hand, use a Java "\n" (newline) character. public void show(String msg) throws Exception { Functions.showMessage(msg+"
"); } public void log(String msg) throws Exception { Logger.info(msg, "YourClass"); } public void debug(String msg) throws Exception { show(msg); log(msg); }
  /**
   * CALLED FROM THE PLATFORM (hence the Parameters argument)
   */
  public void doSomething(Parameters p) throws Exception
  {
     try {
        //Record incoming parameters in the log
        //log( "Method params:\n"+ p.toString().replace(",","\n") );
        String objectID = p.get("object_id");
        String recordID = p.get("id");  
        // Define the parameters for some operation
        Parameters params = Functions.getParametersInstance();
        params.add("key", "value");
        //...
        // Do it.
        // Result.getCode() >= 0 on success, -1 on failure
        Result r = Functions.doSomething(params);
        if (r.getCode() < 0) {
           // Display message to user, add an entry to debug log, and
           // roll back the current transaction (no changes are committed).
           String msg = "Error <doing something>:\n"+ r.getMessage();
           Functions.throwError(msg);      
        }  
        debug("Success");
     } catch (Exception e) {
        String msg = e.getMessage() + "\n methodName(): "+e.getClass().getName(); 
        log(msg);  
        Functions.throwError(msg);
     }
  }
  /**
   * CALLED INTERNALLY(a utility function of some sort)
   */
  public String getSomeValue(String x) throws Exception
  {
     try {
        ...
     } catch (Exception e) {
        String msg = e.getMessage() + "\n methodName(): "+e.getClass().getName(); 
        Functions.throwError(msg);
     }
  }
  /**
   * UNIT TEST. (Note the @TestMethod pragma)
   */
  @TestMethod
  public void test1_DescribeTheTestHere() throws Exception
  {
     String expect = "some result";        
     String actual = methodThatReturnsSomeResult();
     RunTest.assertEquals(expect, actual);
  }

} // end class </syntaxhighlight>

Thumbsup.gif

Best Practice:

  1. Wrap code in a try..catch block, to guard against unexpected exceptions. (If not caught, they are simply ignored, and the method fails silently.)
  2. When you detect an error, put a detailed message into the Debug Log. Then call Functions.throwError to generate an exception, display a message for the user, and roll back the current transaction.