코드 냄새 27 - 연관 배열

[키, 값], 마법, 빠르고, 가단성 및 오류 가지치기.

핵심요약: 신속한 프로토타이핑에는 어레이를 사용하고 중요한 비즈니스에는 객체를 사용하십시오.

문제


  • 커플링
  • 정보 숨기기
  • 코드 중복
  • 빠른 실패
  • 무결성

  • 솔루션


  • 개체 구체화
  • 응집력 있는 작은 개체 만들기
  • 빈혈 상태로 두지 말고 응집력 있는 관계를 찾으십시오.

  • 샘플 코드



    잘못된




    <?
    
    $coordinate = array('latitude'=>1000, 'longitude'=>2000); 
    //Its OK. they are just arrays. a Bunch of raw data
    

    빈혈



    <?
    
    final class GeographicCoordinate {
    
        function __construct($latitude, $longitude) {
            $this->longitude = $longitude;
            $this->latitude = $latitude;
        }
    }
    
    $coordinate = new GeographicCoordinate(1000, 2000);
    //should throw an error since these values don't exist on Earth
    

    검증됨



    <?
    
    final class GeographicCoordinate {
    
        function __construct($latitude, $langitude) {
            if (!$this->isValidLatitude($latitude)) {
                throw new InvalidLatitudeException($latitude);
                //...
                $this->longitude = $longitude;
                $this->latitude = $latitude;
            }
        }
    }
    
    $coordinate = new GeographicCoordinate(1000, 2000);
    //trows an error since these values don't exist on Earth
    

    오른쪽


    학위는 구체화할 가치가 있다



    <?
    
    final class Latitude {
        function __construct($degrees) {
            if (!$degrees->between(-90, 90)) {
                throw new InvalidLatitudeException($latitude);
            }
            //...
        }
    }
    

    많은 사람들이 원시적인 집착에 시달리고 있으며 이것이 지나친 디자인이라고 생각합니다.
    소프트웨어 설계는 결정을 내리고 장단점을 비교하는 것입니다.
    최신 가상 머신은 수명이 짧은 작은 개체를 효율적으로 처리할 수 있기 때문에 오늘날 성능 인수는 유효하지 않습니다.

    <?
    
    final class GeographicCoordinate {
    
        function distanceTo(GeographicCoordinate $coordinate) {
        }
    
        function pointInPoligon(Polygon $polygon) {
            //....
        }
    }
    
    //Now we are in geometry world (and not in array world anymore). we can safely do many exciting things.
    

    발각



    Associative Arrays는 첫 번째 접근 방식으로 매우 우수하기 때문에 금지할 수 없습니다.

    데이터 내보내기, 직렬화, 지속성 및 기타 우발적인 구현 문제에 적합합니다.

    우리는 우리 시스템에서 그것들을 피해야 합니다.

    태그


  • 프리미티브

  • 결론



    객체를 생성할 때 객체를 데이터로 생각해서는 안 됩니다. 이것은 일반적인 오해입니다.

    우리는 우리에게 충성을 유지하고 실제 사물을 발견해야 합니다.

    대부분의 연관 배열은 응집력이 있고 실제 엔터티를 나타내므로 이를 일급 객체로 취급해야 합니다.

    처지











    학점



    사진 제공: Melissa Askew on Unsplash


    There’s nothing more permanent than a temporary hack.



    카일 심슨






    이 기사는 CodeSmell 시리즈의 일부입니다.




    최종 업데이트: 2021/09/24

    좋은 웹페이지 즐겨찾기