Are "passive" objects considered a good design practice? - model-view-controller

I find myself very often creating an object that has no public methods and is self-contained. It typically handles events of arguments passed to its constructor in its private methods and does not raise any events or expose any public methods.
I am calling this type of objects "passive" objects - objects that do not have any public methods defined. All interaction occurs inside them in private methods and events of arguments passed in constructor.
Typically it is some utility class, like one that assures that two forms will be sticked together:
public class StickyForm : IDisposable
{
private readonly Form form;
private readonly Form parentForm;
public StickyForm(Form form, Form parentForm)
{
this.form = form;
this.form.StartPosition = FormStartPosition.Manual;
this.parentForm = parentForm;
this.parentForm.LocationChanged += new EventHandler(parent_LocationChanged);
this.parentForm.SizeChanged += new EventHandler(parent_SizeChanged);
SetLocation();
}
void parent_SizeChanged(object sender, EventArgs e)
{
SetLocation();
}
void parent_LocationChanged(object sender, EventArgs e)
{
SetLocation();
}
private void SetLocation()
{
//compute location of form based on parent form
}
public void Dispose()
{
this.parentForm.SizeChanged -= parent_SizeChanged;
this.parentForm.LocationChanged -= parent_LocationChanged;
}
}
But sometimes it is also some kind of controller, providing interaction between two views:
public class BrowseController
{
private IBrowserView view;
private IFolderBrowser folderBrowser;
public BrowseController(IFolderBrowser folderBrowser, IBrowserView view)
{
this.view = view;
this.folderBrowser = folderBrowser;
this.folderBrowser.NodeOpened += folderBrowser_NodeOpened;
}
private void folderBrowser_NodeOpened(object sender, Core.Util.TEventArgs<IPictureList> e)
{
this.Browse(e.Value);
}
public void Browse(IPictureList content)
{
//stripped some code
AddItemsToView(content);
}
private void AddItemsToView(IPictureList browser)
{
//call methods on view
}
}
Are such "passive" objects considered a good design practice?
Is there a better name for this kind of class?

Seems like fine design to me. I'm not sure about the name passive though. Those classes do seem pretty active. They react to events and do stuff. I would think a class is more passive if you have to call methods on it to get it to do stuff, but normally it wouldn't do anything unless poked.
How about the name "controller". "controller" is the more usual name for a class used in a UI that causes interaction between a view and data, and they quite often don't need to have public methods.
I'm sure there's other ideas for names.

I don't see anything wrong with that. If it results in clean, readable code, go for it!

I wouldn't call the objects that react to notifications and update their state completely passive.
One other thought, if the objects simply adjust their state to reflect changes in the outside world without providing much of their own, you may slice their "functionality" and put it into other more active "components". There may be not enough reason for these objects to exist.
If this organization however makes you code structure better, clearer and more maintainable, then use it and don't worry about it.

I think that there's one important criteria to meet with this design: can you test it? The designs you have seem to be testable, but you may have to be careful as I can see this leading to some rather untestable code.
In regards to the name, I think this may be an example of the Mediator pattern.

Conceptually this appears to be an implementation of strategy pattern. Although in this particular case the reasoning is different from strategy pattern', it still yields very readable and nicely granulated code. Go for it.
UPDATE: to make a little clearer what I mean consider two (or more) classes derived from StickyForm
public class VeryStickyForm : StickyForm
{
//some implementation here
//but interface is completely inherited from StickyForm
}
public class SomewhatStickyForm : StickyForm
{
//some implementation here
//but interface is completely inherited from StickyForm
}
And you decide which one to use dynamically depending on run-time state... you implement a strategy.
As I said your solution is conceptually similar to strategy: you select some behavioral aspect of your application that can be well abstracted into policy and move the implementation of the policy into separate class, that does not know about the rest of the application, and your application does not know much about guts of the policy. Even though you do not use it polymorphically, resemblance to strategy is clear.

Related

C# Attribute or Code Inspection Comment to Encourage or Discourage Call to Base Method from Virtual Method Override

I'm working on a C# project in Unity with Rider.
I sometimes see a base class with an empty virtual method, and then a derived class that overrides that method. The method override has an explicit call to base.MethodName() even though the base method is empty.
public class A
{
public virtual void Method1() { }
public virtual void Method2()
{
// Important logic performed here!
}
}
public class B : A
{
public override void Method1()
{
base.Method();
// Do something else ...
}
public override void Method2()
{
// Do something here ...
}
}
When looking at the method in Rider's IL Viewer, the call to the base method is included, even though the method is empty.
Are there any method attributes or code inspection comments in C# or Rider that could:
Generate a compiler or code inspection warning when calling a base method that is empty.
Generate a compiler or code inspection warning when not calling a base method that is not empty.
For example:
public class A
{
[OmitCallFromOverride]
public virtual void Method1() { }
[RequireCallFromOverride]
public virtual void Method2()
{
// Important logic performed here!
}
}
I can imagine a scenario where multiple derived classes override a method and one or more mistakenly failed to call the base method, which might result in unexpected behavior. Or situations where there are unnecessary calls to an empty base method, which may be wasteful, but unlikely to break anything.
While I'm primarily inquiring about whether such attributes or code inspection comments exist, I am also curious to know of how people might handle these situations, such as simply always calling the base method from an override, keeping important logic out of base virtual methods, or using some other method of communicating whether a base method call is unnecessary or required.
Generate a compiler or code inspection warning when calling a base
method that is empty.
In c#, as far as I know, there is no warning for an empty method. So, I think there is no warning when calling a base method that is empty.
But you are free to write one for you: Write your first analyzer and code fix
Generate a compiler or code inspection warning when not calling a base
method that is not empty.
Not in C#, and I think is not a good idea to force a derived class to call a base method. I can understand that in your scenario, it would be great if all your derived classes method call always the base method, but it will be a very uncommon case. And generally when we need tricky (not intuitive) rules, that means our solution is not very clear, or it will be error-prone.
keeping important logic out of base virtual methods
If you need A.Method1 to be called, maybe let it as a virtual method is not a good idea. You have a virtual method when you want to give to your derived classes the opportunity to use it OR to overwrite it with a more adapted version.
I propose you a solution that maybe you can adapt to your scenario.
abstract class A
{
public abstract void Method1();
public virtual void Method2() { }
public void MustBeCalled()
{
// Here you can put the logic you had in Method1, you need to execute this code, so this method can't be overwrited.
}
public void TemplateMethod()
{
Method1();
MustBeCalled();
// Do something else ...
}
}

Mvc3 custom event hooks

I have a Mvc3-Project where I want to register to custom event hooks.
So that I can register to an event like "User logon". I do not want to do it in the controller, because there is a business logic behind it in an other project.
So in my Mvc3-Project I want to write some classes that will have the code that has to be executed when a User is loged on. But how do I register these classes (or an instance of them) to the event. Is it a good idea to use reflection an search for all classes inherited from a special base class, or is there an other smarter way?
So again, I do not want to monitor the action that is called, I want that the business logic triggers some classes in my Mvc3-Project.
EDIT
As Chris points out in the comments below, MVC3 is stateless, meaning that with this solution you would have to resubscribe for these events on every request. This is probably not a very good solution for MVC.
Have you considered an global event service?
Rough example:
class Example : IEventReceiver
{
public void Init()
{
EventService.Subscribe("Logon", this);
}
private void OnEvent(string eventName)
{
// Do logon stuff here.
}
}
You would need to create the EventService class, which might be a singleton or service. It might have interface similar to the following:
public interface IEventService
{
void Subscribe(string eventName, IEventReceiver receiver);
void Unsubscribe(string eventName, IEventReceiver receiver);
void DispatchEvent(string eventName);
}
public interface IEventReceiver
{
void OnEvent(string eventName);
}

Using DI to cache a query for application lifetime

Using a DI container (in this case, Ninject) is it possible - - or rather, wise to cache a frequently used object for the entire application lifetime (or at least until it is refreshed)?
To cite example, say I have a Template. There are many Template objects, but each user will inherit at least the lowest level one. This is immutable and will never change without updating everything that connects to it (so it will only change on administration demand, never based on user input). It seems foolish to keep querying the database over and over for information I know is not changed.
Would caching this be best done in my IoC container, or should I outsource it to something else?
I already store ISessionFactory (nHibernate) as a Singleton. But that's a little bit different because it doesn't include a query to the database, just the back-end to open and close ISession objects to it.
So basically I would do something like this..
static class Immutable
{
[Inject]
public IRepository<Template> TemplateRepository { get; set; }
public static ITemplate Template { get; set; }
public void Initialize()
{
if(Immutable.Template == null)
{
Immutable.Template = TemplateRepository.Retrieve(1); // obviously better logic here.
}
}
class TemplateModule : Module
{
public void Load()
{
Bind<ITemplate>().ToMethod(() => Immutable.Initialize())InSingletonScope();
}
}
Is this a poor approach? And if so, can anyone recommend a more intelligent one?
I'd generally avoid using staticness and null-checking from your code - create normal classes without singleton wiring by default and layer that aspect on top via the container. Ditto, remove reliance on property injection - ctor injection is always better unless you have no choice
i.e.:
class TemplateManager
{
readonly IRepository<Template> _templateRepository;
public TemplateManager(IRepository<Template> templateRepository)
{
_templateRepository = templateRepository;
}
public ITemplate LoadRoot()
{
return _templateRepository.Retrieve(1); // obviously better logic here.
}
}
class TemplateModule : Module
{
public void Load()
{
Bind<ITemplate>().ToMethod(() => kernel.Get<TemplateManager>().LoadRoot()).InSingletonScope();
}
}
And then I'd question whether TemplateManager should become a ninject provider or be inlined.
As for the actual question... The big question is, how and when do you want to control clearing the cache to force reloading if you decided that the caching should be at session level, not app level due to authorization influences on the template tree? In general, I'd say that should be the Concern of an actual class rather than bound into your DI wiring or hardwired into whether a class is a static class or is a Singleton (as in the design pattern, not the ninject Scope).
My tendency would be to have a TemplateManager class with no static methods, and make that a singleton class in the container. However, to get the root template, consumers should get the TemplateManager injected (via ctor injection) but then say _templateManager.GetRootTemplate() to get the template.
That way, you can:
not have a reliance on fancy ninject providers and/or tie yourself to your container
have no singleton cruft or static methods
have simple caching logic in the TemplateManager
vary the Scoping of the manager without changing all the client code
have it clear that getting the template may or may not be a simple get operation
i.e, I'd manage it like so:
class TemplateManager
{
readonly IRepository<Template> _templateRepository;
public TemplateManager(IRepository<Template> templateRepository)
{
_templateRepository = templateRepository;
}
ITemplate _cachedRootTemplate;
ITemplate FetchRootTemplate()
{
if(_cachedRootTemplate==null)
_cachedRootTemplate = LoadRootTemplate();
return _cachedRootTemplate;
}
ITemplate LoadRoot()
{
return _templateRepository.Retrieve(1); // obviously better logic here.
}
}
register it like so:
class TemplateModule : Module
{
public void Load()
{
Bind<TemplateManager>().ToSelf().InSingletonScope();
}
}
and then consume it like so:
class TemplateConsumer
{
readonly TemplateManager _templateManager;
public TemplateConsumer(TemplateManager templateManager)
{
_templateManager = templateManager;
}
void DoStuff()
{
var rootTempalte = _templateManager.FetchRootTemplate();
Wild speculation: I'd also consider not having a separate IRepository being resolvable in the container (and
presumably having all sorts of ties into units of work). Instead, I'd have the TemplateRepository be a longer-lived thing not coupled to an ORM layer and Unit Of Work. IOW having a repository and a Manager none of which do anything well defined on their own isnt a good sign - the repository should not just be a Table Data Gateway - it should be able to be the place that an Aggregate Root such as Templates gets cached and collated together. But I'd have to know lots more about your code base before slinging out stuff like that without context!

Java - how to design your own type?

Is it possible to design your own Java Type, similar to an extensible enum?
For instance, I have user roles that a certain module uses and then a sub-package provides additional roles.
What would be involved on the JDK side of things?
Since Enums can't be extended, you have to fake it.
Make a class with a protected constructor.
Then you can create public static final FakeEnum instances in your class.
public class FakeEnum {
private String name;
private Object something;
protected FakeEnum(String name, Object otherParam) {
this.name = name;
this.something = otherParam;
}
// public getters
public static final FakeEnum ONE = new FakeEnum("one", null);
public static final FakeEnum TWO = new FakeEnum("two", null);
public static final FakeEnum THRE = new FakeEnum("thre", null);
}
And then you can extend it and add some more things to it like so:
public class ExtendedFakeEnum extends FakeEnum {
public static final FakeEnum EXTENDED_ONE = new FakeEnum("extended_one", null);
public static final FakeEnum EXTENDED_TWO = new FakeEnum("extended_two", null);
}
Ok,
What I will do is write an interface and then several implementations for how to find users to notify in a particular event. The correct implementation will get injected at run-time and then it will do whatever it needs to do to find the correct users. That implementation may simply take arguments to configure the group name to look for and then return a list of users.
I am learning to use interfaces / design by contract more. Most of my development in the past has only ever had a single implementation so I saw this as a moot point and forgot about that tool / means.
Thanks,
Walter
The concept of an extensible enum doesn't make sense. An enum is used to declare statically the entire set of instances that will ever be made for its own type. Allowing it to be extended would make that impossible to ensure.
Designing your own type in Java is impossible. Anything you need to do can be done using various design patterns.
If you need an "extensible enum" it might be that a dictionary would suit you better, look at java.util.Dictionary<K,V> where K is the keyname (how you would refer to the particular value, and V is the value/object that should be returned by said Key.
I think thats the closest I've ever come to an extensible Enum.
Also, have a look at this question on SO, this might solve it too.

RhinoMocks: Correct way to mock property getter

I'm new to RhinoMocks, and trying to get a grasp on the syntax in addition to what is happening under the hood.
I have a user object, we'll call it User, which has a property called IsAdministrator. The value for IsAdministrator is evaluated via another class that checks the User's security permissions, and returns either true or false based on those permissions. I'm trying to mock this User class, and fake the return value for IsAdministrator in order to isolate some Unit Tests.
This is what I'm doing so far:
public void CreateSomethingIfUserHasAdminPermissions()
{
User user = _mocks.StrictMock<User>();
SetupResult.For(user.IsAdministrator).Return(true);
// do something with my User object
}
Now, I'm expecting that Rhino is going to 'fake' the call to the property getter, and just return true to me. Is this incorrect? Currently I'm getting an exception because of dependencies in the IsAdministrator property.
Can someone explain how I can achieve my goal here?
One quick note before I jump into this. Typically you want to avoid the use of a "Strict" mock because it makes for a brittle test. A strict mock will throw an exception if anything occurs that you do not explicitly tell Rhino will happen. Also I think you may be misunderstanding exactly what Rhino is doing when you make a call to create a mock. Think of it as a custom Object that has either been derived from, or implements the System.Type you defined. If you did it yourself it would look like this:
public class FakeUserType: User
{
//overriding code here
}
Since IsAdministrator is probably just a public property on the User type you can't override it in the inheriting type.
As far as your question is concerned there are multiple ways you could handle this. You could implement IsAdministrator as a virtual property on your user class as aaronjensen mentioned as follows:
public class User
{
public virtual Boolean IsAdministrator { get; set; }
}
This is an ok approach, but only if you plan on inheriting from your User class. Also if you wan't to fake other members on this class they would also have to be virtual, which is probably not the desired behavior.
Another way to accomplish this is through the use of interfaces. If it is truly the User class you are wanting to Mock then I would extract an interface from it. Your above example would look something like this:
public interface IUser
{
Boolean IsAdministrator { get; }
}
public class User : IUser
{
private UserSecurity _userSecurity = new UserSecurity();
public Boolean IsAdministrator
{
get { return _userSecurity.HasAccess("AdminPermissions"); }
}
}
public void CreateSomethingIfUserHasAdminPermissions()
{
IUser user = _mocks.StrictMock<IUser>();
SetupResult.For(user.IsAdministrator).Return(true);
// do something with my User object
}
You can get fancier if you want by using dependency injection and IOC but the basic principle is the same across the board. Typically you want your classes to depend on interfaces rather than concrete implementations anyway.
I hope this helps. I have been using RhinoMocks for a long time on a major project now so don't hesitate to ask me questions about TDD and mocking.
Make sure IsAdministrator is virtual.
Also, be sure you call _mocks.ReplayAll()
_mocks.ReplayAll() will do nothing. It is just because you use SetupResult.For() that does not count. Use Expect.Call() to be sure that your code do everything correct.

Resources