Goodbye Singletons, Hello Dependency Injection

Learning software engineering is a process of biting your tongue.  You learn a new concept and revel in the abilities it gives you, and then shortly thereafter, you’re looking at your old code thinking, “did I write that?”  As a nine-month-old iOS developer, I’m still learning tons.

When I started, I saw singletons in iOS as a good thing.  They are easy to use (pretty much one line of code and you can access your class anywhere), but they come with a lot of baggage.  I don’t hold the view that singletons are to be completely avoided, but they should be carefully considered.

The main reason I try to avoid singletons now is because the code using the singleton now has a dependency on the singleton class.  If the singleton class changes, it has to be swapped out everywhere it’s used.  Additionally, singletons make testing difficult, because they have to be spun up when testing classes that use them.  Sometimes, this may not be possible in the testing context, and now you’re stuck with untestable code.

Dependency injection to the rescue.  I started learning about dependency injection while working on a Java Spring Boot application (dependency injection is a core concept in Spring) in my day job.  Dependency injection requires you to pass dependencies used by the calling class through the constructor; alternatively, the dependencies can be properties of the class and set by a dependency injection framework.

Now, since we pass the dependency through the constructor, we could pass a mock class through the constructor too that is the same type as the dependency, allowing us to test the class without spinning up an instance of the actual dependency.  Usually, your dependencies are based off a protocol in Swift (or interface in Java), which allows you to easily create mock classes for testing purposes.  Ah, finally your code can be testable again.

Dependency injection isn’t a complex subject, you just need to get in the mindset of using it, and you will reap the rewards.

Happy coding!
Matt from The Bunch

Abstraction: Code that’s clean, simple, and fun :)

Techopedia defines abstraction in programming as

“The act of representing essential features without including the background details or explanations.”

I like this definition because it’s simple and gets the point across.  When our goal is to write code that’s abstract, we focus on separating the meat and potatoes functionality (the code that gets used a lot), and let the details (the situation-specific code)  fall in place after that.  An example that I ran into while developing LunchBunch is the coding of API calls within the app.  I coded all the calls into the UI classes, so each UI class had its own implementation of the API calls it used (with lots of repeat code). This means the class would build the call, receive it, parse it, and act on it. The building and receiving of the API calls was the same for every call, but was being done in every class that called an API.  I needed something better. I needed abstraction. The value of abstraction is just that, reducing repeat code and keeping the meat and potatoes in one place, while the details (the veggies, if you will) are elsewhere, where they should be.

One issue I ran into while trying to keep my code abstract was deciding on when to stop. By adding some extra arguments and doing some fancy thingy-majigs, I could take almost all the code out of my UI class that didn’t directly affect the UI.  I didn’t do this, though. Why? I think almost half of coding is creating friendly, readable code. Adding arguments that make little sense and doing fancy thingy-majigs isn’t always the answer.  The final solution was to have special classes dedicated to building the API calls and receiving them. Each calling UI class implements an interface associated with that call which forces the class to define two methods, one to handle a successful return, and one to handle an error return. I found this to be the perfect amount of abstraction, and it greatly reduced the amount of repeat code, while keeping code readable and maintainable.

So abstraction is definitely something to keep in mind as you code. Think to yourself, am I writing the same code a lot? Can I make my code cleaner, simpler, and more fun to maintain? Make use of abstract classes and interfaces!

Happy coding!
Brandon from The Bunch

The LunchBunchMobile


There’s a new car on the road! 2016 is going to be a big year for LunchBunch, and I thought I’d start it off right by visiting Mentor Signs & Graphics to get some LunchBunch vehicle graphics.



This sure will make my LunchBunch road trips more exciting!

Mentor Signs did such a great job with my car; they do high-quality work and pay great attention to detail. If you have any graphics or marketing needs, please check them out online, give them a call at 440-951-7446, or like them on Facebook. They also do sweet arcade graphics:, Facebook.

What do you think of the LunchBunchMobile? If you see it out-and-about, snap of photo to let us know on Facebook or Twitter!


Ryan from The Bunch

Cookies vs. Sessions

Cookies and sessions both store unique information for users. The biggest difference between them is where they are stored; cookies are stored locally on the user’s computer, and sessions are stored remotely on the server that the user is accessing via their web browser. Cookies are good for storing data that isn’t sensitive (items in a shopping cart, username, etc.), but they pose a security threat if the remote server trusts them with important information. For example, storing a username in a cookie is useful for auto-populating a login text field, but that same cookie should not be used to authenticate a logged-in user.

One of the benefits of cookies is that–because they are stored on the user’s computer–the server doesn’t need to store any information, and if there are millions of users, that’s a lot of saved space on the server! This locality is the same reason why it’s not a good idea to authenticate with cookies–they can be modified locally before being sent to the server.

Let’s look at an insecure website for example: Bob Roberts logs in with his username, broberts, and his password. After ensuring that the username and password are valid, the server returns Bob’s account page as expected and stores his username in a browser cookie. When Bob requests another page, the server checks the cookie stored on his computer to see who is logged in, sees that it’s “broberts”, and returns the requested information. Sounds good, right? But what if Bob changed the value of that cookie from broberts to bsmith? If there is another user with that username (let’s say Bill Smith), the page that the server returned to Bob would be from Bill’s account. This is where sessions come in handy.

Instead of storing “broberts” on the local machine, a session ID is stored in a local cookie that can be used to look up the session on the server. So when broberts requests a page, his computer sends the session ID to the server with the request, and the server can look up the session based on the ID that Bob sent and use that to get the username. (It’s important to note that the server is storing other information in the session to make sure that the ID wasn’t tampered with–otherwise it would be easy for Bob to change the session ID.)

This is a very brief overview, so I encourage you to read more about cookies and sessions.  These Wikipedia articles go a much deeper and have information on different types.  If you have any questions, please let me know in the comments below!

Happy coding!
Ryan from The Bunch

4 Woes of Organizing a Meal

When beginning to solve a problem, a great place to start is the pain points–the frustrations people have with the current process.  LunchBunch started because of the pain points encountered when grabbing a meal with friends–these were our motivation to create the app.  I’ll address them from my perspective, and hopefully you can relate:

  1. Eating alone or with the same people every day.  I don’t plan who I am going to eat with, so when lunch rolls around at college (now at work), I need to make plans.  Usually this involves texting people who either don’t respond in time or who already have eaten.  Sometimes this results in eating alone, or if I’m with people in class or at work before lunch, we’ll end up going… for the 3rd time this week.  While eating with people I sit with may be easy, there are plenty of friends who I don’t see as often and would love to catch up with.  LunchBunch is the tool that tells me if these friends are available for lunch before it’s too late.  And hey, if you want to eat with the same people every day, LunchBunch will help you organize those meals too!
  2. Organizing a group for lunch is an unwieldy process.  I can create a group message about lunch, but then other people join, maybe some people aren’t in my contacts, and sometimes I end up texting on 5 different threads about the same plans.  LunchBunch consolidates this into one invitation that clearly shows who’s going and where and when we are meeting.  Once the meal is over, the invitation disappears, so I don’t need to worry about clutter in the app.
  3. Not remembering who I want to eat lunch with.  There are many people who I’d love to get a meal with, but I think about it before I go to sleep, not when it’s helpful–before lunch.  With bunches, I can easily group which people I want to get lunch with and broadcast to them first. If they aren’t available, I can edit my broadcast to include everyone else.  Or I can broadcast to everyone from the get go; whatever mood I’m in, LunchBunch makes it simple.
  4. Choosing where to get lunch. Soon, LunchBunch will be partnering with restaurants to make it easier for my buddies and me to decide where to eat.  I’ll be able to see local restaurants and the specials they’re offering–great if I’m on a budget but still want to go out with friends.

What pain points do you encounter when trying to grab a meal with others?  Share in the comments, and maybe LunchBunch can help to solve your lunchtime laments and dinner distresses!

Matt from The Bunch

Android Push Notifications

Push notifications are important. Really important, actually.  When we released our first iteration of the LunchBunch, the most common feedback from users was that notifications didn’t act the way they were expected to.  A friend texted me saying, “I think something’s wrong with my phone, because notifications in your app don’t take me where I expect to go.” He thought it was a software issue on his phone’s part, not on ours! It was then that I realized we needed to focus our attention on notifications.

In this post, we’ll discuss two things: how the notifications get to our phones (specific to Google Cloud Messaging [GCM] notifications), and how we as developers parse them and notify the user. We’ll completely and intentionally ignore the aesthetics of the notification.  That’s actually an important discussion but out of the scope for this post. Check out Android’s Notification Design docs for more information.

Okay, first thing’s first–how do these great bundles of information reach my phone? Take this scenario for example: You just downloaded LunchBunch (congrats on the great decision, by the way), and you need some buddies to grab a meal with. So you add your best friend, Taylor. Well, Taylor is super psyched that you requested to be buddies and immediately accepts! Now, you won’t know that until we at LunchBunch send you a friendly notification. So what do we need to do?

Our application server, now knowing that you and Taylor just became buddies, will send a bit of data with the good news to Google’s servers. You, the user, having subscribed to receive notifications from LunchBunch (we’ll talk about this next), are now sent a notification from Google’s servers, and you can begin planning meals with Taylor. For all that to happen, our application servers need to be registered with Google to send them data, and you as a user need to subscribe to the notifications. I won’t walk you through the setup process (it’s boring, and Google does a good job with it here and here), so let’s get into the client-side code.

How do we subscribe to get notifications from LunchBunch? This all happens in an IntentService. When the app is installed, or when Google deems the last subscription stale, an Intent is kicked off to begin an IntentService (let’s call it CoolAppRegistrationIntentService). We kick it off from the MainActivity, the first activity that loads upon the app opening:

Intent intent = new Intent(this, CoolAppRegistrationIntentService.class);

The job of this IntentService is to get a token from Google to be sent to our Cool App application server. Here are the lines of code that do the magic:

InstanceID instanceID = InstanceID.getInstance(this);
String token = instanceID.getToken(getString(R.string.gcm_defaultSenderId),
        GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);

After these lines, we have a token that will be sent to our application server for communication with the GCM servers. So, we have to get the token to our server. How you do that is up to you, but once you get confirmation from your server that it’s received the token, we’ll want to set some sort of Boolean that keeps the application from sending that token again for no reason, maybe in SharedPreferences:

if (status.equals("success")) {

Sweet! Now we’re all set up to receive notifications. Snap, now we have to actually handle that, too!? No worries, it’s a piece of cake. There’s a GcmListenerService that does all the magic. What you’ll want to do is write your own class–let’s call it CoolAppListenerService–which extends GcmListenerService. You’ll implement a method called onMessageReceived, which has an important parameter–the data of the notification. Exciting, huh? That’s the data you’ll parse and (maybe) display to the user!

What’s been said so far is only bits and pieces–enough to get an understanding of the subscription process…But what I’m about to touch on is the nitty gritty application-specific stuff.

How you handle different notifications is totally up to you, but at some point you’ll want to display a message to the user. You can include this in the data, and extract it easily:

String frontFacingMessage = data.getString("message");
boolean sendNotification = !(TextUtils.isEmpty(frontFacingMessage));

Here we’ve included some message in the data if we want the user to see the change, and if that’s empty we don’t want the user to be privy.

Let’s go through two examples of actually parsing the notification data. First up, the story from before: Taylor just accepted you as a buddy, and LunchBunch is letting you know.

intent = new Intent(this, MainActivity.class);
intent.putExtra("action", "to_bunches");
notificationID = 0;
//Create a new buddy from data
String username = data.getString("username");
String firstName = data.getString("first_name");
String lastName = data.getString("last_name");
if (username!=null && firstName!=null && lastName!=null) {
    database.createBuddy(new Buddy(username, firstName, lastName, 0)); Event());

Whoa! That’s a big chunk of code. What does it all do? Not a whole lot, really. The first few lines create an intent that will be fired off when you click the notification. This one specifies the MainActivity and has an extra on it that will tell the MainActivity to send you to the Bunches page to see the new buddy. Below that, a notification ID is given to the notification, so we can dismiss it (or update it) manually in case the user doesn’t click on it or swipe it away. Finally, the end of this chunk mainly pertains to creating a new buddy to be added to our local database. We pull the username, first name, and last name from the data, and insert the buddy. Oh, and the last line is important–it posts a broadcast to our bunches page to update, in case you were looking at that page when the notification came in! Since the buddy was inserted into the database already, the adapter on the ListView would refresh, showing you the brand spankin’ new buddy in your list.

Now, a really simple and easy second example. The opposite of a new buddy, an ex-buddy. While we hope you never have any ex-LunchBunch-buddies, it’s a good way of seeing an example of when we wouldn’t want to notify you of a change.

String debuddyer = data.getString("username");
if (debuddyer!=null) {
    database.deleteBuddy(debuddyer); // Delete buddy from DB
} Event());

In this instance, all we’ve done is parse for the username of our old friend, delete them from our database, and tell the Bunches Page to refresh. You don’t see any notification ID or Intent here, because there won’t be any actual visual notification.

Great! All done? Nope, not yet. You might have realized that we didn’t actually do anything to notify the user in our first example.  Good eyes, chief!

At the end of the parsing code, we check to see if we should send a notification (using our boolean from before), and if we should, we create one:

private void sendNotification(String message, Intent resultIntent, int notificationID) {
    // Notification attributes
    NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(this)
.setContentTitle("Cool App)
    // Intent to start Activity
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    // Adds the back stack
    // Adds the Intent to the top of the stack
    // Gets a PendingIntent containing the entire back stack
    PendingIntent resultPendingIntent =
            stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
    NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

This is just the basics, but it will do the trick.  We use the NotificationCompat.Builder to build a notification that will look sweet regardless of the API it’s being displayed on.  We set an icon, a title, and the content to be displayed.  Below that, you’ll see the intent that we defined in our new buddy example, which will fire off when the notification is clicked. In that same block of code, we define a back stack, so that the application will navigate the same as if the user had navigated to that place in the app himself, rather than having clicked on a notification.  Finally, we get an instance of NotificationManager and call notify(), using the notification ID we defined in our code.

And there you have it, the user has been notified! Congratulations, you’re well on your way to an app that meets everybody’s high expectations 🙂

How do you use push notifications in your applications? Interested in learning more about a specific concept? Let us know in the comments below!

Brandon from The Bunch