0

As per this anwer methods that do I/O are not 'pure functions' and shouldn't be static. On the other hand this highly upvoted answer makes me think if I don't need any object to call a method it should be static.

I have a class that simply helps in fetching data over a URL. The class has exactly 1 method that does some url preprocessing and calls apache's IOUtils underneath. Should it or should it not be static. The class doesn't have any state and the only state it can modify is outside itself.

  1. I know static methods are hard to test but that feels more an artifact of not having proper dependency injected rather than using a static method. [1]
  2. If static methods that do I/O are scorned upon, why does apache's IOUtils have static methods that fetch bytes from a URL etc. (example : https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/IOUtils.html#toByteArray(java.net.URL))

[1] Why is injecting classes with static methods hard. Is this by design? I mean, I don't want to be forced to pass in a java.lang.Class and use reflection to call the static method -- that feels scary and ugly at the same time. All I want is the ability to pass in a reference to a class (not an object) that has some functionality. Even testing framework PowerMock that supports mocking static methods does it by hacking bytecode and I want to avoid that if possible.

What is the general guidance around this?

  • 1
    If you don't need an object, your method can surely be static. – Stefan Reich Dec 07 '17 at 01:42
  • sure. but that violates the 'no I/O in static methods' school of thought. Additionally, how do I test? – Kedar Mishra Dec 07 '17 at 01:51
  • Which part of the code are you trying to test? The static method that does IO or code that depends on this static method? In general mocking an object in Java is much easier than mocking a class, because with the later basically we need to intercept the class loading process. – xiaofeng.li Dec 07 '17 at 01:51
  • I have no idea why anyone would say "no I/O in static methods". Java functions aren't required to be "pure" anyway. Ah, maybe to allow for mocking/virtualizing. OK, I get that. That's a general decision then - allow for virtualization or not. – Stefan Reich Dec 07 '17 at 01:52
  • @xiaofeng.li : I should have been clearer, sorry my bad. I am talking about testing the code that uses this class which has the static method. I agree with you it requires intercepting class loading etc. My question is, why is it so hard? Is this by design to discourage static methods that make external calls? – Kedar Mishra Dec 07 '17 at 01:56
  • Do not assume that Apache projects are examples of good design. Many are not. – VGR Dec 07 '17 at 03:48

0 Answers0