Setting a readonly "Parent" property in child object from parent - properties

I am trying to reproduce the behaviour found in some WinForms controls (such as DataGridView and DataGridViewColumn) where the child object has a property pointing to the parent. This property is normally readonly, but it somehow changes after the parent's Add() method has been called.
In my code I have two classes, DataGroup and DataEntry, with the latter being the child object.
If I simply implemented something like:
public class DataEntry
{
public DataGroup Parent { get; set; }
}
public class DataGroup
{
public List<DataEntry> DataEntries { get; set; }
public DataGroup()
{
DataEntries = new List<DataEntry>();
}
public void Add(DataEntry de)
{
// Check stuff here
// ...
//
DataEntries.Add(de);
de.Parent = this;
}
}
it would certainly work, but with one major drawback: DataEntry.Parent has a public setter, so the property could be modified from anywhere without any of the checks I designed in DataGroup.Add()
I could maybe do the following:
public class DataEntry
{
private DataGroup _parent;
public DataGroup Parent
{
get { return _parent; }
set
{
_parent = value;
_parent.Add(this);
}
}
}
public class DataGroup
{
...
public void Add(DataEntry de)
{
// Check stuff here
// ...
//
_dataEntries.Add(de);
// de.Parent = this; Already set!
}
...
}
which would work fine in case I wanted to add the child by setting its parent property, but would not update DataEntry.Parent if I called DataGroup.Add()
As I already said, it is quite normal for WinForms controls not to be able to change the Parent property directly in the child, but the property is changed after the Add method is called from the parent.
I can't figure out the link, a way for the parent to modify a property in the child, unless that property is public or exposed through a method, both of which would grant a chance to bypass my checks and ultimately produce errors.

if you just want to hide the method from outside parties you could declare the method internal
internal void SetParent(DataGroup dg)
{
//code to set parent
}
I've never tried this but it might work also. I do it with private all the time.
public DataGroup Parent { get; internal set; }
Another option to hide it from yourself a little more is to have an Explicit Interface Implementation. and even combine it with internal to hide it from outside. When you Explicitly implement an interface the only way to call the method is to cast the object to the interface first. I think something like this would work
internal interface ISetParent
{
void SetParent(DataGroup dg);
}
public class DataEntry : ISetParent
{
void ISetParent.SetParent(DataGroup dg)
{
Parent = dg;
}
public DataGroup Parent { get; private set;}
}
public class DataGroup
{
public List<DataEntry> DataEntries { get; set; }
public DataGroup()
{
DataEntries = new List<DataEntry>();
}
public void Add(DataEntry de)
{
// Check stuff here
// ...
//
DataEntries.Add(de);
((ISetParent)de).SetParent(this);
}
}

Related

Why model binding with a struct doesn't work?

I'm trying to understand why this binding doesn't work.
The binding didn't work until I changed the type from struct to class.
Is this by design or am I missing something?
I'm using asp.net core 2.2 MVC
View Models
Not working
public class SettingsUpdateModel
{
public DeviceSettingsStruct DeviceSettings { get; set; }
}
Working
public class SettingsUpdateModel
{
public DeviceSettingsClass DeviceSettings { get; set; }
}
public class DeviceSettingsClass
{
public bool OutOfScheduleAlert { get; set; }
// other fields removed for brevity
}
public struct DeviceSettingsStruct
{
public bool OutOfScheduleAlert { get; set; }
// other fields removed for brevity
}
Controller
[HttpPost]
public IActionResult Update(SettingsUpdateModel newSettings)
{
// newSettings.DeviceSettings.OutOfScheduleAlert always false on struct but correct on class
return Index(null);
}
View
<input class="form-check-input" type="checkbox" id="out_of_schedule_checkbox" asp-for="DeviceSettings.OutOfScheduleAlert">
Expected: DeviceSettings.OutOfScheduleAlert to bind to a struct the same as class
Actual: only the class parameter was binded
It is by design in complex type model bindings. A struct type is a value type that is typically used to encapsulate small groups of related variables, such as the coordinates of a rectangle or the characteristics of an item in an inventory.
In ComplexTypeModelBinder.cs , the CanUpdateReadOnlyProperty method will mark the properties of value-type model as readonly due to value types have copy-by-value semantics, which prevents us from updating
internal static bool CanUpdatePropertyInternal(ModelMetadata propertyMetadata)
{
return !propertyMetadata.IsReadOnly || CanUpdateReadOnlyProperty(propertyMetadata.ModelType);
}
private static bool CanUpdateReadOnlyProperty(Type propertyType)
{
// Value types have copy-by-value semantics, which prevents us from updating
// properties that are marked readonly.
if (propertyType.GetTypeInfo().IsValueType)
{
return false;
}
// Arrays are strange beasts since their contents are mutable but their sizes aren't.
// Therefore we shouldn't even try to update these. Further reading:
// http://blogs.msdn.com/ericlippert/archive/2008/09/22/arrays-considered-somewhat-harmful.aspx
if (propertyType.IsArray)
{
return false;
}
// Special-case known immutable reference types
if (propertyType == typeof(string))
{
return false;
}
return true;
}
Reference here for more details .
BTY ,if you want to bind struct type model , you could try to send the json data by using ajax request from the view.

OOP - Override init method called in constructor

I have a simple class hierarchy of two classes. Both classes call an init-method specific to that class. Therefor the init-method is overriden in the subclass:
class A
{
public A() { this->InitHandlers(); }
public virtual void InitHandlers() { // load some event handlers here }
}
class B: public A
{
public B() { this->InitHandlers(); }
public virtual void InitHandlers() {
// keep base class functionality
A::InitHandlers();
// load some other event handlers here
// ...
}
}
I know this is evil design:
The call of an overriden method from constructor is error-prone.
B::InitHandlers() would be called twice with this setup.
But semantically it makes sense to me: I want to extend the behaviour of class A in class B by loading more handlers but still keeping the handlers loaded by class A. Further this is a task that has to be done in construction. So how can this be solved with a more robust design?
You can do something like this:
class A
{
protected boolean init = false;
public A() { this->Init(); }
public virtual void Init() {
if (!this->init) {
this->init = true;
this->InitHandlers();
}
}
public virtual void InitHandlers() {
// load some event handlers here
}
}
class B: public A
{
public B() { this->Init(); }
public virtual void InitHandlers() {
// keep base class functionality
A::InitHandlers();
// load some other event handlers here
// ...
}
}
You can see it as a design pattern template method.

check that property setter was called

I have a class I am unit testing and all I want to do is to verify that the public setter gets called on the property. Any ideas on how to do this?
I don't want to check that a value was set to prove that it was called. I only want to ensure that the constructor is using the public setter . Note that this property data type is a primitive string
This is not the sort of scenario that mocking is designed for because you are trying to test an implementation detail. Now if this property was on a different class that the original class accessed via an interface, you would mock that interface and set an expectation with the IgnoreArguments syntax:
public interface IMyInterface
{
string MyString { get; set; }
}
public class MyClass
{
public MyClass(IMyInterface argument)
{
argument.MyString = "foo";
}
}
[TestClass]
public class Tests
{
[TestMethod]
public void Test()
{
var mock = MockRepository.GenerateMock<IMyInterface>();
mock.Expect(m => m.MyString = "anything").IgnoreArguments();
new MyClass(mock);
mock.VerifyAllExpectations();
}
}
There are 2 problems with what you are trying to do. The first is that you are trying to mock a concrete class, so you can only set expectations if the properties are virtual.
The second problem is the fact that the event that you want to test occurs in the constructor, and therefore occurs when you create the mock, and so occurs before you can set any expectations.
If the class is not sealed, and the property is virtual, you can test this without mocks by creating your own derived class to test with such as this:
public class RealClass
{
public virtual string RealString { get; set; }
public RealClass()
{
RealString = "blah";
}
}
[TestClass]
public class Tests
{
private class MockClass : RealClass
{
public bool WasStringSet;
public override string RealString
{
set { WasStringSet = true; }
}
}
[TestMethod]
public void Test()
{
MockClass mockClass = new MockClass();
Assert.IsTrue(mockClass.WasStringSet);
}
}

Behaviours of new constructor added by AspectJ ITD

I am currently applying AspectJ to our project, and I found a behavior which is a bit strange to me.
Q1:
I added a new constructor to my current class with inter-type declaration, and found that the class's member variable is not initialized if the new constructor is used to instantiate my class.
For example:
The class which I'll add a new constructor to:
public class Child {
public String name = "John";
public Child(String desc) {
// TODO Auto-generated constructor stub
}
}
The aspectJ code:
public aspect MyTest {
public Child.new(String desc, int num) {
System.out.println("Child Name:" + this.name);
}
}
If I instantiate the Child with the new constructor:
new Child("A child", 5)
the member variable this.name is not initialized as will be done with the original constructor.
But, if I call the original constructor:
new Child("A child")
the member variable this.name will be initialized to "John" as usual
The result:
Child Name:null
Is this a limitation of AspectJ? Is there anyway to resolve this issue?
I don't really want to add the code for member variable initialization to the new constructor.
Q2:
It seems in the newly added constructor, super.method() can not be correctly resolved.
The class which I'll add a new constructor to:
public class Child extends Parent{
public String name = "John";
public Child(String desc) {
}
}
Child extends Parent. Parent has a method init()
public class Parent {
public void init() {
//....
}
}
I add a new constructor for the Child in my aspect.
public aspect MyTest {
public Child.new(String desc, int num) {
super.init();
}
}
The above aspect code will trigger an exception.
Exception in thread "main" java.lang.NoSuchMethodError: com.test2.Child.ajc$superDispatch$com_test2_Child$init()V
at MyTest.ajc$postInterConstructor$MyTest$com_test2_Child(MyTest.aj:19)
at com.test2.Child.<init>(Child.java:1)
at MainProgram.main(MainProgram.java:11)
My workaround is to define another method for my class Child, and indirectly call the super.method() within that method
For example, add a new method that calls super.init() for Child
public void Child.initState()
{
super.init();
}
Now, I can call initState() in the newly added constructor like below:
public aspect MyTest {
public Child.new(String desc, int num) {
this.initState();
}
}
Is this a limitation of AspectJ? Is this the only way to resolve this issue?
Thank you all for your time :)
Foe the first questions, it seems that the lint warning will appear when compiling:
(unless you close the lint warning)
"inter-type constructor does not contain explicit constructor call: field initializers in the target type will not be executed [Xlint:noExplicitConstructorCall]"
Therefore I'd say it's an AspectJ's limitation.
The best way to do this might be call the other constructors of Child in the constructor added by AspectJ
For example:
public aspect MyTest {
public Child.new(String desc, int num) {
this("Hello"); // -> This will call the constructor of Child, and trigger fields initialization
System.out.println("Child Name:" + this.name);
}
}
For the second question, I think it's a bug of aspectJ.
That decompile the woven target byte code will find that the method “com.test2.Child.ajc$superDispatch$com_test2_Child$init()V” will be inserted. It implies this method should be generate by aspectJ, but there is no such method in the byte code.
The code for an ITD introduction is no different that the code that you would add to a class directly. So without member initialization code in your introduced constructor, members will , of course, remain uninitialized. So you need to change you code in Q1 as follows.
public Child.new(String name, int age) {
this.name = name;
this.age = age;
System.out.println("Child Name:" + this.name);
}
As for Q2, it works fine for me.
class Parent {
public void init() {
System.out.println("P.init");
}
}
class Child extends Parent {
}
aspect Intro {
public void Child.init(){
super.init();
System.out.println("C.init");
}
}
public class Main {
public static void main(String[] args) {
Child c = new Child();
c.init();
}
}
prints:
P.init
C.init
Changing the introduced method to something other than init works too (to match your code).
Regarding your comment: I fail to see what difference you have made in Q1. Sorry, I don't get it.
As for Q2 part of your comment, constructor arrangement works for me:
class Parent {
protected String name;
public Parent(String name) {
this.name = name;
}
}
class Child extends Parent {
int age;
public Child(String name) {
super(name);
}
}
aspect Intro {
public Child.new(String name, int age){
super(name);
this.age = age;
System.out.println("this.name: " + this.name + " this.age: " + this.age);
}
}
prints this.name: myname this.age: 2

Autofac: how do I pass a reference to the component being resolved to one of its dependents?

With the following:
public class AClass
{
public ADependent Dependent { get; set; }
}
public class ADependent
{
public ADependent(AClass ownerValue) {}
}
with the following registrations...
builder.RegisterType<AClass>().PropertiesAutowired().InstancePerDependency();
builder.RegisterType<ADependent>().PropertiesAutowired().InstancePerDependency();
When I resolve an AClass, how do I make sure that 'ownerValue' is the instance of AClass being resolved, and not another instance? Thx
FOLLOW ON
The example above doesn't really catch the problem properly, which is how to wire up ADependent when registering when scanning... for example
public class AClass : IAClass
{
public IADependent Dependent { get; set; }
}
public class ADependent : IADependent
{
public ADependent(IAClass ownerValue) {}
}
// registrations...
builder.RegisterAssemblyTypes(assemblies)
.AssignableTo<IAClass>()
.As<IAClass>()
.InstancePerDependency()
.PropertiesAutowired();
builder.RegisterAssemblyTypes(assemblies)
.AssignableTo<IADependent>()
.As<IADependent>()
.InstancePerDependency()
.PropertiesAutowired();
The function I am looking for really is another relationship type like
public class ADependent : IADependent
{
public ADependent(OwnedBy<IAClass> ownerValue) {}
}
The OwnedBy indicates that ownerValue is the instance that caused ADependent to created. Does something like this make sense? It would certainly make wiring up UI components a breeze.
To extend Steven's approach, you can even Resolve() the second class, passing the first instance as a parameter:
builder.RegisterType<ADependent>();
builder.Register<AClass>(c =>
{
var a = new AClass();
a.Dependent = c.Resolve<ADependent>(TypedParameter.From(a));
return a;
});
You can register a lambda to do the trick:
builder.Register<AClass>(_ =>
{
var a = new AClass();
a.Dependent = new ADependent(a);
return a;
});