User Login Design

The Typical Software Design Story

Usually for the first version of most web applications, we have user and user login. The user login is so simple that it is verified by a username and a password. So we design the class like this.

This works pretty well for now. Project manager is happy. The developers are happy.

A month later, the team wants to simplify the registration process so that more users will sign up. your project manager asked you to support login by facebook and google accounts.

You think about it. You think about adding a type attribute to each user. But the normal users and facebook users have different information to store. This could be an obstacle so you move on and continue to think. It is very tempting to extend  User class to  NormalUserFacebookUser and  GoogleUser. They all have the same behaviours except the credential checking. So you go ahead and implement it. Project manager is happy. All developers are happy.

One more month later, we find that the application needs different type of users and you decided that using inheritance is the best design choice. However, we have already use inheritance for different login types. So what can we do?

Inheritance is not as good as you thought

Back in the college years, your professor taught you about Object-Oriented programming, giving you examples of inheritance to achieve polymorphism, code reuse etc. He didn’t tell you about the limitations. Don’t get me wrong. It might not be the fault of your professor since your OO class only lasts a semester and it wouldn’t have enough time to touch those parts.

Composition is the way

So how can we re-design the system here? Turns out it’s not that hard. We add another class for the purpose of authentication.

Common problem in web applications

Since most web applications have to store the user information and authenticate them some time later, this is a quite common problem in the field. When you are building a  User class next time, it could be a good idea to adapt the above design even before you can have different method to login.

 

 

Head First Design Patterns

head-first-design-patterns

Head First Design Patterns is a light weight introduction to object oriented design patterns. It approaches each design patterns with different perspectives and compares them to each others.

However, just like another book in the Head First series, this book contains tedious exercises and not-so-funny cartoons which I would normally skip through. Those parts make up 40% of the book which is quite annoying.

head_first_design_patterns_exercise

Nevertheless, if these don’t bother you, it will still serve your needs to dive into the world of design patterns.

Edit: Some readers misunderstood me. I don’t really hate the book, but it would be much better if the editor can improve the exercises and the way they the story. Other than that, I still think HFDP is a great book that can guide you into design patterns step by step.