Can State Pattern help with read only states? - state-pattern

I'm trying to model a certain process and I'm thinking that the State Pattern might be a good match. I'd like to get your feedback though about whether State will suit my needs and how it should be combined with my persistence mechanism.
I have a CMS that has numerous objects, for example, Pages. These objects (we'll use the example of Pages, but it's true of most objects) can be in one of a number of states, 3 examples are:
Unpublished
Published
Reworking
When Unpublished, they are editable. Once Published, they are not editable, but can be moved into the Reworking state. In the Reworking state they are editable again and can be Republished.
Obviously the decision for whether these Pages are editable should be in the models themselves and not the UI. So, the State pattern popped into mind. However, how can I prevent assigning values to the object's properties? It seems like a bad idea to have a check on each property setter:
if (!CurrentState.ReadOnly)
Any ideas how to work this? Is there a better pattern for this?

Using wikipedia's Java example, the structure has a Context, which calls methods defined in the base State, which the concrete states override.
In your case, the context is something like a page. In some states, the edit() method is simply a no-op. Some of the actions on the context may execute a state change implicitly. There is never any need in the client code to test which state you are in.

Update:
I actually thought of a method this morning that would work with your specific case and be a lot easier to maintain. I'll leave the original two points here, but I'm going to recommend the final option instead, so skip to the "better method" section.
Create a ThrowIfReadOnly method, which does what it says on the tin. This is slightly less repetitive and avoids the nesting.
Use an interface. Have an IPage that implements the functionality you want, have every public method return an IPage, then have two implementations, an EditablePage and a ReadOnlyPage. The ReadOnlyPage just throws an exception whenever someone tries to modify it. Also put an IsReadOnly property (or State property) on the IPage interface so consumers can actually check the status without having to catch an exception.
Option (2) is more or less how IList and ReadOnlyCollection<T> work together. It saves you the trouble of having to do a check at the beginning of every method (thus eliminating the risk of forgetting to validate), but requires you to maintain two classes.
-- Better Method --
A proper technical spec would help a lot to clarify this problem. What we really have here is:
A series of arbitrary "write" actions;
Each action has the same outcome, dependent on the state:
Either the action is taken (unpublished/reworking), or fails/no-ops (read-only).
What really needs to be abstracted is not so much the action itself, but the execution of said action. Therefore, a little bit of functional goodness will help us here:
public enum PublishingState
{
Unpublished,
Published,
Reworking
}
public delegate void Action();
public class PublishingStateMachine
{
public PublishingState State { get; set; }
public PublishingStateMachine(PublishingState initialState)
{
State = initialState;
}
public void Write(Action action)
{
switch (State)
{
case PublishingState.Unpublished:
case PublishingState.Reworking:
action();
break;
default:
throw new InvalidOperationException("The operation is invalid " +
"because the object is in a read-only state.");
}
}
}
Now it becomes almost trivial to write the classes themselves:
public class Page
{
private PublishingStateMachine sm = new
PublishingStateMachine(PublishingState.Unpublished);
private string title;
private string category;
// Snip other methods/properties
// ...
public string Title
{
get { return title; }
set { sm.Write(() => title = value; }
}
public string Category
{
get { return category; }
set { sm.Write(() => category = value; }
}
public PublishingState State
{
get { return sm.State; }
set { sm.State = value; }
}
}
Not only does this more-or-less implement the State pattern, but you don't need to maintain separate classes or even separate code paths for the different states. If you want to, for example, turn the InvalidOperationException into a no-op, just remove the throw statement from the Write method. Or, if you want to add an additional state, like Reviewing or something like that, you just need to add one case line.
This won't handle state transitions for you or any really complex actions that do different things depending on the state (other than just "succeed" or "fail"), but it doesn't sound like you need that. So this gives you a drop-in state implementation that requires almost no extra code to use.
Of course, there's still the option of dependency injection/AOP, but there's obviously a lot of overhead associated with that approach, and I probably wouldn't use it for something so simple.

Related

How best to store a number in google realtime model, and get atomic change events?

Sounds pretty simple, however...
This number holds an enumerated type, and should be a field within a custom realtime object. Here's its declaration in the custom object registration routine:
MyRTObjectType.prototype.myEnumeratedType =
gapi.drive.realtime.custom.collaborativeField('myEnumeratedType');
I can store it in the model as a simple javascript number, and initialize it like this:
function initializeMyRTObjectType() {
// other fields here
this.myEnumeratedType = 0;
}
...but the following doesn't work, of course, since it's just a number:
myRTObject.myEnumeratedType.addEventListener(
gapi.drive.realtime.EventType.OBJECT_CHANGED, self.onTypeChanged);
I can add the event listener to the whole object:
myRTObject.addEventListener(
gapi.drive.realtime.EventType.OBJECT_CHANGED, self.onTypeChanged);
But I'm only interested in changes to that number (and if I were interested in other changes, I wouldn't want to examine every field to see what's changed).
So let's say I store it as a realtime string, initializing it like this:
function initializeMyRTObjectType() {
var model = gapi.drive.realtime.custom.getModel(this);
// other fields here
this.myEnumeratedType = model.createString();
}
Now I'll get my change events, but they won't necessarily be atomic, and I can't know whether a change, say from "100" to "1001", is merely a change enroute to "101", and so whether I should react to it (this exact example may not be valid, but the idea is there...)
So the question is, is there either a way to know that all (compounded?) changes, insertions/deletions are complete on a string field, or (better) a different recommended way to store a number, and get atomic notification when it has been changed?
You also get a VALUE_CHANGED event on the containing object like you would for a map:
myRTObject.addEventListener(gapi.drive.realtime.EventType.VALUE_CHANGED,
function(event) {
if (event.property === 'myEnumeratedType') {
// business logic
}
});

Immutable State - Propagating Changes to the GUI Efficiently

In a previous question I asked how to idiomatically implement an observer pattern for an F# application. My application now uses a MailboxProcessor as reccomended and I've created some helper functions to create sub-MailboxProcessor's etc. However, I'm at a mental block when it comes to specific case scenarios w.r.t. GUI binding.
Lets say I have a model as such:
type Document = {
Contents : seq<DocumentObject>
}
And the GUI (WPF, XAML) requires binding like so:
interface IMainWindowViewModel
{
IEnumerable<Control> ContentViews { get; }
}
Each ViewModel for each Control will require a DocumentObject (its underlying model) and a way of knowing if it has changed. I supply this as a sub-MailboxProcessor<DocumentObject> so that changes may be propagated correctly, I'm moderately confident this pattern works. Essentially, it maps the service outputs and wraps modification requests (outer interface example below):
let subSvc = generateSubSvc svc (fun doc -> doc.Contents[0]) (fun f -> fun oldDoc -> { oldDoc with Contents[0] = f Contents[0] })
let viewModel = new SomeDocObjViewModel(docObjSvc)
new DocObjView(viewModel)
Now, imagine a modification command now deletes a DocumentObject from MyDocument. The top-level MailboxProcessor now echoes the change to IMainWindowViewModel using it's IEvent<MyDocument>. And here's where my problems begin.
My IMainWindowViewModel doesn't really know which DocumentObject has been deleted. Only that there's a new Document and it has to deal with it. There may be ways of it figuring out but it never really knows directly. This can force me down the path of having to either re-create all the Control's for all DocumentObject's to be safe (inefficient). There are additional problems (such as dangling subSvc's) which I also haven't mentioned here for brevity.
Normally, these kind of dynamic changes would be dealt with something like an ObservableCollection<DocumentObject> which is then mapped into an ObservableCollection<Control>. This comes with all the caveats of shared mutable state and is a little 'hackish'; however, it does do the job.
Ideally, I'd like a 'pure' model, free from the trappings of PropertyChanged and ObservableCollections, what kind of patterns in F# would satisfy this need? Where is it appropriate to draw the line between idiomatic and realistic?
Have you considered using the Reactive Extensions (and Reactive UI further down the road) for the purpose of modelling mutable state (read: your model properties over time) in a functional way?
I don't see anything wrong technically to use an ObservableCollection in your model. After all, you need to track collection changes. You could do it on your own, but it looks like you can save yourself a lot of trouble reinventing the observable collection, unless you have a very specific reason to avoid the ObservableCollection class.
Also, using MailboxProcessor seems a bit overkill, since you could just use a Subject (from Rx) to publish and expose it as an IObservable to subscribe to 'messages':
type TheModel() =
let charactersCountSubject = new Subject()
let downloadDocument (* ... *) = async {
let! text = // ...
charactersCountSubject.OnNext(text.Length)
}
member val CharactersCount = charactersCountSubject.AsObservable() with get
type TheViewModel(model : TheModel) =
// ...
member val IsTooManyCharacters = model.CharactersCount.Select((>) 42)
Of course since we're talking about WPF, the view-model should implement INPC. There are different approaches, but whichever one you take, the ReactiveUI has a lot of convenient tools.
For example the CreateDerivedCollection extension method that solves one of the problems you've mentioned:
documents.CreateDerivedCollection(fun x -> (* ... map Document to Control ... *))
This will take your documents observable collection, and make another observable collection out of it (actually a ReactiveCollection) that will have documents mapped to controls.

Immutable data model for an WPF application with MVVM implementation

I have an application which has a data tree as a databackend. To implement the the MVVM pattern I have a logic layer of classes which encapsulate the data tree. Therefore the logic also is arranged in a tree. If the input is in a valid state the data should be copied to a second thread which works as a double buffer of the last valid state. Therefore one way would be cloning.
Another approach would be to implement the complete data backend to be immutable. This would imply to rebuild the whole data tree if something new is entered. My question is, is there a practical way to do this? I'm stuck at the point where I have to reassign the data tree efficently to the logic layer.
**UPDATE - Some Code
What we are doing is to abstract hardware devices which we use to run our experiments. Therefore we defined classes like "chassis, sequence, card, channel, step". Those build a tree structure like this:
Chassis
/ \
Sequence1 Sequence2
/ | \
Card1 Card2 Card3
/ \
Channel1 Channel2
/ \
Step1 Step2
In code it looks like this:
public class Chassis{
readonly var List<Sequence> Sequences = new List<Sequence>();
}
public class Sequence{
readonly var List<Card> Cards = new List<Card>();
}
and so on. Of course each class has some more properties but those are easy to handle. My Problem now is that List is a mutable object. I can call List.Add() and it changed. Ok there is a ReadOnlyList but I'm not sure if it implements the immutability the right way. Right as in copy by value not reference and not just blocking to write to it by blocking the set methods.
The next problem is that the amount of sequences and step can vary. For this reason I need an atomic exchange of list elements.
At the moment I don't have any more code as I'm still thinking if this way would help me and if it is possible at all to implement it in a reasonable amount of time.
Note that there are new immutable collections for .NET that could help you achieve your goal.
Be very cautious about Dave Turvey's statement (I would downvote/comment if I could):
If you are looking to implement an immutable list you could try storing the list as a private member but exposing a public IEnumerable<>
This is incorrect. The private member could still be changed by its container class. The public member could be cast to List<T>, IList<T>, or ICollection<T> without throwing an exception. Thus anything that depends on the immutability of the public IEnumerable<T> could break.
I'm not sure if I understand 100% what you're asking. It sounds like you have a tree of objects in a particular state and you want to perform some processing on a copy of that without modifying the original object state. You should look into cloning via a "Deep Copy". This question should get you started.
If you are looking to implement an immutable list you could try storing the list as a private member but exposing a public IEnumerable<>
public class Chassis
{
List<Sequence> _sequences = new List<Sequence>();
public IEnumerable<Sequence> Sequences { get { return _sequences; } }
}
18/04/13 Update in response to Brandon Bonds comments
The library linked in Brandon Bonds answer is certainly interesting and offers advantages over IEnumerable<>. In many cases it is probably a better solution. However, there are a couple of caveats that you should be aware of if you use this library.
As of 18/04/2013 This is a beta library. It is obviously still in development and may not be ready for production use. For example, The code sample for list creation in the linked article doesn't work in the current nuget package.
This is a .net 4.5 library. so it will not be suitable for programs targeting an older framework.
It does not guarantee immutability of objects contained in the collections only of the collection itself. It is possible to modify objects in an immutable list You will still need to consider a deep copy for copying collections.
This is addressed in the FAQ at the end of the article
Q: Can I only store immutable data in these immutable collections?
A: You can store all types of data in these collections. The only immutable aspect is the collections themselves, not the items they contain.
In addition the following code sample illustrates this point (using version 1.0.8-beta)
class Data
{
public int Value { get; set; }
}
class Program
{
static void Main(string[] args)
{
var test = ImmutableList.Create<Data>();
test = test.Add(new Data { Value = 1 });
Console.WriteLine(test[0].Value);
test[0].Value = 2;
Console.WriteLine(test[0].Value);
Console.ReadKey();
}
}
This code will allow modification of the Data object and output
1
2
Here are a couple of articles for further reading on this topic
Read only, frozen, and immutable collections
Immutability in C# Part One: Kinds of Immutability

Encapsulation concept

I have problem with concept and implementation of encapsulation.
Can someone explain it to me?
Encapsulation is a moderately easy concept once you realise it (probably) comes from the same base word as capsule.
It's simply a containment of information.
Encapsulation means that a class publishes only what is needed for others to use it, and no more. This is called information hiding and it means classes can totally change their internals without having an effect on any of their users.
In other words, a dictionary class can begin life as a simple array and progress to a binary tree of words then even maybe to some database access functions, all without changing the interface to it.
In an object oriented world, objects hold both their data and the methods used to manipulate data and that is the pinnacle of encapsulation. One way this is done is to make sure each object knows which functions to call to manipulate its data, and ensure the correct ones are called.
As an example, here's a class for maintaining integer lists in my mythical, but strangely Python-like and therefore hopefully easy to understand, language:
class intlist:
private int val[10] # Slots for storing numbers.
private bool used[10] # Whether slot is used or not.
public constructor:
# Mark all slots unused.
for i in 0..9:
used[i] = false
public function add(int v) throws out-of-memory:
# Check each slot.
for i in 0..9:
# If unused, store value, mark used, return.
if not used[i]:
used[i] = true
val[i] = v
return
# No free slots, so throw exception.
throw out-of-memory
public function del(int v) throws bad-value:
# Check each slot.
for i in 0..9:
# If slot used and contains value.
if used[i] and val[i] == v:
# Mark unused and return.
used[i] = false
return
# Value not found in any used slot, throw exception.
throw bad-value
public function has(int v):
# Check each slot.
for i in 0..9:
# If slot used and contains value.
if used[i] and val[i] == v:
return true
# Value not found in any used slot.
return false
Now the only information published here are the constructor and three functions for adding, deleting, and checking for values (including what exceptions can be thrown).
Callers need know nothing about the internal data structures being used (val and used), or the properties of the functions beyond their "signatures" (the content of the "function" lines).
Because everything else is encapsulated, it can changed it at will without breaking the code that uses it.
I could, for example, do any of the following:
make the arrays longer;
store the data sorted, or in a binary tree instead of an array to make it faster.
change the used array into a count array (initialised to zero) so that many occurrences of a single number use just the one slot, increasing the quantity of numbers that can be stored where there are duplicates.
store the numbers in a database, located on a ZX-80 retro-computer located in outback Australia, and powered by methane produced from kangaroo droppings (though you may notice a latency change).
Basically, as long as the published API doesn't change, we am free to do whatever we want. In fact, we can also add things to the API without breaking other code, I just can't delete or change anything that users already rely on.
You should note that encapsulation isn't something new with object orientation. It's been around for ages, even in C by ensuring that information is hidden within a module (usually a source file or group thereof with private headers).
In fact, the stdio.h FILE* stuff is a good example of this. You don't care what's actually behind the pointer since all the functions which use it know how to do their stuff.
link text
I always explain it to people is think of yourself as an object. Other people can see your height, they can see if your smiling, but your inner thoughts, maybe the reason while your smiling, only you know.
Encapsulation is more than just defining accessor and mutator methods for a class. It is broader concept of object-oriented programming that consists in minimizing the interdependence between classes and it is typically implemented through information hiding.
The beauty of encapsulation is the power of changing things without affecting its users.
In a object-oriented programming language like Java, you achieve encapsulation by hiding details using the accessibility modifiers (public, protected, private, plus no modifier which implies package private). With these levels of accessibility you control the level of encapsulation, the less restrictive the level, the more expensive change is when it happens and the more coupled the class is with other dependent classes (i.e. user classes, subclasses).
Therefore, the goal is not to hide the data itself, but the implementation details on how this data is manipulated.
The idea is to provide a public interface through which you gain access to this data. You can later change the internal representation of the data without compromising the public interface of the class. On the contrary, by exposing the data itself, you compromise encapsulation, and therefore, the capacity of changing the way you manipulate the data without affecting its users. You create a dependency with the data itself, and not with the public interface of the class. You would be creating a perfect cocktail for trouble when "change" finally finds you.
There are several reasons why you might want to encapsulate access to your fields. Joshua Bloch in his book Effective Java, in Item 14: Minimize the accessibility of classes and members, mentions several compelling reasons, which I quote here:
You can limit the values that can be stored in a field (i.e. gender must be F or M).
You can take actions when the field is modified (trigger event, validate, etc).
You can provide thread safety by synchronizing the method.
You can switch to a new data representation (i.e. calculated fields, different data type)
However, encapsulation is more than hiding fields. In Java you can hide entire classes, by this, hiding the implementation details of an entire API. Think, for example, in the method Arrays.asList(). It returns a List implementation, but you do no care which implementation, as long as it satisfies the List interface, right?. The implementation can be changed in the future without affecting the users of the method.
The Beauty of Encapsulation
Now, in my opinion, to really understand encapsulation, one must first understand abstraction.
Think, for example, in the level of abstraction in the concept of a car. A car is complex in its internal implementation. They have several subsystem, like a transmission system, a break system, a fuel system, etc.
However, we have simplified its abstraction, and we interact with all cars in the world through the public interface of their abstraction. We know that all cars have a steering wheel through which we control direction, they have a pedal that when you press it you accelerate the car and control speed, and another one that when you press it you make it stop, and you have a gear stick that let you control if you go forward or backwards. These features constitute the public interface of the car abstraction. In the morning you can drive a sedan and then get out of it and drive an SUV in the afternoon as if it was the same thing.
However, few of us know the details of how all these features are implemented under the hood. Think of the time when cars did not have a hydraulics directional system. One day, the car manufactures invented it, and they decide it to put it in cars from there on. Still, this did not change the way in which users where interacting with them. At most, users experienced an improvement in the use of the directional system. A change like this was possible because the internal implementation of a car is encapsulated. Changes can be safely done without affecting its public interface.
Now, think that car manufactures decided to put the fuel cap below the car, and not in one of its sides. You go and buy one of these new cars, and when you run out of gas you go to the gas station, and you do not find the fuel cap. Suddenly you realize is below the car, but you cannot reach it with the gas pump hose. Now, we have broken the public interface contract, and therefore, the entire world breaks, it falls apart because things are not working the way it was expected. A change like this would cost millions. We would need to change all gas pumps in the world. When we break encapsulation we have to pay a price.
So, as you can see, the goal of encapsulation is to minimize interdependence and facilitate change. You maximize encapsulation by minimizing the exposure of implementation details. The state of a class should only be accessed through its public interface.
I really recommend you to read a paper by Alan Snyder called Encapsulation and Inheritance in Object-Oriented programming Languages. This link points to the original paper on ACM, but I am pretty sure you will be able to find a PDF copy through Google.
Encapsulation - wrapping of data in single unit. also we can say hiding the information of essential details.
example
You have a mobile phone.... there it some interface which helps u to interact with cell phone and u can uses the services of mobile phone. But the actually working in cell phone is hide. u don't know how it works internally.
hide/bind something : eg: a capsule (which we consume when v r ill)hide/bind some powder form in itself,, means that capsule encapsulate the powder contained it.
Binding of data and behavior i.e functionality of an object in a secured and controlled manner.
or the best example of encapsulation is a CLASS because a class hides class variables/functions from outside d class..
Encapsulation:
Wrapping up data member and method together into a single unit (i.e. Class) is called Encapsulation.
Eg: we can consider a capsule. Encapsulation means hiding the internal details of an object, i.e. how an object does something. Here capsule is a single Unit contain many things. But we cant see what is there in side capsule.
This is the technique used to protect information about an object from other objects. Like variable we can set as private and property as Public. When we access the property then we validate and set it.
We can go through some other examples. Our Laptop. We can use Laptop but what operations are happening inside that we are not knowing. But we can use that. Same like mobile, TV etc.
We can conclude that a group of related properties, methods, and other members are treated as a single unit or object.An encapsulated object is often called an abstract data type.
There are several other ways that an encapsulation can be used, as an example we can take the usage of an interface. The interface can be used to hide the information of an implemented class.
//Declare as Private
private string _LegName;
// Property Set as public
public string LegName
{
get
{
return _LegName;
}
set
{
_LegName=value;
}
public class LegMain
{
public static int Main(string[] args)
{
Leg L= new Leg();
d.LegName="Right Leg";
Console.WriteLine("The Legis :{0}",d.LegName);return 0;
}
}
Note: Encapsulation provides a way to protect data from accidental corruption.
Thank you
Encapsulation means hiding the data. In other words a class only exposes those properties or information which is authorized to be seen. Consider the below exapmle where a certain property called ConfidentialMessage is accesible only to the Admin role. This property is made private and is returned through another method which checks the role of an user and return the message only for admin.
public class Message
{
public Message()
{
ConfidentialMessage = "I am Nemo";
}
private string ConfidentialMessage { get; set; }
public string GetMessage(string name)
{
string message = string.Empty;
if (name == "Admin")
{
message = this.ConfidentialMessage;
}
return message;
}
}
Putting definition of encapsulate
enclose in a capsule, from en- "make, put in" + capsule + -ate .
now capsule meaning is box, case
In real life example if you put things on desk open then it is accessible to anyone but if you put in case then it is accessible with the key of case to open.
Same way in class if you create a variable then it accessible whenever you create object of that class.But if you create function to access the variable then you have created case and function is key to access the variable.
So in programming language we are creating wrapper of the data by using getter and setter and making it private variable.
Encapsulation is a capsule, consider it to be a class enclosing or hiding fields, properties and functions.
Please check below url encapsulation is simplified with simple programming example.
http://itsforlavanya.blogspot.com/2020/08/encapsulation.html?m=1

Performance penalty of typecasting and boxing/unboxing types in C# when storing generic values

I have a set-up similar to WPF's DependencyProperty and DependencyObject system. My properties however are generic. A BucketProperty has a static GlobalIndex (defined in BucketPropertyBase) which tracks all BucketProperties. A Bucket can have many BucketProperties of any type. A Bucket saves and gets the actual values of these BucketProperties... now my question is, how to deal with the storage of these values, and what is the penalty of using a typecasting when retrieving them? I currently use an array of BucketEntries that save the property values as simple objects. Is there any better way of saving and returning these values?
Beneath is a simpliefied version:
public class BucketProperty<T> : BucketPropertyBase
{
}
public class Bucket
{
private BucketEntry[] _bucketEntries;
public void SaveValue<T>(BucketProperty<T> property, T value)
{
SaveBucketEntry(property.GlobalIndex, value)
}
public T GetValue<T>(BucketProperty<T> property)
{
return (T)FindBucketEntry(property.GlobalIndex).Value;
}
}
public class BucketEntry
{
private object _value;
private uint _index;
public BucketEntry(uint globalIndex, object value)
{
...
}
}
I've created a very similar setup after reading through Rockford Lhotka's book on Business Objects but I avoided the object boxing issue by forcing the implementer of the property to maintain a typed backing field instead. I know this is a trade off but in my case I valued performance over the simplicity of declaring new properties. In order to manage the type throughout the property lookups and management I use Lambda expressions and generics very heavily and so far so good, I'm beating the performance of Dependency Objects and CSLA.
To answer your question, yes you will have a performance hit by using object boxing and also for value types backed by these properties you will be storing keeping an extra pointer in the heap for each value which in general would double the memory footprint for these values. As far as how much a performance hit you will take it depends on how regularly read and write to these properties amongst other factors. If you want to get a feel for the performance difference it would probably be a good idea to make a small test app that runs a loop and boxes some integers as an object and un-boxes them versus storing the same values in a regular field. My guess is that by not doing object boxing and un-boxing you will likely increase your performance at least 2-fold but don't take my word do the test.

Resources