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
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 3 years ago.
Improve this question
I like the DI feature of ASP.NET Core, but am finding that some of my classes end up with huge constructor parameter signatures...
public class Foo {
private IBar1 _bar1;
private IBar2 _bar2;
// lots more here...
public Foo(IBar1 bar1, IBar2 bar2, lots more here...) {
_Bar1 = bar1;
_Bar2 = bar2;
// ...
}
public DoSomething() {
// Use _bar1
}
}
In case this looks like a code smell, it's worth pointing out that any controller is going to use AutoMapper, an email service and 2 or 3 managers related to ASP.NET Identity, so I have 4 or 5 dependencies before I start injecting a single repository. Even if I only use 2 repositories, I can end up with 6 or 7 dependencies without actually violating any SOLID principles.
I was wondering about using a parameter object instead. I could create a class that has a public property for every injected dependency in my application, takes a constructor parameter for each one, and then just inject this into each class instead of all the individual Bars...
public class Foo {
private IAllBars _allBars;
public Foo(IAllBars allBars) {
_allBars = allBars;
}
public DoSomething() {
// Use _allBars.Bar1
}
}
The only disadvantage I can see is that it would mean that every class would have every dependency injected into it via the parameter object. In theory, this sounds like a bad idea, but I can't find any evidence that it would cause any problems.
Anyone any comments? Am I letting myself into potential trouble by trying to make my constructor code neater?
What you're describing sounds like the service locator pattern, and while it seems tempting to simplify your code by eliminating all those constructor parameters, it usually ends up hurting maintainability in the long run. Check out Mark Seemann's post Service Locator violates encapsulation for more details about why it should be avoided.
Generally, when you find yourself with a class with dozens of constructor parameters, it means that class might have too many responsibilities. Can it be decomposed into a number of smaller classes with narrower goals? Rather than introducing a "catch-all" class that knows about everything, maybe there's a complex part of your application that you can abstract behind a facade.
Sometimes, you do end up with large coordinator classes that have many dependencies and that's okay in certain circumstances. However, if you have many of these it's usually a design smell.
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 method set in an POCO entity that set the basic property and the navigation property. In some cases, I don't need to verify some conditions, but in another cases I need to verify to ensure that the information is coherent in the database, but this verification makes me to get extra data from database.
So by the moment I have my basic method that is this:
public void setMyProperty(MyType paramProperty)
{
this.Property = paramProperty;
this.IDProperty = paramProperty.IDPorperty;
paramProperty.MyNavigationCollection.Add(this);
}
For the method that verifies the data, I guess that I have two options.
First one, I can create a new method for business logic, somthing like that:
public void setPropertyBi(MyType paramProperty)
{
//check conditons
//If all OK then
this.setPorperty(paramProperty);
}
But I have another option, use only one method, not the basic method and the other for business checks. Something like that:
public void setProperty(MyType paramType, bool paramDoChecks)
{
if(paramDoChecks)
{
//Do checks
}
//if all OK
this.Property = paramProperty;
this.IDProperty = paramProperty.IDPorperty;
paramProperty.MyNavigationCollection.Add(this);
}
Which is the recommended option? or there are another ways?
People here seem to prefer the flag, I personally think it is horrible.
You want to achieve two different things: just set a property; validate AND set a property. IMHO it should be two separated methods.
Just don´t write two different Methods if it´s one equaly functionality. Just add a Parameter which makes the validation-difference like you´ve written last.
But don´t forget to enter the behaviour if validation failed. separate it well.
You could add a Boolean ValidationRequiredproperty to MyType which you can set before the call to setMyProperty().
I prefer to have two methods: CanSetProperty and SetProperty.
CanSetProperty: just check the condition, does not change anything in the parameter.
SetProperty: will modify the paramenter.
I think this code is a good candidate to follow the Command Query Separation Pattern
The fundamental idea is that we should divide an object's methods into
two sharply separated categories:
Queries: Return a result and do not change the observable state of the
system (are free of side effects).
Commands: Change the state of a
system but do not return a value.
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 5 years ago.
Improve this question
I have huge class that implements usage of some client:
public class Client : IClient
{
internal Client(string username, string password){
//login process here
}
//some private methods that make sure connection stays alive, etc
public void Action1(string param1){
//something here...
}
public void Action2(string param1, string param2){
//something else here...
}
}
As it currently is, it's 5000+ lines long mainly because of lots of different public methods.
I'm wondering what is the best practice to properly organize and refactor this, preferably without making method calls more complicated?
Use partial classes and group things into logical sets per each partial class.
Also, if some methods make logical set, consider wrapping them into separate class.
Those 2 should reduce your lines of code per file dramatically.
Usually big class are "hiding" inside other classes (see uncle Bob on "Clean Code").
In your case I'd split the class creating Action classes and making some machanics that lets the Client use some sort of IAction or BaseAction. Thus splitting the logic of every action into a separate class.
To be more precise I'd rather need some more info and code.
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'm trying to improve my coding standards by implementing interfaces and abstract classes when necessary, however I would like to ask about practises regarding abstract classes.
I'm creating a web application and one aspect of the site I need to do some data processing, I have created an abstract class and it looks something like this.
public abstract class TestAbstractClass
{
public abstract void doDataProcessing();
}
And I need to implement this 'doDataProcessing' method a few times throughout the application dependent on where the user is on my site, it will do VERY similar data processing, just with one or two different things.
For example:
User is on certain page:
public Page1Class: TestAbstractClass
{
public override void doDataProcessing()
{
//do data processing
}
}
User is on another page
public Page2Class: TestAbstractClass
{
public override void doDataProcessing()
{
//do data processing but with slight change
}
}
User is on another page
public Page3Class: TestAbstractClass
{
public override void doDataProcessing()
{
//do data processing but with another change
}
}
Would this be best practise? Or is it better just making one class, and just doing various conditional statements on what is being passed into the 'doDataProcessing()' method?
I feel if I do it using the method I have posted, I will be having a lot of duplicate code in these 3 classes, is that OK?
I hope this makes sense.
This feels like you need to decompose the solution a bit more. doDataProcessing sounds like it is something that could be broken into smaller pieces. There are high-level design patterns that could help you structure this.
If doDataProcessing is a similar thing but with small changes, then look at the Strategy pattern or the Decorator pattern.
If you are not going to have any implementation in the base doDataProcessing then just go with an interface as #phuzi recommended. Abstract classes are best used if you have some logic that is exactly the same in most cases, and in odd scenarios you can override and/or extend the base logic in the inherited classes.
EDIT
From the information you gave me I would probably do the following:
public abstract class TestAbstractClass
{
public void Process()
{
MethodThatGetsCalledEveryTime();
doDataProcessing();
}
public virtual void doDataProcessing()
{
// can add frequent logic here
}
protected void MethodThatGetsCalledEveryTime()
{
// do stuff here
}
}
this way you can ensure that the "MethodThatGetsCalledEveryTime" will always be called, and if you add additional logic to doDataProcessing that will run as well from the appropriate place.
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.