c448548
c448548

Reputation: 125

Refactoring duplicate code in C# net core

I have an existing controller code in .net core 2.0 as follow:

[Route("api/[controller")]
public class UserController: Controller
{
    DBConnect c = null;
    KeyCheck chk = null;

    public UserController(IOptions<SystemSettings> settings)
    {
        c = new DBConnect(settings);
        chk = new KeyCheck();
    }

    public CoreResponse EditUser(string key, [FromBody]User input) {

        // duplicate part start
        CoreResponse response = new CoreResponse();
        response.status = "fail";
        response.errors = new List<string>();

        if (!chk.isValidKey(c, key)) {
            response.errors.Add("Invalid Key")
        }
        // duplicate part end

        // query exection logic here
        response.status = "success"
        // query execution end

        return response;
    }
}

The part commented on duplicate part start and duplicate part end is repeated in every single place. I would like to remove those part and become something like this. Is this possible and how could it be done. Or any other advice on refactoring these code?

[CheckKey]
public CoreResponse EditUser(string token, [FromBody]User input) {
    CoreResponse response = new CoreResponse();

    // query exection logic here
    response.status = "success"
    // query execution end

    return response;
}

Upvotes: 0

Views: 560

Answers (1)

Eric J.
Eric J.

Reputation: 150118

A new instance of your controller is created for every HTTP request it serves, so you can safely move universal initialization logic into the constructor and move commonly used logic into a private method.

CoreResponse response;
public UserController(IOptions<SystemSettings> settings)
{
    c = new DBConnect(settings);
    response = new CoreResponse();
    response.status = "fail";
    response.errors = new List<string>();
}

// Could also return bool if you want the caller to take a different
// action if the validation fails.
private void ValidateKey(string key)
{
    chk = new KeyCheck();
    if (!chk.isValidKey(c, key)) {
        // Response already initialized in constructor
        response.errors.Add("Invalid Key")
    }
}

public CoreResponse EditUser(string key, [FromBody]User input) {
    ValidateKey(key);
}

Upvotes: 2

Related Questions