Interface segregation principle for a framework interface with optional features - oop

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.

Related

.NET Core DI Service Collection non modifiable service for integrity

I have been investing time into .NET core and the Dependency Injection model using the ServiceCollection object.
Is there any way to protect the integrity of the service implementations that have already been added to the collection?
I would like to know that the original implementation of a service I have added hasn't been modified or replaced at some point during runtime.
In the case of security, if I was an attacker who knew what I was doing and had a remote code execution vulnerability, I could replace a key service implementation and aim to hide with a form of persistence.
In the case of fool proofing, if I had a large project I would hate to have to go debugging why something went wrong to find out a developer replaces the implementation of a service that was in widespread use.
Any suggestions? Perhaps there is some protection that prevents this, or its just not a concern?
You could implement IServiceCollection manually, defining a class, with a List<ServiceDescriptor> to implement all methods declared in the interfaces.
Then, modify the methods that may change the values of the items which are registries, adding notifying operations to determine whether the values are changed.

Implementing .Net DI Compile Time Proxies?

I'm not so much seeking a specific implementation but trying to figure out the proper terms for what I'm trying to do so I can properly research the topic.
I have a bunch of interfaces and those interfaces are implemented by controllers, repositories, services and whatnot. Somewhere in the start up process of the application we're using the Castle.MicroKernel.Registration.Component class to register the classes to use for a particular interface. For instance:
Component.For<IPaginationService>().ImplementedBy<PaginationService>().LifeStyle.Transient
Recently I became interested in creating an audit trail of every class and method call. There's a few hundred of these classes so writing a proxy class for each one by hand isn't very practical. I could use a template to generate the code but I'd rather not blow up our code base with all that.
So I'm curious if there's some kind of on the fly solution. I know nHibernate creates proxy classes at some point which overlay all the entity classes. Can someone give me some guidance on how I might be able to do something similar here?
Something like:
Component.For<IPaginationService>().ImplementedBy<ProxyFor<PaginationService>>().LifeStyle.Transient
Obviously that won't work because I can only use generics to generalize the types of methods but not the methods themselves. Is there some tricky reflection approach I can use to do this?
You are looking for what Castle Windsor calls interceptors. It's an aspect-oriented way to tackle cross-cutting concerns -- auditing is certainly one of them. See documentation, or an article about the approach:
Aspect oriented programming is an approach that effectively “injects” pieces of code before or after an existing operation. This works by defining an Inteceptor wrapping the logic being invoked then registering it to run whenever a particular set/sub-set of methods are called.
If you want to apply it to many registered services, read more about interceptor selection mechanisms: IModelInterceptorsSelector helps there.
Using PostSharp, things like this can be even done at compile time. This can speed the resulting application, but when used correctly, interceptors are not slow.

Dependency injection vs singleton, Initialization

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.

What criteria should one used to determine if Dependency Injection Framework should be used? [duplicate]

I've had a certain feeling these last couple of days that dependency-injection should really be called "I can't make up my mind"-pattern. I know this might sound silly, but really it's about the reasoning behind why I should use Dependency Injection (DI). Often it is said that I should use DI, to achieve a higher level of loose-coupling, and I get that part. But really... how often do I change my database, once my choice has fallen on MS SQL or MySQL .. Very rarely right?
Does anyone have some very compelling reasons why DI is the way to go?
Two words, unit testing.
One of the most compelling reasons for DI is to allow easier unit testing without having to hit a database and worry about setting up 'test' data.
DI is very useful for decoupling your system. If all you're using it for is to decouple the database implementation from the rest of your application, then either your application is pretty simple or you need to do a lot more analysis on the problem domain and discover what components within your problem domain are the most likely to change and the components within your system that have a large amount of coupling.
DI is most useful when you're aiming for code reuse, versatility and robustness to changes in your problem domain.
How relevant it is to your project depends upon the expected lifespan of your code. Depending on the type of work you're doing zero reuse from one project to the next for the majority of code you're writing might actually be quite acceptable.
An example for use the use of DI is in creating an application that can be deployed for several clients using DI to inject customisations for the client, which could also be described as the GOF Strategy pattern. Many of the GOF patterns can be facilitated with the use of a DI framework.
DI is more relevant to Enterprise application development in which you have a large amount of code, complicated business requirements and an expectation (or hope) that the system will be maintained for many years or decades.
Even if you don't change the structure of your program during development phases you will find out you need to access several subsystems from different parts of your program. With DI each of your classes just needs to ask for services and you're free of having to provide all the wiring manually.
This really helps me on concentrating on the interaction of things in the software design and not on "who needs to carry what around because someone else needs it later".
Additionally it also just saves a LOT of work writing boilerplate code. Do I need a singleton? I just configure a class to be one. Can I test with such a "singleton"? Yes, I still can (since I just CONFIGURED it to exist only once, but the test can instantiate an alternative implementation).
But, by the way before I was using DI I didn't really understand its worth, but trying it was a real eye-opener to me: My designs are a lot more object-oriented as they have been before.
By the way, with the current application I DON'T unit-test (bad, bad me) but I STILL couldn't live with DI anymore. It is so much easier moving things around and keeping classes small and simple.
While I semi-agree with you with the DB example, one of the large things that I found helpful to use DI is to help me test the layer I build on top of the database.
Here's an example...
You have your database.
You have your code that accesses the database and returns objects
You have business domain objects that take the previous item's objects and do some logic with them.
If you merge the data access with your business domain logic, your domain objects can become difficult to test. DI allows you to inject your own data access objects into your domain so that you don't depend on the database for testing or possibly demonstrations (ran a demo where some data was pulled in from xml instead of a database).
Abstracting 3rd party components and frameworks like this would also help you.
Aside from the testing example, there's a few places where DI can be used through a Design by Contract approach. You may find it appropriate to create a processing engine of sorts that calls methods of the objects you're injecting into it. While it may not truly "process it" it runs the methods that have different implementation in each object you provide.
I saw an example of this where the every business domain object had a "Save" function that the was called after it was injected into the processor. The processor modified the component with configuration information and Save handled the object's primary state. In essence, DI supplemented the polymorphic method implementation of the objects that conformed to the Interface.
Dependency Injection gives you the ability to test specific units of code in isolation.
Say I have a class Foo for example that takes an instance of a class Bar in its constructor. One of the methods on Foo might check that a Property value of Bar is one which allows some other processing of Bar to take place.
public class Foo
{
private Bar _bar;
public Foo(Bar bar)
{
_bar = bar;
}
public bool IsPropertyOfBarValid()
{
return _bar.SomeProperty == PropertyEnum.ValidProperty;
}
}
Now let's say that Bar is instantiated and it's Properties are set to data from some datasource in it's constructor. How might I go about testing the IsPropertyOfBarValid() method of Foo (ignoring the fact that this is an incredibly simple example)? Well, Foo is dependent on the instance of Bar passed in to the constructor, which in turn is dependent on the data from the datasource that it's properties are set to. What we would like to do is have some way of isolating Foo from the resources it depends upon so that we can test it in isolation
This is where Dependency Injection comes in. What we want is to have some way of faking an instance of Bar passed to Foo such that we can control the properties set on this fake Bar and achieve what we set out to do, test that the implementation of IsPropertyOfBarValid() does what we expect it to do, i.e. return true when Bar.SomeProperty == PropertyEnum.ValidProperty and false for any other value.
There are two types of fake object, Mocks and Stubs. Stubs provide input for the application under test so that the test can be performed on something else. Mocks on the other hand provide input to the test to decide on pass\fail.
Martin Fowler has a great article on the difference between Mocks and Stubs
I think that DI is worth using when you have many services/components whose implementations must be selected at runtime based on external configuration. (Note that such configuration can take the form of an XML file or a combination of code annotations and separate classes; choose what is more convenient.)
Otherwise, I would simply use a ServiceLocator, which is much "lighter" and easier to understand than a whole DI framework.
For unit testing, I prefer to use a mocking API that can mock objects on demand, instead of requiring them to be "injected" into the tested unit from a test. For Java, one such library is my own, JMockit.
Aside from loose coupling, testing of any type is achieved with much greater ease thanks to DI. You can put replace an existing dependency of a class under test with a mock, a dummy or even another version. If a class is created with its dependencies directly instantiated it can often be difficult or even impossible to "stub" them out if required.
I just understood tonight.
For me, dependancy injection is a method for instantiate objects which require a lot of parameters to work in a specific context.
When should you use dependancy injection?
You can use dependancy injection if you instanciate in a static way an object. For example, if you use a class which can convert objects into XML file or JSON file and if you need only the XML file. You will have to instanciate the object and configure a lot of thing if you don't use dependancy injection.
When should you not use depandancy injection?
If an object is instanciated with request parameters (after a submission form), you should not use depandancy injection because the object is not instanciated in a static way.

Creating a wrapper for BeaaS (Parse/Stackmob/...)

I'm currently developing an app using Parse and I'd like to start abstracting their SDK as I don't know if and when I'm going to replace their backend with another by other provider or by ours.
Another motivation is separating issues: all my apps code will use the same framework while I can just update the framework for any backend specifics.
I've started by creating some generic classes to replace their main classes. This generic classes define a protocol that each adapter must implement. Then I'd have a Parse adapter that would forward the calls to the Parse SDK.
Some problems I can predict is that this will require a lot of different classes. In some cases, e.g. Parse, they also have classes for dealing with Facebook. Or that the architecture in some parts can be so different that there'll be no common ground to allow something like this.
I've actually never went so far with Stackmob as I am with Parse so I guess the first versions will share Parse's own architecture.
What are the best practices for something like this?
Is there something like this out there? I've already searched without success but
maybe I'm looking in the wrong direction;
Should I stick with the Parse SDK just making sure that the code using
it is well identified and contained?
I'm the Developer Evangelist at Applicasa.
We've built a cool set of tools for mobile app developers, part of which includes offering a BaaS service that takes a bit different approach compared to Parse, StackMob, and others. I think it provides a helpful perspective for tackling the problem of abstracting away from third-party SDK APIs in a way that would allow you to replace backends by other providers or your own.
/disclaimer
Is there something like this out there? I've already searched without success but maybe I'm looking in the wrong direction
While there are other BaaS providers out there that provide similar and differentiating features, I'm not aware of a product out there that completely abstracts away third-party providers in an agnostic manner.
What are the best practices for something like this?
I think you already show to be on a solid footing for getting started in the right direction.
First, you're correct in predicting that you'll end up with a number of different classes that encapsulate objects and required functionality in a backend-agnostic way. The number, of course, will depend on what kind of abstraction and encapsulation you're going after. The approach you outline also sounds like the way I'd begin such a project, as well—creating classes for all the objects my application would need to interact with, and implementing custom methods on those classes (or a base class they all extend) that would do the actual work of interacting with a backend provider.
So, if I was building an app that, for example, had a Foo, Bar, and Baz object, I'd create those classes as part of my internal API, with all necessary functionality required by my app. All app logic and functional operations would only interact with those classes, and all app logic and functionality would be data backend-agnostic (meaning no internal functionality could depend on a data backend, but the object classes would provide a consistent interface that allowed operations to be performed, while keeping data handling methods private).
Then, I'd likely make each class inherit from a BaseObject class, which would include the methods that actually talked to a data backend (provider-based or my own custom remote backend). The BaseObject class might have methods like saveObject, getById:, getObjects (with some appropriate parameters for performing object filtering/searching). Then, when I want to replace my backend data service in the future, I'd only have to focus on updating the BaseObject class methods that handle data interaction, while all my app logic & functionality is tied to the Foo, Bar, and Baz classes, and doesn't actually care how get/save/update/delete operations work behind the scenes.
Now, to keep things as easy on myself as possible, I'd build out my BaaS schema to match internal object class names (where, depending on the BaaS requirements, I could use either an isKindOfClass: or NSStringFromClass: call). This means that if I was using Parse, I'd want to make my save method get the NSStringFromClass: of the class name to perform data actions. If I was using a service like Applicasa, which generates a custom SDK of native objects for data interactions, I'd want to base custom data actions on isKindOfClass: results. If I wanted even more flexibility than that (perhaps to allow multiple backend providers to be used, or some other complex requirement), I'd make all the child classes tell BaseObject exactly what schema name to use for data operations through some kind of custom method, like getSchemaName. I'd probably define it as a BaseObject method that would return the class name as a string by default, but then implement on child classes to customize further. So, the inside of a BaseObject save method might look something like this:
- (BOOL) save {
// call backend-specific method for saving an object
BaasProviderObject *objectToSave = [BaasProviderObject
objectWithClassName:[self getSchemaName]];
// Transfer all object properties to BaasProviderObject properties
// Implement however it makes the most sense for BaasProvider
// After you've set all calling object properties to BaasProviderObject
// key-value pairs or object properties, you call the BaasProvider's save
[objectToSave save];
// Return a BOOL value to indicate actual success/failure
return YES; // you'll want this to come from BaaS
}
Then in, say, the Foo class, I might implement getSchemaName like so:
- (NSString) getSchemaName {
// Return a custom NSString for BaasProvider schema
return #"dbFoo";
}
I hope that makes sense.
Should I stick with the Parse SDK just making sure that the code using it is well identified and contained?
Making an internal abstraction like this will be a fair amount of work up front, but it will inevitably offer a lot of flexibility to implement as you wish. You can implement CoreData, reject CoreData, and do whatever you'd like really. There are definite advantages to building internal app logic/functionality in a data-agnostic way, even if it's to allow yourself the ease of trying out another BaaS in, say, a custom branch of your app code to see how you like another provider (or to give you an easy route to working with developing your own data solution).
I hope that helps.
I'm the Platform Evangelist at StackMob and thought I'd chime in on this question. We built our iOS SDK with a Core Data interface. You'll use regular Core Data and we've overridden the NSIncremental Store to persist to StackMob instead of SQLLite.
You can checkout an example of the Core Data code.
http://developer.stackmob.com/tutorials/ios/Create-an-Object
If you want see what methods are being leveraged by Core Data to communicate with StackMob.
http://developer.stackmob.com/tutorials/ios/Lower-Level-CRUD-API