r/javahelp • • Jun 01 '21

Why would i bother making an Interface if i only have one Class using that Interface?

Is the only good reason that i "might" need it it the future? or is it other good reasons to start with that?

The class i am talking about is a Grid class. And i am making a grid based game.

18 Upvotes

17 comments sorted by

•

u/AutoModerator Jun 01 '21

Please ensure that:

  • Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions

  • You include any and all error messages in full

  • You ask clear questions

  • You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.

    Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar

If any of the above points is not met, your post can and will be removed without further warning.

Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.

Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.

Code blocks look like this:

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.

If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.

To potential helpers

Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

19

u/funnythrone Jun 01 '21

This is a highly opinionated subject, and there is no one right answer.

Having said that, I prefer there being an interface and coding to that interface even if there is only 1 implementation of it ever. The reason being it's much easier to mock an interface. Also, it's more of a personal preference for me as that is the style I'm used to. Slightly anecdotal, I have observed that if an interface is defined first, we clearly define the behaviour which is all we should care about. It doesn't impose any restrictions on the implementation, so theoretically it is possible to switch implementations at a later point of time. It also allows the option to have runtime decision of which implementation to use.

For your particular example, if you have only one implementation, you are free to not use an interface. If you later decide that you need a separate implementation of Grid, you will have to extract out the interface. This is trivial with most modern IDEs (example Intellij Idea). However, your usage of the Grid class might depend on internal implementation if there is only ever one implementation. If you have the discipline to avoid doing that, then it doesn't matter if you don't have an interface at the moment. Because if required later, you can extract the interface without breaking any functionality.

2

u/HecknChonker Extreme Brewer Jun 01 '21

The reason being it's much easier to mock an interface.

Why do you think this? I mock concrete classes all the time in my tests without any issues, and it's a single line of code.

var blah = mock(Blah.class);

6

u/philipwhiuk Employed Java Developer Jun 01 '21

I dunno who downvoted this. It's correct.

Creating interfaces for one implementation rarely improves design. It's hard to actually know what the interface really is until you have at least two implementations.

1

u/dued03 Jun 01 '21

I’m pretty new to Java, would you mind explaining the purpose of interfaces to me? I can’t seem to find an explanation online that explains why you would use one

5

u/wildjokers Jun 01 '21

You don't need to create an interface for only one implementation. Only create an interface if you actually have more than implementation. In the future if you actually do have more than one implementation it is quite easy to extract an interface (IDEs can do this for you).

People that still insist on having an interface even if there is only one implementation don't realize that practice started back when mocking frameworks could only mock interfaces. That is no longer the case so it is no longer needed. Create an interface only if you have more than implementation.

Here is Martin Fowlers take on it:

https://martinfowler.com/bliki/InterfaceImplementationPair.html

5

u/Prateeeek Jun 01 '21

If you think the higher level class(the class which calls some other class) can be reused later somewhere else, make it depend on an interface. Checkout the Wikipedia(trust me it's not bad :p) article for dependency inversion principle.

1

u/taftster Jun 01 '21

I generally think "nouns" (like a Grid) should not generally have an interface associated to them. These are your data carriers and they can be simple and model the data that you have.

I believe "behaviors" should, however, have interfaces for them. In your case, the game logic that operates on the Grid would have an interface.

So let your Grid class maintain the state of the Grid, but then offload the algorithm / game logic to a class which implements an interface.

Yes, it's about the future, but it's also practical and helps you keep a good design approach. Using interfaces helps to shape your OO design, helping to enforce separation of concerns.

Interfaces can also lend themselves to good test orientation (test driven design, etc.). A behavior class can be more easily mocked if it has a related interface to go with it.

1

u/Hadse Jun 01 '21

Thanks!

8

u/nutrecht Lead Software Engineer / EU / 20+ YXP Jun 01 '21

When it's in done an application it's an outdated practice. This was done back when mocking concrete classes was a pain in the ass. Nowadays we have proper tooling for this and in general having SomeInterface with just one SomeInterfaceImpl concrete class is considered a bad practice.

And no, it's not really a 'discussion' unless you're working with devs who are behind the curve.

When you write a library there's a good reason for it (due to extracting an interface breaking compatibility) but outside of that, it's not really a question. Unfortunately a lot of people don't understand the origins and just follow the dogma they've been taught.

1

u/HecknChonker Extreme Brewer Jun 01 '21

This really should be the top comment in this thread.

2

u/[deleted] Jun 01 '21 edited Jun 01 '21

I think you are asking this question backwards.

You are proposing a solution "should I use an interface", without explaining what about your architecture would suggest that an interface would be required. Kind of like back in the day of Design Patterns first got popular, where people would judge code based on whether it checked off the list of Design Patterns.

This is called a solution in search of a problem.

Typically, interfaces are used to implement the Strategy Pattern or Dependency Inversion. If you're not doing either of those things, creating an interface "just in case" doesn't make any sense.

3

u/[deleted] Jun 01 '21

This is one of those never ending debate in OOP.
Entire OOP is based on this good reason that you might have to do something in future -> maybe reuse or change etc.
You are making a grid based game of type1. You might in future want to make grid based game of type2. Only because you abstracted things in your previous project, you can as is reuse abstracted and tested components of type1 in type2.
Or you might in future go for a better grid. Then you can as is reuse abstracted and tested components of previous version.
Specially, in Enterprise Applications (B2B or Client-Vendor business models) - this makes a significant difference in helping reduce costs across the delivery model.
For your hobby project (probably) -> YMMV

3

u/HecknChonker Extreme Brewer Jun 01 '21

I fully disagree.

In practice, prematurely optimizing for future use-cases is an anti-pattern. It leads to more overall effort being spent to produce lower quality code.

You should be refactoring the code when it makes sense to, which is at the point where you actually need to re-use something.

1

u/[deleted] Jun 02 '21

I do not see how it can be fully or completely incoherent.
What negative effect it is exactly causing for it to be anti-pattern?
It could be more or less depending on the delivery model.
Reuse is in the sense of code that is already deployed. Why would anyone want to refactor already tested deployed code in production and increase costs?
It is more of the designer's prerogative than the developer's.

1

u/HecknChonker Extreme Brewer Jun 02 '21

The reality is the vast majority of development is "agile", meaning you only really have solid feature definitions for the next week or two of work. Everything beyond that is less well defined.

The entire idea of agile development is that you need to be able to adapt as requirements change, because you cannot know 100% of the requirements up front. The goal is to optimize your workflow so you can adapt to the to those constantly changing requirements. Less code is almost always going to be more flexible than more code.

If you start optimizing your code for something you "might" do in a few months there is a high chance you will predict the future requirements incorrectly. This means you spent extra effort building the wrong thing leading to a less flexible code base that is harder to make changes too. The other case is that you end up not needing to reuse or extend that feature, in which case the premature optimization was just a waste of effort and the extra code you added is just bloat that isn't adding anything of value.

So when you actually go to extend the code it ends up being a huge lift. This means you spent more effort up front doing the wrong thing, and significantly more effort trying to fix it later.

If you have a good set of unit tests that give you confidence that all your use cases work refactoring isn't a big risk as you will know you broke something.

There's exceptions. If you are working on a NASA rover you might have detailed requirements up front. But then you probably aren't using java.

1

u/[deleted] Jun 02 '21

ok