简体   繁体   中英

Should Users be class or arrays of structures?

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?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM