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.

你可能感兴趣的:(Code smell for several similar groups of constants)