온라인 번역 서비스 용 래퍼를 쓰고 있습니다. 현재 OnlineTranslator
클래스는 스파게티 코드처럼 저에게보기 흉하게 보입니다. 왜냐하면 밑줄 서비스 (Bing, 실제로)에서 발생할 수있는 많은 오류에 대한 예외 생성 때문입니다.스파게티 코드, 예외 처리 및 오류 처리?
예외 및 오류를 어떻게 처리하는지 잘 이해하지 못합니다. 내 코드를 리팩토링하는 모든 변경 (누가 패턴을 말 했나요?)? 코드에서 이렇게 많은 if
을 제거하는 방법은 무엇입니까?
<?php
namespace DL\AdminBundle\Service;
class OnlineTranslator
{
private $_service;
private $_languages;
private $_from;
private $_to;
private $_ERRORS = array(
'UNSUPPORTED_DETECTION' => "'%s' service doesn't support language
detection. Manually call 'setFrom' to set the source language.",
'UNSUPPORTED_FROM_LANGUAGE' => "Source language code '%s' unrecognized
or not supported by this service.",
'UNSUPPORTED_TO_LANGUAGE' => "Destination language code '%s'
unrecognized or not supported by this service.",
'MISSING_TO_LANGUAGE' => "Destination language code is missing.",
'GENERIC_SERVICE_ERROR' => "'%s' service returned an error: %s."
);
function __construct(IOnlineTranslator $service)
{
// Imposta il servizio e la lingua sorgente su auto
$this->_service = $service;
$this->_from = 'auto';
$response = $this->_service->getLanguages();
if ($response->error)
throw new Exception(sprintf(
$this->_ERRORS['GENERIC_SERVICE_ERROR'],
$this->_service->getName(), $response->data));
$this->_languages = $response->data;
}
function setFrom($languageCode)
{
// Controlla se la lingua è supportata
if (!in_array($languageCode, $this->_languages))
throw new Exception(sprintf(
$this->_ERRORS['UNSUPPORTED_FROM_LANGUAGE'],
$languageCode));
// Imposta la lingua sorgente
$this->_from = $languageCode;
}
function setTo($languageCode)
{
// Controlla se la lingua è supportata
if (!in_array($languageCode, $this->_languages))
throw new Exception(sprintf(
$this->_ERRORS['UNSUPPORTED_TO_LANGUAGE'],
$languageCode));
// Imposta la lingua destinazione
$this->_to = $languageCode;
}
function translate($text)
{
// Controlla che sia impostata la lingua di destinazione
if (!isset($this->_to))
throw new Exception($this->_ERRORS['MISSING_TO_LANGUAGE']);
// Se detect è auto controlla che il servizio lo supporti
if ('auto' == $this->_from && !$this->_service->isDetectAware())
throw new Exception(sprintf(
$this->_ERRORS['UNSUPPORTED_DETECTION'],
$this->_service->getName()));
// Imposta la lingua sorgente chiamando il metodo detect
$response = $this->_service->detect($text);
if ($response->error)
throw new Exception(sprintf(
$this->_ERRORS['GENERIC_SERVICE_ERROR'],
$this->_service->getName(), $response->data));
$this->_from = $response->data;
// Traduci il testo chiamando il metodo translate
$response = $this->_service->translate($text, $this->_from,
$this->_to);
if ($response->error)
throw new Exception(sprintf(
$this->_ERRORS['GENERIC_SERVICE_ERROR'],
$this->_service->getName(), $response->data));
return $response->data;
}
}
?>
무엇이 문제입니까? – KingCrunch
@KingCrunch'if','if','if' 그리고 다시'if'. – gremo
'if' 블록이 어떤 이유로 문제가됩니까? –