X caliber
X caliber

Reputation: 50

How to write optimized constructor in a class >

I wrote writing an email class, but I am not sure if this is the best way to write this... here's the code for it...

class email
{
    string value;
    string domain;
    string com;
    string username;
    string encrypted;
    bool state ;
public:
    email(const string& val)
        :value{ val}, state{false},com(),domain(),username(),encrypted()
    {
        for (int i = 0; i < value.size(); ++i)
        {
            if (value[i] == '@')
            {
                username = value.substr(0, i);
                for (int j = i; j < value.size(); ++j)
                {
                    if (value[j] == '.')
                    {
                        domain = value.substr(i, j);
                        com = value.substr(j+1, value.size()-1);
                        state = true;
                    }
                }
            }
        }
        if (state)
        {
            for (auto letter : value)
            {
                if (letter == ';' || letter == '\'' || letter == '[' || letter == ']')
                {
                    state = false;
                    
                }
            }

        } else throw "invalid string";
        if (state)
        {
            encrypted = username;
            for (int i = 0; i < username.size() / 2; ++i)
            {
                swap(encrypted[i], encrypted[encrypted.size() - 1 - i]);
                encrypted[i] = static_cast<char>(static_cast<int>(encrypted[i]) + 3);
                
            }
        }else throw "invalid charecters";
    }
    const string& get_domain() { return domain; }
    const string& get_username() { return username; }
    const string& get_com() { return com; }
    const string& get_enc() { return encrypted; }
    const  bool good () const { return state; }
};

It's not completed yet, this is just a quick sketch from what I can remember because I don't have the actual code right now, my question is should I make another class to support the email class.. or is this the right way? I wrote a lot of code inside the constructor, that's what I am worried about.

Upvotes: 1

Views: 76

Answers (1)

Volker Hantschel
Volker Hantschel

Reputation: 36

You could break the for loops, if you have done your stuff. First for: after you found '@' you do not have to loop to the end Third for: after you found an error, you could throw immediatelly

Upvotes: 2

Related Questions