Win a copy of TensorFlow 2.0 in Action this week in the Artificial Intelligence and Machine Learning forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Paul Clapham
  • Bear Bibeault
  • Jeanne Boyarsky
Sheriffs:
  • Ron McLeod
  • Tim Cooke
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Jj Roberts
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • salvin francis
  • Scott Selikoff
  • fred rosenberger

DRY, when it is worth to create an interface

 
Greenhorn
Posts: 18
1
IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have got a small method, like:


or any other small method. It is needed in two classes. Should I create it in both classes? Or should I make an interface just for this one method? Isnt it form over substance? What is the rule in such cases?
 
Saloon Keeper
Posts: 12431
269
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There's no hard rule, but in general if you find yourself repeating code, even if it's just twice, you will want to extract the code and make it callable from the original locations.

Where to put the method depends on what the relationship between the classes where it is used is. Most of the times the classes are in the same package, and you can put a so called 'Utility class' in the same package that contains static helper methods.

Speaking of which, you aught to make your methods static if they don't access instance members and don't override a base method.
 
Marshal
Posts: 70684
288
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
...and utility class methods are usually all static.

That return statement looks complicated. What does that utility method do that you can't do with String#isBlank() or String#isEmpty()? Do you really want an Optional[""]? What is going to happen if you pass null to that method?
 
I'm thinking about a new battle cry. Maybe "Not in the face! Not in the face!" Any thoughts tiny ad?
the value of filler advertising in 2020
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic