0

I can't understand if I am doing code in right way. I have vibed application.

Code inside main:

User user = new User(database);
user.getUserByName("admin");

User Class:

class User
{
    string login;
    string password;

    //....
    void getUserByName(string login)
    {
        // sql request here
        this.login = row[1].coerce!string;
        this.password = row[2].coerce!string;
    }
    //...
}

How long on instance of class will be live? For example 3 users come to my site: David, Jow, Mike, so getUserByName would be called 3 times.

user.getUserByName("David");
user.getUserByName("Jow");
user.getUserByName("Mike");

Does it mean that with every new logging users class fields login and password would be overwritten in my code? It's seems yes. But is it good? Or would I have any problem like this:

for example if the field in instance of class would be initialized by David and then second user will login and field would be changed by Jow?

I decided to check my idea. And did:

    void getUserByName(string login)
    {
        writeln("login before: ", login);
        Prepared prepared = prepare(database.connection, `SELECT id, login, password, usergroup from users WHERE login=?`);
        Thread.sleep(1.seconds); // pause till new getUserByName with another name will be called (as I think)
        prepared.setArgs(login);
        ResultRange result = prepared.query();
    ...
}

and in main:

user.getUserByName("David");
user.getUserByName("Jow"); // calling another

But it's very strange that I am getting:

login before: David
login after: David
login before: Jow
login after: Jow

But I expected that after calling (second): user.getUserByName("Jow"); and after sleep I will get something like:

login before: David
login after: Jow

And I can't understand why...

Another variant as I understand is make users as structure and create new copy of structure for every user. Is it good? Or maybe there is another better solution?

Dmitry Bubnenkov
  • 9,415
  • 19
  • 85
  • 145
  • There would be no difference if you use a struct or a class. Your user class represents a single user. I think "getUserByName" should be a static method, an independent function or the constructor, so you can do: 'new User("David")' or 'new User("Jow")'. – belka Feb 12 '17 at 09:58
  • You should probably choose an entirely different software pattern to split logic and models away from each other too. Considering you're using vibe.d, go for MVC or anything along those lines. – Bauss Feb 12 '17 at 10:24

1 Answers1

1
writeln("login before: ", login);

That login does not refer to the login field of the class, because you have an argument named login. If you want the class field you'll need:

writeln("login before: ", this.login);
Idan Arye
  • 12,402
  • 5
  • 49
  • 68