我有很多函数(funcOne, funcTwo, etc.
),它们都在开头共享相同的检查块(我想将这些块移动到一个单独的函数或者其他东西所以我不会重复代码,但是问题是我使用return。请继续阅读)
我想要做的是将这些检查移到单独的功能中。但问题是我使用的return;
将返回新函数,但不会从funcOne and funcTwo
返回。有人可以帮我重构这段代码,所以我不必在每个使用它们的函数中重复重复检查。
protected function funcOne(event:MouseEvent):void { if( check 1 doesn't pass){ Alert.show("error 1, returning); return; } if( check 2 doesn't pass){ Alert.show("error 2, returning); return; } .... more checks here, all of them return specific messages //if all checks pass //execute the specific code of this funcOne } protected function funcTwo(event:MouseEvent):void { if( check 1 doesn't pass){ Alert.show("error 1, returning); return; } if( check 2 doesn't pass){ Alert.show("error 2, returning); return; } .... more checks here, all of them return specific messages //if all checks pass //execute the specific code of this funcTwo }
答案 0 :(得分:3)
protected function funcOne(event:MouseEvent):void
{
if( !checkAll(event) ){
return;
}
//if all checks pass
//execute the specific code of this funcOne
}
protected function funcTwo(event:MouseEvent):void
{
if( !checkAll(event) ){
return;
}
//if all checks pass
//execute the specific code of this funcTwo
}
private function checkAll(event:MouseEvent):Boolean
{
if( check 1 doesn't pass){
Alert.show("error 1, returning);
return false;
}
if( check 2 doesn't pass){
Alert.show("error 2, returning);
return false;
}
return true;
}
答案 1 :(得分:2)
您可以在错误检查功能中构建一串错误,然后将该字符串返回到主函数。如果字符串包含内容,则显示该内容并中断您的程序;
protected function funcOne(event:MouseEvent):void
{
errors = checkForErrors();
if( errors != null || errors != "" )
{
Alert.show( errors );
return;
}
}
protected function checkForErrors():String
{
var errorString:String = '';
if( check 1 doesn't pass){
errorString +="error 1\n";
}
if( check 2 doesn't pass){
errorString +="error 1\n";
{
return errorString;
}
答案 2 :(得分:1)
这是一种快速的方法。如果要在其他地方处理警报,也可以返回实际的消息字符串。如果消息字符串为null,则表示没有错误。
protected function funcOne(event:MouseEvent):void
{
if(validate())
{
//if all checks pass
//execute the specific code of this funcOne
}
}
protected function funcTwo(event:MouseEvent):void
{
if(validate())
{
//if all checks pass
//execute the specific code of this funcOne
}
}
//returns false if not valid
protected function validate():Boolean
{
var errorMessage:String = null;
if( check 1 doesn't pass)
errorMessage = "error 1, returning";
else if( check 2 doesn't pass)
errorMessage = "error 2, returning";
if(errorMessage)
Alert.show(errorMessage);
return !errorMessage as Boolean; //will return true if errorMessage is null
}