I'm starting to see Contexts everywhere I look. In ASP.NET MVC, there are ControllerContexts, RequestContexts, HttpContexts, FormContexts. In Entity Framework, you have ObjectContexts and DbContexts. Ninject has Ninject.Activation.IContext.
What the heck is a context?
Well, it's kind of a dependency-injection thing, that allows people to say 'Here is the environment you will operate in'. Generally, they provide, unsurprisingly, the "context" for whatever it is. I.e., some state. Perhaps the URL, perhaps some HTTP headers, whatever.
You are seeing a lot of them because ASP.NET is focused on testing and hence allows these items to be "swapped in", such that you can provide your own context implementations (i.e. define your own state), so that you can run tests appropriately and successfully.
If you're wondering what state is, well it's just various bits of data that are "given", by the environment. I.e. today it is cold in the office. This is part of the state. But perhaps I want to run my test when it is hot in the office, so I would be able to subclass OfficeContext and return the appropriate state for the appropriate method/etc.
IMO, Context denotes some (possibly mutable) state about some thing. Typically context would be cross-cutting layers and often carries domain neutral data across layers.
Context is information outside of the scope of the thing you're currently doing but which has implications that may be essential.
Imagine if someone asks you the meaning of the English word "fly". There are multiple definitions: the buzzing little inspects or the sustained act of gliding through air. In order to give the right answer you need the context which tells you which definition they're looking for - are they reading a book about Diptera or the Wright brothers?
Regarding computing, say you're implementing an HTTP handler. It might be able to generate a response without knowing anything else (Hello, World!) but it's more likely that it needs the context of the HTTP request information - what were the request parameters, acceptable encoding types, etc. so it can produce a meaningful response to the user agent.
I think of them as being like your environment variables and profile settings in a telnet/ssh session. They bundle together different settings to allow tools to perform differently based on the context (i.e. environment) they're run in.
IMO, it's just another argument. In my (limited) experience, I've seen it be the calling class. You have to know what you're doing to do what you're doing well. Context is what you're doing, what's happening/running.
The above answers are by and large quite good. The only thing I would add is that its most common usage is as a "glue" to lower layers of a system. Generally the system in question is some kind of "container" system, where your code is executed inside of a larger code base that hides a lot of execution details from you. The context is the abstracted interface to that larger system.
Related
This question might be asked a thousand of times but a lot of confusions and contradictions in the answers.
I ask about the validations in the context of domain driven design.
In which layer should the validations be done mainly ?
Is it acceptable for the object to be in invalid state? because many answers said that it's okay and mainly because of historical data and the business rules may change over time and loading historical data might cause problems?
Many implementations consider throwing exceptions in the domain layer and mapping the messages to the UI although Martin Fowler recommends to Replacing Throwing Exceptions with Notification in Validations! When to return messages and when to throw exceptions in the validation context ?
Many articles explain some tips or paths to follow like Vladimir Khorikov and jbogard in their articles but in the comments they confess that they do things a wee differently now. Are these patterns still valid?
Should I use framework like FluentValidation and if I use it, Is this frame work used only in the application layer as an alternative to the MVC annotations ?
When Should I use Business Rule Framework (BRF) instead?
I know many questions here but they target the same spot(Validation in DDD).
Note: I don't use CQRS pattern because it made the application so complex.
So I have (domain layer,data layer, application layer(MVC), and shared kernel)
In which layer should the validations be done mainly ?
Mainly in Domain, except for infrastructure related validation, e.g. xsd validation or json schema for instance.
Is it acceptable for the object to be in invalid state? because many
answers said that it's okay and mainly because of historical data and
the business rules may change over time and loading historical data
might cause problems?
It can be acceptable, because validation is done into domain it should not be the case. On a point of view of business, objects cannot be in an invalid business state, however, some times, like in the real life, process can be in an invalid/temporary state. We call it eventual consistency (https://en.wikipedia.org/wiki/Eventual_consistency), I suggest you take a look at this. At the end the system will be in a valid state and that's all that matter, if its temporarily invalid, well, the effort might be bigger to maintain such system but sometimes you have no choice.
Many implementations consider throwing exceptions in the domain layer
and mapping the messages to the UI although Martin Fowler recommends
to Replacing Throwing Exceptions with Notification in Validations!
When to return messages and when to throw exceptions in the validation
context ?
I am not a big fan of exceptions in the domain layer unless this is clearly a pre-requisite thesis broken. For instance an input too large for a field, or a negative price for an item. If you cannot build a valid business object, then in my opinion this is a very valid case for an exception. In case this is a business case, a message is best suited.
Many articles explain some tips or paths to follow like Vladimir
Khorikov and jbogard in their articles but in the comments they
confess that they do things a wee differently now. Are these patterns
still valid?
Should I use framework like FluentValidation and if I use it, Is this
frame work used only in the application layer as an alternative to the
MVC annotations ?
Best recommendations in DDD is to never use framework, Spring or JDBC might help however but in general you should do it by hand. We have written even stores by hand, application services and Oracle projections and event bus. Its more faster, more maintainable, and you learn a lot more. Vaughn Vernon in his book (Implementing Domain Driven Design) gives very good examples and a project you can look at: https://github.com/VaughnVernon/IDDD_Samples (written in Java)
When Should I use Business Rule Framework (BRF) instead?
Again, don't use a framework
There are actually several different activities that might be called "validations", and they are all handled somewhat differently.
Message validation usually happens as close to the boundary as we can manage. When I receive an HTTP request, I'm going to verify that the request itself is well formed, that the right media type is specified in the meta data, that the request body can be processed cleanly, that the resulting DOM has all of the required fields, that the known data nodes are all of the appropriate type, that the values present are within the allowed ranges, all before I worry about the current state of the domain model.
Often, this validation takes the form of transforming the data from the message into a graph of value objects in the domain; that will usually look like factories or builders that know how to take domain agnostic value types and convert them into domain specific values. The domain model won't normally know anything about the message format, and won't know about the serialization (JSON is not normally a domain concern).
There is a similar separation of concerns when reading values from the persistent store - the value factories will know how to create values from primitives, but won't necessarily know anything about JSON, or results sets, and so on.
The "business logic", which validates whether a given message is meaningful given the current state of the domain, usually lives within the domain model.
Is it acceptable for the object to be in invalid state?
It shouldn't ever be acceptable for an object to be in an invalid state.
BUT there are valid states that aren't reachable. Negative account balances are becoming a significant liability for the company, so a new business rule is introduced that prevents withdrawals that would result in a negative balance. That doesn't change the fact that Bob's account balance is negative. It's still a valid state, just one that isn't reachable with the new rules.
When to return messages and when to throw exceptions in the validation context ?
Don't use exceptions to implement contingency management.
There are straight answers for your questions. So I put the answers with no background.
In which layer should the validations be done mainly?
Both server and client side for more accurate and secure applications. Regardless of design context. For server side you may employ different ways like fluent validation or Data Annotation (Model) or bring them to client with integration libraries like jquery-unobtrusive-ajax. Server side validation is more important, since CRUD operations needs to be validated to avoid anomalies and etc ....
In terms of your question, layers are View and Model (Data Access).
Is it acceptable for the object to be in invalid state? because many
answers said that it's okay and mainly because of historical data and
the business rules may change over time and loading historical data
might cause problems?
It's acceptable, required fields or empty values for required dependencies fires error when you show or process data store in Database. Here, there is no speaking about changes which can be over time. We only consider now. We employ patterns and programming rules to create flexibility/maintainability. Validations and entry dependencies can be changed over time.
Many implementations consider throwing exceptions in the domain layer
and mapping the messages to the UI although Martin Fowler recommends
to Replacing Throwing Exceptions with Notification in Validations!
When to return messages and when to throw exceptions in the validation
context ?
Showing exception in client-side is a good technique for development days or notifying corresponding user about the error which prevents data to be changed/stored. considering that: some systems really have no strategy to show additional info to the end user. Some reports can make the app more vulnerable to intrude. This is completely based on the software type you are developing. A good practice is showing a simple error in client-side and store error logs inside server (with comprehensive details).
Many articles explain some tips or paths to follow like Vladimir
Khorikov and jbogard in their articles but in the comments they
confess that they do things a wee differently now. Are these patterns
still valid?
Some people may have personal architectures with their own naming. But some of them are official and widely used like Unit Of Work or Repository Pattern which add some layers to famous pattern (MVC) to achieve more accurate, clean and maintainable code/application. Follow the main purpose behind any pattern.
Should I use framework like FluentValidation and if I use it, Is this
frame work used only in the application layer as an alternative to the
MVC annotations ? When Should I use Business Rule Framework (BRF)
instead?
FluentValidation is an alternative to DataAnnotations working like the FluentAPI. Note that both used to define rules for properties belonging to a defined class (a database table). There's a concept named ViewModel which contains a transformation(with some changes) for Main Model class (Table) mainly targeting the validation in front-end. You may employ both for a project, mapping each Model to its ViewModel or vice versa. If you are using a repository pattern, say, have a Data Access Layer, So some of the validation is inside this layer. If you're using ViewModel, so it's inside application layer. But, As an advice, These are worthless. The key success is to understand main purpose behind any technique/architecture/pattern. You can find tons of article around each of them and focus on purpose, then you can decide what to do to have a more clean/standard/maintainable/flexible/etc... code.
And the Final Tip : Increasing the modularity increases the cost to integration (software cost) Although decreases cost for each module. Use a moderate design for your project. Combining architectures sometimes not only is not a good idea but also increases the cost and development hardships. More details in software design basics
I'm doing some research on the workflow concepts and specifically BPMN standard. And I'm mostly interested in the available software on the subject.
I've already studied software like Activiti and jBPM, both of which are implemented in Java. As great as they are, I'm looking for something else. Even though such software call themselves BPM Engine I would rather name them BPM Engine Servers. They are stand alone servers (with web based GUI) which makes it really hard to embed them in other servers.
Now my question is: Is there a concept as BPM Engine in the manner it only executes the given BPM with the given data, only one step? Without any GUI or direct user interaction (something like a library)? What should I search for? What is it named? Are my expectations valid?
[UPDATE]
I've spent the last hours studying Activiti's user guide. I'm still not sure if I can use it the way I want it to! And I'll be grateful if someone can confirm it.
I'm interested in a console-like application which I can run whenever I like, give it the previously running process (most likely serialized as a string). The engine should construct the process based on the given history.
Once the process is reconstructed, I would like to move it forward one step by telling it what has happened. Then it should inform me of the next tasks to be performed and shutdown.
Finally I'll be storing the updated process after getting it as a string (the engine should serialize it in a way so it can unserialize it later).
I don't want the engine to have its own database or memory storage. I want it to shutdown completely once it's done. This is what I mean by Engine, no user interaction, no storage access.
Can any of the BPM engines perform in such a way?
perhaps I am missing your point, but Activiti is really nothing more than a jar file that can be embedded in any other java application. Certainly in order to run Activiti in any meaningful way you need a backing datastore (database) and one or more process definition, but as you can see from the unit tests that are part of Activiti, the database can be in memory and the process definition can be included in the war. There are many examples of Activiti (and likely jBPM) used as simply an embedded state machine with no exposed UI or user interaction.
My company has implemented a number of such solutions for different organizations.
If I have missed your point, feel free to give me an example of your requirement, I'm sure we have addressed it at one time or another.
You might be interested in Bonita BPM.
This open source BPM solution offers an execution engine that can be used as a standalone.
Just like its competitors, it also offers an optional GUI in the form of a web based application: Bonita Portal.
I think the challenge for what you want to do is that most of the BPM Engines separate the definition of the process from the execution. So for most of them you need someplace that will allow you to store the definition long term (typically a database) and then they track the state of a given instance of that definition for you.
If you wanted a truly stateless BPMN "interpretation" engine, then your serialized data would have to include not only the current state of the process, but he process definition as well. I'm sure this can be done, but I don't think any of the engines have taken this approach as doing so would add complexity to the solution, and solves a problem that not many people seem to be asking about.
Additionally it begs the question "given that we now have a process that knows what task it is on, how does that task actually get executed?" In most of the solutions I've seen the execution of the task takes place in the same server as the engine. In some where the execution is in a different technology, the "executor" doesn't understand the Process much at all except to make a call to signal "okay this thing is done" and the engine handles what happens next. You want to have this data in a serialize data structure of some sort, so the question would arise "If we have this stateless BPMN Engine, would the executor of the task have to update the serialized data to indicate the state change for the task".
There are other requirements of the BPMN specification that I think would make your approach very difficult, such as how to handle items like Intermediate Message Events that are either waiting for a specific time, or a message, before moving the process forward. While all of these are potentially solvable, it certainly would take significant re-engineering of current approaches.
I'm working on an iOS app where we need different binaries for each customer based on their needs. A customer may want to change all the colors, icons and texts. We can do that through white labeling process. The problem here, though, is when they ask for different behavior, for instance, removing login screen and making it optional to login.
I thought we can use dependency injections and use different handlers for each customer if needed. For instance, we can have LoginHandler1 and LoginHandler2, both implementing ILoginHandler and inherit from UIViewController.
However, use of dependency injection is costly, it slows down the app because resolving is expensive comparing to normal instantiation.
The other way is to define all these behaviors in the app and enable/disable them in a plist file. like "is login optional? yes/no"
Any suggestions?
Thanks
You should create the entire object graph up-front, in the composition root. Object creation, and constructor injection, should not take much time at all as long as your constructors are not doing any actual work.
That being said, there are times when creating the entire object graph at the start of the application may take longer than is acceptable. In those cases, you can use lazy-loading to defer the costly initialization until later - while still creating the objects in the composition root.
Mark Seemann describes this approach in more detail here: Compose object graphs with confidence.
I thought we can use dependency injections and use different handlers for each customer if needed.
You thought right. Flexibility is one of the main reasons people use DI.
However, use of dependency injection is costly, it slows down the app because resolving is expensive comparing to normal instantiation.
It really doesn't cost that much at all. Have you tried it yourself? Unless the object in question (i.e. the object being injected) is very expensive to instantiate, you have no real reason to stay away from DI and Inversion Of Control. Also, as #Lilshieste noted above, creating the object graph up front (see AppDelegate) will probably make this even less a problem.
A good way of doing that is described here:
http://cocoapatterns.com/passing-data-between-view-controllers/ and here http://cocoapatterns.com/ios-view-controller-transitions-mediator-pattern/
The other way is to define all these behaviors in the app and enable/disable them in a plist file. like "is login optional? yes/no"
While less "elegant", this solution is a pretty useful one, especially if the project is not really big in terms of number of classes and VCs. It is also the easiest one to implement if the app code is already laid out and introducing major design changes would ask for lots of refactoring.
Always take action based on the task at hand, there is rarely if ever a single solution to a software design problem.
I wonder what sort of things you look for when you start working on an existing, but new to you, system? Let's say that the system is quite big (whatever it means to you).
Some of the things that were identified are:
Where is a particular subroutine or procedure invoked?
What are the arguments, results and predicates of a particular function?
How does the flow of control reach a particular location?
Where is a particular variable set, used or queried?
Where is a particular variable declared?
Where is a particular data object accessed, i.e. created, read, updated or deleted?
What are the inputs and outputs of a particular module?
But if you look for something more specific or any of the above questions is particularly important to you please share it with us :)
I'm particularly interested in something that could be extracted in dynamic analysis/execution.
I like to use a "use case" approach:
First, I ask myself "what's this software's purpose?": I try to identify how users are going to interact with the application;
Once I have some "use case", I try to understand what are the objects that are more involved and how they interact with other objects.
Once I did this, I draw a UML-type diagram that describe what I've just learned for further reference. What happens after depends on the task I've been assigned, i.e. modify the code, document the code etc.
There is the question of what motivation do I have for learning the new system:
Bug fix/minor enhancement - In this case, I may focus solely on that portion of the system that performs a specific function that needs to be altered. This is a way to break down a huge system but also is a way to identify if the issue is something I can fix or if it is something that I have to hand to the off-the-shelf company whose software we are using,e.g. a CRM, CMS, or ERP system can be a customized off-the-shelf system so there are many pieces to it.
Project work - This would be the other case and is where I'd probably try to build myself a view from 30,000 feet or so to know what are the high-level components and which areas of the system does the project impact. An example of this is where I'd join a company and work off of an existing code base but I don't have the luxury of having the small focus like in the previous case. Part of that view is to look for any patterns in the code in terms of naming conventions, project structure, etc. as this may be useful once I start changing some code in the system. I'd probably do some tracing through the system and try to see where are the uglier parts of the code. By uglier I mean those parts that are kludge-like and may have some spaghetti code as this was rushed when first written and is now being reworked heavily.
To my mind another way to view this is the question of whether I'm going to be spending days or weeks wrapping my head around a system like in the second case or should this be a case where it hopefully takes only a few hours, optimistically that is, to get my footing to make the necessary changes.
I know there is a lot of talk about BPM these days and I am conscious that some may see it to be a craze rather than a fundamentally important piece of software.
As someone from what most would call 'The Business', I have been doing my best to learn about BPM to ensure we continue to make decisions that not only make sense to the business, but IT as well.
I have noticed while reading that mention is made to application workflow when sometimes discussing BPM. I hadn't given this much thought until recently.
Therefore, what is the difference? When would you use one and not the other?
BPM is about the process and improving it, which takes into account users and potentially more than one application,e.g. an ERP system may have more than one application to it, though there may be other uses of the term. Note that the process could be viewed without what applications or technologies are used.
Application workflow is how an application is used to go from a to b. Here it is a specific set of code that is used and what happens over the course of an application getting from a to b. In this case, the application is front and center rather than the process.
Does that provide an answer? Another way to think of it is that multiple application workflows can make up a system which is used in a process that can have BPM applied to it.
Late to the game, but workflow is to database as BPMS is to DBMS. (Convenient how the letters line up, huh?)
IOW, BPM(S) is traditionally meant to refer to a particular framework/application that allows you to manage business processes: defining them, storing them, versioning them, measuring them, etc. This is similar to how a DBMS manages databases.
Now, a workflow is a definition, much like a database is a definition. In the former case, it is a definition of operations/work (Fufill Order), steps thereof (Send Invoice) and rules/constraints on the work (If no stock, send notice). In the latter, similar case, it is a definition of data structure (CREATE TABLE) and constraints (InvoiceTotal must be > $0.00).
I think this is a potentially confusing subject, particular as some development environments use a type of process flow model to generate user facing applications (I'm thinking about Outsystems here, for example).
But, for me, the distinction is crystal clear. Application workflow, as people talk about it, refers to a user's path through an application, i.e. the pages they complete/visit, the data they enter, etc. on their way to completing a transaction of some sort. Application orkflow is a poor term for this though, I think application flow would be more meaningful.
BPM on other hand, is about modelling and executing a workflow process. By workflow, in this context, I mean a series of discrete steps (or tasks) that have to be completed (either programmatically or via human interaction) in a certain order to complete a process. These tasks can be implemented as individual application modules (each with their own "application workflow", see above). The job of the workflow engine is to make sure that these separate steps are assigned to the right people (of groups of people) in the right sequence, and that overall the process completes in an orderly way.
I don't think there's a clear answer to this at all. These are words, as opposed to theoretical concepts. If you add the word "checklist" into the mix - that just turns out to be a linear version of a process (but you can have conditionals in checklists - making them a workflow).
I am not sure how to help in reframing this question, but it's almost as if no answer can ever be possible. My own thoughts are at https://tallyfy.com/improving-efficiency-workflow-vs-business-process-management/