Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Monday, December 21, 2015

Try to avoid using Static Methods in your code

I have been coming across allot of static code in the projects I work on.  It really makes practicing TDD, or any unit testing, a pain because static methods are not easily mocked.   Static methods also force your code to be highly coupled.  

A better approach is to not use static methods and instead use dependency injection.   This lends itself to being a better testable decoupled approach. 

Here are a few articles I have come across that do a pretty good job better explaining why you should try to avoid using Static in object oriented languages:

Wednesday, January 8, 2014

Duplicate entries put into HashSet Java issue

I have recently run into an issue using HashSet.addAll(Object) where duplicates are added to my Set.

I even made sure that the Object I was using Overrode hashCode().

Apparently the addAll() implementation for HashSet doesn't check for duplicates.  This is bad because a reason for using a Set over a List is to avoid duplicate values.

If you loop through all of the values in the collection you are adding to the Set it works as expected not adding the duplicates.  This is the approach I took to get around this issue.

for (item in myCollection){
    set.add(item)
}

vs what I was trying to do which didn't work:

set.addAll(myCollection)

Another approach could be extend the HashSet and override the addAll() with the logic I used.