重构您的代码以从 Sonarqube 的 Swift 项目中的可自定义参数获取此 URI

问题描述

我正在处理 iOS 项目,为了代码质量/覆盖率检查,我已将 Sonarqube 设置到我的项目中。检查代码质量的好库。

它运行成功,我们也解决了大部分问题。 对于 api url,我们已经在一些常量类中声明并将每个类调用到相应的类。 但是,Sonarqube 为此抛出了以下错误并且无法理解以解决问题。

SomeConstant.Swift

import Foundation

struct SomeConstant {
    static let signInURL = "https://somesigninurl.com"
    static let signUpURL = "https://somesignuprl.com"
    static let baseURL = "https://somebaseurl.com"
    static let dashBoard = ""\(baseurl)"/dashboard/"
}

错误

重构您的代码以从可自定义的参数中获取此 URI。

他们的文档给出了以下解决方案,但我不明白他们为什么要调用编码和所有其他东西。所以,我确实正确理解了下面的代码

如何解决这个问题,有什么建议吗?

public class Foo {
    // Configuration is a class that returns customizable properties: it can be mocked to be injected during tests.
    private var config:Configuration
    public init(myConfig:Configuration) {
        config = myConfig
    }
    public func listUsers() -> [User] {
        var users:[User]
        // Find here the way to get the correct folder,in this case using the Configuration object
        let location = config.getProperty("myApplication.listingFile")
        // and use this parameter instead of the hard coded path
        let fileContent = NSString(contentsOfFile: location,encoding: NSUTF8StringEncoding,error: nil)
        users = parse(fileContent!)
        return users
    }
}

解决方法

Refactor your code to get this URI from a customizable parameter. 意味着您必须从可自定义的源中读取数据,例如配置文件:

配置文件.txt:

signInURL = "https://somesigninurl.com"
signUpURL = "https://somesignuprl.com"
baseURL = "https://somebaseurl.com"
dashBoard = ""\(baseurl)"/dashboard/"
用于解决您的问题的

伪代码如下所示:

import Foundation

struct SomeConstant {
    static let signInURL = config.getProperty("signInURL")
    static let signUpURL = config.getProperty("signUpURL")
    static let baseURL = config.getProperty("baseURL")
    static let dashBoard = config.getProperty("dashBoard")

    private var config:Configuration
    public init(myConfig:Configuration) {
        config = myConfig
    }   
}

截至

但我不明白为什么他们称编码和所有其他事情

非兼容解决方案中 Sonarqube 文档中的一个示例在读取文件内容时具有编码部分,根据您的问题,我假设您没有它,因此您可以忽略它。

public class Foo {
    public func listUsers() -> [User] {
        var users:[User]
        let location = "/home/mylogin/Dev/users.txt"     // Non-Compliant
                                                             \/_____HERE_YOU_GO_____________
        let fileContent = NSString(contentsOfFile: location,encoding: NSUTF8StringEncoding,error: nil)
        users = parse(fileContent!)
        return users
    }
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...