What is the terminology for what this method attempts? - c#

I don't know:
if this works.
if it's a good idea.
what it is called in order
to find out more about it.
But I think the intent is fairly apparent.
public static class DebugLogic
{
public static bool ThrowIfNull = false;
public static T OrNew<T>(this T obj) where T : class
{
if (obj != null) return obj;
else if (ThrowIfNull) throw new ArgumentNullException(//to do...);
else return Activator.CreateInstance<T>();
}
}
Intended usage:
var customer = order.Sale.OrNew().Customer.OrNew().Name
What am I doing? Is this insane or helpful? It seems helpful.

I think the idea of having an OrNew method is fine. Especially if you're striving to make a fluent interface. However I would change 3 things about it
Don't have a hidden flag that controls the behavior (ThrowIfNull). This makes it impossible for someone to read an OrNew call an understand what it does.
Use a new constraint in favor of the less safe Activator.CreateInstance<T>() call
I'd call it something other than DebugLogic. Generally (but not always) extension method containers end with the Extensions .
For example
public static class LogicExtensions {
public static T OrNew<T>(this T obj) where T : class, new() {
if (obj != null) {
return obj;
}
return new T();
}
}

The name of this operation is clearly: DefaultIfNull

Related

c# - How to allow specific class call specific method

In my code i need to allow only class EchoProcess call method GetStorePrivateData from class MainData.I thnk it not better way but in this code it work done.How should i do?
** In future class MainData will have more protected class and allow specific other class to call it.
internal sealed class EchoProcess : MainData
{
private EchoProcess()
{
}
public static string EchoPrivate(string someCondition)
{
var result = GetStorePrivateData<EchoProcess, Key>();
//Condition here >
return "";
}
private class Key
{
}
}
internal class MainData
{
protected MainData()
{
}
private static readonly List<string> StorePrivateData = new List<string>();
protected static List<string> GetStorePrivateData<TEcho, TKey>() where TEcho : class where TKey : class
{
return CheckAllowGetStorePrivateDataClassAccess<TEcho, TKey>() ? StorePrivateData : null;
}
private static bool CheckAllowGetStorePrivateDataClassAccess<TEcho, TKey>()
{
var thisClass = MethodBase.GetCurrentMethod().DeclaringType;
var echoProcessType = typeof(TEcho);
var isEchoProcess = echoProcessType.Name == "EchoProcess";
var keyType = typeof(TKey);
var isKey = keyType.Name == "Key";
var isEqualNameSpace = thisClass.Namespace.Equals(echoProcessType.Namespace) &&
keyType.Namespace.Equals(echoProcessType.Namespace);
var keyTypeFullName = $"{echoProcessType.FullName}+{keyType.Name}";
var isEqulaKeyTypeNameSpace = keyType.FullName.Equals(keyTypeFullName);
return isEqualNameSpace && isEqulaKeyTypeNameSpace && isEchoProcess && isKey;
}
}
In my code I need to allow only class EchoProcess call method GetStorePrivateData from class MainData.
Do not do any of this stuff with reflection or stack traces.
Both types are internal. They're in the same assembly. Mark the method you wish to restrict callers on as internal. Now any code in your assembly can call that method. Who cares? You wrote that code; if you don't like it, you can change it.
This is a problem that should be solved by communicating with the coders who are writing the assembly about what the correct protocols are for using assembly implementation details. This is an interpersonal team relationships problem, so don't try to solve it by writing code. Mark the method as internal, and if there's a call site that you don't like, then talk to the developer who wrote it during code review to find out why they thought that was a good idea.
In future class MainData will have more protected class and allow specific other class to call it.
Glad to hear it... the solution I provide below isn't ideal (e.g. you won't get any errors at compile time), and there are object models that are probably better suited for this.
In my code i need to allow only class EchoProcess call method GetStorePrivateData from class MainData.I thnk it not better way but in this code it work done.How should i do?
It is pretty easy to write code that inspects the call stack (you can obtain a copy with var s = new StackTrace() and walk the stack with s.GetFrames()). You can walk the call stack and see if EchoProcess was the caller or if the call came from somewhere else. Here is a simple example:
static public class CallPermissionHelper
{
static public bool IsAllowed<T>() where T : class
{
var callers = new StackTrace()
.GetFrames()
.Select
(
f => f.GetMethod().DeclaringType
);
var immediateCaller = callers.ElementAt(1);
var firstOutsideCaller = callers
.Skip(2)
.Where
(
t => t != immediateCaller
)
.FirstOrDefault();
return (firstOutsideCaller == typeof(T));
}
}
The logic is straightforward:
Obtain a list of callers, derived from the stack trace.
Ignore the first frame (which references the current code location, not very helpful)
Check the second frame to determine the class that called our helper class. In our case it will be MainData. We can ignore any stack frames from this class, e.g. if it is calling itself or using utility functions, since obviously it has permission to call itself.
Check the rest of the frames for any other classes, working down the stack. If the first class we run into is EchoProcess, we return true. In all other cases we return false.
Here is how to use it in your example:
internal sealed class EchoProcess : MainData
{
private class Key {}
public static string GetPrivateFromMainData()
{
return MainData.GetStorePrivateData<EchoProcess, Key>();
}
}
internal class MainData
{
public static string GetStorePrivateData<TEcho, TKey>() where TEcho : class where TKey : class
{
var allowed = CallPermissionHelper.IsAllowed<EchoProcess>(); //Magic!!!
return allowed ? "Allowed" : "Blocked";
}
}
public class Program
{
public static void Main()
{
var a = EchoProcess.GetPrivateFromMainData();
var b = MainData.GetStorePrivateData<object, object>();
Console.WriteLine("a={0}", a);
Console.WriteLine("b={0}", b);
}
}
Output:
a=Allowed
b=Blocked
See my code on DotNetFiddle

one winform to add and update data

I usually in my web projects use one webform for adding and update data. I just scratched winforms environment so I was thinking to use same approach one form to add and update data.
I was thinking to use two constructors on addEditForm like
public AddEditForm()
{
.. to do new object
}
public AddEditForm(MyDataObj obj)
{
... to do edit
}
so, is this right approach or is there better practice?
thanks
As I said in my comment I use this approach too, of course when I'm not using MVP(which is a different story)
About calling InitializeComponent() you need it in your form construction because it is the method which (as you can tell from it's name) initializes your form and controls on it and without it you'll get an empty form.
But if you are concerned about calling InitializeComponent() twice, I prefer this:
MyDataObj _myObject;
public AddEditForm()
{
InitializeComponent();
}
public AddEditForm(MyDataObj obj)
:this()
{
if(obj == null) //you're creating the object
_myObject = new MyDataObj();
else // you're editing it
_myObject = obj;
}
// Continue my work with _myObject
You can create different constructors in the following way:
MyDataObj editItem=null;
public AddEditForm()
{
InitializeComponent();
//Other common code for initialization.
}
public AddEditForm(MyDataObj obj) : this()
{
editItem = obj;
//Other code specific to editing.
}
If the object editItem is null, then the form can be considered in Add mode, otherwise Edit mode.
A property also can be made for the same
For example:
public bool IsEditMode
{
get
{
return (editItem != null);
}
}
hope it helps...
The approach you posted is the normal approach for creating such a form.
But sometimes you will see something like this.
public AddEditForm(MyDataObj obj, int mode) //1 = edit, 2 = create
{
... to do edit
}
If you think about it, this is not a good alternative. It's harder to understand and looks ugly.
Do I need to call InitializeComponent() in every constructor?
Unless you do constructor chaining (which would not work here), yes you do.
Please look #Virus answer for a way to only call it once.
The correct approach would be:
public partial class CustomerForm: Form
{
private object instance;
public CustomerForm()
{
InitializeComponent();
SetData(BLL.CreateNewEmptyObject());
}
public CustomerForm(object details)
: this()
{
SetData(details);
}
public void SetData(object details)
{
instance = details;
//bind the details to controls
}
private void Save()
{
BLL.Save(instance);
}
public bool EnableEdit {get{...
}
Usage Examples:
var newCustomerFrm = new CustomerForm();
var existingCustomerFrmReadOnly = new CustomerForm(BLL.GetCustomerById("123"))
{
EnableEdit = false
};
var existingCustomerFrmToEdit = new CustomerForm(BLL.GetCustomerById("123"))
{
EnableEdit = true
};

Using a Static class as a collection/container of other objects

I have a design question. I'm working with a Coded UI test framework that someone wrote and I am maintaining. I am convinced the way this is designed incorrectly but I thought I would get some other opinions. It's basically a large static class whose sole purpose is to create and return other objects.
Good/Bad...why? I am lobbying to take on a pretty significant refactor and want to please my case convincingly to my manager.
public static class ParentClass
{
private static ChildClass1 childClass1;
private static ChildClass2 childClass2;
// 10+ more of the same
// Properties
public ChildClass1 ChildClass1
{
get
{
if (childClass1 == null)
{
childClass1 = new ChildClass1();
}
return childClass1;
}
}
public ChildClass2 ChildClass2
{
get
{
if (childClass2 == null)
{
childClass2 = new ChildClass2();
}
return childClass2;
}
}
// 10+ more of the same
}
[TestClass]
public class TestClass1
{
[TestMethod]
public void TestMethod1()
{
var x = ParentClass.ChildClass1.SomeMethod();
Assert.IsNotNull(x);
}
[TestMethod]
public void TestMethod2()
{
var x = ParentClass.ChildClass2.SomeMethod();
Assert.IsNotNull(x);
}
// 10+ more of the same
}
This is something like a singleton pattern but it does not become clear from the provided code why it is designed this way.
var x = ParentClass.ChildClass1.SomeMethod();
could easily be replaced with
var x = new ChildClass1().SomeMethod();
and then you can get rid of ParentClass.ChildClass1 and ParentClass.childClass1 unless ParentClass.ChildClass1 is used several times and carries state from method call to method call.
But while this does not really look elegant and might be overly verbose, I would not consider this a major issue.
Personally I would have implemented it this way but it is hard to tell if this would work for all the omitted code.
[TestClass]
public class TestClass1
{
private static void ExecuteTestCore<T>() where T : new(), IHaveAMethod
{
var x = new T().SomeMethod();
Assert.IsNotNull(x);
}
[TestMethod]
public void TestMethod1()
{
TestClass1.ExecuteTestCore<ChildClass1>();
}
[TestMethod]
public void TestMethod2()
{
TestClass1.ExecuteTestCore<ChildClass2>();
}
// 10+ more of the same.
}
internal interface IHaveAMethod
{
void SomeMethod();
}
It's hard to tell if this is "good" or "bad" without knowing how it's used, but I would suggest looking at IoC containers. They offer this type of capability and much more out of the box
In general, IoC containers can be very useful if used as part of Dependency Injection. If you're not using DI then this static class is probably not very helpful
https://stackoverflow.com/questions/2515124/whats-the-simplest-ioc-container-for-c
If you have a hard time suggesting IoC to the suits (as others have suggested).. show them smaller code perhaps?
public class ParentClass<T> where T : class, new() {
private static T _instance = null;
private static readonly object _locker = new object();
public static T GetObject() {
if (_instance == null) {
lock (_locker) {
if (_instance == null) {
return new T();
}
return _instance;
}
}
}
}
(Disclaimer: Not tested. Possibly not the best thread-safe implementation either)
Also: The design as it stands is hard to maintain.. and wreaks of DRY violations.
For what I can see this class is a "singleton container" I think this can be OK.
If exists a better way to do it? I think it depends of the context of usage.
Useful links:
SingletonPattern
ObjectFactory

Does C#.NET have an allocation helper class similar to mine?

I have implemented the following class:
public class ClassAllocator<T>
where T : new()
{
public delegate T Allocator();
T obj;
Allocator allocator = () => new T();
public ClassAllocator( T obj )
{
this.obj = obj;
}
public ClassAllocator( T obj, Allocator allocator )
{
this.obj = obj;
this.allocator = allocator;
}
public T Instance
{
get
{
if( obj == null )
{
obj = allocator();
}
return obj;
}
}
}
I feel like something this simple & useful should be in .NET somewhere. Also, I realize that the class I made is somewhat incorrect. The class is designed to work with objects that don't have a default constructor, yet my 'where' clause requires it in all cases.
Let me know if there is something in .NET I can use so I can get rid of this class, as I would hate to continue using a reinvented wheel.
Thanks!!!!
UPDATE:
I'm using .NET 3.5. Sorry I didn't mention this before, I wasn't aware it was relevant until a few good answers started flowing in :)
Sounds like you're looking for the Lazy<T> Class.
Lazy<T> Class
Provides support for lazy initialization.
Lazy initialization occurs the first time the Lazy<T>.Value property is accessed
The Lazy class

Which is best for perfomance?

Which of the following code snippets performs fastest?
if(ClassTestBase is ClassTestChild1)
or
if(ClassTestBase.Type == EClassType.Child1)
Update:
Here is the full scenario:
public enum EInheritanceTree
{
BaseClass,
Child1,
Child2,
Child3
}
public class MyBaseClass
{
public virtual EInheritanceTree MyClassType
{
get
{
return EInheritanceTree.BaseClass;
}
}
}
public vlasse MyChildClass1 : MyBaseClass
{
public override EInheritanceTree MyClassType
{
get
{
return EInheritanceTree.Child1;
}
}
}
Consider a method that has to compare the class type to see what kind it is. Which is the best?
public bool IsChild1(MyBaseClass myClass)
{
if(myClass is MyChildClass1)
return true;
return false;
}
or
public bool IsChild1(MyBaseClass myClass)
{
if(myClass.MyClassType == EInheritanceTree.Child1)
return true;
return false;
}
Have you thought about using a profiler to test which is more performant yourself? Visual Studio comes with a profiler.
I would be more concerned about the need to have an enum that hold inheritance information about your application.
If you're worried about performance, don't wrap all this in functions. Any code that says:
if (Obj.IsChild1() ) foo;
Should just do:
if(myClass.MyClassType == EInheritanceTree.Child1) foo;
If you're worried about the performance, any notions you may have that says to hide everything behind functions needs to be revisited. Also, why don't you just use polymorphism - that's the "right" way to make subclasses act differently.
Regardless, do some timing of your own. It's the only way to be certain which is faster.

Categories