How to make a non-editable object editable - c#

This is how my class object looks like:
Class MyInfo :IDisposable
{
List<MYObject> list;
public long X { get; private set; }
public IList<RasterFieldInfo> FieldInfo
{
get
{
return _ fields.AsReadOnly();
}
}
}
I do have an object MyInfo which is read-only (no public setter), I am looking an efficient way to make it writeable.
I cannot make this object as writeable (i.e. I cannot make setters as public) because that will give an impression to user that he is making changes to original object (while that is not true) and due to other reasons. What I am looking for is:
Minimal code duplication, this class has lots of code inside it.
Ease of use for the person going to use this object.
Best possible design and implementation.
I cannot make any setters as public to make it writeable.
Editable object usage will be as follows:
MyInfo obj = ds.GetInfo();
MyInfo editableObj = Obj.CreateEditableObject();
….
//Modify members of editableObj
…
Ds.SetInfo(editableObj);
Issue is how to provide an editable object of the same type by calling CreateEditableObject method.

You can use this pattern (sadly I don't remember how its called)
class MyInfo
{
public int MyProperty{ get; private set; }
public MyInfo WithMyProperty(int value)
{
return new MyInfo(){ MyProperty = value };
}
}
MyInfo obj = ds.GetInfo();
MyInfo modified = obj.WithMyProperty(1234);
The original object is of course not modified.

Related

Can I create and object that "self-loads" properties from a data source?

I have a design pattern question that I'm hoping you can help me with.
I have a C# application that stores objects in a database as JSON. Currently, a dedicated class handles loading the JSON, deserializing, and returning the object. This works great, but I'm wondering if there is an approach that would allow the object to "self-load" (for lack of a better term).
What I am doing now is (short-hand code):
public class MyObject {
public string Name;
public string Rank;
public int SerialNo;
}
public class DataTransport{
public MyObject LoadMyObject(string ObjectId){
string ObjectJSON = fetch.from.database;
return ObjectJSON.deserialize.object;
}
}
DataTransport dt = new DataTransport();
MyObject mo = dt.LoadMyObject("object123");
What I would like to do is something like:
public class MyObject {
public string Name;
public string Rank;
public int SerialNo;
public MyObject(string ObjectId){
DataTransport dt = new DataTransport();
this = dt.LoadMyObject(ObjectId);
}
}
MyObject mo = new MyObject("object123);
Obviously this fails, but is there a similar mechanism to have the constructor replace itself with the object loaded from the database?
I've thought about loading and manually assigning properties when instantiated, but that risk and hassle doesn't pass the cost/benefit smell test.
Thanks in advance for your help!
You could essentially do what you want if you made your LoadMyObject() method populate an existing object instance from the JSON instead of creating a new one. Maybe PopulateMyObject() would be a better name for it:
public void PopulateMyObject(string ObjectId, object target)
{
string ObjectJSON = FetchJsonFromDatabase(ObjectId);
PopulateObjectFromJson(ObjectJSON, target);
}
Incidentally, Json.Net supports populating existing objects from JSON out of the box, so you could use its JsonConvert.PopulateObject method as a drop-in replacement for PopulateObjectFromJson in the above code.
Then in your object constructors you just do:
public MyObject(string ObjectId)
{
DataTransport dt = new DataTransport();
dt.PopulateMyObject(ObjectId, this);
}
Concept fiddle: https://dotnetfiddle.net/I9bHeN
Of course, #MickyD makes a very good point in the comments that you would be tightly coupling all your model objects to the DataTransport object, which may not be desirable.

How to create a "pointer-like" class, easily exposing functions of member?

What I am trying to do is find the most elegant way to create a "pointer-like" class for a specific object/class type that I have in a project.
What I mean is a little confusing without an example. Take this really simple class:
public class MyClass
{
private string _name;
public string GetName() { return _name; }
public void SetName(string name) { _name = name; }
}
I want to create a second class which is like a pointer to it like this:
public class MyClassPtr
{
private MyClass _obj;
public bool IsValid = false;
public MyClassPtr(MyClass obj) { _obj = obj; IsValid = true; }
public void InvalidatePtr()
{
IsValid = false;
obj = null;
}
// SOME MAGIC HERE?
}
The challenge: The key is that I want to elegantly have MyClassPtr provide an interface to all of the public methods/members in MyClass without writing wrappers and/or accessors around each method/member.
I know that I could do this:
public class MyClassPtr
{
public string GetName() { return _obj.GetName(); }
...
}
But that's what I want to avoid. Is there some fundamental abstraction that I don't know of that I can apply to MyClassPtr to allow it to easily re-expose the methods/members in MyClass directed through _obj? I do NOT want MyClassPtr to inherit MyClass. Should MyClassPtr be a type instead, and some trick with accessors to expose the methods/members of MyClass?
Edit: More context on why I am looking for such a design through an example. Here is the overall goal. Imagine a platform that parses through data about people and when it finds information about a person, it creates an instance of Person with that information. You could get a handle to that person like:
Person person1 = platform.GetPerson(based_on_data);
Now, imagine the platform had two instances of Person that it thought were different people, but all of a sudden information came in that strongly suggested those two instances actually refer to the same person. So, the platform wants to merge the instances together in to a new object, let's call it personX.
Now, floating around in the platform someone had a copy of one of those two instances that got merged, which was person1. What I want to do is on-the-fly replace person1 with personX. Literally, I want person1==personX to be true, NOT just that they are two different objects with the same data. This is important since the platform could make a change to personX and unless the two objects are literally equal, a change to personX would not be automatically reflected in person1.
Since I can't on-the-fly replace person1 with personX I had that idea that I wouldn't give direct access to Person, instead I would give access to PersonPtr which the platform (on-the-fly) can change what Person it is pointing to. This would insurance that once person1ptr gets updated to point to personX, if a change is made in personX it will be seen in person1ptr
You could of course use something like
public class MyClassWrapper
{
MyClass _obj;
public MyClassWrapper(MyClass obj)
{
_obj = obj;
}
public void Invoke(Action<MyClass> action)
{
action(_obj);
}
public U Invoke<U>(Func<MyClass, U> func)
{
return func(_obj);
}
public void ChangeTo(MyClass obj)
{
_obj = obj;
}
}
Given your class looks like
public class MyClass
{
public string Name { get; set; }
}
Example:
var person1 = new MyClass { Name = "Instance1" };
var person2 = new MyClass { Name = "Instance2" };
var wrapper = new MyClassWrapper(person1);
wrapper.Invoke(x => x.Name += "original");
var x = wrapper.Invoke(x => x.Name); // Instance1original
wrapper.ChangeTo(person2);
var y = wrapper.Invoke(x => x.Name); // Instance2
but it has a major drawback: you can't access members directly, so you can't bind the data (to a DataTable or a Control).
It would be better to implement all members of your class also in your wrapper class. If you're afraid changes in your class will be forgotten to be implemented in your wrapper, just use an interface:
public interface IMyClass
{
string Name { get; set; }
}
public class MyClass : IMyClass
{
public string Name { get; set; }
}
public class MyClassWrapper: IMyClass
{
MyClass _obj;
public MyClassWrapper(MyClass obj)
{
_obj = obj;
}
public string Name
{
get { return _obj.Name; }
set { _obj.Name = value; }
}
}
Note that regardless which approach you use, you'll have to always keep a reference to the wrapper instance to actually change the underlying instance (using something like static aside).
Also, changing the underlying instance of such a wrapper without telling the component using it that it changed don't seem to be a good idea. Maybe your system is simple enough to get away with a wrapper; that's something you have to decide for yourself.
Maybe your wrapper should simply have an Invalid flag (and/or use an event to signal a change of the underlying object.). Once the underlying object is merged, it is set to true and each member access should throw an exception. This would force the component using the wrapper to deliberately react to changes and to reload the data from your service.
All in all, I think using such a wrapper will just clutter up your code and be error prone (just imagine adding multithreading to the mix). Think twice if you really need this wrapper.
Why not just simply ask your service for a new instance of your class everytime you use it (the service can simply use a cache)? Sure, you can't prevent that someone somewhere keeps a reference; but at least you'll keep your sanity.

Best way to create instance of child object from parent object

I'm creating a child object from a parent object. So the scenario is that I have an object and a child object which adds a distance property for scenarios where I want to search. I've chosen to use inheritance as my UI works equivalently with either a search object or a list of objects not the result of a location search. So in this case inheritance seems a sensible choice.
As present I need to generate a new object MyObjectSearch from an instance of MyObject. At present I'm doing this in the constructor manually by setting properties one by one. I could use reflection but this would be slow. Is there a better way of achieving this kind of object enhancement?
Hopefully my code below illustrates the scenario.
public class MyObject {
// Some properties and a location.
}
public class MyObjectSearch : MyObject {
public double Distance { get; set; }
public MyObjectSearch(MyObject obj) {
base.Prop1 = obj.Prop1;
base.Prop2 = obj.Prop2;
}
}
And my search function:
public List<MyObjectSearch> DoSearch(Location loc) {
var myObjectSearchList = new List<MyObjectSearch>();
foreach (var object in myObjectList) {
var distance = getDistance();
var myObjectSearch = new MyObjectSearch(object);
myObjectSearch.Distance = distance;
myObjectSearchList.add(myObjectSearch);
}
return myObjectSearchList;
}
The base class needs to define a copy constructor:
public class MyObject
{
protected MyObject(MyObject other)
{
this.Prop1=other.Prop1;
this.Prop2=other.Prop2;
}
public object Prop1 { get; set; }
public object Prop2 { get; set; }
}
public class MyObjectSearch : MyObject
{
public double Distance { get; set; }
public MyObjectSearch(MyObject obj)
: base(obj)
{
this.Distance=0;
}
public MyObjectSearch(MyObjectSearch other)
: base(other)
{
this.Distance=other.Distance;
}
}
This way the setting of properties is handled for all derived classes by the base class.
You can use reflection to copy properties.
public class ChildClass : ParentClass
{
public ChildClass(ParentClass ch)
{
foreach (var prop in ch.GetType().GetProperties())
{
this.GetType().GetProperty(prop.Name).SetValue(this, prop.GetValue(ch, null), null);
}
}
}
There is no easy way to do this, unfortunately. As you said, you would either have to use reflection, or create a "Clone" method that would generate a new child object using a parent object as input, like so:
public class MyObjectSearch : MyObject {
// Other code
public static MyObjectSearch CloneFromMyObject(MyObject obj)
{
var newObj = new MyObjectSearch();
// Copy properties here
obj.Prop1 = newObj.Prop1;
return newObj;
}
}
No matter what, you're either going to end up writing reflection code (which is slow), or writing each property out by hand. It all depends on whether or not you want maintainability (reflection) or speed (manual property copy).
A generic solution would be to serialize it to json and back. In the json-string is no information about the class name from which it was serialized.
Most people do this in javascript.
As you see it works well for pocco objects but i don't guarantee that it works in every complex case. But it does event for not-inherited classes when the properties are matched.
using Newtonsoft.Json;
namespace CastParentToChild
{
public class Program
{
public static void Main(string[] args)
{
var p = new parent();
p.a=111;
var s = JsonConvert.SerializeObject(p);
var c1 = JsonConvert.DeserializeObject<child1>(s);
var c2 = JsonConvert.DeserializeObject<child2>(s);
var foreigner = JsonConvert.DeserializeObject<NoFamily>(s);
bool allWorks = p.a == c1.a && p.a == c2.a && p.a == foreigner.a;
//Your code goes here
Console.WriteLine("Is convertable: "+allWorks + c2.b);
}
}
public class parent{
public int a;
}
public class child1 : parent{
public int b=12345;
}
public class child2 : child1{
}
public class NoFamily{
public int a;
public int b = 99999;
}
// Is not Deserializeable because
// Error 'NoFamily2' does not contain a definition for 'a' and no extension method 'a' accepting a first argument of type 'NoFamily2' could be found (are you missing a using directive or an assembly reference?)
public class NoFamily2{
public int b;
}
}
If a shallow copy is enough, you can use the MemberwiseClone method.
Example:
MyObject shallowClone = (MyObject)original.MemberwiseClone();
If you need a deep copy, you can serialize/deserialize like this: https://stackoverflow.com/a/78612/1105687
An example (assuming you write an extension method as suggested in that answer, and you call it DeepClone)
MyObject deepClone = original.DeepClone();
I first came accros this question when I was looking for doing this.
If you are able to work with C# 9 and record-classes. You only have to create a new constructor in the sub-class taking in a base class object and hand it over to the subclass:
public record MyObject {
...
}
public record MyObjectSearch :MyObject
{
public MyObjectSearch(MyObject parent) : base(parent) { }
...
}
Then you can create the child object like this:
MyObject parent = new();
MyObjectSearch m = new MyObjectSearch(parentObj) { Distance = 1.1};
Credits to https://stackoverflow.com/a/64573044/2582968
Seems natural for the base object to have constructor with parameters for its properties:
public class MyObject
{
public MyObject(prop1, prop2, ...)
{
this.Prop1 = prop1;
this.Prop2 = prop2;
}
}
So then, in your descendant object you can have:
public MyObjectSearch(MyObject obj)
:base(obj.Prop1, obj.Prop2)
This reduces duplication related to assignments. You could use reflection to automatically copy all properties, but this way seems more readable.
Note also, that if your classes have so much properties that you're thinking about automatizing of copying of the properties, then they are likely to violate the Single Responsibility Principle, and you should rather consider changing your design.
There are libraries to handle this; but if you just want a quick implementation in a few places, I would definitely go for a "copy constructor" as previously suggested.
One interesting point not mentioned is that if an object is a subclass, then it can access the child's private variables from the within the parent!
So, on the parent add a CloneIntoChild method. In my example:
Order is the parent class
OrderSnapshot is the child class
_bestPrice is a non-readonly private member on Order. But Order can set it for OrderSnapshot.
Example:
public OrderSnapshot CloneIntoChild()
{
OrderSnapshot sn = new OrderSnapshot()
{
_bestPrice = this._bestPrice,
_closed = this._closed,
_opened = this._opened,
_state = this._state
};
return sn;
}
NOTE: Readonly member variables MUST be set in the constructor, so you will have to use the child constructor to set these...
Although I don't like "up-sizing" generally, I use this approach a lot for analytic snapshots...

Design Pattern for Object Modification with Timestamp

I have a colleciton of objects which need to maintain several time-stamps for that last time certain properties within the object was updated (one time-stamp per property).
I would just implement the time-stamp update in the setter except that the deserialization library being used first creates an object, then updates all of its properties (using the object's setter). This means that all my time-stamps would be invalidated every time my program deserializes them.
I'm thinking I need a singleton class or some update method which handles updating the properties and also controls the time-stamp update. Is there a better way to implement this behavior? Does a design pattern exist for this behavior?
If you separate your serialization concerns from your business layer, it should help find you some flexibility to hammer out a solution. Have 99% of your API work with your business object (which updates timestamps when properties update), then only convert to/from some data-transfer-object (DTO) for serialization purposes only.
For example, given some business object like this:
public class MyObject
{
public DateTime SomeValueUpdated { get; private set; }
private double _SomeValue;
public double SomeValue
{
get
{
return _SomeValue;
}
set
{
SomeValueUpdated = DateTime.Now;
_SomeValue = value;
}
}
public MyObject()
{
}
//for deserialization purposes only
public MyObject(double someValue, DateTime someValueUpdated)
{
this.SomeValue = someValue;
this.SomeValueUpdated = someValueUpdated;
}
}
You could have a matching DTO like this:
public class MyObjectDTO
{
public DateTime SomeValueUpdated { get; set; }
public double SomeValue { get; set; }
}
Your DTO can be specially adorned with various XML schema altering attributes, or you can manage the timestamps however you see fit and your business layer doesn't know and doesn't care.
When it comes time to serialize or deserialize the objects, run them through a converter utility:
public static class MyObjectDTOConverter
{
public static MyObjectDTO ToSerializable(MyObject myObj)
{
return new MyObjectDTO {
SomeValue = myObj.SomeValue,
SomeValueUpdated = myObj.SomeValueUpdated
};
}
public static MyObject FromSerializable(MyObjectDTO myObjSerialized)
{
return new MyObject(
myObjSerialized.SomeValue,
myObjSerialized.SomeValueUpdated
);
}
}
If you wish, you can make any of the properties or constructors of MyObject to be internal so only your conversion utility can access them. (For example, maybe you don't want to have the public MyObject(double someValue, DateTime someValueUpdated) constructor publicly accessible)

Design problem causing inability to get returned proper dataType

I have an object that has properties of another object and one called DataValue, but the type that I want DataValue to return depends on information contained in the object in the other property. I'm not convinced my way is the best way to do this.
I have this business object called an AssetStructure.
An AssetStructure object contains a generic list of IAssetStructureField objects, which are a series of objects that basically hold information about the data that can be held in that field, a default value of a certain datatype and some displaying information properties. Each of the objects implementing the IAssetStructureField interface will hold different datatype. For example, one's DefaultValue's type maybe string and the other maybe a List<ofCustomType>.
I have my Asset object containing a generic list of objects called AssetDataField. The AssetDataField has properties of one containing the AssetStructureField and one called DataValue, the Asset's data for that StructureField.
My problem is datatype of AssetDataField DataValue property, it will need to be different depending on the details of the AssetStructureField object. This StructureField may hold data representing all the user groups with access to the Asset (datatype List<UserGroups>), and another might just be a description field (datatype string), so I need the DataValue coming out of the AssetDataField to be of the same type.
What I'm thinking of doing now, and that I feel can probably be done much better, is having the AssetDataField.DataValue return an object, and then cast it to the typeof the AssetDataField.StructureField.DefaultValue.
object fieldValue;
object fieldDefaultValue;
Asset certainAsset = new Asset(32423);
foreach (AssetDataField dataField in certainAsset.DataFields)
{
fieldDefaultValue = datafield.StructureField.DefaultValue;
fieldValue = datafield.DataValue as typeof(fieldDefaultValue);
// then do stuff depending on what typeof(fieldValue) is. This is where I
// see things getting particularly ugly. Not only just because that
// this class here will need to know the possible types that may be
// returned, so it can deal.
if (typeof(fieldValue) == whatever)
{
// deal;
}
else if (typeof(fieldValue) == whatever2)
{
// deal differently;
}
}
Does anyone have any suggestions? I am not a opposed, at all, to a complete redo. I'm really sorry this is so long-winded, I just wanted to try and explain the situation well. I tried to put together a UML diagram to help out, but my ArgoUML was acting up. Thanks for any insights at all that you can provide.
It seems like you should make AssetDataField a possibly abstract base class, and derive other classes from it to perform the work. For example:
class Program
{
static void Main(string[] args)
{
Asset certainAsset = new Asset(32423);
foreach (AssetDataField dataField in certainAsset.DataFields)
{
dataField.Deal();
}
}
}
class Asset
{
public List<AssetDataField> DataFields = new List<AssetDataField>();
public Asset(int id)
{
// Load asset #id
if (id == 32423)
{
DataFields.Add(new AssetDataFieldString());
DataFields.Add(new AssetDataFieldFloat());
}
}
}
abstract class AssetDataField
{
public AssetDataField()
{
FieldValue = DefaultValue;
}
public abstract object DefaultValue { get; }
public abstract object FieldValue { get; set; }
public abstract void Deal();
}
abstract class AssetDataFieldType<T> : AssetDataField
{
protected T internalValue;
public override object FieldValue
{
get
{
return TypedValue;
}
set
{
TypedValue = (T)System.Convert.ChangeType(value, typeof(T));
}
}
public virtual T TypedValue
{
get
{
return internalValue;
}
set
{
internalValue = value;
}
}
}
class AssetDataFieldString : AssetDataFieldType<string>
{
public override object DefaultValue
{
get { return "Default String"; }
}
// Optionally override TypedValue
public override void Deal()
{
Console.WriteLine(TypedValue.PadLeft(20));
}
}
class AssetDataFieldFloat : AssetDataFieldType<float>
{
public override object DefaultValue
{
get { return 0; }
}
// Optionally override TypedValue
public override void Deal()
{
Console.WriteLine(TypedValue.ToString("#0.000"));
}
}
Note: this smells like the result of querying an EAV based system. In the same way that meta data is the backbone of this sort of system the code referencing it should strive to know what it is accessing (and thus the types) at compile time. That said if you want to simply display the data this sort of thing is required no matter what.
C# is statically typed so you cannot put 'different things' into the same 'slot' (variable, array location) unless the slot is the right 'shape' to take all of them(1). The only slot currently available in c# for this is object. This will work but will box any value types(2).
In c# 4.0 you can use dynamic, which under the hood will be an object but at least will let you invoke any methods on it you want even if the compiler doesn't think it's legal via object.
If all the types in question share a common interface then you can avoid object and get some useful semantics (say if double Sum(double d) was a meaningful operation for any instance you were dealing with then this could yield useful results. However it sounds like you do not control the types present (and thus stand no chance of getting them to conform to useful interfaces).
If the set of possible types is tractable the technique described below can work but it is still cumbersome.
// boxes if needed
public interface IGeneralValue
{
object Value { get; }
Type GetValueType();
}
public class Value<T> : IGeneralValue
{
public T Value { get; set;}
object IGeneralValue.Value
{
get { return (object)this.Value; }
}
public Type GetValueType()
{
return typeof(T);
}
}
Then you can stay statically typed where possible but if not something similar to your previous code will work.
Asset certainAsset = new Asset(32423);
foreach (IGeneralValue dataField in certainAsset.DataFields)
{
object fieldValue = datafield.Value;
Type fieldType = dataField.GetValueType();
if (typeof(double).Equals(fieldType))
{
double d = ((double)fieldValue);
}
else if (typeof(string).Equals(fieldType))
{
string d = ((string)fieldValue);
}
else if (typeof(whatever).Equals(fieldType))
{
// deal with whatever
}
else
{
// the safe option
throw new NotSupportedException(fieldType +" is not supported!");
}
}
Without unsafe code or unions (only structs) at least.
This has implications not just on performance, you cannot unbox an int as a double for example, despite that conversion working on unboxed instances.

Categories

Resources