Providing ToString() for my custom object - c#

I have a class with lots of, lots of, lots of properties.
In my programm i have to log heavily. Often I have to manually
build log strings like
string log = "Current state of object:" + "Property1" + myObj.Property1 + ...
I just thought what if override ToString and provide logging of whatever I need. It is considered goog practice?
How can I provide formatter control string? Say I want my ToString to operate in two modes
one is complete ouput of all properties and another light version wheere only relevant properties are output
Something like MyObj.ToString("full") and MyObj.ToString("basic")

Overriding ToString is indeed good practice, so long as you provide good information.
As for having different types of ToString - this is possible, but then you will not be overriding ToString, but providing an overload (that any using class will need to know about).
I would implement the lightweight version as the override and create a VerboseToString function for the full set of properties.
If you have many such objects, you can create a IVerboseString interface with a VerboseToString method and implement it in your objects. This way you can simply use the interface reference in your logging.

That's an excellent practice
You could, of course, parametrize the ToString method, but it would no longer mean an implicit conversion from object to string, so you can't write, say, string x = myObject; you will have to call ToString explicitly.

Why are you overriding ToString but not creating a method that takes Enum as parameter and does what you want inside?

I can't think of any particular problem associated with it, and myself I often appreciate it for spitting out info in unit tests or trace etc. but I'd take issue with your implementation for verbose and concise outputs - don't use voodoo strings or any kind of arbitrary input - I'd prefer it here id you either took an input argument bool verbose or you explicitly created a ToStringVerbose() method. It's also good practice IMHO for your overridden method to use base.ToString() as part of it's implementation.

Related

Overriding Equals for classes with many properties in C#

I have a number of data classes that have over 25 properties of different value types (and this may change in the future as requirements change). I would like to override equals, mostly for unit testing purposes.
Currently, the only way I know how to do this is to actually test for equality of each property hard coded. This seems bad for two reasons - first, I will have to write a lot of code to test 25 properties for equality - second, if a property in one of the classes is added at a later point in time, the Equals method will not check that, and most likely this will go unnoticed and lead to problems down the road.
Since Equals usually checks for the properties of classes, there should be a way to dynamically compare the properties of the classes being compared, which ensures that property changes to a class don't result in an incorrect implementation of Equals. Is there a way to do this?
you could write something like this using reflection - but this would be very slow.
I would stick with overriding equals but think about which part you really need for equal. I usually only check the immutable parts (like Id) for equality and just ignore the mutable fields and I think this is a good practice.
Try using reflection to compare the properties. See Comparing object properties in c# for more info!
If your class is an entity, it should have a property which allows you to uniquely identify each instance.
If your class is implemented as a value type, you'll have to check for equality by checking each property.
In the latter case, in order to prevent tedious work, you could make use of reflection to get all properties of the class at runtime, retrieve the value and use the TypeDescriptor classes to compare the values.
You can use some AOP Frameworks. If the properties you're goona to compare are much more then those ones you gonna to avoid, mark the properties to skip with special custom attribute.
Maybe T4 can help you out. With it you can generate code at a click. Within this function you can then use the slow reflection mechanism to create a hard-coded GetHashCode() function that will be called at runtime. For a first look into T4 take a look at Scotts blog about it. Or simply try searching for Text Template Transformation Toolkit with your favorite search engine.

Overloaded methods in interface

my question for today: are overloaded methods in interface bad? You know, the "omit parameters if you don't care, we'll figure out the default values" kind of overloaded methods.
Like that:
void Add(object item);
void Add(object item, bool shouldDoSomething);
void Add(object item, bool shouldDoSomething, IUltraObscureDeviceContext context);
In this case I tend to think that only the latter belongs to an interface and others should be implemented in abstract class on top of it. But then again, I'm not sure.
Also, there are times when you just want different overloads doing slightly different work (stop me right there if overloaded methods should never be used for that). Or sometimes you can't just stuff nulls in place of some parameter, you want the exception thrown if something is null. Should I not use overloading in this case?
So basically I'm looking for some guidelines on overloaded methods in interfaces vs overloaded methods in abstract classes implementing these interfaces and so on.
Thanks in advance
If the defaults depend on the receiver of the method call, declare them as interface methods.
If the defaults are just defaults irrespective of the receiver, create the various reduced-argument-list overloads as extension methods and save implementors the headache of having to supply all the overloads themselves.
If you're dealing with some sort of nitty-gritty 80/20 rule exceptions, where implementation-independent defaults are almost but not quite always sufficient, you have a few options, none of which are that good:
Deal with it as if they're always different, declare them as interface methods, and reimplement them everywhere. Not very DRY.
Deal with it as if they're always different, declare them as interface methods, and inherit a base class that provides the 80% default implementation. Kind of clumsy, and not good if your sole base-class slot is already occupied.
Create another interface containing those specific methods. Declare extension methods with matching signature against the original interface. In the extension methods, as-cast the this argument to the new interface type, and if it matches, call it there, otherwise fill in stock defaults. Very funky, reliant on dynamic casting so not that great in an inner loop, but it decouples the defaults from both implementor and caller without sacrificing flexibility for implementors that can't take the "default defaults".
Overloaded methods in an interface maybe Ok if the design of the interface warrants it. I've personally never needed to do this.
I wouldn't define default parameters values in an interface. That is an implementation detail that implementing classes that choose to surface.
you comment about having different implementations for the overloads....
Don't do that. Think of implementation of these overloaded methods as calling the one method that has all of the parameters defined with some default values. That's how users of your code would expect things to be.
If you need different behavior then use polymorphism. That's what its there for.
IMO if the interface/contract spells it out, there should be no problem. However the goal is to simplify things when exposing an interface and hide the details. And thats where optional params come in handy.Pefectly object oriented languages like Python do not even have overloading AFAIK

When is it correct to create an extension method?

I have a piece of code like the following:
public class ActivityHelper
{
public void SetDate(IList<Activity> anActivityList)
{
foreach(Activity current in anActivityList)
{
current.Date = DateTime.Now;
}
}
//More methods, properties, fields, etc...
}
This could easily be converted to an extension method. For example:
public static void SetDate(this IList<Activity> aList)
{
foreach(Activity current in anActivityList)
{
current.Date = DateTime.Now;
}
}
The original function doesn't use any instance specific data or methods from the ActivityHelper class which makes it seem like it is in the incorrect place. Is this the correct time to write an extension method? What are the correct scenarios in which to create extension methods?
Brad Adams has written about extension method design guidelines:
CONSIDER using extension methods in any of the following scenarios:
To provide helper functionality relevant to every implementation of an interface, if said functionality can be written in terms of the core interface. This is because concrete implementations cannot otherwise be assigned to interfaces. For example, the LINQ to Objects operators are implemented as extension methods for all IEnumerable types. Thus, any IEnumerable<> implementation is automatically LINQ-enabled.
When an instance method would introduce a dependency on some type, but such a dependency would break dependency management rules. For example, a dependency from String to System.Uri is probably not desirable, and so String.ToUri() instance method returning System.Uri would be the wrong design from a dependency management perspective. A static extension method Uri.ToUri(this string str) returning System.Uri would be a much better design.
I think Extension methods are only appropriate if there is a compelling reason to make the method an extension method.
If the type is one you do not control, and the method should appear to be integral to the type, or if there is a compelling reason to not put the method directly on the type (such as creating an unwanted dependency) then an extension method could be appropriate.
Personally, if the expectation of the user of your API will already be to use the "ActivityHelper" class when working with collections of Activities, then I would probably not create an extension method for this. A standard, non-extension method will actually be a simpler API, since it's easily understood and discoverable. Extension methods are tricky from a usage standpoint - you're calling a method that "looks like" it exists somewhere other than where it actually exists. While this can simplify syntax, it reduces maintainability and discoverability.
In my experience extension methods work best when they:
Don't have side-effects (most of the extension methods my team wrote that have side-effects, we ended up removing because they caused more problems than they helped)
Offer functionality that applies to every possible instance or value of the type they're extending. (Again citing an example from my team, string.NormalizeUrl() is not appropriate because not all strings are even URLs anyway)
Well i usually create extension methods to help me write codes which have a smooth flow. Its generally depends upon the method you are creating.
If you feel that the method should have already been in framework and is too general then its okay to create an extension method for that.
But you need to first analyze that the class you are extending will always will be in state that your extension method can handle.
For Guidelines here to Brad's Article
http://blogs.msdn.com/b/brada/archive/2009/01/12/framework-design-guidelines-extension-methods.aspx
In essence, Extension Methods provide a more fluent style syntax for Helper methods. This translates into the ability to seemingly add functionality to types or all implementations of interfaces.
However, I generally steer away from declaring Extension Methods with a void returntype, as I feel the usefulness of this fluent style syntax, which allows you to compose statements, is negated when the method in question doesn't return anything.
However, I guess it can be handy to have your methods picked up by IntelliSense... :-)

When should extension methods be avoided?

Before you start pointing me to duplicates just know that I have read nearly all the posts on SO about extension methods. I am just trying to play devil's advocate for a minute to consider the alternative to my working opinion.
Recently I was working on a project and a need came up for a method to be a base of an interface. So I suggested we write an extension method and it was shot down. Saying it added complexity and harder to debug.
I of course argued and got on SO to find all the wonderful posts that show the many reasons why to use extension methods. Not to forget that a lot of the .net framework uses them. We eventually did not use it as I was overruled by the team.
But then it got me thinking, are there times when an extension method could be used but shouldn't be?
I really couldn't think of any but thought I would post here and see if anyone could think of any other reasons why they shouldn't be used.
Any time you have a function which is "generally applicable" to an object of a certain type, regardless of its state, an extension method is a good choice.
For example, today I added two new extension methods to our codebase:
public static XElement ToXElement(this XmlElement element) { }
public static XmlElement ToXmlElement(this XElement element) { }
Both of these are, generally speaking, valid on the types they extend regardless of the state of the instance or where we are using it.
If your method does not meet that criteria, it should probably be moved to a helper method closer to the context where the particular case is always true or easily checked.
For example, a developer recently nominated this to be an extension method:
public static bool ParseYesNoBool(this string input) { }
There are two problems here: first, this will appear on all strings in the application, even though the number of strings which might ever be candidates for this case are very small. So we've broken the first rule, in that it is not useful regardless of state. Similarly, but second, the consumer of this functionality is limited to a single parser for one particular connector to an external system. So promoting implementation-specific functionality into the general-use namespace makes no sense. This was downgraded to a helper method in the parser.
As far as readability and debugging, that is just incorrect for a developer of any reasonable skill level.
In general if you control the source-code for the assembly and adding the method does not cause any breaking changes to existing code (which would have been the case if for example LINQ had not been implemented via extension methods) it is better to just add a normal method.
This discussion of the Framework Design Guildelines section on extension methods contains some good advice. I think the relevant portion for your scenario is:
To provide helper functionality relevant to every implementation of an interface, if said functionality can be written in terms of the core interface.
If your proposed usage did not pass that test then it should have been shot down.
I would say you should avoid them when "they do not make the intend of the code more clear". Of course, whether or not some code (or codeing style) is "more clear" varying widely between people, so that's pretty much useless. (I had one boss who said we shoudl avoid using interfaces because they made the code "too complex and hard to understand")
Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.
Any time you break the intent and design for the feature I would recommend reconsidering the use of an extension method. I see a few situations when you don't want to use an Extension method:
1) Changing the Object Model to allow for an Extension method: The class you want to create an extension on is an abstract class. This is going to require you either make each inherited class it's own version of the extension or remove abstract from the class. Either way, you are changing the object model in order to use an extension method.
2) Forgetting the Decorator Pattern: The number of extension methods you create for a class exceeds three. I find it is easier to organize/communicate and maintain the domain/object model with decorated objects than with extended objects. However, the opposite is also true: If a decorated object has less than four methods, I find a lot of almost "empty" objects in my project.
3) Private functions: Private functions are meant to modify(create, delete, etc..) the object and extension methods are meant to use the type, much like a struct would. If you find the extension is being assigned to another instance of the type then it probably should not be in an extension.

invoking method declaration without reflection

I have a base class (order) with a set of sub classes (productorder, specialorder, partsorder etc).
Only Some of these sub classes implement a particular interface (ITrackingCustomer) which has a single method declaration (object getcustdetails()).
As part of my solution all of my orders are processed in a central place, i.e. any crud methods pass through a central layer. Within this central layer I want to do the following:
If order is of type ITrackingCustomer
Then invoke method getcustdetails()
I have this working using the following code:
if (typeof(ITrackingCustomer).IsAssignableFrom(Order.GetType()))
{
MethodInfo theMethod = Order.GetType().GetMethod("getcustdetails");
object y = theMethod.Invoke(Order, null);
}
I am happy with the first part using isassignablefrom but would like to use a less performance intensive method for the second part (i.e. the reflection using invoke).
My question is:
Is there a more efficient way of doing this as I have read that using the invoke command is costly.
ITrackingCustomer ord = Order as ITrackingCustomer;
if (ord != null)
{
object y = ord.getcustdetails();
}
You can do:
if(Order is ITrackingCustomer) {
((ITrackingCustomer)Order).getcustdetails();
}
As others have mentioned, you can use the is and as operators to determine if an object is of a certain type. However, polymorphism is usually better suited for solving this type of problem.
If it is feasible, perhaps you can place a getcustdetails() method on Order. Make it virtual if it has a suitable default implementation (i.e. return no details or null), or abstract if it makes sense that all Order types must implement it. Since you have the ITrackingCustomer interface, I suspect that an abstract method won't work well. However, for Order types that implement ITrackingCustomer, you can then implement getcustdetails() accordingly.
At this point, it sounds like you would be able to do away with ITrackingCustomer, but I can't say for certain without knowing more details about how this interface is used.
Once this is done, you won't need to perform any type checks since calling Order.getcustdetails() always dispatches to the correct concrete implementation.
If you are trying to do call by name instead of invoking a member in an interface and you want to be able to call the same method thousands of times, then other than a cast (which I assume you can't do because you don't know the type) or reflection is to JIT compile the call.
Rick Strahl has a nice blog article on the performance costs of various ways to call method and the comments lead to this article which shows how to pull a delegate out to a non-virtual method.
Finally, I wrote a blog article on how to build adapter classes on the fly. What you can do with that is make a directly callable object that meets an abstract class:
public abstract class CustomerDetailsGetter {
public abstract object getcustdetails();
}
// ...
AdapterCompiler compiler = new AdapterCompiler();
AdapterFactory<CusomterDetailsGetter> factory = compiler.DefineAdapter<CustomerDetailsGetter>(Order.GetType());
// now, my code assumes you want to construct an object from whole cloth
// but the code could be changed to invoke the default constructor and set the
// adapted object.
CustomerDetailsGetter getter = factory.Construct(null)
object info = getter.getcustdetails();
Now, I need to be clear - there are only two reasons to do this:
you want to be able to have call-by-name semantics when you know the target arguments at compile time and you don't know have the target assembly, and you want your code to be CLEAN. An example of this is code that knows it wants to create and use a particular object, but doesn't know if the assembly will be available until run time and is forbidden to have a reference.
you want to call object methods a la reflection, but want to do this fast, fast, fast and will be calling them thousands or millions of times.
If it's a "call once" thing, you're way better off writing a helper method to do what you want.

Categories

Resources