백엔드 개발 파이썬 튜토리얼 조건문을 피하는 지혜

조건문을 피하는 지혜

Aug 14, 2024 am 10:41 AM

The Wisdom of Avoiding Conditional Statements

순환복잡도는 코드의 복잡도와 얽힘 정도를 측정하는 척도입니다.

높은 순환적 복잡성은 좋은 것이 아니라 오히려 그 반대입니다.

간단히 말하면 순환적 복잡성은 프로그램에서 가능한 실행 경로 수에 정비례합니다. 즉, 순환적 복잡성과 조건문의 총 개수(특히 중첩)는 밀접한 관련이 있습니다.

그래서 오늘은 조건문에 대해 알아보겠습니다.

안티 if

2007년 프란체스코 시릴로는 Anti-if라는 운동을 시작했습니다.

프란체스코 시릴로는 뽀모도로 기법을 창안한 사람입니다. 저는 지금 이 블로그 글을 쓰고 있습니다. "포모도로 아래"

이름부터 이 캠페인의 내용을 금방 알아차렸을 것 같아요. 흥미롭게도 이 운동의 추종자 중에는 컴퓨터 과학자가 꽤 많습니다.

그들의 주장은 확고합니다. 만약 진술이 악하다면 프로그램 실행 경로가 기하급수적으로 증가하게 됩니다.

간단히 말하면 순환적 복잡성입니다. 높을수록 코드를 읽고 이해하는 것뿐만 아니라 테스트로 다루기도 더 어려워집니다.

물론, 테스트에 포함된 코드의 양을 보여주는 일종의 "반대" 지표인 코드 적용 범위가 있습니다. 하지만 이 측정항목은 적용 범위를 확인하기 위한 프로그래밍 언어의 풍부한 도구와 함께 순환적 복잡성을 무시하고 단지 "본능"을 기반으로 if 문을 흩뿌리는 것을 정당화합니까?

아닌 것 같아요.


거의 if 하나를 다른 if 안에 중첩하려고 할 때마다 중첩된 if가 없거나 if가 전혀 없이 다르게 다시 작성될 수 있는 정말 어리석은 일을 하고 있다는 것을 깨닫게 됩니다.

'거의'라는 단어를 보셨죠?

저는 이 사실을 바로 알아채기 시작한 것이 아닙니다. 내 GitHub를 보면 순환적 복잡성이 높을 뿐만 아니라 완전히 순환적 광기를 지닌 오래된 코드의 예를 두 개 이상 찾을 수 있습니다.

이 문제를 더 잘 인식하게 된 계기는 무엇입니까? 아마도 제가 약 1년 전에 배우고 받아들인 몇 가지 현명한 것들과 경험이 있을 것입니다. 오늘 제가 여러분께 말씀드리고 싶은 내용은 바로 이것입니다.


if 문을 파괴하는 두 가지 신성한 기술

  1. 파다완님, 알 수 없는 값의 각 조건부 검사를 해당 값이 이미 알려진 위치로 이동하세요.
  2. 파다완님, 더 이상 조건부 확인이 필요하지 않도록 인코딩된 논리의 정신 모델을 변경하세요.

1. 알려지지 않은 것을 알려라

아직 "알지" 못하는 것을 확인하는 것은 아마도 "본능"에 기초한 조건문을 사용하는 가장 일반적인 원인일 것입니다.

예를 들어 사용자의 연령을 기준으로 작업을 수행해야 하고 해당 연령이 유효한지(합리적인 범위 내에 있는지) 확인해야 한다고 가정해 보겠습니다. 다음과 같은 코드가 나올 수 있습니다.

from typing import Optional

def process_age(age: Optional[int]) -> None:
    if age is None:
        raise ValueError("Age cannot be null")
    if age < 0 or age > 150:
        raise ValueError("Age must be between 0 and 150")
로그인 후 복사

우리 모두 비슷한 코드를 수백 번 본 적이 있고 작성해 본 적이 있을 것입니다.

논의된 메타 원칙에 따라 이러한 조건부 검사를 어떻게 제거할 수 있나요?

연령에 따른 특정 사례에서는 제가 가장 좋아하는 접근 방식을 적용할 수 있습니다. 즉, 원시적인 집착에서 벗어나 사용자 정의 데이터 유형을 사용하는 것입니다.

class Age:
    def __init__(self, value: int) -> None:
        if value < 0 or value > 150:
            raise ValueError("Age must be between 0 and 150")
        self.value = value

    def get_value(self) -> int:
        return self.value

def process_age(age: Age) -> None:
    # Age is guaranteed to be valid, process it directly
로그인 후 복사

만세, 하나 줄이면! 연령 확인 및 검증은 이제 항상 별도의 클래스의 책임과 범위 내에서 "연령이 알려진 곳"에서 이루어집니다.

Age 클래스에서 if를 제거하려는 경우 유효성 검사기와 함께 Pydantic 모델을 사용하거나 if를 주장으로 대체하여 더 멀리/다르게 진행할 수 있습니다. 지금은 중요하지 않습니다.


동일한 메타 아이디어 내에서 조건부 검사를 제거하는 데 도움이 되는 다른 기법이나 메커니즘에는 조건을 다형성(또는 익명 람다 함수)으로 대체하고 교묘한 부울 플래그가 있는 함수 분해와 같은 접근 방식이 포함됩니다.

예를 들어 다음 코드(끔찍한 복싱이죠?)는 다음과 같습니다.

class PaymentProcessor:
    def process_payment(self, payment_type: str, amount: float) -> str:
        if payment_type == "credit_card":
            return self.process_credit_card_payment(amount)
        elif payment_type == "paypal":
            return self.process_paypal_payment(amount)
        elif payment_type == "bank_transfer":
            return self.process_bank_transfer_payment(amount)
        else:
            raise ValueError("Unknown payment type")

    def process_credit_card_payment(self, amount: float) -> str:
        return f"Processed credit card payment of {amount}."

    def process_paypal_payment(self, amount: float) -> str:
        return f"Processed PayPal payment of {amount}."

    def process_bank_transfer_payment(self, amount: float) -> str:
        return f"Processed bank transfer payment of {amount}."
로그인 후 복사

if/elif를 match/case로 바꿔도 상관없습니다. 똑같은 쓰레기입니다!

다음과 같이 다시 작성하는 것은 매우 쉽습니다.

from abc import ABC, abstractmethod

class PaymentProcessor(ABC):
    @abstractmethod
    def process_payment(self, amount: float) -> str:
        pass

class CreditCardPaymentProcessor(PaymentProcessor):
    def process_payment(self, amount: float) -> str:
        return f"Processed credit card payment of {amount}."

class PayPalPaymentProcessor(PaymentProcessor):
    def process_payment(self, amount: float) -> str:
        return f"Processed PayPal payment of {amount}."

class BankTransferPaymentProcessor(PaymentProcessor):
    def process_payment(self, amount: float) -> str:
        return f"Processed bank transfer payment of {amount}."
로그인 후 복사

그렇죠?


부울 플래그를 사용하여 함수를 두 개의 별도 함수로 분해하는 예는 시간이 오래 걸리고 고통스러울 정도로 친숙하며 엄청나게 짜증납니다(솔직한 의견으로는).

def process_transaction(transaction_id: int,
                                                amount: float,
                                                is_internal: bool) -> None:
    if is_internal:
        # Process internal transaction
        pass
    else:
        # Process external transaction
        pass
로그인 후 복사

두 가지 기능은 코드의 2/3가 동일하더라도 어떤 경우에도 훨씬 더 좋습니다! 이는 DRY와의 절충이 상식의 결과이며 코드를 더 좋게 만드는 시나리오 중 하나입니다.


The big difference here is that mechanically, on autopilot, we are unlikely to use these approaches unless we've internalized and developed the habit of thinking through the lens of this principle.

Otherwise, we'll automatically fall into if: if: elif: if...

2. Free Your Mind, Neo

In fact, the second technique is the only real one, and the earlier "first" technique is just preparatory practices, a shortcut for getting in place :)

Indeed, the only ultimate way, method — call it what you will — to achieve simpler code, reduce cyclomatic complexity, and cut down on conditional checks is making a shift in the mental models we build in our minds to solve specific problems.

I promise, one last silly example for today.

Consider that we're urgently writing a backend for some online store where user can make purchases without registration, or with it.

Of course, the system has a User class/entity, and finishing with something like this is easy:

def process_order(order_id: int,
                                  user: Optional[User]) -> None:
    if user is not None:
        # Process order for a registered user
       pass
    else:
        # Process order for a guest user
           pass
로그인 후 복사

But noticing this nonsense, thanks to the fact that our thinking has already shifted in the right direction (I believe), we'll go back to where the User class is defined and rewrite part of the code in something like this:

class User:
    def __init__(self, name: str) -> None:
        self.name = name

    def process_order(self, order_id: int) -> None:
        pass

class GuestUser(User):
    def __init__(self) -> None:
        super().__init__(name="Guest")

    def process_order(self, order_id: int) -> None:
        pass
로그인 후 복사

So, the essence and beauty of it all is that we don't clutter our minds with various patterns and coding techniques to eliminate conditional statements and so on.

By shifting our focus to the meta-level, to a higher level of abstraction than just the level of reasoning about lines of code, and following the idea we've discussed today, the right way to eliminate conditional checks and, in general, more correct code will naturally emerge.


A lot of conditional checks in our code arise from the cursed None/Null leaking into our code, so it's worth mentioning the quite popular Null Object pattern.

Clinging to Words, Not Meaning

When following Anti-if, you can go down the wrong path by clinging to words rather than meaning and blindly following the idea that "if is bad, if must be removed.”

Since conditional statements are semantic rather than syntactic elements, there are countless ways to remove the if token from your code without changing the underlying logic in our beloved programming languages.

Replacing an elif chain in Python with a match/case isn’t what I’m talking about here.

Logical conditions stem from the mental “model” of the system, and there’s no universal way to "just remove" conditionals entirely.

In other words, cyclomatic complexity and overall code complexity aren’t tied to the physical representation of the code — the letters and symbols written in a file.

The complexity comes from the formal expression, the verbal or textual explanation of why and how specific code works.

So if we change something in the code, and there are fewer if statements or none at all, but the verbal explanation of same code remains the same, all we’ve done is change the representation of the code, and the change itself doesn’t really mean anything or make any improvement.

위 내용은 조건문을 피하는 지혜의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

<gum> : Bubble Gum Simulator Infinity- 로얄 키를 얻고 사용하는 방법
4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
Nordhold : Fusion System, 설명
4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
Mandragora : 마녀 트리의 속삭임 - Grappling Hook 잠금 해제 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

Python vs. C : 학습 곡선 및 사용 편의성 Python vs. C : 학습 곡선 및 사용 편의성 Apr 19, 2025 am 12:20 AM

Python은 배우고 사용하기 쉽고 C는 더 강력하지만 복잡합니다. 1. Python Syntax는 간결하며 초보자에게 적합합니다. 동적 타이핑 및 자동 메모리 관리를 사용하면 사용하기 쉽지만 런타임 오류가 발생할 수 있습니다. 2.C는 고성능 응용 프로그램에 적합한 저수준 제어 및 고급 기능을 제공하지만 학습 임계 값이 높고 수동 메모리 및 유형 안전 관리가 필요합니다.

Python 학습 : 2 시간의 일일 연구가 충분합니까? Python 학습 : 2 시간의 일일 연구가 충분합니까? Apr 18, 2025 am 12:22 AM

하루에 2 시간 동안 파이썬을 배우는 것으로 충분합니까? 목표와 학습 방법에 따라 다릅니다. 1) 명확한 학습 계획을 개발, 2) 적절한 학습 자원 및 방법을 선택하고 3) 실습 연습 및 검토 및 통합 연습 및 검토 및 통합,이 기간 동안 Python의 기본 지식과 고급 기능을 점차적으로 마스터 할 수 있습니다.

Python vs. C : 성능과 효율성 탐색 Python vs. C : 성능과 효율성 탐색 Apr 18, 2025 am 12:20 AM

Python은 개발 효율에서 C보다 낫지 만 C는 실행 성능이 높습니다. 1. Python의 간결한 구문 및 풍부한 라이브러리는 개발 효율성을 향상시킵니다. 2.C의 컴파일 유형 특성 및 하드웨어 제어는 실행 성능을 향상시킵니다. 선택할 때는 프로젝트 요구에 따라 개발 속도 및 실행 효율성을 평가해야합니다.

Python vs. C : 주요 차이점 이해 Python vs. C : 주요 차이점 이해 Apr 21, 2025 am 12:18 AM

Python과 C는 각각 고유 한 장점이 있으며 선택은 프로젝트 요구 사항을 기반으로해야합니다. 1) Python은 간결한 구문 및 동적 타이핑으로 인해 빠른 개발 및 데이터 처리에 적합합니다. 2) C는 정적 타이핑 및 수동 메모리 관리로 인해 고성능 및 시스템 프로그래밍에 적합합니다.

Python Standard Library의 일부는 무엇입니까? 목록 또는 배열은 무엇입니까? Python Standard Library의 일부는 무엇입니까? 목록 또는 배열은 무엇입니까? Apr 27, 2025 am 12:03 AM

Pythonlistsarepartoftsandardlardlibrary, whileraysarenot.listsarebuilt-in, 다재다능하고, 수집 할 수있는 반면, arraysarreprovidedByTearRaymoduledlesscommonlyusedDuetolimitedFunctionality.

파이썬 : 자동화, 스크립팅 및 작업 관리 파이썬 : 자동화, 스크립팅 및 작업 관리 Apr 16, 2025 am 12:14 AM

파이썬은 자동화, 스크립팅 및 작업 관리가 탁월합니다. 1) 자동화 : 파일 백업은 OS 및 Shutil과 같은 표준 라이브러리를 통해 실현됩니다. 2) 스크립트 쓰기 : PSUTIL 라이브러리를 사용하여 시스템 리소스를 모니터링합니다. 3) 작업 관리 : 일정 라이브러리를 사용하여 작업을 예약하십시오. Python의 사용 편의성과 풍부한 라이브러리 지원으로 인해 이러한 영역에서 선호하는 도구가됩니다.

과학 컴퓨팅을위한 파이썬 : 상세한 모양 과학 컴퓨팅을위한 파이썬 : 상세한 모양 Apr 19, 2025 am 12:15 AM

과학 컴퓨팅에서 Python의 응용 프로그램에는 데이터 분석, 머신 러닝, 수치 시뮬레이션 및 시각화가 포함됩니다. 1.numpy는 효율적인 다차원 배열 및 수학적 함수를 제공합니다. 2. Scipy는 Numpy 기능을 확장하고 최적화 및 선형 대수 도구를 제공합니다. 3. 팬더는 데이터 처리 및 분석에 사용됩니다. 4. matplotlib는 다양한 그래프와 시각적 결과를 생성하는 데 사용됩니다.

웹 개발을위한 파이썬 : 주요 응용 프로그램 웹 개발을위한 파이썬 : 주요 응용 프로그램 Apr 18, 2025 am 12:20 AM

웹 개발에서 Python의 주요 응용 프로그램에는 Django 및 Flask 프레임 워크 사용, API 개발, 데이터 분석 및 시각화, 머신 러닝 및 AI 및 성능 최적화가 포함됩니다. 1. Django 및 Flask 프레임 워크 : Django는 복잡한 응용 분야의 빠른 개발에 적합하며 플라스크는 소형 또는 고도로 맞춤형 프로젝트에 적합합니다. 2. API 개발 : Flask 또는 DjangorestFramework를 사용하여 RESTFULAPI를 구축하십시오. 3. 데이터 분석 및 시각화 : Python을 사용하여 데이터를 처리하고 웹 인터페이스를 통해 표시합니다. 4. 머신 러닝 및 AI : 파이썬은 지능형 웹 애플리케이션을 구축하는 데 사용됩니다. 5. 성능 최적화 : 비동기 프로그래밍, 캐싱 및 코드를 통해 최적화

See all articles