How to implement IReactiveNotifyPropertyChanged on a base class that alreay implements INotifyPropertyChanged - inotifypropertychanged

Currently I have this generic implementation by inheriting from an existing base class that provides INotifyPropertyChanged. I cannot change this base class, but I want to provide the property change notifications also as an Observable so I implement the IReactiveNotifyPropertyChanged interface as well.
I find the code below (obtained through a process of trial and error) to be quite involved and was wondering if this could be done in a more simple, concise manner.
Also, I'm struggling to come up with ideas to suppress notifications. Any thoughts?
public class MyReactiveClass<T> : PropertyChangeNotifyingBaseClass<T>, IReactiveNotifyPropertyChanged<T>
where T : class
{
public MyReactiveClass()
{
Changed = Observable.FromEventPattern<PropertyChangedEventHandler, PropertyChangedEventArgs>
(
t => PropertyChanged += t, // add handler
t => PropertyChanged -= t // remove handler
// conversion from EventPattern to ReactivePropertyChangedEventArgs
).Select(ev => new ReactivePropertyChangedEventArgs<T>(ev.Sender as T, ev.EventArgs.PropertyName));
Changing = Observable.FromEventPattern<System.ComponentModel.PropertyChangingEventHandler, PropertyChangingEventArgs>
(
t => PropertyChanging += t, // add handler
t => PropertyChanging -= t // remove handler
// conversion from EventPattern to ReactivePropertyChangedEventArgs
).Select(ev => new ReactivePropertyChangedEventArgs<T>(ev.Sender as T, ev.EventArgs.PropertyName));
}
public IObservable<IReactivePropertyChangedEventArgs<T>> Changing { get; }
public IObservable<IReactivePropertyChangedEventArgs<T>> Changed { get; }
public IDisposable SuppressChangeNotifications()
{
// how to deal with suppression of change notifications?!
return Disposable.Empty;
}
}

You have written the shortest possible piece of code to implement Changed and Changing observables, what do you want to achieve more? :)
Since you need Changed, Changing, SuppressChangeNotifications, and maybe in a month you will want something else of ReactiveObject, the best solution would be to use ReactiveObject as base class.
But if you can't do that, I will suggest you to download the source code of reactiveui and take just the pieces of code that you need:
https://github.com/reactiveui/ReactiveUI
You better don't implement certain features by yourself. The creators of the framework have dealt with many bugs and issues so their code is certainly more solid of what I or you can produce by ourselves (unless we're genius).

Related

Computed properties in a PageModel

I have a subclass of PageModel that looks like this:
public class DetailsModel : PageModel
{
...
public IList<Comment> Comments { get; set; }
...
public async Task<IActionResult> OnGetAsync(int? id)
{
Comments = await _context.Comment.Where(comment => comment.LinkId == id).ToListAsync();
...
}
...
}
Moving the code to the property definition
Instead of computing the property value inside OnGetAsync, I had considered having the computation code be at the property definition site:
public IList<Comment> Comments
{
get
{
return _context.Comment.Where(comment => comment.LinkId == Link.Id).ToList();
}
}
One downside there is that the code is no longer async.
The code runs each time the property is called (which may or may not be desired).
Putting the code in a method
Finally, I can put the code in a method instead of a property:
public async Task<IList<Comment>> Comments()
{
return await _context.Comment.Where(comment => comment.LinkId == Link.Id).ToListAsync();
}
Now it's async again. But we have a little syntactic overhead at the callsite:
await Comments()
I.e. we need to use await and the parens.
Question
I like the second approach as the code is kept close to the property definition. This is especially nice when there are many properties. (It seems awkward to have a long list of property definitions only to set them up later in OnGet.) But as mentioned, there are a couple of potential downsides.
What is the idiomatic and recommended way to do something like this?
If you consider the .NET guidelines for property design, there are some relevant bits:
AVOID throwing exceptions from property getters
and
Property getters should be simple operations and should not have any
preconditions. If a getter can throw an exception, it should probably
be redesigned to be a method.
Generally properties should be simple and performant, otherwise a method is a better choice. Using a method also gives you control over exactly when it is invoked, which is more difficult with properties that execute on access.
In this case, it would be ideal to keep any queries etc in the OnGetAsync where you and others expect to find it, and certainly to keep it on an async path.

Using Test Doubles with DbEntityEntry and DbPropertyEntry

I am using the new Test Doubles in EF6 as outlined here from MSDN . VS2013 with Moq & nUnit.
All was good until I had to do something like this:
var myFoo = context.Foos.Find(id);
and then:
myFoo.Name = "Bar";
and then :
context.Entry(myFoo).Property("Name").IsModified = true;
At this point is where I get an error:
Additional information: Member 'IsModified' cannot be called for
property 'Name' because the entity of type
'Foo' does not exist in the context. To add an
entity to the context call the Add or Attach method of
DbSet.
Although, When I examine the 'Foos' in the context with an AddWatch I can see all items I Add'ed before running the test. So they are there.
I have created the FakeDbSet (or TestDbSet) from the article. I am putting each FakeDbSet in the FakeContext at the constructor where each one gets initialized. Like this:
Foos = new FakeDbSet<Foo>();
My question is, is it possible to work with the FakeDbSet and the FakeContext with the test doubles scenario in such a way to have access to DbEntityEntry and DBPropertyEntry from the test double? Thanks!
I can see all items I Add'ed before running the test. So they are there.
Effectively, you've only added items to an ObservableCollection. The context.Entry method reaches much deeper than that. It requires a change tracker to be actively involved in adding, modifying and removing entities. If you want to mock this change tracker, the ObjectStateManager (ignoring the fact that it's not designed to be mocked at all), good luck! It's got over 4000 lines of code.
Frankly, I don't understand all these blogs and articles about mocking EF. Only the numerous differences between LINQ to objects and LINQ to entites should be enough to discourage it. These mock contexts and DbSets build an entirely new universe that's a source of bugs in itself. I've decided to do integrations test only when and wherever EF is involved in my code. A working end-to-end test gives me a solid feeling that things are OK. A unit test (faking EF) doesn't. (Others do, don't get me wrong).
But let's assume you'd still like to venture into mocking DbContext.Entry<T>. Too bad, impossible.
The method is not virtual
It returns a DbEntityEntry<T>, a class with an internal constructor, that is a wrapper around an InternalEntityEntry, which is an internal class. And, by the way, DbEntityEntry doesn't implement an interface.
So, to answer your question
is it possible to (...) have access to DbEntityEntry and DBPropertyEntry from the test double?
No, EF's mocking hooks are only very superficial, you'll never even come close to how EF really works.
Just abstract it. If you are working against an interface, when creating your own doubles, put the modified stuff in a seperate method. My interface and implementation (generated by EF, but I altered the template) look like this:
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Model
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public interface IOmt
{
DbSet<DatabaseOmtObjectWhatever> DatabaseOmtObjectWhatever { get; set; }
int SaveChanges();
void SetModified(object entity);
void SetAdded(object entity);
}
public partial class Omt : DbContext, IOmt
{
public Omt()
: base("name=Omt")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<DatabaseOmtObjectWhatever> DatabaseOmtObjectWhatever { get; set; }
public void SetModified(object entity)
{
Entry(entity).State = EntityState.Modified;
}
public void SetAdded(object entity)
{
Entry(entity).State = EntityState.Added;
}
}
}

Avoid adding/extending methods to interface

I have a scenario , where my current interface looks like
public interface IMathematicalOperation
{
void AddInt();
}
After an year i expect the interface to be extended with AddFloat method and also expect 100 users already consuming this interface. When i extend the interface with a new method after an year i don't want these 100 classes to get changed.
So how can i tackle this situation ? Is there any design pattern available already to take care of this situation ?
Note: i understand that i can have a abstract class which implement this interface and make all the methods virtual , so that clients can inherit from this class rather than the interface and override the methods . When i add a new method only the abstract class will be changed and the clients who are interested in the method will override the behavior (minimize the change) .
Is there any other way of achieving the same result (like having a method named Add and based on certain condition it will do Float addition or Integer addition) ?
Edit 1:
The new method gets added to the interface also needs to be called automatically along with the existing methods(like chain of responsibility pattern).
There are at least two possible solution I can think of:
Derive your new interface from your old interface
public interface IMathematicalOperation
{
void AddInt();
}
public interface IFloatingPointMathematicalOperation : IMathematicalOperation
{
void AddFloat();
}
Have simply a parallel interface which contains the new method and have all classes which need the new interface derive from it
I'd suggest the second solution, since I don't understand why you would want an established interface to change.
I encountered a similar issue some time ago and found the best way was not to try and extend an existing interface, but to provide different versions of the interface with each new interface providing extra functionality. Over time I found that was not adding functionality on a regular basis, may once a year, so adding extra interfaces was never really an issue.
So, for example this is your first version of the interface:
public interface IMathematicalOperation
{
void AddInt();
}
This interface would then be implemented on a class like this:
public class MathematicalOperationImpl : IMathematicalOperation
{
public void AddInt()
{
}
}
Then when you need to add new functionality, i.e. create a version 2, you would create another interface with the same name, but with a "2" on the end:
public interface IMathematicalOperation2 : IMathematicalOperation
{
void AddFloat();
}
And the MathematicalOperationImpl would be extended to implement this new interface:
public class MathematicalOperationImpl : IMathematicalOperation, IMathematicalOperation2
{
public void AddInt()
{
}
public void AddFloat()
{
}
}
All of your new/future clients could start using the version 2 interface, but your existing clients would continue to work because they will only know about the first version of the interface.
The options provided are syntactically viable but then, as is obvious, they won't apply to any previous users.
A better option would be to use the Visitor pattern
The pattern is best understood when you think about the details of OO code
this.foo(); // is identical to
foo(this);
Remember that there is always a hidden 'this' parameter passed with every instance call.
What the visitor pattern attempts to do is generalize this behavior using Double dispatch
Let's take this a hair further
public interface MathematicalOperation
{
void addInt();
void accept(MathVisitor v);
}
public interface MathVisitor {
void visit(MathematicalOperation operation);
}
public class SquareVistor implements MathVisitor {
void visit(MathematicalOperation operation) {
operation.setValue(operation.getValue() * 2);
}
}
public abstract class AbstractMathematicalOperation implements MathematicalOperation {
public void accept(MathVisitor f) {
f.visit(this); // we are going to do 'f' on 'this'. Or think this.f();
}
}
public class MyMathOperation extends AbstractMathematicalOperation {
}
someMathOperation.visit(new SquareVisitor()); // is now functionally equivalent to
someMathOperation.square();
The best bet would be for you to roll-out your initial interface with a visitor requirements, then immediately roll-out an abstract subclass that gives this default implementation so it's cooked right in (As the above class is). Then everyone can just extend it. I think you will find this gives you the flexibility you need and leaves you will the ability to work with legacy classes.

Avoiding spaghetti code (gamestatemanager)

I am writing a StateManager for a game (I'm using C++ and SFML, but I tried to hide language specific elements because this is a question about any OOP language).
I have a setup in which a StateManager updates the current active state. However, a State must be able to change the active state (e.g. pressing "Play" in a menu starts a PlayingState), so I keep a reference to the StateManager in my State class.
Here's an UML diagram to make things more clear.
As you see, StateManager and State both reference eachother.
How can I avoid spaghetticode? Should I make the StateManager a singleton class? While we're at it, should the game class be a singleton class? I could easily do this, but I don't really like other classes in my game being able to access the game class or statemanager class, even if I am the only programmer.
You need to design in contracts also known as interfaces. For example, a state (in principle) does not need access to the state machine. The implementation of a state may need access though. Example in C#:
public interface IState
{
void Render();
void Update();
}
public interface IStateMachine
{
void ChangeState(IState newState);
}
public class MenuState : IState
{
private IStateMachine _stateMachine;
public MenuState(IStateMachine stateMachine)
{
_stateMachine = stateMachine;
}
public void Render()
{
}
public void Update()
{
}
}
public class StateMachineImplementation : IStateMachine
{
public void ChangeState(IState newState)
{
}
}
Notice Any implementation of IState is unaware of any IStateMachine implementation, they just work on contracts. Also notice that MenuState is not concerned about where 'IStateMachine' comes from (Inversion of Control), it just uses it.
You could add in another function into IStateMachine for GetStates() if you needed to.
Ultimately, you use these contracts to avoid coupling; which means you can completely replace the implementation of IStateManager and (assuming that adheres to the contract), MenuState will still work fine.
There's nothing wrong with bidirectional references. Look at Qt's parent/child model for QWidgets. If each State can only affect one StateManager, make each State take a pointer to a StateManager "parent" in its construction, or set it later. A StateManager can keep track of its "children" in a collection, and each child knows who its parent is, so it can inform that parent of any changes.
Edit:
I think the first thing to look at would be to break your State class up. Currently it represents both a state and an action to change into that state. Actions should have knowledge of a StateMachine, to tell it to change states. States should be internal to the StateMachine.

Design Pattern for late binding class (without switch case for class assignment)

I have a base class where all common functions are written. I many classes which override this functions by virtual keyword. Like,
public class Base
{
public virtual void sample()
{
..............
}
}
public class a : Base
{
public override sample()
{
}
}
public class implement
{
public void ToSample()
{
Base baseclass = new Base();
Switch(test)
{
case a: baseclass = a();
break;
case b: baseclass = b();
break;
}
baseclass.sample();
}
}
This perfect code for current situation but now I have more class to be assign in switch case. It is not good practice for adding huge amount of cases so I want something that automatically assign child class.
Is anybody know something to be implement ?
As stated in the comment, you can decouple the implementation by using dependency injection. Note however, that in some cases you have no choice but doing that kind of switch (e.g. when you need to create a class based on a text received in a socket). In such cases the important thing is to always keep the switch statement encapsulated in one method and make your objects rely on it (or, in other words, don't copy-and-paste it everywhere :)). The idea here is too keep your system isolated from a potentially harmful code. Of course that if you add a new class you will have to go and modify that method, however you will only have to do it in one time and in one specific place.
Another approach that I have seen (and sometimes used) is to build a mapping between values an classes. So, if your class-creation switch depends on an integer code, you basically create a mapping between codes and classes. What you are doing here is turning a "static" switch into a dynamic behavior, since you can change the mappings contents at any time and thus alter the way your program behaves. A typical implementation would be something like (sorry for the pseudocode, I'm not familiar with C#):
public class implement
{
public void ToSample()
{
class = this.mapping.valueForKey(test);
Base baseclass = new class();
baseclass.sample();
}
}
Note however that for this example to work you need reflection support, which varies according to the language you are using (again, sorry but I don't know the C# specifics).
Finally, you can also check the creational family of patterns for inspiration regarding object creation issues and some well known forms of solving them.
HTH