Is it possible to inject an NSManagedObject instance using the Typhoon framework? - ios

I would like to inject NSManagedObject subclasses with the Typhoon framework. I have not seen an example of that, but I am thinking it might be possible.
I am using MO Generator, and have a superclass in between the NSManagedObject and the ultimate child class.It's in this common abstract base class where I would want to inject if that makes any difference.
Has anyone had any success with this?
Any advice would be appreciated. Please let me know if there is more information that I can provide.

Setting up Core Data with Typhoon:
Firstly, if you want to set up Core Data with Typhoon, so that you could inject, for example, data sources into your view controllers, there is a Typhoon+CoreData+RAC sample application that was kindly posted by Ryoichi Izumita. It shows:
Typhoon's UIStoryboard integration
Core Data
Reactive Cocoa
In this sample . . .
The top-level assembly is CDRApplicationAssembly
The AppDelegate is injected at startup with some Core Data components. This allows the app delegate to save the context when the application is terminated.
The's a CDRViewController, which is declared on the main story board. Because we've boot-strapped Typhoon from the app's plist file all storyboards will be an instance of TyphoonStoryboard. These work just like regular storyboards with the added benefit that dependencies are injected according to the rules outline in our assembly. This controller is injected with a Core Data datasource.
Ryoichi-san created a category on NSManagedObjectContext, making it easier to set up with DI and integrate Reactive Cocoa.
Core Data Assembly:
The main assembly refers to a helper assembly - CDRCoreDataComponents, which is responsible for setting up core data. Some of the values in this file are loaded from a configuration file, which makes it easy to set up eg production vs test environments.
Now to address your question specifically. . .
Injecting model classes themselves:
Often persistent domain objects tend to have properties without methods, and many argue that this should not be the case (its called by Martin Fowler and others 'the anemic domain object anti-pattern). They argue that in a correct object-oriented design, model objects will have behaviors as well as properties, and that the ideal place for behaviors is close to the data that they represent.
The problem is that:
In order for domain objects to have behaviors, they must often rely on collaborators.
But of course, if the objects seek out their own dependencies, we'd have another anti-pattern. DI is required.
The 'hook-point' approach (supported by Typhoon):
We can instruct Typhoon to inject a pre-obtained instance as follows:
Knight* knight = ... //Loaded from persistent storage
[componentFactory inject:knight]; //Matches by type
[componentFactory inject:knight withDefinition:#selector(selectorInAssembly)];
This is the 'hook-point' approach. After obtaining an instance we tell Typhoon to inject it. First we inject the TyphoonComponentFactory itself into our Data Access Object, network client or whatever will be emitting the object. As the last step, we tell Typhoon to inject our model, according to the recipe defined in the assembly. Et voila!
A custom core data integration (not supported by Typhoon):
Instead of using this 'hook-point' approach, perhaps we could provide a tighter integration with Core Data (as we've done with UIStoryBoard), so that the above step is not necessary? This is not currently supported by Typhoon.
Using AOP to Inject Domain Objects: (not supported by Typhoon)
In fact, besides a specific solution for Core Data, there's another approach to inject any domain object using "AOP". By that we mean intercepting and instrumenting all of a domain object's init methods to subsequently load dependencies according to the rules in an Assembly. This is how the #Configurable annotation in Spring (a popular DI+AOP framework for Java) works. The problem is finding a suitable way to associate the model object with a TyphoonComponentFactory, without this being too invasive (ie a singleton). There's some drawbacks to saying "every instance of this Product, Car and Holiday are associated with this assembly", which is why we've favored the "hook-point' approach so far.
Your Feedback:
If you're happy with the hook-point approach then great. If you're interested in either a specific core data integration or the "AOP" solution described above, then we'd enjoy exploring it with you. There's been a few discussions already.

Related

SpecFlow - Context Injection vs Scenario Context

Anyone using SpecFlow will likely have come across Context Injection and Scenario Context for storing data across different binding classes. (For more detail see: https://specflow.org/documentation/Sharing-Data-between-Bindings/)
As a Developer, the Scenario Context just seems very brittle compared with the Context Injection. You use strings to save and retrieve data and it is basically a global variable system, which to me normally seems wrong. The dependency injection, on the other hand, works nicely with different classes being able to be created to store different types of data.
Can anyone see a reason why you would want to use Scenario Context over Context Injection? I cannot think of any but maybe I am missing something?
On the difference: In addition to that context injection gives you better static type safety. (I have written a post about the decentralized architecture model you can build up with context injection: http://gasparnagy.com/2017/02/specflow-tips-baseclass-or-context-injection/)
Why Scenario Context? First of all, this feature existed before context injection and has been used in many tutorials, etc. So it is somewhat better known.
Also scenario context is somewhat an easier programming concept. You just get and set some global variable. For context injection, you have to understand constructors, instance fields and local variables. I think these are important things to learn anyway, but might be too much at once (without help).
Scenario context might be also useful is when you write generic SpecFlow plugins and you don't want to be dependent on the fine details of the dependency management system of the concrete project, but this is a pretty special case anyway.
Scenario context is using strings. Which means you can pass the string as a parameter of your test. You could write a generic test method to store something in a Scenario Context variable.
Eg :
public void GenericSaveIntTestMethod(string variableName, int intToSave){
ScenarioContext.Current[variableName] = intToSave;
}
You could reuse this. Saving different int's with different names.
I'm not sure if this is good or bad practice, but I've seen it used in the framework I'm working in.
I'm not sure if there is a way to do this with Context Injection.

How can I split domain logic and data access in Grails

How can I split domain logic and data access in Grails (and is it a good idea)?
Many software applications we write are rather data(base) centered and in Grails one often persist from service classes or controllers directly to a database configured in DataSource.groovy. It is easy to change database, but we are not really independent of the persistence implementation in the code.
I am trying to write an application that opens for different persistence and data source (not only database) implementations and focus on the business domain instead of database entities. This is also a plus when testing (easy to write fake/mock persistence)
Initially I have only one persistence implementation - Grails domain classes, using GORM. But it is a possibility that I in the future would like to have other data sources than a database, for example rest services or something else.
For now, I only have the database as data source though and do mostly crud stuff (and some domain logic). I think I am still in a way stuck in "old" thinking, focused on database persistence, because most of my business domain classes, have a Grails domain class equivalent that is a copy of it. When domain classes are to be persisted, I just copy the properties to the Grails domain class.
I am not very happy with this solution. I can think of at least two possible improvements/changes:
My Grails domain classes could be organised more differently from the business domain classes, so I don't just copy properties from one class to the other. This will still involve a lot of property mapping from one class to the other when reading or writing from/to the database though.
Maybe there is a way to use business domain classes, from a regular src/main/groovy package and decorate with GORM stuff? Or in some other way split the domain logic and persistence? I have seen it is possible to do this by using hibernate conf over the domain classes. Is this the only way?
I have seen some interesting discussions of Grails architecture, including clean architecture, hexagonal architecture and ddd, but I have not found any examples yet. Are there any?
At this point, as I said, much of the functionality is CRUD stuff, but not everything. And further on, the application may have more business logic, so I would prefer not to use the "default" architecture of Grails with views, controllers, services, domain. I want a "core" application that is in a way independent of grails view/controllers and domain/GORM
It's been some time since you posted your question, but this is a very interesting topic for me...
I currently work in big-ish Java8 projects that implement principles of clean architecture, ddd, cqrs and hexagonal architecture among others. I also have limited experience with Grails 1.x projects and I remember asking the same questions as you are now.
Now that I have a broader perspective, I honestly think that it doesn't make sense to force Grails into a clean architecture. You're going to have a very painful time trying to achieve it and you probably won't be pleased with the result.
Everything in Grails is designed to be used in an opinionated, convention based way. Starting with GORM being an ActiveRecord implementation and following by every little decision that they've made about directory structure, semantics on artifacts that you need to define (controllers, services, models...), etc.. I'm not saying this is bad. In fact, this is great when you're developing something that fits into this schema-of-things.
This coupling and implicit behavior between your artifacts makes really hard to model your business logic apart from your data access (or your http interaction, or any other interaction with third parties for that matter).
From a DDD point of view you should favor data or collection based Repositories over ActiveRecord implementations. Then you can start separating your persistence logic from your Domain model. Trying to do this while maintaining ActiveRecord-like interaction with your persistence layer is going to produce a very "dirty" layer of adaptation with lots of repetition.
You will have a really hard time especially while trying to adapt complex Domain with aggregate objects that should go into different database tables, for example.
Now, addressing the two improvements that you suggest, this is what I can tell you about them:
My Grails domain classes could be organised more differently from the business domain classes, so I don't just copy properties from one class to the other. This will still involve a lot of property mapping from one class to the other when reading or writing from/to the database though.
You can indeed do what you say. Just place some code on src/groovy folder. The main problem that you will face here is dependency injection. Grails automagically injects dependencies on your services and controllers when they're defined in the standard directories. For everything else, you need to explicitly tell Grails how to take dependencies and pass them to your custom artifacts.
Maybe there is a way to use business domain classes, from a regular src/main/groovy package and decorate with GORM stuff? Or in some other way split the domain logic and persistence? I have seen it is possible to do this by using hibernate conf over the domain classes. Is this the only way?
If you decorate your Domain objects defined in src/groovy with GORM (if it is even possible) you will have the same problem. Your mission here is to isolate your Domain from the persistence logic. Doing so by having any GORM in it fails its purpose.
Everything considered my advice here would be to:
switch to other less coupled libraries that let you desing your own architecture (i.e. Ratpack, Jooq) or
if that is not an option, just embrace the Grails-way-to-do-things completely.
There is a very comprehensive list of libraries that you can browse for inspiration: Awesome Java

In Dependency Injection where is an object to be injected created?

If it was created by the class that is injecting it into the object that uses it then isn't it just moving object creation one step up the stack? And wouldn't this mean that all objects needed by lower level classes would need to be passed through each object one at a time until it reached the object that needed it?
All objects and their dependencies could be set up at the very beginning, but wouldn't this dent performance as objects will be hanging around until needed?
Yes, it is moving the object instantiation up the stack. But it is moving it up the stack to a place where you can make a better decision as to which implementation to actually use. If I want to replace my data access layer with a stubbed version to do performance testing of the business logic, I can without changing a single line of the business logic code.
There are may ways to inject your dependencies. In my case, I use constructor injection everywhere. Using this method, if a lower level class needs a dependency, it just puts the interface for that dependency in its constructor. No need to pass from a class higher up in the stack. If you need the same instance in both classes, then you should look at the lifestyle/scope of when registering your dependency into the container so that both classes happen to get passed the same instance.
Some DI implementations use lazy loading to instantiate their objects. (i.e. it's not until the object is attempted to be used that it is actually instantiated) Some do not. Also, you would need quite the large dependency graph to make a dent in performance. Keep your constructors simple and fast (a good practice anyway) and this will not be a problem, I assure you. And DI containers are smart about releasing objects that are no longer in use (again, pay special attention to lifestyle/scope).
I hope this helps.

asp.net MVC ddd DRY vs loose coupling and persistance/data access layer

So as I understand it with good loose coupling I should be able to swap out my DAL with a couple lines of code at the application root.
I have 2 DAL written, Linq-to-sql and a JSon file repository (for testing and because I wanted to try out the System.Web.Scripting.JavascriptSerializer).
linq to sql will create entities instead of my business models. and feed them upwards through an IRepository which is using constructor injection at the application root.
my JSon layer doesn't have any autogenerated classes from which to deserialize so I'm lost as to a simple way to have it depend on an interface or abstract class and still function.
This question is based on the following assumptions/understandings:
I believe I would need the linq to sql layer to implement an interface so the application domain at compile time can dictate that the entity classes are going to have a place to read/write all the current model's fields
Any Business logic dictates a need for another set of classes with almost the same names and same properties in the model layer
Then conversion methods that take the DALs objects and translate them to business objects and back would be needed. (even if both sides are implementing the same interface this seems very inefficient)
This code is yet another place that would have to make a change if the model class or interface changed (interface, business class, view, dal entity)
Deserialization of any alternative DALs requires I create 'entities' with the same properties and fields in that layer(more duplication)
So to meet all of the flexibility/agility goals it appears I need an interface for each application domain/business object, a concrete class where business logic can live, and DAL objects that implement the interface (this means layers that don't autogenerate entities would have to be hand coded pure duplication).
How would I use loose coupling without a ton of duplication and loss of DRY?
Welcome to the beautiful and exciting world of loosely coupled code :)
You understand the problem correctly, but let me first reiterate what you are already implying: The Domain Model (that is, all Domain classes) must be defined independently of any specific Data Access technology, so you can't use auto-generated LINQ to SQL (L2S) classes as a basis for your Domain classes for the simple reason that you can't really reuse those together with other technologies (as you have found out with your JSON-based Repository).
Interfaces for each Domain object is not even going to help you, because to avoid Anemic Domain Models you will need to implement behavior in the Domain classes (and you can't put behavior into interfaces).
This means that to hydrate and dehydrate Domain objects you must have some mapping code. It has always been like this: in the old days we had to map from IDataReader instances to Domain classes, while now we need to map from Data (L2S) classes to Domain classes.
Could we wish for something better? Yes. Can we get something better? Probably. The next version of the Entity Framework will support Persistence Ignorance for exactly this reason: you should be able to define your Domain model as POCOs and if you provide a map and a database schema, EF will take care of the rest.
Until that arrives Microsoft doesn't have anything that offers this kind of functionality, but NHibernate does (caveat: I have zero experience with NHibernate, but lots of smart people say that this is true, and I trust them on that). This is a major reason that so many people prefer NHibernate over EF.
Loose coupling requires lots of mapping, so I can only second queen3's suggestion of employing AutoMapper for this kind of tedious work.
As a closing note I do want to point out a related issue: Mapping doesn't necessarily imply a violation of DRY. The best example is when it comes to strongly typed ViewModels that correspond to a given Domain object. Don't be fooled by the semantic similarity. They may have more or less the same properties with the same values, but their responsibilities differ vastly. As an application grows, you will likely experience that little divergences sneak in here and there, and you will be glad you have that separation of concerns - even if it initially looked like a lot of repetitious work.
In any case: Loose coupling is more work at the beginning, but it will enable you to keep on evolving an application where a tightly coupled application would freeze in maintenance hell long before. You are in for the long haul, but instant gratification it ain't.
Not that I understand the problem correctly, but to solve duplicated classes you may use AutoMapper.
Note that you may apply mapping declaratively or using reflection, i.e. semi-automatically. For example see here - this is not about data layer, but shows how simple attributes can help to automate mapping. In that case MVC applies attributes, but you may invent your own engine that looks for [Entity("Order")] attribute and applies AutoMapper.
Also you cannot have 100% persistence independency with just "couple of lines". ORM selection plays big role here. For example Linq-To-SQL cannot use plain classes (POCOs) so it's not as easy to re-use them as with NHibernate, for example. And with Repository you're going to have many queries in the data layer; different ORMs usually have different query syntax or implementation (even Linq not always compatible between ORMs) so switching data access can be a matter of replacing data layer completely, which is not couple of lines (unless your app is "Hello, world!").
The solution with AutoMapper above is actually a kind of self-baked ORM... so maybe you need to consider a better ORM that suites your requirements? Why don't you use EF4, especially given that it supports POCOs now, and is very similar to Linq-to-SQL, at least with query language?

When to use Dependency Injection

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.

Resources