Is it bad practice to have Events in interfaces? c# - c#

I'm trying to use interfaces more, and often I find myself putting events into the interface. It feels strange, because I'm leaving up to the implementer to know when to raise these events within their implementation.
For example, I have an ILevellable interface, which simply states an object should have xp, a level and a max level, and some methods which modify these values. Classes referencing ILevellable would probably want to know when it levelled up, so I add an Action for OnLevelUp... but the implementation might not put that in the correct place.
public interface ILevellable
{
int Level { get; }
int MaxLevel { get; }
int XP { get; }
event Action<bool> OnXPChanged;
event Action<ILevellable> OnLevelUp;
event Action OnMaxLevelReached;
void LevelUp(int newLevel);
}
Am I supposed to trust that users implementing this interface will know where to implement this? I would assume not. Especially because some events might have arguments which, again, the user might have no idea what it is supposed to represent.
I appreciate any guidance! I am new to working like this.
Thanks!

It's fine to define events in your interfaces. However it is consistent with convention to have both a 'sender' and 'event args' passed into the event. TypedEventHandler is an easy way to do it. For example:
using Windows.Foundation;
public struct LevellableChange {
public LevellableChange( int dl, int dxp)
{
this.ChangeInLevel = dl;
this.ChangeInXP = dxp;
}
int ChangeInLevel { get; }
int ChangeInXP {get;}
}
public interface ILevellable
{
int Level { get; }
int MaxLevel { get; }
int XP { get; }
event TypedEventHandler< ILevellable, LevellableChange> Changed;
}
Then the standard approach to implementing them would be like this:
public class Levellable: ILevellable
{
public event TypedEventHandler<ILevellable, LevellableChange> Changed;
public int Level {
get {
return this._level;
}
private set {
if (value != this._level) {
int oldLevel = this._level;
this._level = value;
this.Changed?.Invoke(this, new LevellableChange(value - oldLevel, 0));
}
}
}
private int _level;
// similar for XP.
}
One other comment, it is useful to have a class implementing INotifyPropertyChanged, and then get in the habit of deriving from it. Together with a snippet in Visual Studio it makes things a lot easier. It's true that for the example above, INotifyPropertyChanged would not be enough since it doesn't give the change to the previous value.

First of all you are not having delegate types in your interface definition but events. Check this answer by Jon Skeet to see the difference between delegates and events. After saying that it is totally fine to have events in your interface, even .Net does it, consider for instance the famous INotifyPropertyChanged interface. It just defines an event...
Secondly:
Am I supposed to trust that users implementing this interface will know where to implement this?
When you define an interface you really do not care about implementers as much as about consumers, and so, for a consumer that sees your contract definition it is useful to know that he/she can susbscribe to an event named OnLevelUp. Let's say I am indeed consuming your interface, I do not know how or when you trigger OnLevelUp event, and I should not really care, because you have given to that event a very semantic and meaningful name, so I can pretty much be sure that it will be triggered when the ILevellable's Level property is increased.

Related

Is an abstract class with fields considered not a good practice?

I created an abstract class that implements an interface. This abstract class will be the base of several concrete classes that need to populate the properties of that interface.
The CLR compliance warnings pop up on the first two examples. I understand what they represent and there are several questions here that cover them.
To make the field different I can add a trailing underscore. It is accepted by the compiler. Is this a correct style choice. I don't think it stands out very well and may be a code smell. But I may just not be used to it.
Or am I wrong to make an abstract ancestor that defines property fields? The idea of course is to save duplication of work and help to enforce a standard implementation, but I can see that it might have its own smell in the descendent when it starts assigning values to these "hidden" fields.
namespace MyLittleCompany.Widgety
{
public abstract class MlcWidgetInformation : IMlcWidgetInformation
{
//Compiler complains of Non-CLR Compliance (case difference only)
protected int sides; //Number of sides for this widget
//Compiler complains of Non-CLR Compliance (non-private name with underscore
// is not compliant)
protected int _hooks; //Number of hooks on this widget
//Compiler is happy with a trailing underscore
protected int feathers_; //Number of feathers on this widget
// Interface items
public Sides { get { return sides; } }
public Hooks { get { return _hooks; } }
public Feathers { get { return feathers_; } }
}
}
=====================================
namespace MyLittleCompany.Widgety
{
public class SmallWidgetInformation : MlcWidgetInformation
{
public SmallWidgetInformation()
{
// Is this a smell? As in "What are these things?"
sides = 6;
_hooks = 3;
feathers_ = 1;
}
}
}
Having to create an abstract base class just to avoid repeatedly defining three fields isn't a code smell, but:
It does feel like taking DRY to extremes,
and (assuming you use inheritance elsewhere), you block the opportunity to inherit from other classes.
However, if you are willing/able to use VS2015 and C# 6, help is at hand. The new read-only auto properties allow you to do this, removing the need for the base class without repetition:
public interface IMlcWidgetInformation
{
int Sides { get; }
int Hooks { get; }
int Feathers { get; }
}
public class SmallWidgetInformation : IMlcWidgetInformation
{
public int Sides { get; } = 6;
public int Hooks { get; } = 3;
public int Feathers { get; } = 1;
}
Until C# 6 becomes more widely adopted, you are left choosing between inheritance and repeating yourself.
It's absolutely accepted to make protected fields in abstract classes.
Naming conventions are guidelines only and it depends on the styling tool you are using. Use the style that you and/or your team preffer and customize your tool from that. The most important thing is that the project is consistent in its own.
I've personally never seen the trailing underscore in use before, but I can see the benefit in it. Might be a pretty smart way to show protected fields. I would definately approve of that convention if I ran into a team that used it.

OOP principles in C#

I have a library (no source), to an certain object of which, I need to add some properties.
What would be the a way to do it ? I'm aware I could extend the class and add properties to the child. As well I know there are NO Extension Properties in C# yet. What would you suggest ? Thank you !
The metadata of class could be something like :
public class ResultClass
{
public IList<Item> Results { get; set; }
public int TotalResults { get; set; }
}
and I want to add a :
String description;
to it. Thanks.
There are a couple strategies you could take. Inheritance is the most obvious one. You might also consider composition. Can you give us some more details about what the object is and what properties you need to add to it and why?
After seeing the expanded question:
Either strategy outlined above (composition or inheritance) will probably work for you. Personally, I prefer composition. I think it better insulates you from changes that might be made to the third party library. It also forces you to work through the public interface of the library class, which is preferable when you have no knowledge or control of the internals of a class.
Here is the most basic example of composition.
public CompositeClass
{
private ResultClass _resultClass = new ResultClass();
public IList<Item> Results
{
get { return _resultClass.Results; }
set { _resultClass.Results = value; }
}
public int TotalResults
{
get { return _resultClass.TotalResults; }
set { _resultClass.TotalResults = value; }
}
//
// New Property
//
public string Description { get; set; }
}
Why do you need to add properties? If this is for binding purposes then I would suggest creating a wrapper class or creating your own inherited type that can raise PropertyChanged events in response to various state changes in your third party types. Instead of telling us your proposed solution you should tell us the actual problem you are trying to solve. Also (as I can't vote to close/migrate), this is not really a valid discussion for this site.
I think you are mixing up Extension Methods with Extension Properties.
And the last ones do not exist in C#.
So you should extend the class or create an inheriting class.

Private 'set' in C# - having trouble wrapping my brain around it

I've seen a lot of example code written using something like (please forgive how horribly canned this is):
public class Test
{
public object Thingy { get; private set; }
}
Unfortunately, these kinds of examples never really explain why 'set' is set as private. So, I'm just wondering if there's a good, common example that will illustrate to me why something like this would be used.
I sort of see it - the property can be run to process some extra logic in addition to setting that field. I'm just confused on how it would be invoked, and why this approach would be used rather than a generic setter method.
This would be if you have a property that you don't want anyone to set but your class. This can be handy with database id's. The internal class can set it but you wouldn't want anyone else changing it. So you can give them read access but not write.
EDIT: One more point on this is that using what you showed there is helpful for automatic properties. Unfortunately with automatic properties you are unable to only specify get so to avoid exposing a setter publicly it is just made private.
EDIT: Just thought I would throw in an example. Automatic properties are great for clean, terse code. But like you showed there is a limitation in that you have to have get and set. So before it was like this for a property like you showed:
public class Test
{
private object thingy;
public object Thingy
{
get { return thingy; }
}
}
Now we can get rid of that unneeded private declaration but it requires both. So make private to get around that.
I know this was overkill on the explanation but different things kept popping in my head.
As a simple example; it is a cheap way of making an "immutable enough" object (for use in threading, state, etc). But also anywhere where the client simply shouldn't need to assign it, or can't be trusted to assign it (correctly).
Another example might be a list:
public List<Foo> Items {get;private set;}
since we might call obj.Items.Add() etc, but we would rarely assign obj.Items = .... However, this example is marred by needing explicit initialization in the constructor, and XmlSerializer hates it - to be honest for lists I mainly use:
private readonly List<Foo> items = new List<Foo>();
public List<Foo> Items {get { return items;}}
which solves both of these.
As another example, contrasting:
private readonly int foo;
public int Foo {get{return foo;}}
vs
private readonly int foo;
public int Foo {get{return foo;} private set {foo=value;}}
this pattern may be useful in serialization, for example with DataContractSerializer (with the addition of some attributes), since many serializers will still look for private accessors. This avoids us having to decorate our internal state (foo), but gives the veneer of privacy to the set.
Ultimately anything can be bypasses and assigned via reflection, so private set is only intended to avoid accidental damage to data.
The private makes it into a readonly property. A common example is if you have multiple classes passing around a single object, you don't want another class to be able to modify the instance.
Basically, it is a readonly property. If it was written in full (not as an auto property) you would simply leave out the setter.
Two examples that are largely the same:
class Foo1
{
public int Id { get; private set; }
public Foo1()
{
Id = lastId ++;
}
}
class Foo2
{
private int _id;
public int Id { get { return _id; } }
public Foo2()
{
_id = lastId ++;
}
}
I've seen this used with the design:
public class whatever
{
public string WhateverId { get; private set; }
public static whatever Create(string whateverId)
{
return new whatever() { WhateverId = whateverId };
}
}
So you create whatever class, but after it's created the id can't be changed because it might break things that are connected to it.
the private set just gives the simple initializer syntax, I kind of like it for some scenarios.
Also can be used if it's changeable, but you need to manage it when changes are made
public void SetWhateverId(string whateverId)
{
DisconnectAllCurrentWhateverIdReferences();
WhateverId = whateverId;
ReconnectAllPreviousWhateverIdReferences();
}
This syntax allows you to provide a public-facing property that appears read-only to consumers of your API but internally can be changing. By auto-implementing in this way, you avoid having to write boilerplate code such as a distinct setter or a backing field for the value, and you leave room in your design to add a bespoke set algorithm if it is deemed necessary at some point in the future without having to decide right away.
private set is very handy for simple immutable value types.
struct Point
{
public int X { get; private set; }
public int Y { get; private set; }
public Point(int x, int y)
{
this = default(Point);
X = x;
Y = y;
}
}
This is just laziness that comes about from auto-properties. Before auto properties were around, people would implement the getter and omit the setter for properties which are meant to be read-only.
public class Test
{
private /*readonly*/ Type _thingy;
public Type Thingy { get { return _thingy; } }
}
Hopefully, C# 5 will allow you to create auto-properties with a getter only - because that's what everyone wants. (They should make readonly setters in auto-props too, I need that badly)
To answer the question of a common scenario where this might be used...
In an MVP pattern, if your Model exposes some properties for your Presenter I would write
public string Bazinga { get; private set; }
Now, the Model can change this value but other classes that use it cannot.

C# Language Design: explicit interface implementation of an event

Small question about C# language design :))
If I had an interface like this:
interface IFoo {
int Value { get; set; }
}
It's possible to explicitly implement such interface using C# 3.0 auto-implemented properties:
sealed class Foo : IFoo {
int IFoo.Value { get; set; }
}
But if I had an event in the interface:
interface IFoo {
event EventHandler Event;
}
And trying to explicitly implement it using field-like event:
sealed class Foo : IFoo {
event EventHandler IFoo.Event;
}
I will get the following compiler error:
error CS0071: An explicit interface implementation of an event must use event accessor syntax
I think that field-like events is the some kind of dualism for auto-implemented properties.
So my question is: what is the design reason for such restriction done?
Interesting question. I did some poking around the language notes archive and I discovered that this decision was made on the 13th of October, 1999, but the notes do not give a justification for the decision.
Off the top of my head I don't see any theoretical or practical reason why we could not have field-like explicitly implemented events. Nor do I see any reason why we particularly need to. This may have to remain one of the mysteries of the unknown.
I guess it might have to do with the fact that you can't call an explicit interface implementation from other members of the class:
public interface I
{
void DoIt();
}
public class C : I
{
public C()
{
DoIt(); // error CS0103: The name 'DoIt' does not exist in the current context
}
void I.DoIt() { }
}
Note that you can call the method by upcasting to the interface first:((I)this).DoIt();. A bit ugly but it works.
If events could be explicitly implemented as ControlFlow (the OP) suggested, then how would you actually raise them? Consider:
public interface I
{
event EventHandler SomethingHappened;
}
public class C : I
{
public void OnSomethingHappened()
{
// Same problem as above
SomethingHappened(this, EventArgs.Empty);
}
event EventHandler I.SomethingHappened;
}
Here you cannot even raise the event by upcasting to the interface first, because events can only be raised from within the implementing class. It therefore seems to make perfect sense to require accessor syntax for explicitly implemented events.
When explicitly implementing an event that was declared in an interface, you must use manually provide the add and remove event accessors that are typically provided by the compiler. The accessor code can connect the interface event to another event in your class or to its own delegate type.
For example, this will trigger error CS0071:
public delegate void MyEvent(object sender);
interface ITest
{
event MyEvent Clicked;
}
class Test : Itest
{
event MyEvent ITest.Clicked; // CS0071
public static void Main() { }
}
The correct way would be:
public delegate void MyEvent(object sender);
interface ITest
{
event MyEvent Clicked;
}
class Test : Itest
{
private MyEvent clicked;
event MyEvent Itest.Clicked
{
add
{
clicked += value;
}
remove
{
clicked -= value;
}
}
public static void Main() { }
}
see Compiler Error CS0071
This would not actually be an original thought by myself.
However, I thought I might respond to this:
"Off the top of my head I don't see any theoretical or practical reason why we could not have field-like explicitly implemented events. Nor do I see any reason why we particularly need to. This may have to remain one of the mysteries of the unknown."
-Eric Lippert
In Chapter 23 of A Programmer's Introduction to C#, Second Edition, Eric Gunnerson wrote:
"[I]f another class also wanted to be called when the button was clicked, the += operator could be used, like this:
button.Click += new Button.ClickHandler(OtherMethodToCall);
Unfortunately, if the other class wasn't careful, it might do the following:
button.Click = new Button.ClickHandler(OtherMethodToCall);
This would be bad, as it would mean that our ButtonHandler would be unhooked and only the new method would be called."
...
"What is needed is some way of protecting the delegate field so that it is only accessed using += and -=."
He goes on over the next few pages to comment on including the add() and remove() methods to implement this behavior; being able to write to those methods directly and the consequence of storage allocation for unneeded delegate references.
I would add more, but I respect the author too much to do so without his permission. I recommend finding a copy of this book and would recommend anything by Eric Gunnerson in general (blog, etc...)
Anyway, I hope this is relevant to the topic and if so, hope it shines light on this "mystery of the unknown"? (I was reading this very chapter and searching Stack Overflow for insight into event handler logic considerations when creating custom collections from custom objects) - I only mention this because I claim no specific authority on this particular subject. I am merely a student in search of "enlightenment" myself :-)

Interfacing common functionality between controls

I'm not really sure how to ask this question. Suppose I have a class that needs to access certain properties of a Control (for example, Visible and Location). Perhaps I want to use the same class to access properties of another item that have the same name, but the class might not derive from Control. So I tried making an interface:
public interface IThumbnail {
bool Visible { get; set; }
int Height { get; set; }
int Width { get; set; }
Image Image { get; set; }
Point Location { get; set; }
event EventHandler Click;
}
Note that, for example, PictureBox happens to implement this interface. However, because the class definition does not say that it implements IThumbnail, I can't cast PictureBoxes to IThumbnails--I get an InvalidCastException at runtime. But why can't the CLR 'figure out' that PictureBox really does implement IThumbnail (it just doesn't explicitly say it does).
Also, what should I do to handle this situation? I want a way to access some of the PictureBox's properties without having my class know it's modifying a PictureBox.
Thx, Sam
PS- I'm a newbie to interface programming, so I apologize if this is a stupid q.
It's not a stupid question, it's a good one. :)
What you're asking for on the interface is commonly referred to as "duck-typing." It isn't supported right now, but C#4.0 will support it via the new "dynamic" keyword.
You've really got three choices that I'm aware of at this point:
You can go up the tree until you find the common ancestor (probably Component) and then downcast to your supported types. If the downcast fails, you throw or handle appropriately.
Pro: Minimal code duplication.
Con: You're trading away compile-time type safety for runtime type safety. You have to add error checking/handling for invalid casts.
Code:
public void UseThumbnail(Component c)
{
PictureBox p = c as PictureBox;
if(p != null) // do whatever
// so forth
}
You can duplicate functionality as appropriate for everything that you need to implement this functionality for.
Pro: Maintain compile time type safety
Con: You're duplicating code for different types. This can grow into a significant maintenance burden, especially if you're handling more than two similar classes.
Code:
public void UsePictureBox(PictureBox p)
{
// Some code X
}
public void UseOtherControl(OtherControl p)
{
// Some code X
}
You can create your special interface and subclass the classes you want to support to expose that common functionality.
Pro: You get compile time safety and can program against your new interface.
Con: You have to add an empty subclass for everything you're dealing with, and you need to use them.
Code:
public class ThumbnailPictureBox : PictureBox, IThumbnail
{ }
I guess you would have to make you own class that derives from PictureBox. That new class would also implement IThumbnail.
public class MyPictureBox : PictureBox, IThumbnail {
}
The CLR can't figure out that PictureBox implements the same method signature as IThumbnail because it's just not supported yet. The feature you are talking about here is often reffered to as Duck Typing, and it's a feature of dynamic languages such as Ruby - it should be available in .NET and C# with the next release (C# 4) and the DLR (dynamic language runtime).
To get the functionality you require right now, you can write a class that implements the IThumbnail interface and encapsulates an instance of a PictureBox.
public class ThumbnailPictureBox
{
private PictureBox _pictureBox;
public ThumbnailPictureBox(PictureBox pictureBox)
{
_pictureBox = pictureBox;
}
public bool Visible
{
get { return _pictureBox.Visible; }
set { _pictureBox.Visible = value; }
}
// etc...
}
If the class you're interested in creating an interface for is not "sealed" then your could create a new class and inherit from the non-sealed class, implementing the interface.
If it were sealed (and I don't think PictureBox is) you'd probably want to build a wrapper class that implements the interface that you're interested in and contains a PictureBox control, exposing only the members that you're interested in.
You could create your own class that implements the interface and has a PictureBox behind the scenes
class MyPictureBox: IThumbnail
{
private PictureBox _pictureBox = new PictureBox();
bool Visible
{
get
{
return _pictureBox.Visible;
}
set
{
_pictureBox.Visible = value;
}
}
//implement the rest, you get the idea
}
This pattern would also be useful in the event that you want to extend a 3rd party's "PictureBox" that is sealed, in which case you would not be abel to extend from it.
Actually Derik Whittaker just did a nice podcast on this pattern at dimecasts.net here
There are hundreds of interfaces in the .net runtime. If interfaces were left to be implicitly implemented, and the compiler were to go through and match up interfaces automatically to classes, every class you program could be matched to interfaces that you didn't even want it to.
As the other posters have suggested, your situation is exactly what OO is meant to solve ;)
Try extending PictureBox to implement your interface.
The situation you are describing is exactly what Interfaces are for
public interface IThumbnail
{
bool Visible {get; set;}
string FilePath {get; set;}
}
public class Bar : IFoo
{
bool Visible {get; set;}
int SomeNumber {get; set;}
/*
rest of Bar functionality
*/
}
public class SomeClass
{
public void DisplayThumbnail(IThumbnail thumb)
{
//Do Stuff to things.
}
}
Once it is implemented that way, for any aspect of your program that shouldn't have access to any Bar functionality, but SHOULD have access to any IThumbnail functionality, just pass them an object of type IThumbnail
Bar bar = new Bar();
SomeClass someClass = new SomeClass();
someClass.DisplaySomething((IThumbnail) bar);
Now the DisplaySomething function cannot access any Bar exclusive functionality. It can only access the IThumbnail specific parts of it.
EDIT
This question deals with the same issue
Will C#4.0 allow dynamic casting, If not, should it?

Categories