Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am working with C#.NET and basically have a page containing many areas.
In my code-behind, I basically want to be able to do something like:
bool result1 = MyClass.Section["area1"].Process();
bool result4 = MyClass.Section["area4"].Process();
I need to write a class that would call some kind of "Process" method and be able to have it accept a parameter like "area1" inside that method.
Any help on getting me started with this would be greatly appreciated, thank you!
Following the normal .NET naming conventions I'll assume you mean, by your example, that MyClass is being referenced statically rather than by instance (which may not be a big change). Given that assumption, it appears you have a class like:
static class MyClass
{
public static IIndexer Section { get; }
}
IIndexer in this case could be any type that implements an indexer property that takes a string and returns a type that has a method named Process which in turn returns a bool. IIndexer could theoretically look like:
interface IIndexer
{
ISomething this[string] { get; }
}
Next we'll fill in the ISomething blank above with a simple IProcess interface so we don't have to know anything about your specific implementation:
interface IProcess
{
bool Process();
}
So now the indexer above can be changed to:
IProcess this[string] { get; }
Of course, none of the above has any real executable code, but outlines the objects necessary to do what you're after. Now when you go to run your code using your fulfilled contracts the call chain is pretty simple:
bool result1 = MyClass.Section["area1"].Process();
// MyClass.Section > IIndexer.this[string] > IProcess.Process
To POC the idea, a good way to mock the IIndexer implementation might be to use Dictionary<string, IProcess> as it'll give you a usable indexer for your purposes.
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
Imagine I have the following class:
public class MyWeirdCollection
{
private IList<string> _myTrueList;
private IList<string> _myFalseList;
public MyCollection()
{
_myTrueList = new List<string>();
_myFalseList = new List<string>();
}
public void Add(string item, bool listType)
{
if (listType)
{
_myTrueList.Add(item);
}
else
{
_myFalseList.Add(item);
}
}
public IList<string> Get(bool listType)
{
return listType ? _myTrueList : myFalseList;
}
}
How would I go about unit testing the Get and Add methods? I'm doubting between 2 possible solutions:
Making the 2 lists protected instead of private, so I can create an inheriting TestableWeirdCollectionClass that exposes the content of the lists to the test
Leave the class as it is and test Add and Get together? i.e. calling Add to add some elements and then Get to see if the correct values come back.
I'm leaning towards option no. 2, but would like some more opinions. Thanks.
Definitely go for the option 2. Pretty much every test I can imagine must go though Add, then Get, together.
When testing you are ultimately testing the public interface, not the internal state. The whole idea of the test code is that you give items to it, then you get them back with the appropriate key. In your particular case it uses private lists to hold the items, but this may not be the case (you might store them to a database or file, rely on another class or something else). This is ultimately an implementation detail, the important bit is that Add and Get always play together, therefore you should it.
I would strongly recommend option 2. The reason is that your whole class should be consider a unit, and be tested as such. Making methods public for the sole purpose of unit testing can be motivated in some rare cases for very complex classes, but should be avoided if at all possible.
See also
Is it bad practice to make methods public solely for the sake of unit testing.
Would you rather make private stuff internal/public for tests, or use some kind of hack like PrivateObject
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I want to create an application that maintains a list of Computer objects, checks those objects for availability (using Ping) and if they're available use PSExec to add or remove users to/from the list of administrators.
Currently I can not figure out how to build my classes - which class should be responsible for what (I want to use the common patterns, such as SRP, as good as possible without "overkilling" it.).
When looking at the availability-check, should there be an "extra" class doing the ping request or should this be done by the computer object (instance) itself? If an extra class should be used, how should the computer (and other) object(s) be notified about the changed availability? With a Property?
Tho thoughts regarding this kind of stuff drives me crazy and prevents me from getting any further...
I know there is no correct answer as this is obviously a design and opinion question but I'd appreciate it if I could get an experts opinion here - hopefully this brings me back on track.
Hi I have come up with the following according to the description provided. The Computer class is adhering to SRP as it is only concerned with Computer objects. All the operations are delegated to specialized classes. Currently I have added only a class to check availability. We can also add a specialized class for adding removing users.
Open for discussion and refinement.
public class Computer
{
// properties of the computer class
public IList<User> Users;
// IAvailabiity checker
private readonly IAvailabilityChecker _checker;
// constructor
public Computer(IAvailabilityChecker checker)
{
this._checker = checker;
}
// operations
public void AddUser()
{
if (this._checker.IsAvailable())
{
// add user
}
}
public void RemoveUser()
{
}
}
public class User
{
}
public interface IAvailabilityChecker
{
bool IsAvailable();
}
public class AvailabilityChecker
{
public bool IsAvailable()
{
// availability checker logic
return true;
}
}
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I have a class with functions to read data files. When read the class stores this datas in public properties.
After that I write the content of the puplic properties into a database.
Then it repeates. This means I read again datas with this class.
Before it repeates I want to clean the class.
What is the best way to do it?
Is it better to clear the content of the public properties manually or is it better to dispose the class. Maybe this is the more elegant way to do it?
Let's assume your class looks similar to:
public class MyClass
{
public double IntField { get; set; }
public string StringField { get; set; }
}
And your application something like:
public class MyApp
{
public void Execute() {
var myClass = new MyClass();
// set properties
myClass.IntField = 123;
myClass.StringField = "Hello";
// save to DB
}
}
Each time your application runs, it will run the Execute method which will create a new instance of your class. This way all class properties will be empty or "clean" as you call it.
create new method , name it let say "clear_data" , call it before load data from function that do it . also may be you will need call it from destructor to prevent memory leaks (in case you have pointers that point to some allocated memory ).
What about Memento pattern? Might be useful for you:
https://www.codeproject.com/Articles/186184/Memento-Design-Pattern
Or, as already pointed out, you have 3 other good possibilities:
- Create a method Clear() that sets properties to default value,
- If you have some unmanaged resources, you can use IDisposable interface,
- Create static readonly property holding Empty instance of the class and reassign it. But I would go with Memento/Clear way.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
Imagine we have an interface like below:
public interface ISome
{
void MethodOne();
int MethodTwo();
string MethodThree();
}
A class implements the interface:
public class Some : ISome
{
// Implementation...
}
Here is how it may be used:
public class App
{
public App(ISome)
{
// This class needs the whole interface: All three methods
}
}
I have a new requirement and it only needs one method from it: MethodThree and it can use the implementation provided by Some. Now I have 2 options:
Use ISome in the new class, like App uses it. The problem with this is that the new class does not really depend on the whole interface but only one method.
Split the interface like this using inheritance:
public interface INewSome
{
string MethodThree();
}
public interface ISome : INewSome
{
void MethodOne();
int MethodTwo();
}
The benefits of the 2nd option are:
The new class will depend on INewSome
Some still implements the whole interface so existing code will not break.
Unit testing will be much clearer since we know we just need to mock/stub one method in INewSome
Questions
I cannot think of a benefit for option 1 aside from not having to introduce a new interface. Do you know of a benefit with option 1?
Do you have another suggestion?
Am I overlooking anything and is this good/bad design?
what you have done in the option 2 is correct and goes perfectly with the fourth goal which is Interface Segregation Principle
From Wikipedia many client-specific interfaces are better than one general-purpose interface
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I want to dynamically access classes in c# in the way like Java class.forName(). I have only found things like Class.forName() equivalent in .NET? but I don't want to create instances.
In detail: I have got a simple text file containing a list of classes. I read them using file.ReadLine() (so I have got all class names as strings) and then I want to execute the same static method on each class: class1.method(); class2.method; and so on. The classes all exist and I need to access them. How can I do that?
C# doesn't support static interfaces (or static members in interfaces), so unless you want to use factory classes (the usual approach), you'll need to use reflection to invoke the static method directly.
void Main()
{
Console.WriteLine(Type.GetType("A").GetMethod("Hi").Invoke(null, new object[] {}));
}
class A
{
public static string Hi() { return "Hi!"; }
}
You might want to use a fully-qualified name for the type to make this work really well. Using just the name of the type is tricky, especially when you're trying to invoke types from other assemblies (which you probably are, otherwise there'd be no reason to use reflection - just use a dictionary of delegates or whatever).
You can use System.Reflection to load the Assembly into memory and then drill down to the type followed by getting the required method and invoke.
Refer to the documentation
GetMethod
If you have names of your desired Type then you can use Type.GetType(string) method.
Example if you have a class like this :
namespace MeProgram.BusinessLogic
{
public class MeObject {}
}
Full class name of that object should be "MeProgram.BusinessLogic.MeObject".
Now you can use that name inside of Type.GetType(string) method like such :
string className = "MeProgram.BusinessLogic.MeObject";
Type classType = Type.GetType(className);