Constructor chain with intermediate variables

I have the following situation with overloaded designers with whom I am struggling to find a good solution. I don't see how to use an intermediate assignment with a chain of constructors.

The following actions are invalid, but show what I want to do

public MyThing(IServiceLocator services, int? userId)
{
    // blah....
}

public MyThing(IServiceLocator services, string userName)
{
    User user = services.UserService.GetUserByName(userName);
    int userId = user == null ? null : (int?)user.Id;
    // call the other constructor   
    this(services, userId);
}

The only way I know to write above in valid code is

public MyThing(IServiceLocator services, string userName)
    : this(services,
           services.UserService.GetUserByName(userName) == null ?
              null : (int?)services.UserService.GetUserByName(userName).Id)

which is not only ugly code, but also requires a double call to the database (unless the compiler is smart enough to fix it, which I doubt).

Is there a better way to write above?

+3
source share
3 answers

:

public MyThing(IServiceLocator services, string userName)
{
    User user = services.UserService.GetUserByName(userName);
    int? userId = user == null ? null : (int?)user.Id;

    Initialize(services, userId);
}


public MyThing(IServiceLocator services, int? userId)
{
    Initialize(services, userId);
}

private void Initialize(IServiceLocator services, int? userId)
{
    // initialization logic
}

, factory :

private MyThing(IServiceLocator services, int? userId)
{
    // blah....
} 

public static Create(IServiceLocator services, int? userId)
{
    return new MyThing(services, userId);
}

public static Create(IServiceLocator services, string userName)
{
    User user = services.UserService.GetUserByName(userName);
    int userId = user == null ? null : (int?)user.Id;

    return new MyThing(services, userId);
}

:

var myThing = MyThing.Create(services, 123);
var myOtherThing = MyThing.Create(services, "userName");

factory (refactoring.com)

+2

, . , Java, , # .

+1

You can use the static helper method:

public MyThing(IServiceLocator services, int? userId)
{
    // blah....
}

public MyThing(IServiceLocator services, string userName)
    : this(services, GetUserId(services, userName))
{
}

private static int? GetUserId(IServiceLocator services, string userName)
{
    User user = services.UserService.GetUserByName(userName);
    return (user == null) ? (int?)null : user.Id;
}
+1
source

Source: https://habr.com/ru/post/1778945/


All Articles