Program Tip

반환이있는 Switch 문 — 코드 정확성

programtip 2020. 10. 11. 11:16
반응형

반환이있는 Switch 문 — 코드 정확성


대략 다음과 같은 구조의 C 코드가 있다고 가정 해 보겠습니다.

switch (something)
{
    case 0:
      return "blah";
      break;

    case 1:
    case 4:
      return "foo";
      break;

    case 2:
    case 3:
      return "bar";
      break;

    default:
      return "foobar";
      break;
}

이제 분명히 "중단"은 코드가 올바르게 실행되는 데 필요하지 않습니다.하지만 내가 거기에 두지 않으면 나쁜 습관처럼 보입니다.

어떻게 생각해? 제거해도 괜찮습니까? 아니면 "정확성"을 높이기 위해 보관 하시겠습니까?


break문을 제거하십시오 . 필요하지 않으며 일부 컴파일러는 "연결할 수없는 코드" 경고를 표시합니다.


나는 완전히 다른 방법을 취할 것입니다. 방법 / 기능 중간에 반환하지 마십시오. 대신 반환 값을 지역 변수에 넣고 끝에 보냅니다.

개인적으로 다음 내용이 더 읽기 쉽습니다.

String result = "";

switch (something) {
case 0:
  result = "blah";
  break;
case 1:
  result = "foo";
  break;
}

return result;

개인적으로 나는 반품을 제거하고 휴식을 유지합니다. 변수에 값을 할당하기 위해 switch 문을 사용합니다. 그런 다음 switch 문 뒤에 해당 변수를 반환합니다.

이것이 논쟁의 여지가 있지만, 좋은 디자인과 캡슐화는 한 가지 방법과 한 가지 방법을 의미한다고 항상 느꼈습니다. 논리를 보장하는 것이 훨씬 더 쉽고 함수의 순환 복잡성을 기반으로하는 정리 코드를 실수로 놓치는 일이 없습니다.

한 가지 예외 : 리소스를 획득하기 전에 함수 시작 부분에서 잘못된 매개 변수가 감지되면 일찍 반환해도 괜찮습니다.


휴식을 유지하십시오-휴식이 이미 제자리에 있으면 나중에 코드를 편집 할 때 문제가 발생할 가능성이 적습니다.

그렇긴하지만 (나를 포함한) 많은 사람들이 함수 중간에서 돌아 오는 것은 나쁜 습관이라고 생각합니다. 이상적으로 함수에는 하나의 진입 점과 하나의 종료 점이 있어야합니다.


그들을 제거하십시오. case명령문에서 반환하는 것은 관용적 이며 그렇지 않으면 "연결할 수없는 코드"노이즈입니다.


나는 그들을 제거 할 것이다. 내 책에서, 그와 같은 데드 코드는 실수로 간주되어야합니다. 왜냐하면 이중 테이크를하고 스스로에게 "어떻게 그 라인을 실행할 수 있을까요?"


나는 보통 그들없이 코드를 작성합니다. IMO, 데드 코드는 엉성함 및 / 또는 이해 부족을 나타내는 경향이 있습니다.

물론 다음과 같은 것도 고려할 것입니다.

char const *rets[] = {"blah", "foo", "bar"};

return rets[something];

편집 : 편집 된 게시물을 사용해도이 일반적인 아이디어는 잘 작동 할 수 있습니다.

char const *rets[] = { "blah", "foo", "bar", "bar", "foo"};

if ((unsigned)something < 5)
    return rets[something]
return "foobar";

어떤 시점에서, 특히 입력 값이 희소 한 경우 (예 : 1, 100, 1000 및 10000) 대신 희소 배열이 필요합니다. 트리 또는 맵으로 구현할 수 있습니다 (물론이 경우에도 스위치가 작동 함).


나는 그것들을 제거하고 default : branch를 정의한다고 말할 것입니다.


배열을 갖는 것이 더 낫지 않을까요?

arr[0] = "blah"
arr[1] = "foo"
arr[2] = "bar"

그리고 할 return arr[something];?

일반적으로 관행에 관한 것이라면 break진술을 스위치에 유지해야 합니다. return앞으로 진술이 필요하지 않은 경우 다음으로 넘어갈 가능성이 줄어 듭니다 case.


"정확성"의 경우 단일 진입, 단일 출구 블록이 좋은 생각입니다. 적어도 그들은 제가 컴퓨터 공학 학위를 받았을 때였습니다. 그래서 아마도 변수를 선언하고 스위치에 할당하고 함수의 끝에서 한 번 반환합니다.


어떻게 생각해? 제거해도 괜찮습니까? 아니면 "정확성"을 높이기 위해 보관 하시겠습니까?

그들을 제거하는 것이 좋습니다. 사용은 return이다 정확하게 시나리오 break사용할 수 없습니다.


흥미 롭군. 이 답변의 대부분은 중복 break진술이 불필요한 혼란 이라는 데 동의하는 것 같습니다 . 반면에 나는 break스위치 진술을 사건의 '종결' 이라고 읽었습니다 . case끝나지 않는 블록은 break버그를 통해 잠재적으로 떨어질 때 나에게 튀어 나오는 경향이 있습니다.

내가있을 때 그것이 얼마나 그 것이 아니 어서, return대신의 break,하지만 내 눈을 '읽기'스위치의 경우 블록, 그래서 나는 개인적으로 각각 것을 선호하는 방법의 case과 쌍 break. 그러나 많은 컴파일러는 불필요한 / 접근 불가능한 break이후 에 대해 불평 return하고 있으며 어쨌든 나는 소수에 속하는 것 같습니다.

따라서 break다음을 제거 하십시오 return.

주의 :이 모든 것은 단일 진입 / 퇴장 규칙을 위반하는 것이 좋은 생각인지 아닌지를 무시하는 것입니다. 그 정도면 안타깝게도 상황에 따라 달라진다는 의견이 있습니다 ...


나는 그들을 제거하라고 말한다. 코드를 읽을 수 없어서 '안전한면에 있기 위해'중단해야하는 경우 코딩 스타일을 재고해야합니다. :)

또한 나는 항상 switch 문에서 break와 return을 혼합하지 않고 그중 하나를 고수하는 것을 선호했습니다.


나는 개인적으로 breaks 를 잃는 경향이 있습니다. 이 습관의 원인 중 하나는 Windows 앱용 프로그래밍 창 프로 시저에서 비롯된 것 같습니다.

LRESULT WindowProc (HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    switch (uMsg)
    {
        case WM_SIZE:
            return sizeHandler (...);
        case WM_DESTROY:
            return destroyHandler (...);
        ...
    }

    return DefWindowProc(hwnd, uMsg, wParam, lParam);
}

개인적으로이 접근 방식은 각 핸들러에서 설정된 반환 변수를 선언 한 다음 마지막에 반환하는 것보다 훨씬 간단하고 간결하며 유연합니다. 이 접근 방식을 감안할 때 breaks는 중복되므로 이동해야합니다. 유용한 목적 (구문 적으로 또는 IMO 시각적으로)을 제공하지 않고 코드 만 부풀립니다.


I think the *break*s are there for a purpose. It is to keep the 'ideology' of programming alive. If we are to just 'program' our code without logical coherence perhaps it would be readable to you now, but try tomorrow. Try explaining it to your boss. Try running it on Windows 3030.

Bleah, the idea is very simple:


Switch ( Algorithm )
{

 case 1:
 {
   Call_911;
   Jump;
 }**break**;
 case 2:
 {
   Call Samantha_28;
   Forget;
 }**break**;
 case 3:
 {
   Call it_a_day;
 }**break**;

Return thinkAboutIt?1:return 0;

void Samantha_28(int oBed)
{
   LONG way_from_right;
   SHORT Forget_is_my_job;
   LONG JMP_is_for_assembly;
   LONG assembly_I_work_for_cops;

   BOOL allOfTheAbove;

   int Elligence_says_anyways_thinkAboutIt_**break**_if_we_code_like_this_we_d_be_monkeys;

}
// Sometimes Programming is supposed to convey the meaning and the essence of the task at hand. It is // there to serve a purpose and to keep it alive. While you are not looking, your program is doing  // its thing. Do you trust it?
// This is how you can...
// ----------
// **Break**; Please, take a **Break**;

/* Just a minor question though. How much coffee have you had while reading the above? I.T. Breaks the system sometimes */


Exit code at one point. That provides better readability to code. Adding return statements (Multiple exits) in between will make debugging difficult .


If you have "lookup" type of code, you could package the switch-case clause in a method by itself.

I have a few of these in a "hobby" system I'm developing for fun:

private int basePerCapitaIncomeRaw(int tl) {
    switch (tl) {
        case 0:     return 7500;
        case 1:     return 7800;
        case 2:     return 8100;
        case 3:     return 8400;
        case 4:     return 9600;
        case 5:     return 13000;
        case 6:     return 19000;
        case 7:     return 25000;
        case 8:     return 31000;
        case 9:     return 43000;
        case 10:    return 67000;
        case 11:    return 97000;
        default:    return 130000;
    }
}

(Yep. That's GURPS space...)

I agree with others that you should in most cases avoid more than one return in a method, and I do recognize that this one might have been better implemented as an array or something else. I just found switch-case-return to be a pretty easy match to a lookup table with a 1-1 correlation between input and output, like the above thing (role-playing games are full of them, I am sure they exist in other "businesses" as well) :D

On the other hand, if the case-clause is more complex, or something happens after the switch-statement, I wouldn't recommend using return in it, but rather set a variable in the switch, end it with a break, and return the value of the variable in the end.

(On the ... third? hand... you can always refactor a switch into its own method... I doubt it will have an effect on performance, and it wouldn't surprise me if modern compilers could even recognize it as something that could be inlined...)

참고URL : https://stackoverflow.com/questions/3065438/switch-statement-with-returns-code-correctness

반응형