How to implement a turnoff switch when using composition (java)? - java

I have a very simple Player class in java that uses some strategies object all inheriting from the interface PlayerStrategy.
Some implementations of PlayerStrategy are simple but a few others are so resource intensive that I need to make sure I free resources properly when the strategy stops being used. Those strategies have an additional method: turnOff() that takes care of that.
Now if Player leaves the game I'd like it to call turnOff() in all the strategies it has that need it.
The problem is that only a few strategies need turnOff() so I don't feel comfortable adding that method to the PlayerStrategy interface.
Right now when a Player stops playing it checks through reflection if the method turnOff() exists in its strategy. But it's clunky and ugly. Is there a better way?

Avoid Reflection: Reflection is a bad idea. Wherever you can (and it seems you can), avoid it.
It's Good to have turnOff() in the Interface: If you have to use interface... believe me adding turnOff() or cleanup() method is a good idea; even if most of the subclasses will have just empty curly brackets. You wouldn't need to do extra work if they get updated in future to use some resource that requires a clean up.
You can get What You Want but the Cost is Higher: If you are really rigid and sure that subclasses wouldn't extend any other class. You may make the PlayerStrategy a abstract class with turnOff() as empty method. This will solve both your issue, but will limit the subclasses ability to extend other class.

If you do not want to change your implementations of PlayerStrategy, you can use the facade pattern to handle the turnOff.

Related

Workaround for a lack of multiple inheritance

I am currently working on a videogame (assignment), and the problem I have is the following:
The player can move vertically and horizontally, but some other objects can only move vertically OR horizontally. I would love to have an abstract class "HorizontalMovingObject" and "VerticalMovingObject", and have an abstract class "MovingObject" which extends both these classes. I was wondering if there happens to be a workaround for this?
I currently have these abstract classes, but find myself constantly copying code from the unidimensional moving classes to the regular moving class. I have tried a couple of things, but all felt wrong somehow. I worked through interfaces for the unidimensional moving parts, but there is a default underlying behavior that should extend to all objects moving in that direction, and thus it feels wrong to write these over and over again. I tried the reverse and have for example the horizontal class extend the MovingObject class, but with all its vertical components set to 0, which somehow felt even worse.
I know this might not seem like a very important detail, but it has been driving me crazy for some reason. Mostly because I come from C++.
Any help is appreciated!
I would love to have an abstract class "HorizontalMovingObject" and
"VerticalMovingObject", and have an abstract class "MovingObject"
which extends both these classes.
The workaround for that is interface.
MovingObject should implement both HorizontalMovingObject and VerticalMovingObject
I currently have these abstract classes, but find myself constantly
copying code from the unidimensional moving classes to the regular
moving class. I have tried a couple of things, but all felt wrong
somehow.
Java 8 introduces default methods that allow to define default implementations for interfaces.
Note that if a class implements both HorizontalMovingObject and VerticalMovingObject , which both have a same default method, you should override it to make the class compile : default interfaces allow to mix inherited behaviors from distinct interfaces while no ambiguity is present about which method is inherited. When it is not the case, a compilation error occurs.
An alternative to Java 8 interfaces default method to achieve this requirement is using the decorator pattern : define each part of behavior that you want to reuse in a specific decorator class, chain the decorators designed to work together and and add these to the decorated class that need these specific behavior.
This approach favors composition over inheritance and requires more boiler plate code but is more flexible.
One workaround that can be done for multiple inheritance is using default methods of interfaces.
I personally don't think it's a good idea, this is not what default methods are there for, but technically it's a loop-hole you can expliot
A better solution for me can be to have some MovingObjectAbs class that will hold the shared direction-agnostic logic that both horizontal and vertical classes will extend, or to have some utility classes that will have shared logic.

Game programming: passing main class to every object

I know it's not efficient, but I don't really know why.
Most of the time, when you implement your game you got a main class which has a loop and updates every frame and creates certain objects.
My question is why it's not considered efficient to pass the main class to every object in its constructor?
In my case, I developed my game in Java for Android, using LibGDX.
Thank you!
It increases coupling (how much objects depend on each other) and therefore reduces re-usability and has the tenancy to produce 'spaghetti code'. I don't really understand what you mean by not being 'efficient', but this is why you shouldn't do it.
You should also consider why you need that main class in every single object. If you really think you do, you might need to reconsider your system design. Would you mind elaborating on why you think you need it?
Mostly, it is a matter of coupling the code and making proper design decisions.
You should avoid dependencies between classes whenever possible. It makes the code easily maintainable and the whole design clearer.
Consider the case: you are creating a simulation racing game. You have a few classes for such entities: wheel, engine, gearshift knob, etc... and non-entities: level, player...
Let's say, you have some main point (i.e. GameEngine class where you create instances).
According to you're approach you want to pass GameEngine's instance in entities constructors (or related mutator methods). It's not the best idea.
You really want to allow wheels or breaks to have the knowledge about the rest of the world (such as player's informations, scores, level etc.) and give them access to it's public interface methods?
All classes should have at small level of responsibility (and knowledge about other items) as possible.
If you really need reference to some kind of main point object in you're classes consider using dependency injection tools, such as Dagger.
It won't make you're game design better, but, at least, forces you to favor composition over inheritance - what leads to create better code.
It's not entirely inefficient, since (afiak in the general case) passing a reference to a method is quite cheap when you consider the number of JVM opcodes required, however, a possibly more efficient way of doing this would be to make a static instance of the game class and access that static field from the other classes. You would have to test these two options yourself.
In addition, passing a reference to the methods could make maintaining the code harder, as you have ultimately added a dependency.

What is the optimal way to share code between Activities with different base classes?

I have the following problem:
I have an abstract Activity class, lets call it MyAbstractActivity, that contains some code I'd like to reuse (for example: a standard service binder, common menu items, common initialization code, etc. etc.). Normally I would just use it to subclass my concrete activities and be done with it.
However, I occasionally need to use another supertype, such as a ListActivity or a MapActivity.
So the question is: how do I avoid duplicating that support code within an Activity, if I have to use another base class?
I have thought up of a solution based on the decorator pattern, like this one:
.
However, I see a problem with this approach:
What to do with protected methods (like onCreate())? Should I introduce an additional "bridge" class that makes them public for the purpose of the decorator, similarly to the way presented below (starting to look a bit byzantine...)?
Any other way?
I hope I made myself relatively clear. Thanks in advance for any feedback!
PS. Using static utility classes is not a good solution in my opinion, since it introduces a possibility of hard-to-identify programming bugs.
If I understand correctly, neither Fragments nor the Decorator Pattern are clean or appropriate solutions for what you want to accomplish. They were designed to solve other problems.
I find myself moving "support" code, or "framework" code, or "all that verbose, repetitive, boilerplate crap" to static utility methods. This isn't necessarily the approach I'd take on a non-Android project, but in my Android projects, it works pretty darn well.
Also, know that you don't need to subclass ListActivity to have a ListView.

Java class containing only private members

Lately I met a situation where I needed to create a custom VideoView to my android application. I needed an access to the MediaPlayer object and to add some listeners.
Unfortunately (for me), all members of the VideoView class are private, so even extending the class wouldn't help me to gain access to its MediaPlayer object (or anything else), I had to make a complete duplicate of the class with my modifications.
Well, although it is sound like I'm complaining for the "hard work", it is easier than extending the class in this case (since all the source is available...), but it made me really doubt this method of information hiding. Is this a better practice than leaving main components available to modification / access (protected, not public)? I mean, I understand that if I extend the VideoView class, someday maybe they'll change something in the VideoView class and I might have troubles, but if they'll change the class, my own (duplicate) version will have a bigger difference from the VideoView class, and my goal is not to create my own video view, but to extend the available VideoView.
When a programmer makes something private, they're making a bet that nobody else will ever need to use or override it, and so there will be a payoff from the information hiding. Sometimes that bet doesn't come off. Them's the breaks.
I usually prefer composition rather than inheritance in such situations.
EDIT:
It's safe to use inheritance when both subclass and super class are in the control of the same programmer but implementation inheritance can lead to a fragile API. As you mentioned if superclass implementation changes then subclass can break or more worst - will do unintended things silently.
The other approach would be to have private field that references an instance of the existing class (VideoView) known as composition and each instance method in the new class invokes the corresponding method on the contained instance of the existing class and returns the results. This wrapper approach can be referred as 'Decorator' pattern as well
I can't speak for the reasoning of the particular VideoView developers, but if you're developing an API, and determine that the state represented by certain data needs to always follow certain rules in order to maintain the integrity and intended purpose of the object, then it makes sense to make the member vars private so you can control their modification.
It does limit what other devs can do, but I assume that's the point. There's some things that, if they were to be changed, you would want it to go through discussion and verification amongst the group that has governance over the API. In that case it makes sense to privatize so that modifications to it can't get out of hand outside of the group's oversight.
I don't know that there's a static rule of thumb that determines when something needs to fall into this category, but I can definitely see the use in certain cases.
When I read all the enlightening answers (and comments) and commenting to those I realized that I expected something which is irrelevant from some classes. In the case of VideoView fr example, this class is already the last in the inheritance chain. It should not be extended, as it is one logical unit, very specific and very tight, for a very specific purpose. My needs, to get special states from the view and the MediaPlayer, were needs for QC purposes, and such needs really shouldn't be considered when providing a product which is a closed unit (although the source is open). This is a reasonable argument and I find it satisfing. Sometimes not every concept of OOP should be implemented. Thank you all for the responses.

Java Interfaces Methodology: Should every class implement an interface?

I've been programming in Java for a few courses in the University and I have the following question:
Is it methodologically accepted that every class should implement an interface? Is it considered bad practice not to do so? Can you describe a situation where it's not a good idea to use interfaces?
Edit: Personally, I like the notion of using Interfaces for everything as a methodology and habit, even if it's not clearly beneficial. Eclipse automatically created a class file with all the methods, so it doesn't waste any time anyway.
You don't need to create an interface if you are not going to use it.
Typically you need an interface when:
Your program will provide several implementations for your component. For example, a default implementation which is part of your code, and a mock implementation which is used in a JUnit test. Some tools automate creating a mock implementation, like for instance EasyMock.
You want to use dependency injection for this class, with a framework such as Spring or the JBoss Micro-Container. In this case it is a good idea to specify the dependencies from one class with other classes using an interface.
Following the YAGNI principle a class should implement an interface if you really need it. Otherwise what do you gain from it?
Edit: Interfaces provide a sort of abstraction. They are particularly useful if you want to interchange between different implementations(many classes implementing the same interface). If it is just a single class, then there is no gain.
No, it's not necessary for every class to implement an interface. Use interfaces only if they make your code cleaner and easier to write.
If your program has no current need for to have more than 1 implementation for a given class, then you don't need an interface. For example, in a simple chess program I wrote, I only need 1 type of Board object. A chess board is a chess board is a chess board. Making a Board interface and implementing that would have just required more code to write and maintain.
It's so easy to switch to an interface if you eventually need it.
Every class does implement an interface (i.e. contract) insofar as it provides a non-private API. Whether you should choose to represent the interface separately as a Java interface depends on whether the implementation is "a concept that varies".
If you are absolutely certain that there is only one reasonable implementation then there is no need for an interface. Otherwise an interface will allow you to change the implementation without changing client code.
Some people will shout "YAGNI", assuming that you have complete control over changing the code should you discover a new requirement later on. Other people will be justly afraid that they will need to change the unchangeable - a published API.
If you don't implement an interface (and use some kind of factory for object creation) then certain kinds of changes will force you to break the Open-Closed Principle. In some situations this is commercially acceptable, in others it isn't.
Can you describe a situation where it's not a good idea to use interfaces?
In some languages (e.g. C++, C#, but not Java) you can get a performance benefit if your class contains no virtual methods.
In small programs, or applications without published APIs, then you might see a small cost to maintaining separate interfaces.
If you see a significant increase in complexity due to separating interface and implementation then you are probably not using interfaces as contracts. Interfaces reduce complexity. From the consumer's perspective, components become commodities that fulfil the terms of a contract instead of entities that have sophisticated implementation details in their own right.
Creating an interface for every class is unnecessary. Some commonly cited reasons include mocking (unneeded with modern mocking frameworks like Mockito) and for dependency injection (e.g. Spring, also unneeded in modern implementations).
Create an interface if you need one, especially to formally document public interfaces. There are a couple of nifty edge cases (e.g. marker interfaces).
For what it's worth, on a recent project we used interfaces for everything (both DI and mocking were cited as reasons) and it turned out to be a complete waste and added a lot of complexity - it was just as easy to add an interface when actually needed to mock something out in the rare cases it was needed. In the end, I'm sure someone will wind up going in and deleting all of the extraneous interfaces some weekend.
I do notice that C programmers first moving to Java tend to like lots of interfaces ("it's like headers"). The current version of Eclipse supports this, by allowing control-click navigation to generate a pop-up asking for interface or implementation.
To answer the OP's question in a very blunt way: no, not all classes need to implement an interface. Like for all design questions, this boils down to one's best judgment. Here are a few rule of thumbs I normally follow:
Purely functional objects probably
don't need to (e.g. Pattern,
CharMatcher – even though the
latter does implement Predicate, it
is secondary to its core function)
Pure data holders probably don't need
to (e.g. LogRecord, Locale)
If you can
envision a different implementation
of a given functionality (say, in-memory
Cache vs. disk-based Cache), try to
isolate the functionality into an interface. But don't go too far trying to predict the future either.
For testing purposes, it's
very convenient when classes that do
I/O or start threads are easily mockable, so
that users don't pay a penalty when
running their tests.
There's nothing
worse than a interface that leaks its
underlying implementation. Pay attention where you draw the line and make sure your interface's Javadoc is neutral in that way. If it's not, you probably don't need an interface.
Generally
speaking, it is preferable for
classes meant for public consumption
outside your package/project to
implement interfaces so that your
users are less coupled to your
implementation du jour.
Note that you can probably find counter-examples for each of the bullets in that list. Interfaces are very powerful, so they need to be used and created with care, especially if you're providing external APIs (watch this video to convince yourself). If you're too quick in putting an interface in front of everything, you'll probably end up leaking your single implementation, and you are only making things more complicated for the people following you. If you don't use them enough, you might end up with a codebase that is equally hard to maintain because everything is statically bound and very hard to change. The non-exhaustive list above is where I try to draw the line.
I've found that it is beneficial to define the public methods of a class in a corresponding interface and when defining references to other classes strictly use an interface reference. This allows for easy inversion of control, and it also facilitates unit testing with mocking and stubbing. It also gives you the liberty of replacing the implementation with some other class that implements that interface, so if you are into TDD it may make things easier (or more contrived if you are a critic of TDD)
Interfaces are the way to get an polymorphism. So if You have only one implementation, one class of particularly type, You don't need an interface.
A good way of learning what are considered good methodologies, especially when it comes to code structure design, is to look at freely available code. With Java, the obvious example is to take a look at the JDK system libraries.
You will find many examples of classes that do not implement any interfaces, or that are meant to be used directly, such as java.util.StringTokenizer.
If you use Service Provider Interface pattern in your application interfaces are harder to extend than abstract classes. If you add method to interface, all service providers must be rewritten. But if you add non-abstract method to the abstract class, none of the service providers must be rewritten.
Interfaces also make programming harder if only small part of the interface methods usually have meaningfull implementation.
When I design a new system from scratch I use a component oriented approach, each component (10 or more classes) provide an interface, this allows me (sometimes) to reuse them.
When designing a Tool (Or a simple system) I think this must not necessarily be an extensible framework I introduce interfaces when I need a second implementation as an option.
I saw some products which exposed nearly every functionality by an interface, it took simply too much time to understand unnecessary complexity.
An interface is like a contract between a service provider (server) and the user of such a service (client).
If we are developing a Webservice and we are exposing the rest routes
via controller classes, controller classes can implement interfaces
and those interfaces act as the agreement between web service and the
other applications which use this web service.
Java interfaces like Serializable, Clonnable and Remote
used to indicate something to compiler or JVM.When JVM sees a class
that implement these interfaces, it performs some operation on the to
support Serialization, cloning or Remote Method Invocation. If your class needs these features, then you will have to implement these interfaces.
Using Interface is about to make your application framework resilient to change. Since as I mentioned here (Multiple Inheritance Debates II: according to Stroustrup) multiple inheritance was cancelled in java and c# which I regret, one should always use Interface because you never know what the future will be.

Categories