Coming from a Java background, I have to implement something in C#. The class is a domain object which is composed of multiple other domain objects. I don't like to have a constructor with 10 fields, so I thought of using the builder design pattern! Here is what I came up with:
public class MyDomainObject
{
public DomainObject1 Obj1 { get; private set; }
public DomainObject2 Obj2 { get; private set; }
public DomainObject3 Obj3 { get; private set; }
...
public class DomainObjectBuilder
{
private MyDomainObject _domainObj = new MyDomainObject();
public DomainObjectBuilder(DomainObject1 obj1)
{
_domainObj.Obj1 = obj1;
}
public DomainObjectBuilder withDomainObject2(DomainObject2 obj2)
{
_domainObj.Obj2 = obj2;
return this;
}
.....
public MyDomainObject Build()
{
// Construct and Return the MyDomainObject
}
}
}
Now is this implementation thread safe? When I instantiate my domain object the following way:
var myDomainObject = new DomainObjectBuilder(obj1)
.withDomainObject2(obj2)
.withDomainObject3(obj3).build();
What happens if the calls between withDomainObject2 and withDomainObject3 is handled by different threads?
I haven't come across any code that splits a builder on multiple threads. The simple answer given your requirements is simply (no it is not thread safe).
Consider this example using your MyDomainObject class:
private MyDomainObject _myObj;
void Main(string[] args)
{
DomainObject1 obj1 = new DomainObject1();
_myObj = new MyDomainObject(obj1);
Thread oThread1 = new Thread(ThreadProc1);
oThread1.Start();
Thread oThread2 = new Thread(ThreadProc2);
oThread2.Start();
MyDomainObject myObjFinal = _myObj.Build();
DomainObject2 obj2 = myObjFinal.Obj2; //No guarantee that Obj2 is set or initialized
DomainObject3 obj3 = myObjFinal.Obj3; //No guarantee that Obj3 is set or initialized
}
void ThreadProc1()
{
DomainObject2 obj2 = new DomainObject2();
MyDomainObject myObjModified = _myObj.withDomainObject2(obj2);
DomainObject3 objNew = _myObj.Obj3; //No guarantee that Obj3 is set or initialized
}
void ThreadProc2()
{
DomainObject3 obj3 = new DomainObject3();
MyDomainObject myObjModified = _myObj.withDomainObject3(obj3);
DomainObject2 objNew = _myObj.Obj2; //No guarantee that Obj2 is set or initialized
}
As you can see there is no guarantee that any of the objects is initialized or set when called after Build() in the main thread. The same applies when trying to access an object that is initialized in a different thread.
you don't need a constructor wit too many things.... the thing that you may not call some of these method, mean some of them are optional, i see that also i java, but here after some reversion of .NET framework, you can do it more simple... like this:
A a = new A(Required properties){
Name="x",
Family="Y",
OpetionalProperty3 = "z",
.......
};
and if you do not have any thing required, you can remove the parentheses at all( when you define optional properties).
A a = new A{
Name="x",
Family="Y",
OpetionalProperty3 = "z",
.......
};
And about your case and thread handeling, check out the 'volatile' syntax for variables - it ensure last value is in the field on every thread call
Related
From C# - The C# Memory Model in Theory and Practice, Part 1 & 2
https://msdn.microsoft.com/en-us/magazine/jj863136.aspx
https://msdn.microsoft.com/en-us/magazine/jj883956.aspx
... the compiler and the hardware can subtly transform a program’s memory
operations in ways that don’t affect the single-threaded behavior, but
might affect the multithreaded behavior.
It means C# compilers can set an object reference before its constructor finish. Is readonly sufficient to write immutable objects for multi-thread?
In Java, when a field is declared as final, it is ready before the parent object reference is observable, stated in Java Language Specification 17.5
https://docs.oracle.com/javase/specs/jls/se8/html/jls-17.html#jls-17.5
when the object is seen by another thread, that thread will always see
the correctly constructed version of that object's final fields. It
will also see versions of any object or array referenced by those
final fields that are at least as up-to-date as the final fields are.
Do readonly fields work the same as final in Java? Are the two pieces of code below thread-safe?
1st piece
public class A
{
private readonly string s1;
public A()
{
s1 = "abc";
}
public string S1 => s1;
// or public string S1 { get; }
}
public class B
{
private volatile A a = null; // a will not be set to null anymore
public void SomeFunction()
{
Task.Run(() =>
{
while (a == null) ;
Console.WriteLine(a.S1);
});
a = new A();
}
}
2nd piece
public class A
{
private readonly string s1;
public A()
{
s1 = "abc";
Thread.MemoryBarrier();
}
public string S1 => s1;
}
public class B
{
private A a = null;
public void SomeFunction()
{
Task.Run(() =>
{
while (a == null) ;
Console.WriteLine(a.S1);
});
a = new A();
}
}
Alternatively, A can be in this form
public class A
{
public A()
{
S1 = "abc";
}
public string S1 { get; }
}
Can C# compilers inline the object construction like this?
public class B
{
private viotile A a = null;
public void SomeFunction()
{
Task.Run(() =>
{
while (a == null) ;
Console.WriteLine(a.S1);
});
a = new memory for A
a.s1 = "abc";
}
}
C# here means .Net Framework, .Net Core, ECMA and/or other variances
Reference Is it possible to observe a partially-constructed object from another thread?
I have a class that has several lists. The name of this class is Trans .
I want use this lists in another forms but I'm not able to call it's lists.
When I make an object from the Trans class it's lists will reset.
How can I use this lists in all of forms of the project ?
class Trans
{
public static List<string> name_list = new List<string>();
public static List<string> family_list = new List<string>();
public static List<string> phoneno_list = new List<string>();
public List<string> name_Sec_list { set { name_list = value; } get { return name_list; } }
public List<string> family_Sec_list { set { name_list = value; } get { return name_list; } }
public List<string> phoneno_Sec_list { set { name_list = value; } get { return name_list; } }
}
And Form1
Trans data = new Trans();
data.name_Sec_list.Add(name.Text);
data.family_Sec_list.Add(name.Text);
data.phoneno_Sec_list.Add(name.Text);
When I'm on Form2 and wanna to use my lists I can't So I should make object from Trans class and this work will make list values null.
you could use a singleton pattern:
class Trans {
private static Trans instance;
private Trans() { }
public static Trans Instance() {
if (instance == null) {
instance = new Trans();
}
return instance;
}
...
}
use it in first form:
Trans trans = Trans.Instance();
trans.name_Sec_list ....
use it in second form:
Trans trans = Trans.Instance();
trans.name_Sec_list ....
As others have suggested, a quick solution could be to make the properties static. However, this will likely introduce new problems such as testability, and it violates clean code principles.
The Singleton approach is already better, since the you could potentially make it configurable to return a test object for unit tests. However, getting the Singleton requires a static method, which can again be called all over the place.
So, both, static properties and Singletons will increase the likelyness of Spaghetti code. That's because you have no control over who can access the data and who cannot.
You have not exactly specified how many forms you have, how they are opened etc. so I will need to make some assumptions.
The main method could look like this:
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var data = new Trans();
var secondForm = new Form2 {Trans = data};
var mainForm = new Form1 {SubForm = secondForm, Trans = data };
Application.Run(mainForm);
}
And I have modified the Trans class so that it does not have static items any more. I also fixed that class, because IMHO it had a copy/paste problem. It's likely that you introduced all the _Sec_ stuff for testing purposes, so they can likely be removed (they return the same object, which doesn't solve any problem).
class Trans
{
public List<string> name_list = new List<string>();
public List<string> family_list = new List<string>();
public List<string> phoneno_list = new List<string>();
public List<string> name_Sec_list { set { name_list = value; } get { return name_list; } }
public List<string> family_Sec_list { set { family_list = value; } get { return family_list; } }
public List<string> phoneno_Sec_list { set { phoneno_list = value; } get { return phoneno_list; } }
}
What can you see here?
both, Form1 and Form2 have access to the data, so it solves your problem.
the Main() method has control over who gets which data. Everyone who needs that data gets the data.
Nobody else gets access to the data. While everyone could new up a Trans himself, that would just be empty.
Since there's nothing static any more, you can safely use new instances of Trans during unit tests without any side effects
The forms do not create their dependencies themselves. The dependency is now injected into the form. This makes it possible to replace it by a mock object with defined test behavior in a unit test. (Another question is whether you should test UIs in unit tests, but that's a different topic).
You have 3 static lists in your Trans class already, if you want to use them make other also static:
public class Trans
{
public static List<string> name_list = new List<string>();
public static List<string> family_list = new List<string>();
public static List<string> phoneno_list = new List<string>();
public static List<string> name_Sec_list = new List<string>();
public static List<string> family_Sec_list = new List<string>();
public static List<string> phoneno_Sec_list = new List<string>();
}
Then everywhere you want to use these lists you should access them like:
Trans.name_Sec_list.Add(name.Text);
Now you can use these lists in any form that you want.
Just use a static class
public static class Trans
{
public static List<string> name_list = new List<string>();
public static List<string> family_list = new List<string>();
public static List<string> phoneno_list = new List<string>();
}
Usage
Trans.name_list.Add(string);
I'd put the static class in a separate project so it can be referenced elsewhere if needed. But only if needed.
I have an object that only initializes itself with barebones data when constructed (fast), and loads itself for real (slow) when first accessed. The idea is that I'm creating a lot of these barebones objects at startup and hash them into a map, then fully load each object whenever it is individually accessed for the first time. The problem is that I cannot guarantee how clients will interact with this object, there are multiple public methods that might be invoked.
Is there a good pattern to support this kind of situation? The obvious (and my current) solution is to track state with an internal bool, check against that bool in every function that might be invoked, and load that way. But that requires code duplication of that behavior across all public functions, and is vulnerable to errors.
I can imagine a single point-of-entry method that then dishes out behaviors based on a client request type etc., but before I go consider going down that road I want to see if there's a commonly accepted approach/pattern that I might not be aware of. I'm doing this in C#, but any insight is appreciated.
If I understood what you want to achieve, you are looking for the Proxy Design Pattern, more specifically, a virtual Proxy.
Refer to http://www.dofactory.com/net/proxy-design-pattern
A small example would be something like:
public abstract class IObjectProvider
{
public abstract IObjectProvider Object{get;}
public abstract void doStuff();
}
public class RealObject : IObjectProvider
{
public RealObject()
{
//Do very complicated and time taking stuff;
}
public override IObjectProvider Object
{
get { return this; }
}
public override void doStuff()
{
//do this stuff that these objects normally do
}
}
public class ObjectProxy : IObjectProvider
{
private IObjectProvider objectInstance = null;
public override IObjectProvider Object
{
get
{
if (objectInstance == null)
objectInstance = new RealObject();
return objectInstance;
}
}
public override void doStuff()
{
if(objectInstance!=null)
objectInstance.doStuff();
}
}
public class SkeletonClass
{
public IObjectProvider Proxy1 = new ObjectProxy();
public IObjectProvider Proxy2 = new ObjectProxy();
}
static void Main(String[] args)
{
//Objects Not Loaded
SkeletonClass skeleton = new SkeletonClass();
//Proxy1 loads object1 on demand
skeleton.Proxy1.Object.doStuff();
//Proxy2 not loaded object2 until someone needs it
}
Here's an example of dynamic proxy approach.
using System;
using System.Diagnostics;
using Castle.DynamicProxy; //Remember to include a reference, too. It's nugettable package is Castle.Core
namespace ConsoleApp
{
public class ActualClass
{
//Have static instances of two below for performance
private static ProxyGenerator pg = new ProxyGenerator();
private static ActualClassInterceptor interceptor = new ActualClassInterceptor();
//This is how we get ActualClass items that are wrapped in the Dynamic Proxy
public static ActualClass getActualClassInstance()
{
ActualClass instance = new ActualClass();
return pg.CreateClassProxyWithTarget<ActualClass>(instance, interceptor);
}
//Tracking whether init has been called
private bool initialized = false;
//Will be used as evidence of true initialization, i.e. no longer null
private int? someValue = null;
public void Initialize()
{
if (!initialized)
{
//do some initialization here.
someValue = -1; //Will only get set to non-null if we've run this line.
initialized = true;
}
}
//Any methods you want to intercept need to be virtual!
public virtual int replaceValue(int value)
{
//below will blow up, if someValue has not been set to -1 via Initialize();
int oldValue = someValue.Value;
someValue = value;
return oldValue;
}
//block off constructor from public to enforce use of getActualClassInstance
protected ActualClass() { }
}
public class ActualClassInterceptor : ActualClass, IInterceptor
{
public void Intercept(IInvocation invocation)
{
//Call initialize before proceeding to call the intercepted method
//Worth noting that this is the only place we actually call Initialize()
((ActualClass)invocation.InvocationTarget).Initialize();
invocation.Proceed();
}
}
class Program
{
static void Main(string[] args)
{
ActualClass instance1 = ActualClass.getActualClassInstance();
ActualClass instance2 = ActualClass.getActualClassInstance();
int x1 = instance1.replaceValue(41);
int x2 = instance2.replaceValue(42);
int y1 = instance1.replaceValue(82);
Debug.Assert(y1 == 41);
int y2 = instance2.replaceValue(84);
Debug.Assert(y2 == 42);
var read = Console.ReadKey();
}
}
}
Say I have a class declared as follows:
public class ExampleClass
{
public Action<int> Do { get; set; }
public ExampleClass()
{
}
public void FuncA(int n)
{
//irrelevant code here
}
public void FuncB(int n)
{
//other irrelevant code here
}
}
I want to be able to use this class like this
ExampleClass excl = new ExampleClass() { Do = FuncA }
or
ExampleClass excl = new ExampleClass() { Do = excl.FuncA }
or
ExampleClass excl = new ExampleClass() { Do = ExampleClass.FuncA }
I can compile the second option there, but I get a "Delegate to an instance method cannot have null 'this'." exception when I hit that code. The third one doesn't even make sense, because FuncA isn't static.
In my actual code, there will be maybe 10-15 different functions it could get tied to, and I could be adding or removing them at any time, so I don't want to have to have a large switch or it-else statement. Additionally, being able assign a value to 'Do' when instantiating the class is very convenient.
Am I just using incorrect syntax? Is there a better way to create a class and assign an action in one line? Should I just man up and manage a huge switch statement?
You have to create the instance of the class and later set the property to the instance member. Something like:
ExampleClass excl = new ExampleClass();
excl.Do = excl.FuncA;
For your line:
ExampleClass excl = new ExampleClass() { Do = FuncA }
FuncA is not visible without an instance of the class.
For:
ExampleClass excl = new ExampleClass() { Do = excl.FuncA }
Instance has not yet been created that is why you are getting the exception for null reference.
For:
ExampleClass excl = new ExampleClass() { Do = ExampleClass.FuncA }
FuncA is not a static method, you can't access it with the class name.
In object initializer syntax you cannot access the variable being initialized before it is definitely assigned:
ExampleClass excl = new ExampleClass()
{
Do = excl.FuncA //excl is unavailable here
}
Read Object and Collection Initializers (C# Programming Guide) for more info.
You could do the following, for example:
public class ExampleClass
{
public Action<int> Do { get; set; }
public ExampleClass(bool useA)
{
if (useA)
Do = FuncA;
else
Do = FuncB;
}
public void FuncA(int n)
{
//irrelevant code here
}
public void FuncB(int n)
{
//other irrelevant code here
}
}
and use it:
ExampleClass exclA = new ExampleClass(true);
ExampleClass exclB = new ExampleClass(false);
Another idea is if these functions may be declared as static (i.e. they don't need any instance members of the ExampleClass), then this would work:
public class ExampleClass
{
public Action<int> Do { get; set; }
public ExampleClass() { }
public static void FuncA(int n) { /*...*/}
public static void FuncB(int n) { /*...*/}
}
and use it the way you want:
ExampleClass excl = new ExampleClass() { Do = ExampleClass.FuncA };
If you have extension methods make sure that those values are not null before invoking the extension methods or handle nulls inside the extension methods.
For example
public static ExtensionClass
{
public static bool RunExtensionMethod(this object myObject)
{
var someExecutionOnMyObject = myObject.IsValid();
//the above line would invoke the exception when myObject is null
return someExecutionOnMyObject ;
}
}
public void CallingMethod()
{
var myObject = getMyObject();
if(myObject.RunExtensionMethod()) //This would cause "delete to an instance method cannot have null" if myObject is null
{
}
}
To handle this scenario handle nulls and assert nulls if you own the extension class.
public static ExtensionClass
{
public static bool RunExtensionMethod(this object myObject)
{
if(myObject == null) throw new ArgumentNullException(nameof(myObject));
var someExecutionOnMyObject = myObject.IsValid();
return someExecutionOnMyObject ;
}
}
public void CallingMethod()
{
var myObject = getMyObject();
if(myObject != null && myObject.RunExtensionMethod())
{
}
}
As far as I understand the concept of delegates, they simply point to a method. Then when I'm feeling lucky I can go out and invoke the method my delegate is pointing to, right?
Given is the following code:
class Program
{
static void Main(string[] args)
{
Func<MyClass> myAct = GetAct();
Method(myAct);
}
private static Func<MyClass> GetAct()
{
MyClass obj = new MyClass()
{
Prop1 = 5
};
Func<MyClass> myAct = new Func<MyClass>(
() =>
{
MyClass obj2 = new MyClass();
MyClass2 obj3 = new MyClass2()
{
Prop3 = 25,
Prop4 = "test"
};
obj2.Prop2 = ((obj.Prop1 + 5) * obj3.Prop3)
.ToString() + obj3.Prop4;
return obj2;
});
return myAct;
}
static void Method(Delegate func)
{
GC.Collect();
GC.WaitForPendingFinalizers();
var result = func.DynamicInvoke();
}
}
class MyClass
{
public int Prop1 { get; set; }
public string Prop2 { get; set; }
}
class MyClass2
{
public int Prop3 { get; set; }
public string Prop4 { get; set; }
}
Now my delegate myAct (in this case a Func<MyClass>) is pointing to an anonymous function which performs some simple assignation of variables. Nothing special so far.
We invoke the delegate.
Everything went fine, just as we expected. But the question is why? If the delegate just simply points to the anonymous method AND a garbage collection was done, how could the CLR know what obj and it's values are?
Where is the reference to obj stored, to be available when the function is called? Inside the delegate?
Your anonymous method is defined within the scope of GetAct() so CLR makes scope variables available to the anonymous method.
It's similar to how an instance variable is usable by member methods.
Also, review the pitfalls of using closures: http://msmvps.com/blogs/peterritchie/archive/2010/11/03/deep-dive-on-closure-pitfals.aspx