The appropriate way of implementing toggleable features into my code? - java

(I'm a beginner)
What is the recommended/cleanest/most efficient way of implementing features that can be toggled on/off by users?
I'm planning to add some features to my app that the user can toggle on or off in a Settings page. E.g., haptic feedback when tapping certain Views. In my code, this View has a onClickListener that executes the haptic feedback and some other methods. In the Settings page for my app, I'll put something like "Enable haptic feedback" with a Switch. Example
The first idea that comes to mind is just putting if wherever the vibrate method is called. Something like...
myView.setOnClickListener(new View.OnClickListener) {
if (hapticsSwitch.isEnabled) {
vibrate(10) //10 ms feedback
}
//more methods...
}
However, this if would need to be repeated whenever I call any toggleable feature in my app. So perhaps a cleaner way would be putting this if inside those features' methods. E.g.
public void vibrate(Long duration) {
if (hapticsSwitch.isEnabled) {
// ...
}
}
But I have no experience with toggleable features. So, what is the recommended/cleanest/most efficient way of implementing toggleable features into my code?

That is a very nice question and its not specific to toggle, but to "single level of abstraction" as uncle bob calls it.
In my opnion the right thing to do is to put it inside the vibrate function and inside any function that is influenced by that parameter.
There are 2 things you should consider:
Does Vibrate(long duration) can do its job well without hapsticsSwitch. I think the answer to that is no and it will work well only if its caller did the if statement you suggested, other developer can easily fall in that pit and create a bug
How easy it will be to change that logic when this condition will be changed from only looking at hapsticsSwitch && newFeaturehow many changes will you have to make. In my opinion it will be nuch harder to go over all the callers of vibrate.
Final note, I think you might want to use the vibrate without the condition in your app it does not mean you should move the of statement from vibrate(Long duration) to its caller, but you need to split your functions to something like vibrateIfNeeded(Long duration) and vibrate(Long duration) function that vibrate if needed will call.
Tip: read the book called "clean code" by robert c. Martin

Related

Java- Check for key presses not using KeyListener

I'm making a prototype for a videogame using Java (I plan on porting it to Unity later, but since I'm pretty comfortable with Java, I figure it'll be quicker to get an idea for the structure and basic components of my game in Java). Perhaps ironically, however, I have some doubts about how to do this thing in Java.
What is the best way to collect key presses? I know about KeyListeners and how to use them, but they don't seem ideal. I would like to be able to call a keyPress() method once every update cycle (at the beginning of the cycle, specifically) for precision reasons–I have information being updated each cycle and I want it to vary depending on which key is pressed–I realize that being even a couple of frames asynchronous isn't a huge deal, but immediacy of response is pretty important in making the game play well, I feel. I also don't want to be individually alerted every time a different key is pressed, but ideally, I'd like to generate a kind of list of which keys are pressed at any given moment (the game input consists of specific keystrokes, and so at any moment, I want to know what the active keystroke is). There's also other issues, regarding the timings when game events happen that make being synchronized to within 3 or 4 frames pretty important. It is less important that each cycle run fast than it is that I get the response to keys at the beginning of the cycle.
Is there way to do this? If there is, is it a good idea? Would it be too slow to expect any kind of consistent gameplay if I run this every update cycle (I'd expect it might even be faster or at least lighter than a listener)? Are there other places where this could wrong?
Thanks
first you should look at your gameplay.
The use of events will not problem for you. And code disorder and event control make it difficult.
There are many solutions to this. At first, did you used any frameworks (like the Libgdx)? if yes. this is handle, Otherwise you can go yourself.
One way to use "Message Handling". in this solution,You can write the code below.
public interface Telegram {
public boolean handleMessage(final Telegram msg,Object yourObject );
}
public class MessageHandler {
private static Map<String,List<Telegram>> telegramKeyMap = new HashMap<>();
public static void addTelegram(String key,Telegram telegram){
List<Telegram> telegramList = telegramKeyMap.getOrDefault(key, new ArrayList<Telegram>());
telegramList.add(telegram);
}
public static void dispatchMessage(String key,Object addVal){
List<Telegram> telegramList = telegramKeyMap.getOrDefault(key, new ArrayList<Telegram>());
for (Telegram telegram : telegramList) {
telegram.handleMessage(telegram,addVal);
}
}
}
public class Player implements Telegram {
public Player() {
}
#Override
public boolean handleMessage(Telegram msg, Object yourObject) {
return false;
}
}
in this code you can implement Telegram for any classes. then on the listeners call dispatchMessage. for input you can used any Objects(like Listener, keyCode,...)
dispatcher fine any object with this key, them call handleMessage method. Now, each of your objects can handle their work.
second solution : Use "Event Management"
If the first option does not resolve your problem, then I'll take the second solution to the sample code. The message handler is used in most game engine engines, and it does increase the speed of the game, but it's opening up your hands sharply.

Event-driven programming - node.js, Java

I am coming from Java but have been doing some Node.js lately, and have been looking at the EventEmitter module in Node.
What I don't understand is the fundamental difference between Event-driven programming and 'regular' programming.
Here is some psuedo-code to demonstrate my idea of "event-driven" programming.
EventEmitter ee = new EventEmitter();
Function f = new SpecialFunction();
ee.on('grovel',f);
ee.emit('grovel'); //calls function 'f'
the only work the EventEmitter object seems to be doing is creating a hash relationship between the String representation of an event (in this case 'grovel') and a function to respond with. Seems like that's it, not much magic there.
however, my question is - how does event-driven programming really work behind the scenes with low-level events like mouse-clicks and typing? In other words, how do we take a click and turn it into a string (like 'grovel') in our program?
Okay. I will take a run at this.
There are a couple of major reasons to use event emitters.
One of the main reasons is that the browser, which is where JavaScript was born, sometimes forces you to. Whether you are wiring your events straight into your HTML, using jQuery or some other framework/library, or whatever, the underlying code is still basically the same (erm, basically...)
So first, if you want to react to a keyboard or mouse event, like you mentioned, you could just hard bind directly to an event handler (callback) like this:
<div onclick="myFunc(this)">Click me</div>
...or you could do the exact same thing in JS by DOM reference:
document.getElementById('my_element').onclick = function (evt) {
alert('You clicked me');
};
This used to be the primary way we wired up click handlers. One lethal drawback to this pattern is that you can only attach one callback to each DOM event. If you wanted to have a second callback that reacted to the same event, you would either need to combine write it into the existing click handler or build a delegate function to handle the job of calling the two functions. Plus, your event emitter ends up being tightly coupled to the event listener, and that is generally a bad thing.
As applications became more complex, it makes more sense to use event listeners, instead. Browser vendors (eventually) settled on a single way to do this:
// Build the handler
var myHandler = function (evt) {
alert('You clicked me too');
window.myHandlerRef = this; // Watch out! See below.
};
// Bind the handler to the DOM event
document.getElementById('my_element').addEventListener('click', myHandler);
The advantage to this pattern is that you can attach multiple handlers to a single DOM event, or call one single event handler from several different DOM events. The disadvantage is that you have to be careful not to leak: depending on how you write them, event-handling closures (like myHandler above) can continue to exist after the DOM element to which they were attached have been destroyed and GCed. This means it is good practice to always do a removeEventListener('click', myHandler). (Some libraries have an off() method that does the same thing).
This pattern works well for keyboard events as well:
var giveUserAHeadache = function (evt) {
alert('Annoying, isn\'t it?');
};
document.addEventListener('keypress', giveUserAHeadache);
Okay. So that is how you usually handle native browser events. But developers also like to use this pattern of event delegation in their own code. The reason you would want to do this is so you can decouple your code as much as possible.
For example, in a UI, you could have an event emitted every time the user's browser goes offline (you might watch navigator.onLine for example). Maybe you could have a green/red lamp on your page header to show the online state, and maybe you could disable all submit buttons when offline, and maybe also show a warning message in the page footer. With event listeners/emitters, you could write all of these as completely decoupled modules and they still can work in lock-step. And if you need to refactor your UI, you can remove one component (the lamp, for example), replace it with something else without worrying about screwing up the logic in some other module.
As another example, in a Node app you might want your database code to emit an error condition to a particular controller and also log the error -- and maybe send out an email. You can see how these sorts of things might get added iteratively. With event listeners, this sort of thing is easy to do.
You can either write your own, or you can use whatever pattern is available in your particular environment. jQuery, Angular, Ember and Node all have their particular methods, but you are free to also build your own -- which is what I would encourage you to try.
These are all variations of the same basic idea and there is a LOT of blur over the exact definition or most correct implementation (in fact, some might question if these are different at all). But here are the main culprits:
Observer
Pub-Sub
Mediator

What does the "openSettings" or "openSearch" mean in Android official tutorial? [duplicate]

I'm just started the Android beginners tutotial and I now face a problem. On this page under "Respond to Action Buttons" it tells me to define a switch statement with some of the options calling the openSearch() and openSettings() methods. These methods however, are not defined yet (duh) which thus gives me an error.
The tutorial doesn't say anything however, about how to define them. Can anybody give me a pointer on what and where I should define thess methods? Should they be in the same file, and if so, what should they contain?
These methods are just examples that Google put in to show how you would use a switch statement. You can put anything you want in there, but I think the point is to make function calls from a switch statement, instead of putting the code of a function in the statement, to keep code clean. The functions would probably be declared in the same .java file in some fashion like
private void openSearch() {
// start or show the search activity/fragment
}
They can technically contain anything you want them to, depending on what you want the action bar button to do. If you simply want to see that the buttons work, you can splash a Toast notification to see something appear
private void openSearch() {
Toast.makeText(this, "Search button pressed", Toast.LENGTH_SHORT).show();
}
You'll have to import the Toast package which can be done by Ctrl+Shift+O. (Or Cmd+Shift+O for Mac)
Hope this helps clear up confusion.
This is the code that you have to use in those methods:
private void openSearch(){
startActivity(new Intent(SearchManager.INTENT_ACTION_GLOBAL_SEARCH));
}
private void openSettings(){
startActivity(new Intent(Settings.ACTION_SETTINGS));
}
The openSearch() method execute the google global search of the cellphone.
The openSettings() method open the global configuration of the cellphone.
I'm also a beginner in android,hope this helps with the question. Good Luck
drees (thanks for Toast) answered the question for the satisfaction of the beginning android programmer (which I am), but to actually answer the question asked, you need to follow the instructions in the Setting Up The Search Interface article, however you need to preemptively understand how to place the commented material here into the switch statement's openSearch() method.
I guess the real question is, though: Why does the android tutorial use this methodology instead of having a nonlinear explanation to add real content as the situation requires OR at least link to it to follow it out OR at least let you know that you're going to be obtain an end product that is at best broken code.

Android - How to avoid duplicate code between activities

This is a bit of a general question, but I will give a specific example for you.
I have a bunch of activities in an App. In all of the activities, there is a Facebook button. When you click the button it takes you to a specific Facebook page. I wish for the button to behave exactly the same way on every page.
Right now, in every single Activity, I create an onClickListener() for the Facebook button and make the intent and start the activity. It's the same code in every single Activity.
What is the best way to write this code once and include it in multiple activities? Is there anyway to include other .java files?
One solution that I know would work, is to make a base CustomActivity class that extends Activity and then have all activities extend CustomActivity. Then put my onClickListener() code in CustomActivity. I'm new to Java though and I wasn't sure if that was the best approach or not. Some of my Activities already extend other custom activity classes as is, so extending things that extend more things might get kinda messy, I dunno.
UPDATE
Playing the devil's advocate here: Lets say I went with the inheritance route and I create some CustomActivity that I want my Activities to extend. CustomActivity would contain a bunch of general code that I need to use for all Activities, including but not limited to the Facebook button functionality. What happens when there is an Activity that I need to use generic code from the CustomActivity but there is no Facebook button in that specific Activity?
A common base class is perhaps the best approach. (It doesn't work quite so well if some of your activities extend Activity and some extend Activity subclasses (such as ListActivity).
An alternate approach is to create a separate class that implements the logic of your click listener. This doesn't eliminate all duplicate code — each activity still needs to instantiate and register a listener — but the logic for what to do will only need to be written once in the listener class.
In either alternative, you might consider assigning the android:onClick attribute to the button. That way you don't need to register a click listener; you just need to implement the target method in each activity. This is particularly useful with the base class approach.
UPDATE
Suppose you go the inheritance route and you want an activity with no Facebook button. If you are using the android:onClick technique, then you don't have to do anything different in your code — since no button will invoke your onClick method, the method will just sit there doing nothing. If you are installing an OnClickListener in code, then you just need to test that the button exists (i.e., that findViewById() did not return null) before registering the listener.
Generally a common base class is NOT the best approach (although it's certainly valid).
This took me (and every OO programmer who "gets" OO that I know of) a while to really grok, but you should use inheritance as sparingly as you possibly can. Every time you do it you should ask yourself if there is REALLY no other way to do this.
One way to find out is to be very strict with the "is-a" test--if you call your base activity a "Facebook Activity", could you really say that each child "is" a Facebook activity? Probably not. Also if you decided to add in Twitter to some of the pages (but not others), how do you do this?
Not that inheritance is completely out! A great solution might be to extend a control to launch your facebook activity and call it a facebook button--have it encapsulate all the stuff you need to do to connect to facebook. Now you can add this to any page you want by simply dragging it on (I'm pretty sure android tools let you add new components to the pallet). It's not "Free" like extending your activity class, but in the long run it will cost you a lot less stress.
You probably won't believe me now, we all need to learn from our own experience, just keep this in mind and use it to evaluate your code as you evolve it over time.
--edit, comment response--
You can encapsulate any facebook activity you think you will use a lot in it's own class--get it to a bare minimum so you can just add it to any class in a one-liner.
At some point, however, you may decide that it's STILL too much boilerplate, I totally understand. At that point you COULD use an abstract base activity like you suggest, but I wouldn't hard-code it to handle facebook explicitly, instead I'd have it support behaviors such as facebook (and maybe others), and turn-on these behaviors as desired. You could then tell it NOT to add the facebook behavior to a given screen if you like, or add in Twitter to some of them.
You can make this boilerplate minimum, for instance if you want "Standard" functionality, you shouldn't have to do anything special, if you wish to disable facebook you might start your constructor with:
super(DISABLE_FACEBOOK_BEHAVIOR);
and if you want one that also enables Twitter you could use:
super(DISABLE_FACEBOOK_BEHAVIOR, ENABLE_TWITTER_BEHAVIOR);
with a constructor like AbstractAction(BehaviorEnum... behaviors).
This is more flexible and you actually can say that each if your activities IS-A "behavior supporting activity" with a clear conscience.
It is, of course, a perfectly good approach to be less flexible at first and refactor into a pattern like this later when you need to, just be on the look-out for your inheritance model causing problems so you don't let it mess you up for too long before you fix it.
Well, extending things is the principle of OOP, so I don't think this is a problem to have more than one level of subclasses. The solution you thought about is in my opinion the best.
Absolutely. Use inheritance to gain some reusability as you should with OOP. You'll find, as you progress, that there are gonna be more and more things you'd like to reuse in your activities -- things more complex than an onClickListener for a FB button -- so it's a great idea to start building a nice, reusable "super" activity that you can inherit from.

Asynchronous programming best practices

I have recently written my first Android app which was roughly 8,000-10,000 lines of code. One thing that continuously hindered my use of normal design patterns was android's heavy use of asynchronous calls (opening dialogs, activities, etc). Due to this, my code very quickly began looking "spaghetti" like, and I eventually started to dislike looking at certain classes.
Are there specific design patterns or programming methodologies which are for systems such as these that anyone would recommend? Are there any suggestions for writing manageable asynchronous code?
Use global variables
If you do not want to mess up your code with simple Intent.putExtra() calls and manage this things for each unique Activity you'll have to use global variables within the application. Extend Application and store data that you need as long your application is alive. To actually implement it, use this excellent answer. This will make dependencies between activities disappear. For example, say that you need a "username" for your application during the application's life cycle - this is an excellent tool for just that. No need for dirty Intent.putExtra() calls.
Use styles
One common mistake when making the first Android application is that one usually just start writing the XML views. The XML files will (without problem and very fast) go up to very many lines of code. Here you can have a solution where you just use the style attribute to implement a specific behaviour. For example, consider this piece of code:
values/styles.xml:
<style name="TitleText">
<item name="android:layout_height">wrap_content</item>
<item name="android:layout_width">wrap_content</item>
<item name="android:textSize">18sp</item>
<item name="android:textColor">#000</item>
<item name="android:textStyle">bold</item>
</style>
layout/main.xml:
Now, if you have, let's say, two TextViews and both of them should have the same behaviour, make them use the TitleText style. Sample code:
<!--- ... -->
<TextView
android:id="#+id/textview_one"
style="#style/TitleText"
/>
<TextView
android:id="#+id/textview_two"
style="#style/TitleText"
/>
<!--- ... -->
Simple and you don't need to duplicate code. If you really want to look further on this particular subject, please look at Layout Tricks: Creating Reusable UI Components.
Use strings
This point is short but I think it is important to mention it. Another mistake that developers might do is to skip the strings.xml and just write UI messages (and attribute names) inside the code (where he will need it). To make your application easier to maintain; just define messages and attributes in the strings.xml file.
Create and use a global tool class
When I wrote my first application I just wrote (and duplicated) methods where I needed it. The result? A lot of methods that had the same behaviour between various activities. What I have learned is to make a tool class. For example, let's say you have to make web requests in all of your activities. In that case, skip defining them inside the actual Activity and make a static method for it. Sample code:
public final class Tools {
private Tools() {
}
public static final void sendData(String url,
String user, String pass) {
// URLConnections, HttpClients, etc...
}
}
Now, you can just use this code below in your Activity that needs to send data towards a server:
Tools.sendData("www.www.www", "user", "pass");
However, you get the point. Use this "pattern" where you need it, it will keep you from messing up your code.
Let custom classes define the behaviour where the user needs to interact with your application
This is probably the most useful point. To just define "where the user needs to interact with your application" let's say you have a Menu, which behaviour is very long in terms of lines, why do we keep the Menu's calculations in the same class? Every little item will make your Activity class a painful piece of code longer - your code look like "spaghetti". For example, instead of having something like this:
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem item;
item = menu.findItem(R.id.menu_id_one);
if (aBooleanVariable) {
item.setEnabled(true);
} else {
item.setEnabled(false);
}
// More code...
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem i) {
// Code, calculations...
// ...
// ...
return super.onOptionsItemSelected(i);
}
redesign it to something like this:
private MyCustomMenuInstance mMenuInstance;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mMenuInstance = new MyCustomMenuInstance();
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
mMenuInstance.onPrepareOptionsMenu(menu);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem i) {
mMenuInstance.onOptionsItemSelected(i);
return super.onOptionsItemSelected(i);
}
For example, MyCustomMenuInstance:
public class MyCustomMenuInstance {
// Member fields..
public MyCustomMenuInstance() {
// Init stuff.
}
public void onPrepareOptionsMenu(Menu menu) {
// Do things..
// Maybe you want to modify a variable in the Activity
// class? Well, pass an instance as an argument and create
// a method for it in your Activity class.
}
public void onOptionsItemSelected(MenuItem i) {
// Do things..
// Maybe you want to modify a variable in the Activity
// class? Well, pass an instance as an argument and create
// a method for it in your Activity class.
}
}
You see where this is going. You can apply this to many things, e.g. onClick, onClickListener, onCreateOptionsMenu, the list is long. To learn more "best practices" you can see some sample applications from Google here. Look for how they've implemented things in a nice and correct way.
Last word; keep your code clean, name your variables and methods in a logical manner and especially in a correct way. Always, always understand where you are in your code - that is very important.
From an amateur perspective, I don't expect my first attempt to be a clean, production-ready app. I end up with spaghetti, fettucini and even ravioli code sometimes. At that point, I try to rethink what is what I dislike the most from the code, and search for a better alternative:
Rethink your classes to better describe your objects,
keep the code in each method to a minimum,
avoid dependencies to static variables anywhere you can,
use threads for expensive tasks, don't use them for quick procedures,
separate the UI from the app logic (keep it in your classes instead),
keep private fields anywhere you can: it will be helpful when you want to change your class,
iterate through these until you like the code
One of the most common errors I've seen in asynchronous methods is to use a static variable inside a loop that creates one or more threads, without considering that the value may change in another thread. Avoid statics!
As OceanBlue points out, it may not be clear from this that final static variables do not create any danger, but public static variables that can change. It is not a problem with the statics themselves, but with the notion that they will have a value and then find out that the value changed. It may be difficult to spot where the problem was. Typical examples would be a clicks counter or a timer value, when there could be more than one view clicked or more than one timer.
Hopefully you will receive suggestions from people with much more experience than me. Good luck!
If handling the the UI is your biggest concern, then you'll want to master event-driven coding. The ideas behind event-driven coding are behind all modern UI systems, and are useful in all kinds of things (not just UI).
The easiest way for me to think of it when learning was simply to treat each component and event as if it's self-contained. All you need to worry about is the event object passed into your event method. If you're used to writing applications that run basically from beginning to end, it's a bit of a mind shift, but practice will get you there pretty quickly.
What about using the Model View Controller pattern?
At least you have to isolate in the "model" (object or set of objects)
all the state and its logical management, and have in
a separate class (maybe the Activity class)
all the stuff related to the views, listeners,callbacks, ...)

Categories