How to avoiding calling redundancy in context of variable assignment? - c#

I offten (like at the moment) come to the point to write c# (or vb.net) code like this:
someObject.field_1 = doSomething(
anotherObject_1.propertyA,
anotherObject_1.propertyB);
someObject.field_2 = doSomething(
anotherObject_2.propertyA,
anotherObject_2.propertyB);
// some more field in same schema.
someObject.field_X = doSomething(
anotherObject_X.propertyA,
anotherObject_X.propertyB);
Edit: anotherObject_1 .. anotherObject_X have same typ; someObject and anotherObject have normaly not the same typ.
The Problem is the expandability and maintainability. New field brings me to write nearly same code with only little differences in object naming.
With encapsulate the logic in doSomething(..) I avoid logic redundancy, but the calling redundancy is still annoying.
Is there a way (for example a pattern or a .Net (4.0) language-construct) to avoid this?

You can encapsulate set operation into different method
void SetField(ref int field, object anotherObjectX)
{
field = doSmth(anotherObjectX...);
}
SetField(ref object.field1, anotherObject1);
SetField(ref object.field2, anotherObject2);
SetField(ref object.field3, anotherObject3);
but you still need to add the new line for the each new field

You can use Reflection to reduce code duplication/repetition. If know that your target property would always be called "propertyA" and "propertyB", you can easily use reflection and get/set their value as needed. You can pass in your object as well, and manipulate it there with reflection also.
For example, you can write something like this (note: syntax not fully checked):
public someReturnType DoSomething(object myObject)
{
if (null == myObject)
{
throw new ArgumentNullException("myObject");
}
var propertyA = myObject.GetType().GetProperty("propertyA");
if (null == propertyA)
{
//this object doesn't have any property called "propertyA".
//throw some error if needed
}
var value = propertyA.GetValue(myObject); //You will need to cast as proper expected type
// You can retrieve propertyB similarly by searching for it through GetProperty call.
// Once you have both A and B,
// you can work with values and return your output as needed.
return something;
}

Related

Enforcing method don't return null

As question asked Here 8 years ago but I think there should be a way(New Patterns , New Designs , New Architectures or anything else.) to enforce method don't return null.
As you know there are some implications with returning null in a method one important for me is:
Handling null in Consuming-Side and understandable semantics like:
Method:
public ClassName Do()
{
...
return null;
}
And calling Do() like (Attention Comments also):
var objVal = Do();
//Accessing property of ClassName raised exception
var pnVal = objVal.PropName;//Exception id objVal is null
//But I should handle if it is not null then do anything I want
if(objVal!= null)
{
//Do something
}
after many problem on product by above way I came to this conclusion to generalize all method to follow a pattern to be readable,clean and preventing ambiguous semantic.
so a very basic Way is using Struct type because structure can't be null , if a return type of methods be structure then they can't return null and We know this in compile time not in runtime.
So I implement that above method like:
1- Make DTO out and in for method, in this case just out:
public struct Do_DTO_Out
{
public ClassName Prop1 { get; set; }
public bool IsEmpty
{
get
{
return Prop1 == null;
}
}
public static Do_DTO_Out Empty
{
get
{
return new Do_DTO_Out() { Prop1 = null };
}
}
}
2- And Do method should be:
public Do_DTO_Out Do()
{
try
{
return manipulatedObj;
}
catch (Exception exp)
{
}
return Do_DTO_Out.Empty;
}
3- In consuming side:
var objVal = Do();
if (!objVal.IsEmpty)
//Do something
Is struct is best way ? is it worth to change all method and create DTO in and out for each of them (I think so).
Is there better way to do that , any idea,help,answer would be truly appreciated.
Your 'reference type' to 'struct with property check' conversion seems useless to me. It also requires intimate knowledge of your intention, while the reference type null check is very obvious to anyone reading it later.
I think code contracts could work for you. It provides you with compile time static analysis and runtime checks. Just make sure you have the appropriate contract as post condition:
public ClassName Do()
{
...
object returnValue = null;
Contract.Ensures(returnValue != null);
return returnValue;
}
Assuming that value can never be null otherwise the if is unavoidable (but for a single method call you can now write Do()?.DoSomething()).
If you can introduce code contracts (see Patrick's answer) then I completely agree with Patrick and you should go with them. If it's not viable (because your codebase is already too big or you're targeting an environment where they aren't supported) then I'd first use assertions:
var obj = Do();
Debug.Assert(obj != null);
// Use obj...
We're however moving this responsibility to calling point and it may be tedious. If you want to make this interface explicit then you can use something a struct as you thought but throwing an exception at calling point (where the error is):
public NotNullable<SomeClass> Do() { }
Where NotNullable<T> is defined as:
public struct NotNullable<T> where T : class
{
public NotNullable(T value)
{
Value = value ?? throw new ArgumentNullException(nameof(value));
}
public T Value { get; }
}
However I do not like to explicitly access .Value at calling point then I'd make it transparent adding:
public static implicit operator T(NotNullable<T> rhs)
=> rhs.Value;
Now caller can be:
MyClass obj = Do();
obj.DoSomthing();
And the proper exception is thrown (at run-time, unfortunately) when object is created. Playing with [Conditional("DEBUG")] you may exclude that check for release builds having then a behavior similar to Debug.Assert() and a minimal (but still present) overhead.
Note that this makes sense only if you want to document interface method about this constraint directly in its signature. If you're not interested in this then keep it as simple as possible:
public SomeClass Do()
{
MyClass somevalue = ...
// ...
return NotNull(somevalue);
}
Where NotNull() is a static method define somewhere and imported with using static or even an extension method for object called as return somevalue.NotNull().
I don't especially like this approach because I think Debug.Assert() is enough in these cases but it's just my opinion. Of course maybe someday we will have Nullable Reference Types in C# then we'll get compile-time enforcement (as object? or the other way round object!).
Returning null is a bad practice - better to implement
NullObject Design Pattern

Extension methods, which is a better choice

Following is a test class
public class Test
{
public int a;
}
Following are the Extension methods I have created:
public static class Extension
{
public static void Do1(this Test t,int value)
{
t.a = t.a + value;
}
public static Test Do2(this Test t,int value)
{
t.a = t.a + value;
return t
}
}
Code Usage:
Test t = new Test();
t.a = 5;
Both the following calls lead to same result for t.a, which is 10:
t.Do1(5)
t = t.Do2(5)
There are many instances in my code where I need to implement a similar logic, which one is better, one of them is passing reference by value and internally updating it, other is returning the updated reference. Is using one of them safer, if this kind of code ever gets into multi threaded wrapper, provided all the thread safety is taken care of. Normally to update the referenced variable we need a ref or out keyword, which is like pointer to a pointer, instead of a separate pointer to same memory location as in this case, but here in extension methods, I cannot use them. Please let me know if the question needs further clarity
In your example it does not make sense to return the tvariable. t is a reference, so setting t.a updates the object already. There's no need for ref, out or returning t. One reason for returning t would be to allow you to use method chaining.
You only need ref or out if you want to actually change the reference, not the content of the reference.
You are actually misunderstanding sense of ref and out keywords. Those are used, if you want to replace whole referenced object inside your method, for simple property level update they are not needed at all.
In your example, as Test is a class (reference type), there is no actual difference between two methods, but returning initial Test object as in Do2 method is just pointless, as object was already updated. So best of two will be the first implementation:
public static class Extension
{
public static void Do1(this Test t,int value)
{
t.a = t.a + value;
}
}
Going back to Do2 method - as I said before, referenced object value is already updated inside a method, so there is even no point in assigning return value to initial variable:
t.Do2(5)
is the same as
t.Do(5)

Autofac: how to inject properties with dynamic values?

By Autofac, it's easy to inject a static value to the CurrentDate property to instances of classes in a given assembly:
builder.RegisterApiControllers(asm).WithProperty("CurrentDate", new DateTime(2012, 1, 13));
However, how to inject dynamic values e.g. values returned by a lamda () => { return DateTime.Now; } to the CurrentDate property?
Sounds like you could use pretty standard property injection, like this:
builder.RegisterApiControllers(asm)
.OnActivating(e => { e.Instance.CurrentDate = DateTime.Now; });
Note that you may need to cast e.Instance as it will probably be of type Object.
See Lifetime Events in the documentation for more info.
On second thought, why not just put the initialization in the base class constructor?
public DateTime CurrentDate { get; private set; }
protected ApiController() { CurrentDate = DateTime.Now; }
The current date isn't really a dependency you need a DI container to provide.
Register another service that provides your dynamic values (e.g. IDateTimeService) [I assume it's really something more complex than a DateTime that you want.] The default lifetime for this new service will be Instance per dependency but you could use "Per Matching Lifetime Scope". Your Controllers will already be created per Http request.
Now simply add a dependency from your controllers on the IDateTimeService (in the constructor). In the methods within that controller you can now get hold of the dynamic value you want from that service.
private static readonly IDateTimeService datetimeService;
public MyController (IDateTimeService datetimeService)
{
this.datetimeService = datetimeService;
}
public void SomeMethod()
{
var date = datetimeService.GetDate();
...
}
You need to write custom parameter like this:
public class DelegateParameter : Parameter
{
private readonly string _name;
private readonly Func<object> _getValue;
public DelegateParameter(string name, Func<object> getValue)
{
if (name == null) throw new ArgumentNullException("name");
if (getValue == null) throw new ArgumentNullException("getValue");
_name = name;
_getValue = getValue;
}
public override bool CanSupplyValue(ParameterInfo pi, IComponentContext context, out Func<object> valueProvider)
{
PropertyInfo propertyInfo = GetProperty(pi);
if (propertyInfo == null || propertyInfo.Name != _name)
{
valueProvider = null;
return false;
}
valueProvider = _getValue;
return true;
}
private static PropertyInfo GetProperty(ParameterInfo pi)
{
var methodInfo = pi.Member as MethodInfo;
if (methodInfo != null && methodInfo.IsSpecialName && (methodInfo.Name.StartsWith("set_", StringComparison.Ordinal) && methodInfo.DeclaringType != null))
return methodInfo.DeclaringType.GetProperty(methodInfo.Name.Substring(4));
return null;
}
}
And then use it:
builder.RegisterApiControllers(asm).WithProperty(new DelegateParameter("CurrentDate", () => DateTime.Now));
If you are trying to inject the lambda expression, rather than the result of the lambda expression, you have quite a few imperfect options. Here are just a few; I'm sure that there are more.
Autofac
The Autofac wiki on Google Project Hosting documents four ways of injecting properties. Three of them appear to use constant or default values--you mentioned one of these methods.
The final seems to give the developer a bit more control over properties. It uses the OnActivating event, during which you have a few options. You could:
Set the property and hope it sticks.
If the property lacks an accessible setter, you could use reflection to set it, or its backing property (by default, m_PropertyName for a property named PropertyName, if I recall correctly).
Wrap the instance in a proxy, as they put it: see Polymorphism below.
Polymorphism
Let ClassA contain the property to be modified, Prop1. Create a new class ClassB that extends ClassA. If Prop1 has a virtual modifier, you can override it. Otherwise, use the new modifier to create a similar property in ClassB containing your dynamic code.
In the case of an override, you will need to instantiate ClassB in place of ClassA. This will not work if the framework creates its own instances of ClassA, but as long as you create your own instances of ClassB and pass them to the framework, you should be good to go.
If you are using a new property, in addition to instantiating ClassB, you also have to ensure that whenever you access the new property, the object is cast to ClassB or a descendant type. This generally will not work if another framework is designed to use ClassA, since it will always operate on type ClassA, not ClassB, regardless of your casting.
Bytecode Manipulation
This is nasty stuff, but it will do exactly what you want. C# generally compiles to an assembly/bytecode language called CIL. Microsoft's variant is MSIL, but it's pretty much identical to generic CIL.
I've always used Mono.Cecil for CLI/CLR (.NET, Mono) bytecode manipulation. It seems to work flawlessly, and it's quite nice once you get the hang of it. However, you have to know two things:
How to use CIL
How to use Mono.Cecil
The first one isn't that bad. A few Wikipedia pages with detailed tables are all that you need, provided that you have sufficient experience with CLI. If you think CLI stands for nothing other than "command line interface", then you might run into difficulty.
Mono.Cecil, on the other hand, lacked any form of proper documentation as of about a year ago (2012). The learning curve was impossibly steep. I had a miserable few days trying to figure it out. It's amazing when it works, though.

Getting property type and pass to generic method

Working in .Net 4.5.
I am making classes that encapsulate an ActiveX control (CadCorp SIS activeX control to be specific) and basically replicate some of the objects available internally to that control (but not externally). From the outside the properties of the internal objects have to be manipulated using an API which takes text strings.
In each class I end up writing properties for getting and setting values via the API and i's basically the same code over and over again, e.g. Control.GetInt(TargetDescripor, TargetIdentifier, PropertyName);, so I am trying to use generics to cut down code to a minimum. I now have a method like this:
public T GetPropertyValue<T>(ObjectTypes Target, string PropertyName, int TargetIdentifier = 0)
which identifies the correct API method and returns the required value.
I still have to call this method from every object with the correct descriptor and the correct property name. I have cut down on that further. For example if I get a property in one of the objects I use the following code:
public Class MyObject
{
public bool MyObjectPropertyX
{
get { return this.GetProperty<bool>(); }
}
private const string _MyObjectPropertyX = "APICommandString";
private T GetPropertyValue<T>([CallerMemberName] string PropertyName = null)
{
string apiCommand = (string)this.GetType().GetField("_" + PropertyName, BindingFlags.NonPublic | BindingFlags.Static).GetValue(this);
// Call the method which executes the API command with the correct object
// descriptor and get the value
}
}
and this works just great.
Now I am wondering if it is possible in the property's getter to call the this.GetProperty<T>() with the type parameter being set automatically to the type of the property?
Is that feasible? Or is what I've got now as good as it gets?
UPDATE
Also, I would be interested to know if there are any drawbacks to moving to this kind of method. I will have to make a LOT of API calls, so I am wondering if using reflection will actually slow this down compared to the original code where I called the appropriate method explicitly in each getter and setter?
To address your first point, I don't think you will reduce the get code further without over complicating things; just specifiying the type seems fine to me.
If you want to be able to determine the property name without hardcoding a string, you can use This method with reflection.
On performance, I would say above all: Test it. If you find it is slow, then you could try caching you lookup of property actions. This code will wrap the reflected field.getValue call in a Func<string> so that the reflection lookup is not needed everytime. Bear in mind that the reflection api does some caching internally anyway, so there may be little benefit to this.
private readonly IDictionary<String, Func<String>> _cache = new Dictionary<String, Func<String>>();
private String GetApiCommand(String propertyName)
{
Func<String> command;
if (_cache.TryGetValue(propertyName, out command))
{
return command();
}
var field = GetType().GetField("_" + propertyName, BindingFlags.NonPublic | BindingFlags.Static);//.GetValue(this);
if (field != null)
{
Func<String> action = () => (String)field.GetValue(this);
_cache[propertyName] = action;
return action();
}
throw new NotSupportedException();
}

Strongly-typed property reference to multiple classes with no common interface (C#)

The System.Windows.Documents namespace includes a number of classes with an Inlines property of type InlineCollection. For example, the Paragraph, Bold and Hyperlink classes all have this property.
Each of these classes is decorated with ContentPropertyAttribute ...
[ContentPropertyAttribute("Inlines")]
public class Paragraph : Block
... which means that it is easy enough, using reflection, to detect that a given object exposes this property.
However, I need to be able to access this property in a strongly-typed manner across a selection of the types that implement it.
I am a little surprised that Microsoft didn't make all these classes implement an "IInlineContainer" interface, which would have made type checking and casting very easy.
However, in the absence of such an interface, is there any way to fake this polymorphic functionality, ideally without littering my code with lots of conditions and type checking?
Many thanks for your ideas,
Tim
Edit:
Thanks for your suggestions. A number of people have suggested the idea of a wrapper class, but this is not possible in my situation, as the target objects are not created by my code, but by the other classes in the .NET framework, for example the Xaml parser or the RichTextBox control (in which the containing FlowDocument is being edited).
Edit 2:
There have been several great suggestions here and I thank everyone who shared their ideas. The solution I have chosen to implement employs extension methods, which was suggested by #qstarin, although I have refined the concept to suit my needs, as follows:
public static InlineCollection GetInlines(
this FrameworkContentElement element)
{
if (element == null) throw new ArgumentNullException("element");
if (element is Paragraph)
{
return ((Paragraph) element).Inlines;
}
else if (element is Span) // also catches Bold, Italic, Unerline, Hyperlink
{
return ((Span)element).Inlines;
}
else
{
return null;
}
}
Although this approach requires conditional logic and type casting (which I said I wanted to avoid) the use of extension methods means that it only needs to be implemented in one place, leaving my various calling methods uncluttered.
Extension methods.
public static class InlineContainerExtensions {
public static InlineContainer GetInlines(this Paragraph inlineContainer) {
return inlineContainer.Inlines;
}
public static InlineContainer GetInlines(this Bold inlineContainer) {
return inlineContainer.Inlines;
}
}
If you didn't need to access it in a strongly-typed manner, but just without reflection, you could use dynamic:
dynamic doc = new Bold()
doc.InlineCollection. ...
doc = new Paragraph()
doc.InlineCollection. ...
Another option is to define a wrapper, that exposes a property with the same name, and has an overloaded constructor that takes Bold, Paragraph, etc.
You could implement a wrapper class that exposes an Inlines property and delegates via reflection to the contained object.
Decide if you want to validate that the wrapped object indeed has Inlines in your constructor or when trying to reference it
Employ the Adapter Pattern, write one class for each of those classes you wish to handle, effectively wrapping them in a layer implementing a common layer.
To make the classes discoverable, I would use reflection, tag each such class with an attribute for which class they handle, ie.:
[InlineContainerAdapter(typeof(SpecificClass1))]
public class WrapSpecificClass1 : IInlineContainer
and use reflection to find them.
This would give you several benefits:
You don't have to deal with dynamic, or similar solutions
While you have to use reflection to find the classes, the code you're actually executing once you've created the adapter is 100% yours, hand-coded
You can create adapters for classes that doesn't really implement what you need in the same manner as the rest, by just writing the adapter different
If this sounds like an interesting solution, leave a comment and I'll put up a working complete example.
One way of doing this (apart from using dynamic, which is the easiest solution IMO), you can create dynamically generated methods to return the inlines:
Func<object, InlineCollection> GetInlinesFunction(Type type)
{
string propertyName = ...;
// ^ check whether type has a ContentPropertyAttribute and
// retrieve its Name here, or null if there isn't one.
if (propertyName == null)
return null;
var p = Expression.Parameter(typeof(object), "it");
// The following creates a delegate that takes an object
// as input and returns an InlineCollection (as long as
// the object was at least of runtime-type "type".
return Expression.Lambda<Func<object, InlineCollection>>(
Expression.Property(
Expression.Convert(p, type),
propertyName),
p).Compile();
}
You'd have to cache these somewhere, though. A static Dictionary<Type, Func<object, InlineCollection>> comes to mind. Anyway, when you have, you can simply make an extension method:
public static InlineCollection GetInlines(this TextElement element)
{
Func<object, InlineCollection> f = GetCachedInlinesFunction(element.GetType());
if (f != null)
return f(element);
else
return null;
}
Now, with this in place, just use
InlineCollection coll = someElement.GetInlines();
Because you can check in your GetCachedInlinesFunction whether the property really exists or not, and handle that in a neat fashion, you won't have to litter your code with try catch blocks like you have to when you're using dynamic.
So, your dream-code would be:
foreach (var control in controls) {
var ic = control as IInlineContainer;
if (ic != null) {
DoSomething(ic.Inlines);
}
}
I don't see why you don't want to create a strongly typed wrapper class that uses reflection. With this class (no error handling):
public class InlinesResolver {
private object _target;
public InlinesResolver(object target) {
_target = target;
}
public bool HasInlines {
get {
return ResolveAttribute() != null;
}
}
public InlineCollection Inlines {
get {
var propertyName = ResolveAttribute().Name;
return (InlineCollection)
_target.GetType().GetProperty(propertyName).GetGetMethod().Invoke(_target, new object[] { });
}
}
private ContentPropertyAttribute ResolveAttribute() {
var attrs = _target.GetType().GetCustomAttributes(typeof(ContentPropertyAttribute), true);
if (attrs.Length == 0) return null;
return (ContentPropertyAttribute)attrs[0];
}
}
You could almost get to your dream-code:
foreach (var control in controls) {
var ir = new InlinesResolver(control);
if (ir.HasInlines) {
DoSomething(ir.Inlines);
}
}
You could always superclass them (e.g. InlineParagraph, InlineBold, etc) and have each of your superclasses implement an IInlineContainer interface like you suggested. Not the quickest or cleanest solution, but you at least have them all descending from the same interface.
Depending on your use-case, you could create a public Api that delegated its work to a private method that takes a dynamic. This keeps the strong typing for your public Api and eliminates code duplication, even though it falls back to using dynamic internally.
public void DoSomethingwithInlines(Paragraph p) {
do(p);
}
public void DoSomethingwithInlines(Bolb b) {
do(b);
}
private void do(dynamic d) {
// access Inlines here, using c# dynamic
}

Categories

Resources