【问题标题】:Conditional method chaining in apex顶点中的条件方法链接
【发布时间】:2019-08-08 12:01:52
【问题描述】:

我有一个类LogException

public class LogException extends Exception {
public String ModuleName {get; set;}
public String StackTrace {get; set;}
public String ClassName {get; set;}
public String MethodName {get; set;}
public String ExceptionCause {get; set;}

public void log(Exception ex)
{
    try
    {
        extractExceptionData(ex); 
        writeToObject(ex); 

    }
    catch(Exception e)
    {
         new LogException().Module('LogException').log(e);            
    }

}

public LogException Module(String Name)
{
    ModuleName = name;
    return this;
}

public LogException ExceptionCause(String cause)
{
    ExceptionCause = cause;
    return this;
}

public void extractExceptionData(Exception ex)
{
    try
    {
        stackTrace = ex.getStackTraceString().substringBefore('\n');
        className = stackTrace.substringAfter('.').substringBefore('.');    
        methodName = stackTrace.substringBefore(':').substringAfter(className).substringAfter('.');    
    }
    catch(Exception e)
    {
        new LogException().Module('LogException').log(e); 
    }

}

public void writeToObject(Exception ex)
{
    try
    {
        // insert to object(database) here   
    }

    catch(Exception e)
    {
        new LogException().Module('LogException').log(e);     
    }

}

}

我在这里实现了方法链接。因此,我可以调用像

这样的方法
new LogException().Module('unitTestModule').Log(ex);

new LogException().ExceptionCause('divided by zero').Log(ex);

new LogException().Module('unitTestModule').ExceptionCause('Probably no data in account').Log(ex);

new LogException().ExceptionCause('Probably no data in account').Module('unitTestModule').Log(ex);

我的问题是,我怎样才能实现这个类,我只能在Module 之后调用ExceptionCause

【问题讨论】:

  • 为什么不直接使用重载的构造函数呢?方法链似乎没有添加任何东西,而且比精心挑选的一组构造函数要冗长得多。
  • @DavidReed :你能启发我/给我一个想法,我该如何实现重载的构造函数来实现它?

标签: design-patterns salesforce apex method-chaining


【解决方案1】:

我不会在这里使用方法链接。我只是重写构造函数来填充所需的参数:

public LogException(String module, String exceptionCause) {
}

public LogException(String module) {
    this(module, null);
}
// etc.

你在这里唯一不能做的就是有两个构造函数,它们都接受一个 String 参数 - 你必须愿意通过额外的可选参数来定义所需的层次结构,比如 @987654324 @这里。

参考文档是Apex Constructors

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-06
    • 2012-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多