Is there a way to find references of code that updates objects of a class in VS 2015 with Resharper?
Example: let's say I have the following code:
public class A {
public int Prop1 {get; set;}
public void Update()
{
Prop1 = 100
}
public String ToString()
{
return Prop1.ToString();
}
}
some code:
A a = new A();
a.Prop1 = 100; // write access
a.Update(); // write access
Console.Writeln(a); // read-only access
I want a way of finding only those statements that modify the objects of a class A. In the code above that would be the lines where I have the comment // write access. Resharper can find all the usages of a class but there is too much noise from read-only usages such as linq queries, and I wanted to see only the updates. Reporting the constructor call is fine. Reporting only the statements that set the properties of the objects of class A would be fine as well. The classes that I want to find the updates for are EF entities and they have only a few methods or none.
Thanks
This isn't a Resharper solution. More of a quick-and-dirty search. Assuming that the class is within your solution and there aren't way too many properties, change the properties to read-only. The compiler errors will show you anything that writes to the properties.
ReSharper solution: you can find all usages of the particular property and then there are two separate buttons in results window to show read or write usages separately.
Related
I'm a C# beginner, so easy explanations are greatly appreciated.
I was learning about properties, and got this question: properties give custom access logic to fields, but why can't the field itself contain its getter/setter? In other words, is there a reason why we can't get rid of Example and write custom get/setters under example(field)?
I could not find other posts that answer my question.
class MyClass
{
private int example = 5;
public int Example
{
get;
private set;
}
// here, this Example property only acts as a gateway for example.
// why is it not possible for the field 'example' to contain the
// get/set?
}
Property is an interface to Class, and not always is about storing data, you can always make the variable public member and will work perfectly like property, but the property has its own main job to work as an interface for that value with other classes.
While in many cases the property just works as public parameters, it is not always meant to be used in that way.
I'm building a C# class for matrices. I actually found something on SO to get started with so I don't have to start from scratch. The guy's class has a private property for the rows and columns of the matrix and a get() and set() property. Sometimes the guy refers to the properties themselves by name mRowCount and mColumnCount or by the this.RowCount and this.ColumnCount inside the class for calculation purposes as seen below (I only added relevant code):
public class Matrix
{
private decimal[,] mInnerMatrix;
private int mRowCount, mColumnCount = 0;
public int RowCount
{
get { return mRowCount; }
}
public int ColumnCount
{
get { return mColumnCount; }
}
}
Sometimes in the code the guy uses the properties by name mRowCount and mColumnCount and other times using this.RowCount and this.ColumnCount instead of the former way. What is the difference? Is one way better and if so with respects to what? Particularly in boolean methods where the methods checks to see if the object/matrix is a diagonal, symmetric or square matrix the developer uses the this.RowCount and this.ColumnCount in the loops that run through the mInnerMatrix[] array that holds the matrix's data. Other times he uses the properties themselves. Can anyone explain why someone might do this or is it a mistake? What should I use and should I use it throughout the entire program?
Technically, the get and set methods can be not that straightforward. For instance if you don't store rows and cols count but instead store rows and total elements, you would have to divide total by rows to get cols:
public Cols {get {return _mTotal/_mRows;}}
This is not the best sample, but you can get the idea. In your simple case there will be no difference whether to use a field or a property (if you actually have set methods but omitted them, otherwise the properties are readonly!). But note that one day you might want to implement some logic in get. Then the code that's using properties would work fine but the code that's using fields would fail.
Outside a class you always have to use properties, if any. In fact, you would declare fields private so that only within the class you can access them. Technically you can use both fields and properties outside class, but that would lead to a chaos.
On the other hand I would disagree that mixing properties and fields access within a class is always discouraged. Sometimes you would really need this access, the easiest sample is when your property is readonly (has only get).
If you defined properties - use them wherever possible, inside or outside class, as they may contain additional logic, not only direct member access.
One valid reason not to use properties (use direct access instead) - in constructor,
every other access should be made using properties.
It's rather bad practice to mix direct access and properties within a class
I have a class which is has tons of properties. Most of them are of custom types. I want to get all those properties, type of whose interface is same.
Public class abc:IamLegend
{
few properties
}
public class def:IamLegend
{
few properties
}
public class on_which_iamworking
{
public abc propabc{ get; set; }
public def propdef{ get; set; }
public someothertype propother{ get; set; }
}
I want something which returns propabc and propdef.
I know how to do it using reflection, but I am looking for another way.
I am working on c# 4.0
Thanks
I am afraid that this is not possible at runtime without using reflection. That's what reflection is designed for.
The main problem of reflection is that it is slow. If you don't want to use reflection only because of it's slowness, you could make caching of your property list in some static property or class. I used this tecknique widely in similar problems and there wasn't any problems with perfomance.
If you have holy war against reflection, you could create a special util that parses C# file (or builds your prokects, loads output assembly and use reflection, but only before build, not in run-time), finds needed properties and writes it into autogenerated file (maybe also C# code file) as static-class array-property initializer. And call that util on pre-build event of your project. Then you'll get all needed properties completely without reflections =) (but I wouldn't do that)
Well, there's two ways:
1/
return new List<string> { "propabc", "propdev" };
2/ Reflection :P
If you need to retrieve the list of properties many times and are afraid of the performance impact, compute the list only once and store it in a static property (as the list of properties of a class won't change during runtime).
There is an alternative approach for components. It is TypeDescriptor for classes that implement IComponent. I believe that is used by WPF.
what I mean by that is:
I basically have a class that has too many properties and functions now. To remain performant and understandable, it needs to shrink somehow. But I still need all those properties and methods somewhere.
It's like this right now:
class Apple
float seedCount;
...
...about 25 variables and properties here.
void Update() <-- a huge method that checks for each property and updates if so
In most cases the class needs almost none of those properties. In some cases in needs to be able to grow very selectively and gain a feature or lose a feature.
The only solution I have come up with, is that I create a bunch of classes and place some properties in there. I only initialize this classes object when one of those properties is needed, otherwise it remains null.
class Apple
Seed seed;
Many problems because of that:
I constantly have to check for every single object and feature each frame. If the seed is not initialized I don't have to calculate anything for it. If it is, I have to.
If I decided to put more than 1 property/feature into the Seed class, I need to check every single one of those aswell.
It just gets more and more complicated. The problem I have is therefore, that I need granular control over all the features and can't split them intelligently into larger subclasses. Any form of subclass would just contain a bunch of properties that need to be checked and updated if wanted.
I can't exactly create subclasses of Apple, because of the need for such high granular control. It would be madness to create as many classes as there are combinations of properties.
My main goal: I want short code.
It would be madness to create as many classes as there are combinations of properties.
Sounds like you might be looking for the Decorator Pattern. It's purpose is to make it easier to manage objects that can have many different combinations of properties without an exponentially growing heirarchy. You just have one small subclass for each property or behavior (not necessarily one C# property, just something you can group together) and then you can compose them together at runtime.
In your case, each Apple decorator class will override your Update method, and make the calculations necessary for its parts, and then call base.Update to pass it to the next in line.
Your final answer will heavily depend on exactly what your "Apple" really is.
After reviewing your comments and samples in my other answer, I've thought about the Decorator pattern and how it was being used vs how you want things to work. I've come to the conclusion that Decorator is not right for this purpose. I'm thinking Strategy instead. I have modified the previous sample code for you to take a look at.
I've gotten rid of the decorators altogether. The Broodfather abstract class remains. It has two additional properties an IBroodfatherMagicAbility and an IBroodfatherBloodthirstAbility. This two properties will allow you to access the different attributes that pertain to those abilities, however the key to this all is that the strategy for implementing the abilities can change at runtime (see Strategy pattern).
There are two classes each that implement a "strategy" for both bloodthrist and magic.
IBroodfatherBloodthirstAbility.cs - this is the interface that all "bloodthirst strategies" must implement.
BroodfatherNonBloodThristy.cs - class that implements the attributes for non-bloodthirsty.
BroodfatherBloodThristy.cs - class that implements the attributes for bloodthirsty.
IBroodfatherMagicAbility.cs - this is the interface that all "magical strategies" must implement.
BroodfatherNonMagical.cs - class that implements a strategy for non-magical.
BroodfatherMagical.cs - class that implements a strategy for magical.
BasicBroodfather.cs - this is similar to the previous example, except that now when an instance is created the magic and bloodthrist properties get set to new instances of the non-magical and non-bloodthristy strategy objects.
Program.cs is the driver that shows the classes and how the different strategies can get swapped in and out at runtime.
I think you'll find that more suited to how you wanted things to work.
you may use a nested class in Apple class
http://msdn.microsoft.com/en-us/library/ms173120(VS.80).aspx
I think the key thing here is that you are trying to hold everything in one class. Because of that, the class must be constantly checking what it has and what it doesn't. The solution is to create subclasses or decorators that already know whether or not they have a particular thing. Then they don't have to be checking it each time.
Because you have so many properties which may be combined in different ways, it sounds like the decorator solution is more up your alley.
I think you're in the right path: composition. You compose your class with the other classes that are needed. But you also need to delegate responsibility accordingly. In your example, it's the Seed class that should be responsible for checking it's internal state, and Apple just delegates to it.
As for the optional features problem, maybe you can use null objects instead of null references. This way, you don't need to check for null everytime, and the code is more consistent.
I've been pondering this question for a bit and I've come up with an alternate solution. This may be a bit unorthodox and anti-object oriented, but if you're not faint of heart read on...
Building upon the Apple example: the Apple class can contain many properties, these properties which could be categorized into related groups. For the example I rolled with an Apple class with some properties related to the apple's seeds and others related to the apple's skin.
Apple
a. Seed
a1. GetSeedCount
a2. ...
b. Skin
b1. GetSkinColor
b2. ...
I'm using a dictionary object to store all the apples properties.
I wrote extension methods to define accessors to the properties, using different classes to keep them separate and organized.
By using a dictionary for the properties, you can iterate through all properties stored thusfar at any point (if you have to check all of them, as it sounded like you needed in your update method). Unfortunately you lose strong typing of the data (at least in my sample I did because I'm using a Dictionary< string, string>. You could have separate dictionaries for every type needed, but that would require more plumbing code to route the property access to the correct dictionary.
Using extension methods to define accessors to the properties allows you to separate the code for each logical categories of properties. This keeps things organized into separate chunks of related logic.
Here is a sample I came up with to test how this would work, given with the standard warning that if you were to continue down this path robustification would be in order (validation, error handling, etc.).
Apple.cs
namespace ConsoleApplication1
{
using System.Collections.Generic;
using System.Text;
public class Apple
{
// Define the set of valid properties for all apple objects.
private static HashSet<string> AllowedProperties = new HashSet<string>(
new string [] {
"Color",
"SeedCount"
});
// The main store for all properties
private Dictionary<string, string> Properties = new Dictionary<string, string>();
// Indexer for accessing properties
// Access via the indexer should be restricted to the extension methods!
// Unfortunately can't enforce this by making it private because then extension methods wouldn't be able to use it as they are now.
public string this[string prop]
{
get
{
if (!AllowedProperties.Contains(prop))
{
// throw exception
}
if (Properties.ContainsKey(prop))
{
return this.Properties[prop];
}
else
{
// TODO throw 'property unitialized' exeception || lookup & return default value for this property || etc.
// this return is here just to make the sample runable
return "0";
}
}
set
{
if (!AllowedProperties.Contains(prop))
{
// TODO throw 'invalid property' exception
// these assignments are here just to make the sample runable
prop = "INVALID";
value = "0";
}
this.Properties[prop] = value.ToString();
}
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
foreach (var kv in this.Properties)
{
sb.AppendFormat("{0}={1}\n", kv.Key, kv.Value);
}
return sb.ToString();
}
}
}
AppleExtensions.cs
namespace AppleExtensionMethods
{
using System;
using ConsoleApplication1;
// Accessors for Seed Properties
public static class Seed
{
public static float GetSeedCount(this Apple apple)
{
return Convert.ToSingle(apple["SeedCount"]);
}
public static void SetSeedCount(this Apple apple, string count)
{
apple["SeedCount"] = count;
}
}
// Accessors for Skin Properties
public static class Skin
{
public static string GetSkinColor(this Apple apple)
{
return apple["Color"];
}
public static void SetSkinColor(this Apple apple, string color)
{
apple["Color"] = ValidSkinColorOrDefault(apple, color);
}
private static string ValidSkinColorOrDefault(this Apple apple, string color)
{
switch (color.ToLower())
{
case "red":
return color;
case "green":
return color;
default:
return "rotten brown";
}
}
}
}
Here is a test drive:
Program.cs
namespace ConsoleApplication1
{
using System;
using AppleExtensionMethods;
class Program
{
static void Main(string[] args)
{
Apple apple = new Apple();
apple.SetSkinColor("Red");
apple.SetSeedCount("8");
Console.WriteLine("My apple is {0} and has {1} seed(s)\r\n", apple.GetSkinColor(), apple.GetSeedCount());
apple.SetSkinColor("green");
apple.SetSeedCount("4");
Console.WriteLine("Now my apple is {0} and has {1} seed(s)\r\n", apple.GetSkinColor(), apple.GetSeedCount());
apple.SetSkinColor("blue");
apple.SetSeedCount("0");
Console.WriteLine("Now my apple is {0} and has {1} seed(s)\r\n", apple.GetSkinColor(), apple.GetSeedCount());
apple.SetSkinColor("yellow");
apple.SetSeedCount("15");
Console.WriteLine(apple.ToString());
// Unfortunatly there is nothing stopping users of the class from doing something like that shown below.
// This would be bad because it bypasses any behavior that you have defined in the get/set functions defined
// as extension methods.
// One thing in your favor here is it is inconvenient for user of the class to find the valid property names as
// they'd have to go look at the apple class. It's much easier (from a lazy programmer standpoint) to use the
// extension methods as they show up in intellisense :) However, relying on lazy programming does not a contract make.
// There would have to be an agreed upon contract at the user of the class level that states,
// "I will never use the indexer and always use the extension methods!"
apple["Color"] = "don't panic";
apple["SeedCount"] = "on second thought...";
Console.WriteLine(apple.ToString());
}
}
}
Addressing your comment from 7/11 (the date, not the store) :)
In the sample code you provided, there is a comment that states:
"As you can see, I can't call
BasicBroodmother methods on "monster"
You realize you could do something like this at that point:
BasicBroodmother bm = monster as BasicBroodmother;
if (bm != null)
{
bm.Eat();
}
There isn't much meat to your code, (I understand it was just an example), but when I look at it I get the feeling that you should be able to improve the design. My immediate thought was having an abstract class for broodmother which would contain default implementations of any attributes/actions that are common to all broodmothers. Then specialized broodmothers, like the magical broodmother, would contain any specialized attributes/actions specific to the magical broodmother, but also inherit from the abstract class and if necessary override the nessecary base attributes/actions.
I would take a look at the Strategy pattern for the design of the actions so that the actions (i.e. behaviours like eat, spawn, attack) can be swappable based the type of monster.
[edit 7/13]
Don't have time to go into details right now (need sleep), but I put together some sample code showing a different approach.
The code consists of:
Broodfather.cs - abstract class filled with all things common to different Broodfathers "types."
BasicBroodFather.cs - concrete class that inherits from Broodfather.
BroodfatherDecorator.cs - abstract class to be inherited by all Broodfather decorators.
MagicalBroodfather.cs - this class decorates/wraps a Broodfather with "magic"
BloodthirstyBroodfather.cs - this class decorates/wraps a Broodfather with "bloodthirst"
program.cs - demonstrates two examples: The first starts with a basic broodfather that gets wrapped by magic then by bloodthirst. The second starts with a basic broodfather and wraps it in the other order bloodthirst, then magic.
Maybe your methods are not were they are supposed to be?
If you separated the Seed class from the Apple class, why don't you move the methods that use the Seed information to the Seed class too?
If those methods need information on other Apple properties, you can pass it as a parameter.
By doing this, I guess you can eliminate the initialization checks...
This is a great book about how to solve this kind of problem:
Refactoring
My main goal: I want short code.
Options:
Rewrite all functions as static and create a class for each one.
Rewrite your codebase in Perl.
Remove all comments.
Seen a few examples of code where this happens:
public class Foo
{
string[] m_workID;
public string[] WorkID
{
get
{
return m_workID;
}
private set
{
m_workID = value;
}
}
}
What's the point of this?
Since the use m_workID unnescessary.
In general, the point is to separate implementation (the field) from API (the property).
Later on you can, should you wish, put logic, logging etc in the property without breaking either source or binary compatibility - but more importantly you're saying what your type is willing to do, rather than how it's going to do it.
I have an article giving more benefits of using properties instead of public fields.
In C# 3 you can make all of this a lot simpler with automatically implemented properties:
public class Foo
{
public string[] WorkID { get; private set; }
}
At that point you still have a public getter and a private setter, but the backing field (and property implementation) is generated for you behind the scenes. At any point you can change this to a "normal" fully-implemented property with a backing field, and you'll still have binary and source compatibility. (Compatibility of serialized objects is a different matter, mind you.)
Additionally, in this case you can't mirror the behaviour you want (the ability to read the value publicly but write it privately) with a field - you could have a readonly field, but then you could only write to it within the constructor. Personally I wish there were a similar shorthand for this:
public class Foo
{
private readonly int id;
public int Id { get { return id; } }
...
}
as I like immutable types, but that's a different matter.
In another different matter, it's generally not a good idea to expose arrays like this anyway - even though callers can't change which array WorkID refers to, they can change the contents of the array, which is probably not what you want.
In the example you've given you could get away without the property setter, just setting the field directly within the same class, but it would mean that if you ever wanted to add logging etc you'd have to find all those writes.
A property by itself doesn't provide anywhere to put the data - you need the field (m_workID) for storage, but it entirely correct to hide that behind a property for many, many reasons. In C# 3.0 you can reduce this to:
public string[] WorkID {get; private set;}
Which will do much of the same. Note that exposing an array itself may be problematic, as there is no mechanism for protecting data in an array - at least with an IList<string> you could (if needed) add extra code to sanity check things, or could make it immutable. I'm not saying this needs fixing, but it is something to watch.
In addition to the Object Oriented philosophy of data encapsulation, it helps when you need to do something every time your property is read/write.
You can have to perform a log, a validation, or any another method call later in your development.
If your property is public, you'll have to look around all your code to find and modify your code. And what if your code is used as a library by someone else ?
If your property is private with appropriate get/set methods, then you change the get/set and that's all.
You can use C# 3.0 auto properties feature to save time typing:
public class Foo
{
public string[] WorkID
{
get; private set;
}
}
In addition properties gives you lot of advantages in comparison to fields:
properties can be virtual
properties hide implementation details (not all properties are just trivial variable accessors)
properties can contain validation and logging code and raise change events
interfaces cannot contains fields but properties
A lot of times you only want to provide read access to a field. By using a property you can provide this access. As you mention you may want to perform operations before the field is accessed (lazy loading, e.g.). You have a lot of code in there that just isn't necessary anymore unless you're still working in .Net 2.0-.