Code smell for several similar groups of constants

In programming, if you defined several similar groups of constants like these, and you have several switch statements in your code to do the mapping:

typedef NS_ENUM(NSUInteger, AssetCompressionQuality) {
    AssetCompressionQualitySmall,
    AssetCompressionQualityMedium,
    AssetCompressionQualityLarge,
    AssetCompressionQualityOriginal
};

// These constants are used for the image/video file size calculation
extern float const kAssetSizeCalculationRatioSmall;
extern float const kAssetSizeCalculationRatioMedium;
extern float const kAssetSizeCalculationRatioLarge;
extern float const kAssetSizeCalculationRatioOriginal;

// These constants are used for the image compression parameters
extern float const kJPEGRepresentationSmall;
extern float const kJPEGRepresentationMedium;
extern float const kJPEGRepresentationLarge;
extern float const kJPEGRepresentationOriginal;

switch (self.currentQuality) {
    case AssetCompressionQualitySmall:
        size = size * kAssetSizeCalculationRatioSmall;
        break;
    case AssetCompressionQualityMedium:
        size = size * kAssetSizeCalculationRatioMedium;
        break;
    case AssetCompressionQualityLarge:
        size = size * kAssetSizeCalculationRatioLarge;
        break;
    default:
        size = size * kAssetSizeCalculationRatioOriginal;
        break;
}

You should stop doing this because they look similar and they will have a mapping relationship. The correct way will be creating a new helper class and have the enum defined there and have multiple static mapping methods there. Like this:

typedef NS_ENUM(NSUInteger, AssetCompressionQuality) {
    AssetCompressionQualitySmall,
    AssetCompressionQualityMedium,
    AssetCompressionQualityLarge,
    AssetCompressionQualityOriginal
};

+ (float)assetSizeCalculationRatio:(AssetCompressionQuality)currentQuality {
        switch (currentQuality) {
            case AssetCompressionQualitySmall:
                return kAssetSizeCalculationRatioSmall;
            case AssetCompressionQualityMedium:
                return kAssetSizeCalculationRatioMedium;
            case AssetCompressionQualityLarge:
                return kAssetSizeCalculationRatioLarge;
            default:
                return kAssetSizeCalculationRatioOriginal;
        }
}

In this way, you will have a couple of benefits:

  1. The code is better organized and stayed in one file. So it is easy to maintain if there're any changes or any new types added.
  2. No need to repeat the switch statement in multiple places.
  3. Easy to write unit tests and reduce the typos possibility in multiple places.
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容