If you have a class that authenticates a user and then the API you're using changes its authentication method, you would rewrite the authentication class.
My question is what would you call creating code in in this pattern of "modularizing an operation" in this case authenticating a user? I feel like this is a design pattern, but I can't think of the one or is this just a benefit of smart design with object oriented programming?
Assuming that the mode of authentication is not interchangeable at runtime, you're talking about the Bridge design pattern. Otherwise, the Strategy pattern.
Related
I am designing a authentication framework. I need users of the framework to implement data access logic since it is not the main purpose of the framework and I want to allow multiple data access approaches (SQL, NoSQL, Cache etc.) I don't implement it inside my framework. My framework uses this logic through an interface called IUserStore but the problem is, there are certain methods inside my interface that are used only when certain feature is active and not used otherwise. For example framework will try to access two factor information through GetTwoFactorInfo method only if two factor authentication is enabled.
My question is about interface segregation principle. Is it ok to leave the interface as it is and explain in the documentation that user needs to implement GetTwoFactorInfo only if user wants to use two factor authentication and throw NotImplementedException otherwise? Or should I separate interface for each optional feature and explain in the documentation user should implement and register this interface to service provider to be able to use that feature? A problem with second approach is when injecting services that implement those interfaces to constructors, I need to check if those features are active otherwise I would get an error because service is not registered and I am trying to access those services from service provider. Which leads to extra complexity for my framework classes.
What would be the best way to handle this problem?
There are practical problems with both of the approaches you suggest, but the plan to have clients throw NotImplementedException is far worse.
Let's go through both of them:
Option 1
leave the interface as it is and explain in the documentation that user needs to implement GetTwoFactorInfo only if user wants to use two factor authentication and throw NotImplementedException otherwise
Well, this might work for the problem you have today, but software design is about the problems you'll have tomorrow. What happens if you add support for different authentication methods to future versions of the framework? If you follow this pattern, then you'll add new methods to IUserStore... but this would break existing clients, because they will not have implemented them!
You can get around this particular problem in some languages by providing default implementations for new methods that throw exceptions, but that defeats much of the purpose of defining an interface in the first place -- the type system no longer tells the client what he has to implement.
Also, this pattern only works for pre-existing interfaces. If you add a new authentication method that requires the client to implement a new interface, that you're back to considering something like your second option, and then you'll have an inconsistent mix if versioning strategies. Ick.
Option 2
separate interface for each optional feature and explain in the documentation user should implement and register this interface to service provider to be able to use that feature
This is much better, but also not great, because it introduces hidden rules that clients of your framework have to follow. All of the ways to find out about these rules are frustrating -- read docs, troubleshoot errors, etc.
This is a common problem in lots of dependency injection systems, though, and lots of people don't seem to mind, but things get really complicated as interacting system of hidden rules accumulates.
Option 3
I don't know how you enable this 2-factor feature right now, but I would suggest that you have your customers enable this feature by calling a method that takes the implied dependencies as arguments, like
void enable2FactorAuth(I2FactorInfoStore store)
Then all the hidden rules go away. Your system ensures that you can't enable the feature unless you've implemented the required interfaces. Easy.
If you are thinking that you will lose the ability to configure your product without programming, then I would like to remind you that you do not have that feature. As you said, there is code that clients have to write in order to use 2 factor authentication. They have to implement the store. Requiring them to call a method to enable it will only improve this code, because it will now be obvious why they had to implement that store in the first place.
Today I read a lot of articles about how Singleton Pattern is bad, such as
violating single responsibility principle
inability to subclass
inability to use abstract or interface classes
High coupling across the application
make unit test difficult
And then I remember I have a program with a class named User which has field userName and password and something else related to User. In my conceive the program should only have one user instance, which is created when a human logins in my program. Based on this, should I insist design User class as Singleton Pattern, or is there any good design conceive I should use?
Additionl:
Another doubt. Using Singleton Pattern, I can get the only instance myUser everywhere. If I should not go with Singletion Pattern, How should I get the only instance myUser?
You might want to look at dependency injection. These days there exist many frameworks to assist you with wiring of the dependency injections so that you can specify in the framework that you expect a certain object to behave like a singleton. In other words if another object also requires the same "singleton" object, the framework should not create a new instance, but "inject" the already existing instance.
If you develop in Java, you may for example look at the way Guice did it: https://github.com/google/guice/wiki/Scopes They allow you to specify whether you want to create an "eager singletons" (created even if not needed yet) or "lazy singletons" (created on the fly only when required). Even if you are not using Java other programming languages got similar concepts that you could look out for.
What I would suggest is that you make the "User" object not a singleton and "inject" your "User" object into the classes that requires the "User" object. If possible, let the dependency injection framework of your choice handle the wiring so that you do not accidentally create more than one instance.
This way you will still be able to achieve most of the above mentioned advantages you posted in your question and still enjoy the benefits of a "singleton".
It depends on your context. If your application must have one and only one User, then use Singleton pattern. Your 5 points mentioned will be completely counter-productive.
In your example, this is not the case. But just one and only one instance is mandatory for the execution of one process. You should take in account #Koning response then.
For example, Spring security implements some common patterns of user logged with static methods :
SecurityContextHolder.getContext(). getAuthentication()
If you look at Microsoft memberhship than you will see that they store all data on session level. The best way I see to implement such logic which will be stored on all session level is Singleton pattern, because you won't need two classes working with user data. As alternative you can use static classes, but you couldn't serialize your user data in this case
I'm working on a big project right now, and the app is taking advantage of many different services, as:
Comments, likes, posts, purchase and so on..
I have a class for each service.
Now, I came to a point where I would like to restrict registered users only, for some actions, as post, comment, and so on..
Till now every class use to have only class methods, as the following:
#interface UpdateOrderServies : NSObject
+(void)deleteOrder: (STOrder *)order
andReturn: (void(^)(NSError *error))errorBlock;
+(void)updateOrder: (STOrder *)order
andReturn: (void(^)(NSError *error))errorBlock;
But now, i would like to check first if the user is registerd, and if not, not to return a value.
So the best way i figgerd out is changing the classes to singel tone, and asking every time the class is called, if the user is registerd like so:
+(id) getInstance {
static UpdateOrderServies *__sharedDataModel = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
__sharedDataModel = [[UpdateOrderServies alloc]init];
});
if (![__sharedDataModel userIsRegisterd]) {
return nil;
}
return __sharedDataModel;
}
And it works, but, well, its not a very good answer as you can see.. i would like somthing more generic.
I was thinking about using Typhoon dependency injection, but there is no place were i could check every call if the user is registered...
Any idea for a better way to deal with this issue? more dynamic...
Based on your question above, I think you're not looking for dependency injection but Aspect Oriented Programming.
Aspect Orientes Programming (AOP) is designed to solve exactly the kinds of problem you describe above - those that cut across many modules in your system. Examples:
every time a user interacts with a service, security should be checked.
all transactions should have an audit trail
every store interraction should result in a genius recommendation
If we use normal Object Oriented programming for these cross-cutting requirements, we break the single responsibility principle and a class that should've been nearly about one topic is now taking on more roles which gets confusing, repetitive and messy.
AOP modularizes these cross-cutting concerns and then identifies all of the places these should be applied using method interception. (In AOP we call this a point-cut expression).
In Objective-c you could either do manual AOP using ISA-swizzling, message forwarding or or using NSProxy - these are all ways of achieving method interception at run-time. Alternatively, you could use a library and one such library called 'Aspects' by Pete Steinberger and team. This library doesn't have a point-cut expression language as yet, but is still certainly much simpler than using the ObjC run-time directly to intercept methods.
Summary of how an Authorization Aspect would work:
At login we authenticate our user, using a username/password challenge, oauth token or similar. Having authenticated a user we are now able to authorization service invocations.
Identify each of the services that require authorization, and the required permission (you can whatever scheme you like roles, capabilities, etc).
Good Object Oriented principles say that each class should have a single responsibility. So your service client should be all about invoking the remote service. We could edit the service client to evaluate the logged in user's permissions and decide whether to proceed. But this would be messy and repetitive. Instead we'll use the information in step 2 (permission required for each service) and delegate that evaluation of that to our authorization module.
Now the AOP step: For each service call, we'll tell our AOP lib to intercept service client method and first invoke the authorization module.
This way your cross-cutting requirement (authorizing client invocations) isn't repeated. Now you may to decide for the sake of simplicity that you can prefer with having each service call invoking an authorization module, but it nonetheless helps to know the theory behind AOP and cross-cutting concerns.
Dependency Injection / Typhoon
Dependency injection doesn't really relate directly to your question, though it can certainly help to avoid the pitfalls of your singleton clients:
Creates a clear contract between your classes - increasing code cohesion.
Identify the key 'actors' in your application, and describe the way they are assembled into a whole. Makes it possible to swap one actor for another that will fulfill the same contract.
Simplifies unit testing using mocks and stubs.
Simplifies integration testing - being able to swap one actor for another to put the system into the required state. For example, patching out just an authorization module.
I have a direct question: Is a good pratice use Singleton pattern to control a class responsable for Login tasks, or another pattern is more appropriated? Or do not exist a patter to do this kind os issue?
Thanks.
Few people use singletons these days as they are almost becoming anti-patterns. I would recommend to learn Dependency Injection (DI).
With DI you can register the object you wish to use as singleton with a container and that container will serve or give that object to all other objects that need it. Of course you can register the object as a singleton - but not the usual singleton - and the container will guarantee that all objects which need it will receive the same instance.
Nevertheless, if you are building a small application then It would be better to use the Singleton pattern and avoid DI.
Jon Skeet has a very nice article about Singleton pattern or if you are using Java then you could use Enumerations to implement it, look implementations techniques on Google.
The singleton pattern is used when you have to prevent the creation of more than one instance of the same class. I do not really see the situation in which a login class should only have one instance so i would say using this pattern for a login class is overkill.
Then again, introducing a DI framework when you only need a simple singleton... now thats overkill :)
Yes and no. There's no 'best' or 'worse' practise.
Just do it, if using a singleton makes it easier to test and if the approach will get you to the pub earlier than learning and implementing DI just for the purposes of login.
Currently I am creating a WCF service which has to connect to a DAL which, just connects to a database using ADO.net and stored procedures.
The DAl writes its responses from the database to a datacontract which is passed over the wire to the client via the service.
I was reading that this may possibly be the anti pattern 'CRudy Interface', but I wasn't sure as I am sharing the datacontract.
If I am using an anti pattern, can anyone suggest a better pattern to use for the behavior I require?
Well, there seems to be some controversy about the CRUDy pattern and it's pros and cons. At a minimum, I would call a service interface that makes you write this kind of code to use it an anti-pattern (as commented here):
service.CreateCustomer(c);
foreach(Group group in c.Groups)
service.AddCustomerToGroup(c.CustomerId, group.GroupId);
foreach(Person person in c.Contacts)
service.AddCustomerContact(c.CustomerId, person);
Is exposing CRUDy interfaces bad in itself? I wouldn't say so. What's important is to provide an interface which will
encapsulate knowledge about the underlying processes
not be very chatty
It does seem like the CRUD interface anti-pattern, but it would be good to see some interface examples to confirm.
This paper has a really good discussion on designing better service interfaces.
It includes a critique on, and alternative to, the CRUD anti-pattern.
If you have a cruddy use case to implement you will get a cruddy interface, don't sweat it. The anti-pattern is when you implement non-cruddy things in a cruddy way.