Using TDD approach and avoiding Java static methods - methods

I just got some feedback about a job application Java coding exercise. They did not like the solution and two problems where stated in the feedback (which I'm very grateful for as it's very rare feedback is given):
I did not use TDD approach, apparently.
I overused static methods, I know static methods are anti OO but I only used them in validation and util type methods.
So two questions here:
What are the possible tell-tale signs of not using TDD approach?
What coding style or patterns can be an alternative to static methods?
Following the first two responses I have another question.
Do you agree that using static methods is only bad when it limits the testability of your code and not in them selves bad.
So going back to my job application exercise solution if the static methods do not limit the testability of my code is it still bad to use? my validate method was very simple 'Validator.notNull(p,"paramName")' now why would I ever want to mock that?
Many thanks.

A tell-tale sign of not using TDD is usage of static methods and static class members for collaborators. You cannot override a static method, so you cannot substitute a mock to test the class using such methods in isolation.
Instead of using static collaborators or static methods on the collaborators, you can use dependency injection. In a simple coding exercise you would inject dependency via a constructor or via the setters by hand. In the real life you can use one of available dependency frameworks.

Your static Validaton method seems something that should be part of an object to me.
Say you have an class Drink
public class Drink
{
private readonly string _name;
private readonly double _temperature;
public Drink(string name, double temperature)
{
_name = name;
_temperature = temperature;
}
}
Your businesslogic would be able to instantiate all kinds of drinks, 7up, cola, whatever. You'd like to make sure that a drink has the appropriate temperature to drink it, so you have the need for a Validate method. You could follow your approach:
public void TakeAZip()
{
if (Validation.HasAppropriateTemp)
{
// implement drink
}
}
'
Alternatives for static classes
That way you have an hard dependency on your static Validation class.
Alternatively you could make use of dependency injection.
public void TakeAZip(ITemperatureValidator validator)
{
if (validator.HasAppropriateTemp)
{
// implement drink
}
}
If more convenient you could also choose to pass the Validator via 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 behavior.

Related

How to perform Tests for DTOs?

I am creating a class to store the tests of all DTO classes, but currently I only manage to cover 10% of the coverage. I need to know how to do the #Tests for the DTOs.
My DTO:
#Data
#NoArgsConstructor
public class ActivityDTO {
private Integer id;
private Integer version;
#JsonProperty("working_days")
private MonthWorkingDays workingDays;
}
My Test class:
#Test
public void ActivityDTOTest() {
ActivityDTO obj = BeanBuilder.builder(ActivityDTO.class).createRandomBean();
}
This is the coverage:
My problem: I don't know how to test the DTO class, I'm testing with assertEquals but I don't know how to apply it. Can someone put what the Test class would be like for this DTO class and thus be able to replicate it in the other classes?
This might be subjective, but in general you should not test to increase the coverage, instead you should always think "what exactly" the test checks.
In a nutshell, there can be two things to be tested:
A state of the object
A behavior
Most of the tests usually (arguably, but at least this is what I usually do in my project) tend to check the behavior that is technically implemented as a business logic inside the methods.
Since the DTOs do not really have methods with the logic, you can only test the state of the object.
Another idea: there is no point in checking the code that you haven't written. So yes, following your example in the question, putting lombok annotations will generate some getters/setters/constructors - but its not your code, the proper handling of these annotations was supposed to be checked by lombok team itself.
What you can do if you really want to test DTOs is generate the one with some default values and check that its internal state indeed matches the expected. Something like this:
public class ActivityDTO {
private Integer id;
private Integer version;
// getters / setters maybe
}
#Test
public void test_state_is_correct() {
ActivityDTO underTest = new ActivityDTO(SAMPLE_ID, SAMPLE_VERSION);
assertThat(underTest.getId(), equalTo(SAMPLE_ID));
assertThat(underTest.getVersion(), equalTo(SAMPLE_VERSION));
}
#Test
public void test_equals_two_objects_with_same_values() {
ActivityDTO underTest = new ActivityDTO(SAMPLE_ID, SAMPLE_VERSION);
assertThat(underTest, equalTo(new ActivityDTO(SAMPLE_ID, SAMPLE_VERSION));
}
#Test
public void test_equals_two_objects_with_different_id() {
ActivityDTO underTest = new ActivityDTO(SAMPLE_ID, SAMPLE_VERSION);
assertThat(underTest, not(equalTo(new ActivityDTO(ANOTHER_SAMPLE_ID, SAMPLE_VERSION));
}
#Test
public void test_equals_two_objects_with_different_version() {
ActivityDTO underTest = new ActivityDTO(SAMPLE_ID, SAMPLE_VERSION);
assertThat(underTest, not(equalTo(new ActivityDTO(SAMPLE_ID, ANOTHER_SAMPLE_VERSION));
}
... test for toString()... and hashCode maybe, etc.
This will make the coverage tool happy for sure, but the real question is will it make your code better (more robust and less buggy, etc)?
One thing for sure - these tests are time consuming, boring, and probably give less value to the project. To overcome the frustration of the programmers who absolutely need to write these tests there are even tools for automatic testing of these simple java beans (DTO can be viewed as a java bean), to name a few:
https://github.com/codebox/javabean-tester
https://code.google.com/archive/p/junit-javabean-runner/
http://javabeantester.sourceforge.net/
Now the entirely different story is if you test the behavior of some service or DAO that, say, generates the DTO - these tests whether they're unit or integration tests are really needed. They'll also increase the coverage of the project (and maybe even will cover the code of the DTO, although its not their primary goal), but I would suggest to start writing these tests first.
I don't know what is the best practice but AFAIK you should exclude the DTO classes from the configuration and you don't have to write unit test for them.
If you are using JaCoCo plugin, you better check this out: How to exclude certain classes from being included in the code coverage? (Java)

Annotations for Java enum singleton

As Bloch states in Item 3 ("Enforce the singleton property with a private constructor or an enum type") of Effective Java 2nd Edition, a single-element enum type is the best way to implement a singleton. Unfortunately the old private constructor pattern is still very widespread and entrenched, to the point that many developers don't understand what I'm doing when I create enum singletons.
A simple // Enum Singleton comment above the class declaration helps, but it still leaves open the possibility that another programmer could come along later and add a second constant to the enum, breaking the singleton property. For all the problems that the private constructor approach has, in my opinion it is somewhat more self-documenting than an enum singleton.
I think what I need is an annotation which both states that the enum type is a singleton and ensures at compile-time that only one constant is ever added to the enum. Something like this:
#EnumSingleton // Annotation complains if > 1 enum element on EnumSingleton
public enum EnumSingleton {
INSTANCE;
}
Has anyone run across such an annotation for standard Java in public libraries anywhere? Or is what I'm asking for impossible under Java's current annotation system?
UPDATE
One workaround I'm using, at least until I decide to actually bother with rolling my own annotations, is to put #SuppressWarnings("UnusedDeclaration") directly in front of the INSTANCE field. It does a decent job of making the code look distinct from a straightforward enum type.
You can use something like this -
public class SingletonClass {
private SingletonClass() {
// block external instantiation
}
public static enum SingletonFactory {
INSTANCE {
public SingletonClass getInstance() {
return instance;
}
};
private static SingletonClass instance = new SingletonClass();
private SingletonFactory() {
}
public abstract SingletonClass getInstance();
}
}
And you can access in some other class as -
SingletonClass.SingletonFactory.INSTANCE.getInstance();
I'm not aware of such an annotation in public java libraries, but you can define yourself such a compile time annotation to be used for your projects. Of course, you need to write an annotation processor for it and invoke somehow APT (with ant or maven) to check your #EnumSingleton annoted enums at compile time for the intended structure.
Here is a resource on how to write and use compile time annotations.

How to inject ISession into Repository correctly?

Please correct me on the following scenario. ( Question is at the end)
(I asked a similar question that was un-organized and it was voted to close. So I have summarized the question here into a scope that can be replied with exact answers.)
I am developing a web application with multiple layers using nhibernate as ORM. My layer structure is as follow
Model Layer
Repository Layer
Services Layer
UI Layer
with the above layers, the classes and interfaces are placed as below.
ProductController.cs (UI Layer)
public class ProductController : Controller
{
ProductServices _ProductServices;
NHibernate.ISession _Session;
public ProductController()
{
_Session = SessionManager.GetCurrentSession();
_ProductServices = new ProductServices(
new ProductRepository(), _Session);
}
// Cont..
}
ProductServices.cs (Service Layer)
public class ProductServices : IProductServices
{
protected IProductRepository _ProductRepository;
protected NHibernate.ISession _Session;
public ProductServices(IProductRepository productRepository,
NHibernate.ISession session)
{
_ProductRepository = productRepository;
_Session = session;
_ProductRepository.SetSession(_Session);
}
// cont...
}
ProductRepository.cs (Repository Layer)
public class ProductRepository : IProductRepository
{
NHibernate.ISession _Session;
public void SetSession(NHibernate.ISession session)
{
_Session = session;
}
public IEnumerable<Product> FindAll()
{
return _Session.CreateCriteria<Product>().List<Product>();
}
//cont..
}
From the UI layer, I create the session as request per session and inject into service layer with the help of class constructor. Then set the session of repository with a help of a method.
I am afraid if I pass the _Session directly to repository as constructor, I will not have the control over it under the service layer. Also there is a future extension plan for using a webservice layer.
** Is there a way to ensure in each method of ProductRepository class that _Session is set already, without writing the piece of code if(_Session==null) in each and every method as it is repeating the same code.
** If the above pattern is wrong, Please show me a right way to achieve this goal.
What you are doing amazed me a bit. You applying the constructor injection pattern in the ProductService, which is definitely the way to go. On the other hand you are not injecting the dependencies into the ProductController, but that class is requesting one of those dependencies through a static class (this is the Service Locator anti-pattern) and creates a ProductServices class itself. This makes this class hard to test and makes your application less flexible and maintainable, since you can't easily change, decorate or intercept the use of the ProductServices class, when it's been used in multiple places.
And although you are (correctly) using constructor injection for the dependencies in the ProductServices, you are passing those dependencies on to the product repository, instead of applying the constructor injection pattern on the ProductResopistory as well.
Please show me a right way to achieve this goal.
The right way is to apply the constructor injection pattern everywhere. When you do this, your code will start to look like this:
public class ProductController : Controller
{
private ProductServices _ProductServices;
public ProductController(ProductServices services)
{
_ProductServices = services;
}
// Cont..
}
public class ProductServices : IProductServices
{
private IProductRepository _ProductRepository;
public ProductServices(
IProductRepository productRepository)
{
_ProductRepository = productRepository;
}
// cont...
}
public class ProductRepository : IProductRepository
{
private ISession _Session;
public ProductRepository (ISession session)
{
_Session = session;
}
public IEnumerable<Product> FindAll()
{
return _Session
.CreateCriteria<Product>().List<Product>();
}
//cont..
}
See how each class only takes in dependencies that it uses itself. So the ProductController and ProductServices don't depend on ISession (I made the assumption that only ProductRepoistory needs ISession). See how -from a class's perspective- everything is much simpler now?
Did we actually solve a problem here? It seems like we just moved the problem of wiring all classes together up the dependency graph. Yes we did move the problem. And this is a good thing. Now each class can be tested in isolation, is easier to follow, and the application as a whole is more maintainable.
Somewhere in the application however, a ProductController must be created. This could look like this:
new ProductController(
new ProductServices(
new ProductRepository(
SessionManager.GetCurrentSession())));
In its normal configuration, ASP.NET MVC will create controller classes for you, and it needs a default constructor to do so. If you want to wire up controllers using constructor injection (which you should definitely do), you need to do something 'special' to get this to work.
ASP.NET MVC allows you to override the default ControllerFactory class. This allows you to decide how to create controller instances. However, when your application starts to grow, it will get really awkward very quickly when you are creating your dependency graphs by hand (as my last example shows). In this case, it would be much better to use a Dependency Injection framework. Most of them contain a feature / package that allows you to integrate it with ASP.NET MVC and automatically allows to use constructor injection on your MVC controllers.
Are we done yet? Well... are we ever? There's one thing in your design that triggered a flag in my brain. Your system contains a class named ProductServices. Although a wild guess, the name Services seems like you wrapped all product related business operations inside that class. Depending on the size of your system, the number of people on your team, and the amount of changes you need to make, this might get problematic. For instance, how to you effectively apply cross-cutting concerns (such as logging, validation, profiling, transaction management, fault tolerance improvements) in such way that to system stays maintainable?
So instead of wrapping all operations in a single ProductServices class, try giving each business transaction / use case its own class and apply the same (generic) interface to all those classes. This description might be a bit vague, but it is a great way to improve the maintainability of small and big systems. You can read more about that here.
You can use a dependency injection container such as Autofac to instantiate your session and manage the lifetime of it. Leave the responsibility of instantiating the session to Autofac and simply inject the ISession interface into any classes that require the dependency. Have a look at this post: Managing NHibernate ISession with Autofac
You will also find this wiki page useful about configuring Autofac with MVC3: http://code.google.com/p/autofac/wiki/MvcIntegration3

How to reduce number of injected dependencies on controller

I am using MVC3, Entity Framework v4.3 Code First, and SimpleInjector. I have several simple classes that look like this:
public class SomeThing
{
public int Id { get; set; }
public string Name { get; set; }
}
I have another entity that looks like this:
public class MainClass
{
public int Id { get; set; }
public string Name { get; set; }
public virtual AThing AThingy { get; set; }
public virtual BThing BThingy { get; set; }
public virtual CThing CThingy { get; set; }
public virtual DThing DThingy { get; set; }
public virtual EThing EThingy { get; set; }
}
Each Thingy (currently) has its own Manager class, like so:
public class SomeThingManager
{
private readonly IMyRepository<SomeThing> MyRepository;
public SomeThingManager(IMyRepository<SomeThing> myRepository)
{
MyRepository = myRepository;
}
}
My MainController consequently follows:
public class MainController
{
private readonly IMainManager MainManager;
private readonly IAThingManager AThingManager;
private readonly IBThingManager BThingManager;
private readonly ICThingManager CThingManager;
private readonly IDThingManager DThingManager;
private readonly IEThingManager EThingManager;
public MainController(IMainManager mainManager, IAThingManager aThingManager, IBThingManager bThingManager, ICThingManager cThingManager, IDThingManager dThingManager, IEThingManager eThingManager)
{
MainManager = mainManager;
AThingManager = aThingManager;
BThingManager = bThingManager;
CThingManager = cThingManager;
DThingManager = dThingManager;
EThingManager = eThingManager;
}
...various ActionMethods...
}
In reality, there are twice as many injected dependencies in this controller. It smells. The smell is worse when you also know that there is an OtherController with all or most of the same dependencies. I want to refactor it.
I already know enough about DI to know that property injection and service locator are not good ideas.
I can not split my MainController, because it is a single screen that requires all these things be displayed and editable with the click of a single Save button. In other words, a single post action method saves everything (though I'm open to changing that if it makes sense, as long as it's still a single Save button). This screen is built with Knockoutjs and saves with Ajax posts if that makes a difference.
I humored the use of an Ambient Context, but I'm not positive it's the right way to go.
I humored the use of injecting a Facade as well.
I'm also wondering if I should implement a Command architecture at this point.
(Don't all of the above just move the smell somewhere else?)
Lastly, and perhaps independent of the three above approaches, is should I instead have a single, say, LookupManager with explicit methods like GetAThings(), GetAThing(id), GetBThings(), GetBThing(id), and so on? (But then that LookupManager would need several repositories injected into it, or a new type of repository.)
My musings aside, my question is, to reiterate: what's a good way to refactor this code to reduce the crazy number of injected dependencies?
Using a command architecture is a good idea, since this moves all business logic out of the controller, and allows you to add cross-cutting concerns without changes to the code. However, this will not fix your problem of constructor over-injection. The standard solution is to move related dependencies into a aggregate service. However, I do agree with Mark that you should take a look at the unit of work pattern.
Have you considered using a unit of work design pattern? There is a great MSDN post on what a unit of work is. An excerpt from that article:
In a way, you can think of the Unit of Work as a place to dump all
transaction-handling code. The responsibilities of the Unit of Work
are to:
Manage transactions.
Order the database inserts, deletes, and updates.
Prevent duplicate updates. Inside a single usage of a Unit of Work object, different parts of the code may mark the same Invoice
object as changed, but the Unit of Work class will only issue a
single UPDATE command to the database.
The value of using a Unit of Work pattern is to free the rest of your
code from these concerns so that you can otherwise concentrate on
business logic.
There are several blog posts about this, but the best one I've found is on how to implement it is here. There are some other ones which have been referred to from this site here, and here.
Lastly, and perhaps independent of the three above approaches, is
should I instead have a single, say, LookupManager with explicit
methods like GetAThings(), GetAThing(id), GetBThings(), GetBThing(id),
and so on? (But then that LookupManager would need several
repositories injected into it, or a new type of repository.)
The unit of work would be able to handle all of these, especially if you're able to implement a generic repository for most of your database handling needs. Your tag mentions you're using Entity Framework 4.3 right?
Hope this helps!
I think your main issue is too many layers of abstraction. You are using Entity Framework, so you already have a layer of abstraction around you data, adding two more layers (one per entity) via a Repository and a Manager interface has led to the large number of interfaces your controller depends upon. It doesn't add a whole lot of value, and besides, YAGNI.
I would refactor, getting rid of your repository and manager layers, and use an 'ambient context'.
Then, look at the kinds of queries your controller is asking of the manager layers. Where these are very simple, I see no problems querying your 'ambient context' directly in your controller - this is what I would do. Where they are more complicated, refactor this into a new interface, grouping things logically (not necessarily one per Entity) and use your IOC for this.

Java - how to design your own type?

Is it possible to design your own Java Type, similar to an extensible enum?
For instance, I have user roles that a certain module uses and then a sub-package provides additional roles.
What would be involved on the JDK side of things?
Since Enums can't be extended, you have to fake it.
Make a class with a protected constructor.
Then you can create public static final FakeEnum instances in your class.
public class FakeEnum {
private String name;
private Object something;
protected FakeEnum(String name, Object otherParam) {
this.name = name;
this.something = otherParam;
}
// public getters
public static final FakeEnum ONE = new FakeEnum("one", null);
public static final FakeEnum TWO = new FakeEnum("two", null);
public static final FakeEnum THRE = new FakeEnum("thre", null);
}
And then you can extend it and add some more things to it like so:
public class ExtendedFakeEnum extends FakeEnum {
public static final FakeEnum EXTENDED_ONE = new FakeEnum("extended_one", null);
public static final FakeEnum EXTENDED_TWO = new FakeEnum("extended_two", null);
}
Ok,
What I will do is write an interface and then several implementations for how to find users to notify in a particular event. The correct implementation will get injected at run-time and then it will do whatever it needs to do to find the correct users. That implementation may simply take arguments to configure the group name to look for and then return a list of users.
I am learning to use interfaces / design by contract more. Most of my development in the past has only ever had a single implementation so I saw this as a moot point and forgot about that tool / means.
Thanks,
Walter
The concept of an extensible enum doesn't make sense. An enum is used to declare statically the entire set of instances that will ever be made for its own type. Allowing it to be extended would make that impossible to ensure.
Designing your own type in Java is impossible. Anything you need to do can be done using various design patterns.
If you need an "extensible enum" it might be that a dictionary would suit you better, look at java.util.Dictionary<K,V> where K is the keyname (how you would refer to the particular value, and V is the value/object that should be returned by said Key.
I think thats the closest I've ever come to an extensible Enum.
Also, have a look at this question on SO, this might solve it too.

Resources