I have a Car object which contains a latitude field and a longitude field. I use the observer pattern so that any time either of these fields change in my application, my car object is notified.
I now find the need to create several other car objects whose default values I wish to have the same as what is the current latitude and the current longitude. I can keep this state in my Notifier object and when a new observer (the new car) registers to listen I can re-broadcast out the values so the new listener will be up to date.
Is this a misuse of the observer pattern, i.e bad design?
The only thing that strikes me as dangerous about this approach is that it's easy to code your observers to assume that if they get a notification, something has changed. With the setup you have above, that's no longer true. Therefore your observers will have to check that something truly changed if they are supposed to perform any actions when they receive a notification.
Probably common sense, but also an easy oversight if you're modifying existing code.
I think this is a textbook example of good use of the Observer Pattern.
Of course, there may be some aspect of this that you have misgivings about. If you explain what your concerns are these could be better discussed.
It would be better if your subject (the object which knows the current latitude and longitude) also exposes a getter method. Any new listener (a new car in your example), right after registration, might get the current values (lat/long) and be informed through the broadcast of any change thereafter. This will avoid needlessly notifying already registered listeners.
Consider that in a common variation of the observer pattern, the subject notifies the listeners that a change has happened, and the listeners then actively query the current value from the subject (hence the need of a getter method).
An Observer pattern is used in one to many relationship. When you want to notify multiple objects, when one object changes state. Your case is a many to one. I believe its a misuse (I may be wrong). Obvious impact is complexity of code. But the side effect could be loss of flexibility. Look at it like this, what changes. If you want to add more Car's you can, without changing the notification receiver. The receiver need now know about your new Car's implementation. All it cares about is the state.
Now, what happens when you want to add more receivers, which will be the most probable case (requirements not thought through :)). In this case all your car objects will need a change to refer to a new receiver.
Related
I have a system that lets people create and work with Orders. Orders can have multiple Steps. The Order can have a status of New, InProgress, Done, and Cancelled.
There are a bunch of business rules on what can and can't be done. Examples of rules are "can only add/remove Steps to an Order if the Order is New", "can't move an Order to Cancelled if any Step has a Cost>0", and "the Order must have Approved=true to move from New to InProgress".
I'm trying to find a good way to enforce these rules, other than several if statements splattered all around the code. I saw the Rules design pattern, but everything I can find on that applies to a single object state, and not a change in the object.
My current approach is this. I have a bunch of IRules. Each one has a Validate(Order source, Order destination) method that validates that the transition is allowed by its rule. Each endpoint in my API loads the current Order, creates a new Order with the change made, then calls a method that runs all the rules.
Am I going about this wrong? Any suggestions? Thanks in advance.
You are working on a "State Machine"
you must store your current status enum {New, InProgress}
you receive some events, you handle the event and apply some actions by respecting rules corresponding to the current status ( and eventually with some memory about the previous status)
The best way here is to use a State-Pattern(specific pattern in GoF patterns). State pattern helps you to encapsulate your state according to your business and then do whatever you want according to the internal state.
Your example actually is a Finite-state machine that can be in exactly one of a finite number of states at any given time.
So in this case instead of lots of If-Else or Switch-case you can use state pattern. The State pattern suggests that you create new classes for all possible states of an object and extract all state-specific behaviors into these classes.
For more information you can read this great site and also for real example in C# please have a look here .
What is the difference? To me they seem very similar... Why would you use one over the other?
They're similar in that they will both store the last given value & you can access them via the public property.
Difference is:
ReactiveProperty will issue an event if and only if the value has changed.
BehaviorSubject will issue an event whatever the new value may be.
In their C# code (which is open-sourced) ReacitveProperty checks equality of new value and last value; BehaviorSubject doesn't. In fact none of ISubject implementations checks the equality.
When should you use one over another?
I would use ReactiveProperty when I want callbacks only times the value has changed even though the substitution may occur more frequently. I would use BehaviourSubject when I want callbacks whenever the substitution occurred.
In most cases ReactiveProperty is more useful because generally you want to react to changes. BehaviorSubject has its own use although less common.
Other considerations:
ReactiveProperty.SetValueAndForceNotify() can be used to invoke callbacks regardless the equality.
IObservable.DistinctUntilChanged() can be used to (secondarily) introduce the equality check.
In addition to the differences mentioned in other answers is BehaviorSubject is kinda more encapsulated compared to ReactiveProperty. That is:
BehaviorSubject.Value is get only (but .OnNext(value) is still publicly available).
ReactiveProperty.Value is settable publicly.
Behaviour Subject is one of the implementations of the Subject class. It allows you to retrieve the last value that was pushed by using the outObserver.
Reactive Property is used to provide some sort notification when something happened, it's a simpler alternative to callbacks.
For example:
If you want to chain a lot of methods to an action in your game for instance the movement of an player you can use this Rective Property.
If you want to get the last value that was pushed for instance to make a combo in a fighting game you can use Behaviour Subject.
I have the following delegate
System.Action<SomeMessage> TheDelegate;
Which has a couple subscribers, however as the message gets passed through all the subscribers, each subscriber will do something to it and that change persists and gets passed to the next subscriber, which is something that I don't want.
Is there a way that I can use the original message as the parameter for all subscribers?
Edit:
SomeMessage is a class, thus it gets passed by reference through the subscribers
To name two possibilities:
Clone the message each time it is passed to a subscriber. How is the message structured, is it cheap to clone? Maybe you could even pass it as struct? Cloning could be done by implementing ICloneable, clone on a per-property basis, which can be automated by a framework, e.g, Automapper (http://automapper.org) or, if you mess around with some JSON Lib like JSON.NET, you could do something like var clone = FromJson(ToJson(original)). This is surely not a fast approach but an easy one that works well with deep objects.
Another way would be making the message itself immutable and let each subscriber pass change requests to some kind of collector, e.g.
like this:
interface ICommandSequence
{
void AddCommand(ICommand);
}
and the Action becomes
System.Action<ImmutableMessage, ICommandSequence>
Each subscriber could now pass command instances to the ICommandSequence instance. And after all subscribers have been called, you could execute the command sequence, and apply changes to message objects. How the commands look depends on the way your messages and message processing looks.
If your application cares about a design that is strongly focused on the business domain, you could build commands that represent real-world business events, as it is done in CQRS, for example.
When it comes to designing classes and "communication" between them, I always try to design them in such way that all object construction and composing take place in object constructor. I don't like the idea of object construction and composition taking place from outside, like other objects setting properties and calling methods on my object to initialize it. This especially gets ugly when multiple object try to do thisto your object and you never know in what order your props\methods will be executed.
Unforunatly I stumbl on such situations quite often, especially now with the growing popularity of dependecy injection frameworks, lots of libraries and frameworks rely on some kind of external object initialization, and quite often require not only constructor injection on our object but property injection too.
My question are:
Is it ok to have objects that relly on some method, or property to be called on them after which they can consider them initialzied?
Is ther some kind of pattern for situations when your object acting is receiver, and must support multiple interfaces that call it, and the order of these calls does matter? (something better than setting flags, like ThisWasDone, ThatWasCalled)
Is it ok to have objects that relly on some method, or property to be called on them after which they can consider them initialzied?
No. Init methods are a pain since there is no guarantee that they will get called. A simple solution is to switch to interfaces and use factory or builder pattern to compose the implementation.
#Mark Seemann has written a article about it: http://blog.ploeh.dk/2011/05/24/DesignSmellTemporalCoupling.aspx
Is there some kind of pattern for situations when your object acting is receiver, and must support multiple interfaces that call it, and the order of these calls does matter? (something better than setting flags, like ThisWasDone, ThatWasCalled)
Builder pattern.
I think it is OK, but there are implications. If this is an object to be used by others, you need to ensure that an exception is thrown any time a method or property is set or accessed and the initialization should have been called but isn't.
Obviously it is much more convenient and intuitive if you can take care of this in the constructor, then you don't have to implement these checks.
I don't see anything wrong in this. It may be not so convinient, but you can not ALWAYS use initialization in ctor, like you can not alwats drive under green light. These are dicisions that you made based on your app requirements.
It's ok. Immagine if your object, for example, need to read data from TCP stream or a file that ciuld be not present or corrupted. Raise an exception from ctor is baaad.
It's ok. If you think, for example, about some your DSL language compiler, it can looks like:
A) find all global variables and check if there mem allocation sum sutisfies your device requierements
B) parse for errors
C) check for self cycling
And so on...
Hoe this helps.
Answering (1)
Why not? An engine needs the driver because this must enter the key for the car, and later power-on. Will a car do things like detecting current speed if engine is stopeed? Or Will the car show remaining oil without powering-on it?
Some programming goals won't be able to have their actors initialized during its object construction, and this isn't because it's a non-proper way of doing things but because it's the natural, regular and/or semantically-wise way of representing its whole behavior.
Answering (2)
A decent class usage documentation will be your best friend. Like answer to (1), there're some things in this world that should be done in order to get them done rightly, and it's not a problem but a requirement.
Checking objects' state using flags isn't a problem too, it's a good way of adding reliability to your object models, because its own behaviors and consumers of them will be aware about if things got done as expected or not.
First of all, Factory Method.
public class MyClass
{
private MyClass()
{
}
public Create()
{
return new MyClass();
}
}
Second of all, why do you not want another class creating an object for you? (Factory)
public class MyThingFactory
{
IThing CreateThing(Speed speed)
{
if(speed == Speed.Fast)
{
return new FastThing();
}
return new SlowThing();
}
}
Third, why do multiple classes have side effects on new instances of your class? Don't you have declarative control over what other classes have access to your object?
I have an app which consists of several different assemblies, one of which holds the various interfaces which the classes obey, and by which the classes communicate across assembly boundaries. There are several classes firing events, and several which are interested in these events.
My question is as follows: is it good practice to implement a central EventConsolidator of some kind? This would be highly coupled, as it would need to know every class (or at least interface) throwing an event, and every consumer of an event would need to have a reference to EventConsolidator in order to subscribe.
Currently I have the situation where class A knows class B (but not C), class B knows class C, etc. Then if C fires an event B needs to pick it up and fire its own event in order for A to respond. These kinds of chains can get quite long, and it may be that B is only interested in the event in order to pass it along. I don't want A to know about C though, as that would break encapsulation.
What is good practice in this situation? Centralise the events, or grin and bear it and define events in each intermediate class? Or what are the criteria by which to make the decision? Thanks!
Edit: Here is another question asking essentially the same thing.
You could put the event itself in an interface, so that A didn't need to know about C directly, but only that it has the relevant event. However, perhaps you mean that the instance of A doesn't have sight of an instance of C...
I would try to steer clear of a centralised event system. It's likely to make testing harder, and introduced tight coupling as you said.
One pattern which is worth knowing about is making event proxying simple. If B only exposes an event to proxy it to C, you can do:
public event FooHandler Foo
{
add
{
c.Foo += value;
}
remove
{
c.Foo -= value;
}
}
That way it's proxying the subscription/unsubscription rather than the act of raising the event. This has an impact on GC eligibility, of course - which may be beneficial or not, depending on the situation. Worth thinking about though.
What you could try is using the event brokering of either NInject or the Unity Application Block.
This allows you to, for example:
[Publish("foo://happened")]
public event EventHandler<FooArgs> FooHappened;
[Subscribe("foo://happened")]
public void Foo_Happened(object sender, FooArgs args)
{ }
If both objects are created through the container the events will be hooked up automatically.
I'd probably try to massage the domain so that each class can directly depend on the appropriate event source. What I mean is asking the question why don't A know about C? Is there perhaps a D waiting to emerge?
As an alternative approach you could consider an event broker architecture. It means observers don't know directly about the source. Here's an interesting video.
This would be highly coupled, as it would need to know every class
I think you answered your own question if you consider that coupling is bad! Passing events through a chain of potential handlers is a fairly common pattern in many environments; It may not be the most efficient approach, but it avoids the complexity that your suggested approach would involve.
Another approach you could take is to use a message dispatcher. This involves using a common message format (or at least a common message header format) to represent events, and then placing those messages into a queue. A dispatcher then picks up each of those events in turn (or based on some prioritisation), and routes them directly to the required handler. Each handler must be registered with the dispatcher at startup.
A message in this case could simply be a class with a few specific fields at the start. The specific message could simply be a derivative, or you could pass your message-specific data as an 'object' parameter along with the message header.
You can check out the EventBroker object in the M$ patterns and practises lib if you want centralised events.
Personally I think its better to think about your architecture instead and even though we use the EventBroker here, none of our new code uses it and we're hoping to phase it out one sunny day.
we have our own event broker implementation (open source)
Tutorial at: http://sourceforge.net/apps/mediawiki/bbvcommon/index.php?title=Event_Broker
And a performance analysis at: www.planetgeek.ch/2009/07/12/event-broker-performance/
Advantages compared to CAB:
- better logging
- extension support
- better error handling
- extendable handlers (UI, Background Thread, ...)
and some more I cannot recall right now.
Cheers,
Urs