Using the TDD Approach and Avoiding Java Static Methods

I just got some feedback on the Java exercise on applying application apps. They did not like the solution and the two problems mentioned in the reviews (which I am very grateful for the very rare feedback given):

  • I apparently did not use the TDD approach.
  • I abused static methods, I know that static methods are anti OO, but I used them only in methods of checking and using types.

So, two questions:

What are the possible telltale signs for using the TDD approach?

What style or coding patterns can be an alternative to static methods?

After the first two answers, I have another question.

Do you agree that using static methods is only bad when it limits the testability of your code, and not by itself.

So, back to my decision to use the application, if the static methods do not limit the testability of my code, is it still bad to use? my validation method was very simple: "Validator.notNull (p," paramName ")", why would I ever want to mock it?

Thank you very much.

+4
source share
2 answers

A tell-tale sign of not using TDD is the use of static methods and static class members for collaborators. You cannot override the static method, so you cannot substitute the layout for testing the class using such methods separately.

Instead of using static collaborators or static methods for collaborators, you can use dependency injection. In a simple coding exercise, you must enter the dependency through the constructor or through the setters manually. In real life, you can use one of the available dependency structures.

+3
source

Your static Validaton method seems like something that should be part of an object for me.

Say you have a Drink class

 public class Drink { private readonly string _name; private readonly double _temperature; public Drink(string name, double temperature) { _name = name; _temperature = temperature; } } 

Your business logic will be able to create all kinds of drinks, 7up, cola, whatever. You want to make sure that the drink has the right temperature to drink it, so you need the Validate method. You can follow your approach:

 public void TakeAZip() { if (Validation.HasAppropriateTemp) { // implement drink } } 

Alternatives for static classes

Thus, you have a strong dependency on your static Validation class.

Alternatively, you can use dependency injection .

 public void TakeAZip(ITemperatureValidator validator) { if (validator.HasAppropriateTemp) { // implement drink } } 

If more convenient, you can also pass Validator through the constructor

  private readonly string _name; private readonly double _temperature; private ITemperatureValidator _validator; public Drink( string name, double temperature, ITemperatureValidator validator) { _name = name; _temperature = temperature; _validator = validator; } 

Now you can mock the behavior of your validator, and you can isolate your Drink class from all external actions.

+2
source

All Articles