Playing in Android Land

I’ve been using an iPhone since 2008. I also have an iPad and a Macbook Pro. It’s time to explore the other world, but not as a consumer. That would be too easy. Instead, I’m learning how to build Android apps.

I’m 3 weeks into Codepath’s Android course. The course is free and I’m always up for learning new things. So why not? Plus, I’m tempted to say good-bye to my iOS attachment and move over to Android world.

By using Google’s Image Search API, I built a simple Android app that searches for images. The user can apply filters on the search and share specific images. The searh results is making use of infinite scroll.

On the back end, I’m using:

The code is still a bit messy as I wrap my head around Java. I had no idea how pithy ruby is. I write almost twice the amount of code in Java to do the same thing. Putting this blog post up to see how far along I’ll be in 5 more weeks.

The Reluctant Programmer

Three years ago, I picked up a new hobby. This thing called programming. The more I learned, the more interested I became. It crept into my life unexpectedly and soon I was foregoing sleep to code. But I didn’t call myself a programmer, and I had no desire to work in tech. Coding was a way to entertain myself. I’d build silly little apps, like the one to help with meditation or the waiver application my yoga studio used.

My stereotypes of programmers prevented me from connecting the dots. Yes, I loved to code, but I wasn’t one of them. Programmers were the same guys that played Magic cards in grade school, later World of Warcraft in high school. They wore free t-shirts given away at tech conferences and ugly sandals with socks. Programmers were introverted types, shying away from human interaction and especially girls. No one in my circle of friends was an engineer.

Then I met Nicholas at a Skillshare class. He wore skinny jeans so tight, even I couldn’t fit into them. He sketched all day and understood me. We’d pontificate about life in his East Village walk up, while his cat roamed about. We started collaborating and built what we hoped to become the center of comics on the internet. He called it Binsapp.

I met Adam through the same class. He dressed as if perpetually coming from the gym, wearing shorts and a ratty t-shirt. The only thing we had in common was being from New Hampshire. Well, that and the fact that we were both noobs. We started working on a project for HowAboutWe. He knew I was smart, but impatient. He forced me to take breaks to clear my head.

If it wasn’t for Avi Flombaum, I would have never made the leap. It was him that made me re-evaluate my time-consuming hobby and the possibility of it becoming more. I resisted for months. I told him I couldn’t see myself as a programmer. I talk too fast. I’m vain. And I’m really much too loud. I wouldn’t fit in. Avi reminded me that I was talented at programming. With more time, I would be unstoppable. It’d be a shame not to pursue it. But it was his final point that programming would open doors that convinced me. No matter what industry I was interested in, technology would most certainly play a role.

This blog post is my public thank you to Nick, Adam and Avi. Nick and Adam, thank you for challenging my stereotypes about men in tech. You two understand me, despite our vastly different backgrounds. Avi, thank you for being my teacher, friend and life coach. You believed in me when I doubted myself. You three have a special place in my heart. Most important though, thank you guys for bringing another female into an industry that’s starving for them.

Back to Basics: Ruby’s Method Lookup Path

There are some people that read the instructions from beginning to end, before putting together the furniture. Then there are people like me. We just glance at the diagram, shrug our shoulders, and start building. Fortunately or unfortunately, that’s how I approach programming. When I’m debugging, I’ll throw in a binding.pry, drop into a developer console session and just muck around to see what’s up. But the problem with that is you make assumptions, and you may end up wasting more time making the wrong assumptions.

It pays to go to the source of truth and read the code/documentation, whether that’s the ruby standard library or the gem you’re using. Read what the author wrote, and given that ruby is such an expressive language, it’ll probably make sense!

Helpful resources for digging into the code:

  1. Ruby documentation
  2. Good ol’ Github
  3. Dash - yes, I actually pay for this. Helps when I choose to code with out the internets.
  4. bundle open [gem name] To open up the code right in your favorite text editor

Often times, in gems, there’s a lot of meta-programming and classes/modules that are intertwined. A method call on an object might result in something be counter-intuitive. So how exactly does ruby call a method on an object?

The object first asks itself, which class do I belong to? In the object’s class, is there an instance method by that name? If not, go up the ancestor chain until you find a method with the same name.

1
2
3
4
5
6
7
8
2.1.2 :007 > my_array = %w(Sprinkles Garbage Feline Kitty)
 => ["Sprinkles", "Garbage", "Feline", "Kitty"]
2.1.2 :009 > my_array.class
 => Array 
2.1.2 :010 > my_array.class.ancestors
 => [Array, Enumerable, Object, Kernel, BasicObject] 
2.1.2 :035 > my_array.nil?
 => false 

The method .nil? doesn’t intuitively seem to be exclusive functionality of Arrays. In fact, we can search through the instance methods of arrays to see if that’s true. Passing in false as an argument to instance_methods excludes inherited instance methods. Moving up the chain of ancestors, we search each parent, until we find where the method lives.

Basic Object
Kernel
Object
Enumerable
Array

 

1
2
3
4
5
6
7
8
2.1.2 :040 > Array.instance_methods(false).grep(/^n/)
 => [] 
2.1.2 :041 > Enumerable.instance_methods(false).grep(/^n/)
 => [:none?] 
2.1.2 :042 > Object.instance_methods(false).grep(/^n/)
 => [] 
2.1.2 :043 > Kernel.instance_methods(false).grep(/^n/)
 => [:nil?] 

What is this Kernel class? Actually, it’s a module and it’s included in the Object class. When modules are included in a class, they’re inserted above the class in the chain of ancestors. The ordering matters greatly.

It’s helpful to visualize the chain of ancestors vertically to determine which method ends up being called. You can imagine reading the code in this order, down the screen. If you had a class where a method was defined twice. The last time the method was defined would take precedence.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Array
  def my_method
    puts "first time"
  end

  def my_method
    puts "second time"
  end
end

2.1.2 :054 > Array.new.my_method
second time
 => nil 

Similarly, if you had a method defined twice within the chain of ancestors of an object, the last time the method is defined takes precendence. Now that you understand how methods are called in ruby, leveraging libraries with heavy meta code will be that much easier. Cheers to better coding!

Solution to Your Law of Demeter Code Smells

Sometimes you write code that you’re not too proud of. It’s just too easy to chain a bunch of methods together. However, that’s in violation of the Law of Demeter. Like all design principles, this law helps us write code that is maintainable and adaptable. The basic gist of the Law of Demeter is that any object should assume as little as possible.

- Each unit should have only limited knowledge about other units: only units “closely” related to the current unit.
- Each unit should only talk to its friends; don’t talk to strangers.
- Only talk to your immediate friends.

An object shouldn’t have to reach through another object to call a method. There are times that we really can’t get around this. Take the example below. We have a gift class that belongs to a giver and a receiver. We need to know the full name for whom the gift is for.

1
2
3
4
5
6
7
8
9
10
11
12
class Gift
  belongs_to :giver, class_name: "User"
  belongs_to :receiver, class_name: "User"
end

class User
  attr_accessible :first_name, :last_name

  def full_name
    "#{first_name} #{last_name}"
  end
end

How do we avoid doing something like this: gift.receiver.full_name? With the help of delegate from Rails, we can refactor things to look more like this.

1
2
3
4
5
6
7
class Gift
  belongs_to :giver, class_name: "User"
  belongs_to :receiver, class_name: "User"

  delegate :full_name, to: :giver, prefix: true
  delegate :full_name, to: :receiver, prefix: true
end

Adding the prefix: true option means now we can call gift.receiver_full_name. This brings the knowledge of the method full_name closer to the gift object, so now it is rightfully be able to call the method without violating the Law of Demeter.

Lifehacking Your Commute

I’m not a fan of commuting. Little did I know how spoiled I was in NYC, never living more than a 1.5 mile radius from where I worked. Now my commute is anywhere from 65 minutes to 2 hours one way. But enough about my commute! We are here to talk about how to make it better.

Like a lot of nerds out there, I’m all about productivity. At the office, we all took personality tests, that were based off of Myers-Briggs. The results pointed out that I am motivated by novelty and excitement (duh) and I’m always picking up new skills. Sounds about right! This blog has been documenting my progression as a software engineer. It only makes sense to use my commute time as another opportunity to get better at coding.

The trick is to already have a game plan before you start the commute. Once you get on the train, or start driving, it’s too easy to turn on the music or incessantly check facebook. Be realistic about your game plan. In the morning, you may be able to read a heavy duty programming book, but on your way back you just need to chill. Listen to a podcast then.

Podcasts

They’re a great way to get an overview of technologies you’re not familiar with. My favorites are:

  1. Ruby Rogues
  2. The Changelog
  3. Giant Robots Smashing into other Giant Robots (from Thoughtbot)

Books

The train ride is dedicated alone time. Without a commute, I’d never read as much as I do now. My current read is Head First Java. Turns out, learning an additional language isn’t that hard. More about that in a different blog post.

Pocket

Loooooove Pocket. This is how I do most of my internet reading, sans annoying ads. When Ruby Weekly comes out, I “pocket” the articles I want to read. I also have some IFTT recipes to fill my Pocket with my favorite blogs. Pocket strips all the extra stuff away and delivers the content in an easy to read format.

Coursera

Coursera is an online education platform where you take courses from well known Universities for FREE. You can choose from their many computer science courses, where you’ll have access to video lectures, problem sets, quizzes and even a final exam. The student forum discussion is also helpful. You don’t even need to be in front of your computer to get through the course! All you need is a smart phone. Coursera has a great iPhone app, which is how I watched lectures on my train rides.

Reset Time

Commuting might be your only alone time to decompress. Taking breaks can actually help you be productive and increase creativity, according to this article. The last thing you want to do is brun out. Give that brain its rest.

Converting to Vim

I remember the first career fair that Flatiron held, somebody asked a fellow student what their favorite vim shortcut was. When he admitted to not knowing what vim was, the potential employer turned around and walked away. It was a blessing in disguise. You don’t want to work for closed minded managers that would correlate knowledge of vim to programming potential. Nevertheless, the memory stuck in my head, and I wanted a chance to try for myself. Almost two years later, I’ve finally taken the plunge.

Why Use Vim?

The mouse or touchpad is bad. The single repetitive motion the mouse asks of you, carries tension all the way up to the base of your neck. I’ve tried countless ergonomic solutions. None have worked for me. I end up with a stiff neck and have to turn my whole body to talk to someone. The mouse is also SLOW. During my finance internship training years ago, they took the mouse away and had me build spreadsheets, timed. I love keyboard shortcuts and that’s all vim is. A text editor chock full of shortcuts. Oh yeah, and almost every computer has it built in already. No need to get a license and install. It’s open source! Tons of plugins at your disposal.

How I Made the Leap

Before I installed every plugin known the earth, I started with the bare basics. Borrowed heavily from @rheaton, you can copy my .vimrc and plugin setup here. Follow the README for setup instructions.

Next, I ran vimtutor straight from the command line for a great interactive tutorial. Vim Adventures is another great one to build up that muscle memory. And of course, I watched Upcase’s vim online tutorials

Shortcuts I use regularly

As you go along your normal text editing ways, you may notice yourself doing repetitive tasks. Write it down and google or ask someone if there’s a faster way via vim. Then add the shortcut to your cheat sheet. Pair programming also helps, by observing what shortcuts they use. Just like learning to type, the shortcuts will become part of your muscle memory. Here’s my list.

Pane Navigation

  • Ctrl + w + w: switch panes
  • Ctrl-w + s: horizontal splitting
  • Ctrl-w + v: vertical splitting
  • Ctrl-w + q: close pane

Search and/or Replace:

  • :%s/what i want replaced/newtext/gc
    • g is multiple times per line
    • c is confirm
    • gcc instead of gc if you don’t want to confirm
  • /search_for_this_text
    • n: go to next match
    • N: go to previous match

Navigation:

  • h, j, k, l: your arrows on the home keys (for more daring fun, completely disable your arrows)
  • Ctrl + ^: beginning of line
  • Ctrl + $: end of line
  • w: until the start of the next word, EXCLUDING its first character
  • b: beginning of previous word

Formatting:

  • V: select whole lines
  • v: in select mode
  • Ctrl+ v: visual block mode, select vertically
  • indenting multiple nested blocks: highlight block of text, then =
  • ~: toggles case

Nerdtree:

  • \: access nerd tree
  • m: nerd tree menu
  • shift + \, shift + r: refresh nerd tree

Practice!

There is something to be said of wisdom from experience. I’ve always been quick to jump into things, but I’ve come to realize, sometimes you need to slow down now, to be faster later. So just jump in and start doing it! It will take less than a month before you feel completely comfortable, which isn’t that long in the grand scheme of things.

This blog post can help get you started. My list above only scratches the surface of vim’s power. Very soon, you’ll be combining operators and motions, and tapping away blazingly fast!

Yield Confusion

Photo from Free Images

You’re not alone if you’ve been thoroughly befuddled with yield statements in code. Ruby is incredibly semantic, but not all the time. One way of thinking about yield statements is to compare it to driving. When you merge onto the highway, you must yield to oncoming traffic. Essentially, you let the other car go first, unless they’re way behind you, which in that case, you don’t care. In ruby code land, a method executes each line of code, until it reaches the yield statement, then it lets the block go first, before the rest of the code is executed.

1
2
3
4
5
6
7
8
9
10
11
12
def my_yielding_method
  puts "I love cats"
  yield
end

my_yielding_method do
  puts "i love dogs"
end

I love cats
I love dogs
 => nil

You can also pass in parameters into a yield statement.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
def my_yielding_method
  puts "I love cats"
  yield("sometimes")
end

my_yielding_method { |word|  puts "I love dogs #{word}" }

I love cats
I love dogs sometimes
 => nil

my_yielding_method { |word|  puts "I love people #{word}" }

I love cats
I love people sometimes
 => nil

my_yielding_method { |word|  puts "I love working #{word}" }

I love cats
I love working sometimes
 => nil

Similar to driving, yield statements are all about right of way. It means the block of code outside the method has right of way. After it has finished, the rest of the method may proceed.

Service Objects

As a project grows in lines of code, you may feel icky. Your code feels bloated. You can’t find certain methods. Everything just becomes a mess. It probably feels gross because you know about the Single Responsibility Principle. It states that everything in your code should be responsible for one thing only. Every method should be doing one thing. Every model should be doing one thing. Every controller action should be doing one thing. So you start pushing logic out of the views and into the controller. Then your controllers become 100 lines long. So you start pushing the logic into the models. Now your ActiveRecord model becomes hundreds of lines long, and it feels like you’re stuck with the same mess, just in a different place.

Why should you care to organize your code? To be kind to your future self! Your future self is only going to look at this code again for two reasons: because another feature is being added on OR there was a bug. Your future self does not want to wade through a spaghetti of code. You future self wants to be relaxing next to the pool, sooner rather than later. If your current self pays a little attention to code design and keeps things organized, your code becomes easily extendable and easily testable, and your future self will be happier.

In the code base I’m working on, there was business logic, that was transactional in nature, living in our ActiveRecord models. We had a Subscription resource that was responsible for pausing itself, canceling itself and calculating its own billing cycle. Whew! That’s too much responsibility for one little resource. So we started using Service Objects, like SubscriptionCanceler. Its only responsibility was to cancel the subscription. In fact, we used this naming convention for all our new Service Objects, the object that was being worked on, plus the action that was being done on it.

There were several steps that needed to be taken to properly cancel a user’s account. Each step was a method in our Subscription model.

  1. Invoice the customer any remaining balance
  2. Unsubscribe the user in Stripe
  3. Save relevant cancel information to our database
  4. Trigger a cancel notification

We moved those methods into our Service Object.

app/service/subscription_canceler.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class SubscriptionCanceler
  attr_reader :user, :reason, :subscription

  def initialize(subscription, reason)
    @subscription = subscription
    @user = subscription.user
    @reason = reason
  end

  def run
    return if subscription.canceled?
    invoice_remaining_balance unless box_returned?
    unsubscribe_in_stripe
    ActiveRecord::Base.transaction do
      close_open_invoices
      set_cancel_info
      trigger_cancel_notification
    end
  end

  private
  def invoice_remaining_balance
    ...
  end

  def unsubscribe_in_stripe
    ...
  end

  def close_open_invoices
    ...
  end

  def set_cancel_info
    ...
  end

  def trigger_cancel_notification
    ...
  end

  def box_returned?
    ...
  end
end

Now, our old subscription model would replace all of its cancel related logic with one little method.

app/models/subscription.rb
1
2
3
4
5
6
7
class Subscription < ActiveRecord::Base

  def cancel
    SubscriptionCanceler.new(self, reason).run
  end

end

This also meant our specs wasn’t a bloated mess either. We only have one spec related to cancels. Hurray! My future self is at peace now. Special thanks to @raybizilla for turning me on to this new way of code.

Recursive Algorithms

I signed up for Stanford’s online course, Algorithms: Design and Analysis Part 1, via Coursera. For those people with less traditional comp sci backgrounds, there are plenty of resources to get you up to speed. Lifehacker referenced a list of free, online courses, that would be the equivalent of a bachelor’s degree in computer science. I chose to start with algorithms. This seems to be the weakest point of self-taught programmers because you honestly rarely have to use it. It also happens to be one of the favorite type of problems interviewers like to ask.

I wanted to blog about the merge sort algorithms we’re learning in class or the problem sets I’m working on, but Coursera has a strict honor code that prevents me from facilitating other students from cheating. Instead, I’m going to talk about how to approach those dreaded interview questions that need to be dealt with using recursion. Most of the time, interviewers won’t even say they’re looking for recursion. They’ll just say something like, write me a method that outputs this. But if the output depends on the answer to a simpler instance of the input, you’ve got yourself a recursion question.

Here’s how to approach the problem:

  1. Identify the input. It might be an array, string or number. Usually the problem will be framed something like, “Given a number n … blah blah blah”. So n is your input and you know it’s a number. You might want to ask the interviewer to clarify. Is n a positive integer or is it a float?

  2. Identify how an simpler instance of the input would be helpful. If your input is an integer, the smaller instance of the problem could be n - 1. If your input is an array, a simpler instance could be a subarray of the original array.

  3. Identify the base case. The case where there does not exist a simpler instance of the input.

  4. Write the method, using recursion. A recursive method calls itself with a simpler instance of the input.

Example Interview Question: Write a method that given the index n, output the value in the Fibonacci sequence. The Fibonacci sequence goes something like 1, 1, 2, 3, 5, 8,…

Step 1: The input is n, a positive integer that represents an index.

Step 2: Any value in the Fibonacci sequence is the sum of the previous two values in the sequence. We need the output of n - 1 and n - 2 to calculate n.

Step 3: The base case is at index 0 and 1 because n - 2 for both indexes would result in a negative number, which we know are invalid inputs.

Step 4: Use that recursion magic. Voila!

1
2
3
4
5
6
7
def fibonacci(n)
  if n > 1 # not the base case
    fibonacci(n - 2) + fibonacci(n - 1)
  else
    1
  end
end

One of the reasons why recursion is difficult to understand is our inability to follow how many times the method calls itself till it gets to the base case, then bubbles back up. Seeing a recursive method can leave us questioning, does this really work? I find that starting with a couple steps above the base case will usually help validate the method works. Then, like the comic above, I cross my fingers.

Adventures at RailsConf 2014

My first RailsConf was a relief. For a long time, I’ve felt like an outsider, someone still trying to be a programmer. I think they call this imposter syndrome. But being surrounded by 1,500 Rails enthusiasts made me realize I’m exactly where I need to be.

The opening keynote speaker by the father of Rails, DHH, kicked off the four day conference with the declaration of Computer Science being detrimental to our community. In fact, he calls it pseudo science, a collection of beliefs or practices mistakenly regarded as being based on scientific method, like fad diets. Juice cleanses, anybody? All these programming “laws” are preached to be our way to salvation, where we can rid ourselves of “dirty code.” And the worst offender? The TDD heretics out there.

DHH is controversial. He struck a chord with many people, and must have alienated half of the attendants. I was thrilled. Not because I think algorithms or TDD are stupid, but because he was breaking the mold of what we think a programmer should be. Since graduating Flatiron School, I’ve heard many people claim they only hire Computer Science majors. I’ve even strongly considered going back to school and getting my Masters in Comp Sci. Paying over $60,0000 to achieve a sense of validation? Yes, I was almost there. My teacher pointed out the root of my problem: finding validation from external factors will always leave me feeling inadequate. What I was looking for, is only something I can give myself.

There was a session at RailsConf about the Imposter Syndrome. 70% of all professionals will feel this at one time in their career. In fact, if you’re introverted and a perfectionist, you’re very likely to experience it. If you’re a high achieving woman, even more so. I was expecting to feel like an outsider at the conference. Instead, I found a lot of people like me, curious, clever and eager to help. I was honestly surprised by how friendly everyone was. Not once did I feel uncomfortable being one of the few females there. It seemed that many were going out of their way to be extra respectful because of this fact.

When I started my journey to start programming, I luckily chose Ruby on Rails. Coding in Ruby is eloquent. Building apps on Rails is fast. The Rails community? It’s inclusive and supportive of even someone like me.