I have a class Thing that is deserialized from a JSON file using DataContractJsonSerializer:
[DataContract]
class Thing
{
[DataMember]
public int Id { get; set; }
[DataMember]
public string Name { get; set; }
// and so on...
}
To make this work, all properties need to have public or at least internal setters.
Two other modules (assemblies) need to access this class:
ThingView should have read-only access to most attributes.
ThingEditor needs full access to all attributes.
I could make the setters internal but then the ThingEditor would not get full access.
To restrict access for the ThingView class, the best idea I could come up with is to create a read-only wrapper of the Thing class. But this would involve a lot of code duplication.
Are there better ways to achieve more encapsulation for in a case like this?
(The actual code contains about 20 classes of this type, some of which form nested structures. Also, there are more than two modules that need either read or full access to the properties.)
There is nothing out of the box in the specs that would achieve this. However, you could do something like this for example
public interface IReadOnlInterface
{
int Id { get; }
string Name { get; }
}
public interface IInterface
{
int Id { get; set; }
string Name { get; set; }
}
internal class Thing : IInterface , IReadOnlInterface
{
public int Id { get; set; }
public string Name { get; set; }
}
However there is nothing stopping coders with dirty little fingers casting to the other interface. If its only a runtime issue, then interfaces should be fine. Otherwise youll have to create a better api design with secured data, and proxy type objects with readonly access, Though maybe someone has a better idea.
Related
Let's say I have an interface:
interface IPerson
{
int Age { get; set; }
string Name { get; set; }
bool Alive { get; set; }
}
and a Class:
public class Person : IPerson
{
public int Age { get; set; }
public string Name { get; set; }
}
That would not compile since Person does not implement the Alive Property.
What I would like to know is if there is a way to have the same behaviour, if Person adds an extra property that is not found in its interface.
interface IPerson
{
int Age { get; set; }
string Name { get; set; }
}
and a Class:
public class Person : IPerson
{
public int Age { get; set; }
public string Name { get; set; }
public bool Alive { get; set; } <---- This should prevent it from compiling as well.
}
I would want it to not compile as well, or at the very least give me a compile warning.
No. Interfaces define what members an object must implement. They cannot define members that an object can't implement. You could potentially use your own custom, or third party code analysis tools, to identify cases like this, but there is nothing in the language itself that would support it.
No it is not possible. Are you not trying to define a class itself here? Why do you really need an interface?
However, what you can achieve is make calls to your interface and not your class by doing
IPerson person = new Person();
this way you limit the person object to access only the methods defined in your interface.
There is a way to do this, but not within the object and its a bit silly to use in construction of the object. Using Reflection, you can check the type of an instance of your object and iterate through its properties, throwing an exception if the count or names of properties do not match your desired instance. Please note that if you just check against the interface, implementing objects will pass, so you would check against the desired concrete type. I am on my phone or I'd add some sample code, will try to return to this later.
There is a way to do this, but not within the object and its a bit silly to use in construction of the object. Using Reflection, you can check the type of an instance of your object and iterate through its properties, throwing an exception if the count or names of properties do not match your desired instance. Please note that if you just check against the interface, implementing objects will pass, so you would check against the desired concrete type. I'm on my phone so no sample code. Will try to return to this later.
I have a parent class that I want to have many flat children. That means 10 or more different classes would inherent from one class.
Here is what I have.
Base Class:
[ProtoContract]
[ProtoInclude(500, typeof(Message1Send))]
[ProtoInclude(501, typeof(Message2Send))]
public class MessageBase
{
[ProtoMember(1)]
public string Topic {get;set;}
[ProtoMember(2)]
public string Action { get; set; }
}
2 of many Child Classes:
[ProtoContract]
public class Message1Send : MessageBase
{
[ProtoMember(1)]
public string Property1 { get; set; }
}
[ProtoContract]
public class Message2Send : MessageBase
{
[ProtoMember(1)]
public string Property1 { get; set; }
}
I want to be able to tell the child object I am part of a base class.
I don’t what to get to the point where my base class is as follows:
[ProtoContract]
[ProtoInclude(500, typeof(Message1Send))]
[ProtoInclude(501, typeof(Message2Send))]
[ProtoInclude(502, typeof(Message3Send))]
[ProtoInclude(503, typeof(Message4Send))]
[ProtoInclude(504, typeof(Message5Send))]
[ProtoInclude(505, typeof(Message6Send))]
[ProtoInclude(506, typeof(Message7Send))]
[ProtoInclude(507, typeof(Message8Send))]
[ProtoInclude(508, typeof(Message9Send))]
[ProtoInclude(509, typeof(Message10Send))]
public class MessageBase
{
[ProtoMember(1)]
public string Topic {get;set;}
[ProtoMember(2)]
public string Action { get; set; }
}
Is there a way I can have each one of the Send classes to just add one reference to the base class so I don’t have to keep adding ProtoInclude for every flat child I create?
The problem is one of reliability. Reflection makes veryfew repeatable / reliable guarantees, and it is very important that if you serialize data today, then edit your app to add two new types, each type still has the same number as it did oroginally. Even if you've added some new types, renamed some, and possibly removed two that you weren't really using.
The attribute guarantees this by making the field-number repeatable. The reason it is on the parent (not the child) is that it is much more reliable to walk up the type-chain than down it.
However: if you have a reliable repeatable way of generating field numbers for sub-types, you can use RuntimeTypeModel to configure the serializer to your liking.
I'm sure this has been asked before, but I'm having trouble finding any relevant answers - probably because the generic nature of the terms I'm using.
I have a class - let's call it Foo. Now a given Foo has a variety of properties that define it's nature. For the sake of argument, let's call them Name, Inactive and Notes. There can also be many varieties of Foo, which are each a FooType, for lack of a better word.
So, we have the following class definitions:
public class FooType
{
public byte Id { get; set; }
public string Name { get; set; }
public bool Inactive { get; set; }
public string Notes { get; set; }
}
public class Foo
{
public Guid Id { get; set; }
public FooType TypeOfFoo { get; set; }
public string Name { get; set; }
public bool Inactive { get; set; }
public string Notes { get; set; }
}
Not exactly an ideal situation, I know. Sadly, the Inactive and Notes fields on FooType are a must, so I can't use an enum as I would like. My quandary, then, is that I'm having trouble figuring out a reasonably descriptive name for TypeofFoo and FooType. Calling them TypeofFoo and FooType is ugly and prone to confusion in the future, so I'm looking for alternatives.
Is there any sort of naming convention that covers this?
No, there's no naming convention. In fact, the .NET Framework itself does not avoid using properties that have the same name as their type and even suggest it in some older guidelines:
SolidBrush.Color
Control.Font
It's not a fool-proof solution, and may cause confusion in certain edge cases like calling static members, but it's not so bad that there's reason to avoid it categorically.
I would try to use polymophy to subclass Foo and use a factory with an enumeration FooType to create the objects. Your subclasses should override the general methods to add specific behavior.
But I think the context is important to choose the right pattern. Just using a special naming is confusing in my opinion and doesn't represent your intend of the classes.
I have a situation where I have some DTO classes that should be implemented like:
public class City
{
public string Name { get; set; }
public State State { get; set; }
}
public class State
{
public string Name { get; set; }
}
The problem is, these are actually DTO classes for REST XML resources. And the City resource may include the State resource inline, or it may simply provide the resource ID (a URI). I am handling access to the DTO via the Repository pattern and would like it to be transparent to clients whether State is lazy loaded or not (like how NHibernate does with it's entity classes).
So my current plan is to use Castle DynamicProxy to create a proxy object when the REST Repository detects that the class isn't fully "hydrated" (i.e. not everything is inline). The proxy object will know how to lazy load attributes as needed.
To actually implement this, however, the only thing I've come up with is to have backing attributes for all relationships and put the Xml attributes on those. So the strategy looks like this:
[XmlType]
public class City
{
[XmlElement]
public string Name { get; set; }
[ToOneRestRelationship(BackingPropertyName = "StateBacking")]
public State State { get; set; }
[XmlElement(Name = "state")]
public ResourceBase StateBacking { get; set; }
}
[XmlType]
public class State
{
[XmlElement]
public string Name { get; set; }
}
Then the Repository object knows to set up the proxy object to either get the object from the StateBacking property and use that (inlined resource case) or do a REST request to lazily retrieve the State object (resource URI case, i.e. lazy) from the ID specified in the backing property.
Question
The issue is, this backing field is pretty ugly. What I would like is a way to have Castle generate a class that would have the backing property with the XmlElement attribute applied that I could pass to the XmlSerializer. Then my DTO classes could look more like the first example and wouldn't have to be aware that the actual serialising class has a backing property.
Is something like this possible with Castle or any other Proxy library?
After going an interesting and completely wrong way, i think it is indeed possible to create a backing field that won't be seen by clients. Since proxying works by inheriting from the proxied class, any property on the derived class won't be seen in the scope of the original class. So mixins are the way to go:
Given Foo
public class Foo
{
public virtual string Name { get; set; }
public virtual Bar bar { get; set; }
}
and Bar
public class Bar
{
public virtual string Name { get; set; }
}
We can declare an interface that will let us retrieve the backing field and an implementation
public interface IHasBarBackingField
{
Bar RetrieveBar();
}
public class HasBarBackingField : IHasBarBackingField
{
public HasBarBackingField()
{
// the constructor must contain ways to resolve the bar. Since
// the class is built while proxying you should have all the data
// available at this moment
}
public Bar RetrieveBar()
{
return new Bar(); // example, you could have a backing field somewhere in this class
}
}
Then you just have to mixin both classes when proxying:
var pg = new ProxyGenerator();
var hasBarBackingField = new HasBarBackingField();
var options = new ProxyGenerationOptions();
options.AddMixinInstance(hasBarBackingField);
var test = pg.CreateClassProxy<Foo>(options, new BarInterceptor());
and intercept the call interesting you in order to return the backing Bar
public class BarInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
if (invocation.Method.Name == "get_bar")
{
var hasBarBackingField = invocation.InvocationTarget as IHasBarBackingField;
invocation.ReturnValue = hasBarBackingField.RetrieveBar();
}
else
{
invocation.Proceed();
}
}
}
The HasBarBackingField class should be built to return either the direct object or retrieve the referenced REST object. Hope this helps
Based on what i've seen NSubstitute do i'd say it is possible, as long as your properties are virtual: http://nsubstitute.github.io/help/partial-subs/ .
Creating a City class with virtual property State that is then resolved at runtime using the substitution pattern should be feasable
public class City
{
public string Name { get; set; }
[StateId(10)]
public virtual State State { get; set; }
}
var sCity = Substitute.For<City>();
sCity.State.Returns((core) => {return null; // here you can access informations about the call});
Definitely doable, but it's terra incognita from here on!
This is probably my naivety showing through, but anyway...
I have a generic interface which defines a set of standard methods (implemented differently) across implementations.
I pass the interface into a method as a parameter, this method being responsible for persisting to a database. E.g. I have some implementations called bug, incident, etc, defined from the generic interface (called IEntry). These concerete implementations also make use of IEnumerable
Because a bug is different to an incident, there are different fields. When I pass the interface into a method as a parameter, is there any way to inference the type? So if I pass in the Bug object, I can use its fields, which are not the same fields as in those of Incident. These fields are useful for the persistance to the database. I'm assuming no because there is no way to know what the type to be passed in will be (obviously), but I know people here have more wisdom. In that case, is there a better way of doing things? Because of the similarity, I would like to stick to interfaces.
EDIT: I guess the other way is to make use of some flow control to generate the sql statement on the fly and then pass it in as a parameter.
Thanks
The thing about passing objects and interfaces around is that you really shouldn't be concerned with the actual type, as long as it inherits from/implements the particular base class/interface you're interested in.
So building logic into that method to figure out that it's a bug, and then accessing things that are only present for bugs, that's basically not the OOP way, although it might be the "best" way in your particular case.
I would, however, advise against it, and instead try to build a proper OOP way with polymorphism to handle the differences, instead of building it into the method as special cases.
You mention persistence, is this method responsible for storing the data somewhere? Perhaps you could separate the part that gathers the information to store from the part that stores the information, that way you could ask the object itself to provide you with all the pertinent information, which could vary from one class to another.
Bad Design (as I think was described in the question):
public interface IEntry
{
string Description { get; set; }
}
public class Bug : IEntry
{
public int ID { get; set; }
public string Description { get; set; }
public string UserName { get; set; }
}
public class Incident : IEntry
{
public Guid ID { get; set; }
public string Description { get; set; }
}
public class Persister
{
public void Save(IEnumerable<IEntry> values)
{
foreach (IEntry value in values) { Save(value); }
}
public void Save(IEntry value)
{
if (value is Bug) { /* Bug save logic */ }
else if (value is Incident) { /* Incident save logic */ }
}
}
Improved design (smart entity approach):
public interface IEntry
{
string Description { get; set; }
void Save(IPersister gateway);
}
public class Bug : IEntry
{
public int ID { get; set; }
public string Description { get; set; }
public string UserName { get; set; }
public void Save(IPersister gateway)
{
gateway.SaveBug(this);
}
}
public class Incident : IEntry
{
public Guid ID { get; set; }
public string Description { get; set; }
public void Save(IPersister gateway)
{
gateway.SaveIncident(this);
}
}
public interface IPersister
{
void SaveBug(Bug value);
void SaveIncident(Incident value);
}
public class Persister : IPersister
{
public void Save(IEnumerable<IEntry> values)
{
foreach (IEntry value in values) { Save(value); }
}
public void Save(IEntry value)
{
value.Save(this);
}
public void SaveBug(Bug value)
{
// Bug save logic
}
public void SaveIncident(Incident value)
{
// Incident save logic
}
}
The improved design is only caters for the need to shift the need for change of Persister.Save(IEntry). I just wanted to demonstrate a first step to make the code less brittle. In reality and production code you would want to have a BugPersister and IncidentPersister class in order to conform to the Single Responsibility principle.
Hope this more code-centric example is a help.
The persistance thing is just a method in a class to upload details to a database.
I guess I could write an abstract class with a function for the persistance requirement and that could be based on parameters for it to work. I can use this in each of my interface implementations. Because the way the update to db will happen (pretty much the same but a few words in a sql query change), I can generate this based on method parameters.