Posts Tagged

programming

Squashing commits

In one of my previous employers, we would make one commit per ticket. This seemed to go against the common wisdom “commit often”, but I noticed that it had several advantages.

The first advantage was that the feature was easy to roll back if needed. All you had to do was find the one single commit that represented an entire ticket (which could be a feature, bug, and etc.) and simply git revert it. Compared to having multiple commits for one ticket, you would have to find all the commits and then revert all of them. I find reverting one single commit to be simpler.

The second advantage was that it was easier to code review. This could be entirely a personal preference, but I find one single commit much easier to review and easier on my eyes than following a sequence of commits for a single ticket. But again, this is a personal preference thing. Perhaps some people find it easier to understand what the programmer was thinking by following a sequence of commit messages, almost like reading a story of events that happened during the coding process for a single ticket.

I also think that people just don’t squash commits because they don’t know about it. After I started freelancing, I’ve noticed that squashing commits was one of those random git things that a lot of people didn’t know about. For example, I asked one other freelance developer to squash his commits in the pull request that he made and he didn’t know that was something he could do in git.

For those of you who don’t know how to squash commits, and would like to know, it’s very easy. All you have to do is take the number of previous commits that you would like to “squash” into one and run this in your terminal.

git rebase -i HEAD~{number of commits}

After you run that command, a default text editor set in your terminal will open up with the following content that looks like this.

Note: this is me squashing 3 commits into one so the command I ran would be

git rebase -i HEAD~3

From here, change the last two commit message’s “pick” statements into “squash” so that your editor looks like this.

Save and exit your editor and a new instance of your editor with the following content will open up.

Now, you can just save this file and exit as it is and you’ll have squashed the three commits into one. If you want to write a new commit message, you can delete all of the three commit messages and write a new commit message like this.

And then the commit message for the new one commit will be “NEW COMMIT MESSAGE!!!”.

As I mentioned, I prefer squashing commits especially when working on teams. This is all a personal preference of course and doesn’t mean that squashing is superior compared to multiple commit messages per ticket.

I thought I’d write this up since I’ve came across developers who weren’t aware of this feature in git.

Commenting your code

Commenting your code is one of those things that everyone has a different opinion about.

Most of my programming experience come primarily from working on Ruby on Rails applications. One thing that’s emphasized in the Ruby on Rails community is the importance of writing clean and elegant code that speaks for itself.

In the jobs I’ve held, it generally meant that you shouldn’t be writing comments in your code. Instead, your code should speak for itself so that when another developer looks at it, they know what your code does by reading the code rather than having to read any accompanying comments.

My opinion on commenting code has been that you should be writing your code in a way that doesn’t need comments. This means descriptive variable names, method names, class names, and etc. However, I’ve had a few code reviews done on the projects I’ve worked on in the past few months where the feedback I received is that my code doesn’t have any comments and that I should start commenting my code more frequently.

So, should we comment our code, or should we not?

During the hand-off process of one of the projects I’ve completed, me and the client’s part-time CTO were conducting a code review. One of his immediate feedback was that I should have commented the code more. Me and him got to work over the few weeks after the initial code review and he proceeded to write comments on a lot of the pre-existing code. One example of his commenting on one of the methods was (note: this is just an example of the complexity of the code on hand, this isn’t the real code)

The original code didn’t have comments on it, but the code was commented once I began working with the client’s CTO.

Now, I think most developers will agree that the above method does not need to be commented at all. The name of the method clearly says what the method is intending to do, and ruby methods are named descriptive enough to signify to the developer what the “flatten” and the “sort” method should do. There is absolutely no reason to comment this method. In fact, commenting this method just makes the code more difficult to read since I have to now read over that “#” character in the method.

This reminded me into my first programming class in University where our assignments had categories where we would receive points for commenting our code. Yes, we got deducted points in our programming assignments if we didn’t comment our code, even if the program was trivial.

I thought that the majority of developers would agree with minimal commenting on code, and instead writing your code in a way that it speaks for itself, but after a few of these code review, I realized that there are developers out there who believe that commenting code is something that we should do as developers.

I don’t believe all commenting is bad. In fact, I do believe that there are times where commenting your code is necessary. However, you shouldn’t have to comment your code in 90% of the cases if you’re writing your code in a self-documenting manner. Here’s why I believe that you should opt for writing your code in a self documenting manner rather than commenting.

The computer doesn’t care about your comments

Yep, the computer doesn’t care about the comments in your code when it runs your program. The comments you write are for other humans, and….. it’s written by humans. Which means, we’ll forget to update our comments as we update our code.

Software projects have to constantly change to meet business needs. If your code depends on your comments to make sense, and the functionality of the code changes over time, someone will inevitably forget to update the comment that describes what the code is doing. Yes, the code will run even if you forget to update the comment, but the next developer who comes into the project will end up reading the outdated comments and misunderstand what the code is doing. And since the computer only runs your code and ignores your comments, it’ll be very difficult to understand what’s going on if there are any bugs and problems in your system.

I believe that this is the most important reason you should opt for writing self-documenting code rather than relying on comments. Some people might give arguments such as comments dirtying up your code, comments making your line of code longer, and etc. But at the end of the day, you want your code to speak for itself to better serve business needs, and to more correctly communicate the intention of the code to other developers. Using comments, especially to communicate the intention of the code to other developers is way too brittle.

So when should you comment your code?

There are times where I believe that it’s appropriate to comment your code. The main situation I can think of where commenting your code is appropriate is when the code your are writing is orchestrating some business rules with exceptions that may not be obvious to the developer reading the code.

For example, let’s say there’s a method in your code base that calculates the average of two numbers. Normally, you would sum the two numbers and divide the result by 2. But let’s say for example, you find that the method your looking at is dividing the result by 3. If there aren’t any comments, you would think that this was a bug. But let’s say this isn’t a bug and was intentional due to some weird funky business rule. This would be the perfect time to comment your code. So here’s an example.

If the comment wasn’t there, I would probably look at the code and go “huh, so I guess this is what’s causing the bug”. If this was intentional, and I “fix the bug”, I would cause even more bugs. However, if the comment was there, I would go “Okay, this is a little weird, but I guess this is how it’s supposed to work” and move onto other lines of code.

Conclusion

I strongly believe in writing self-descriptive code and only commenting it’s the only way of better communicating the purpose of the code. It better communicates the intention of the code, reduces potential for bugs, and turns your codebase into something like a blueprint/manual for the business it’s serving.

RubyC 2017 – Kiev Thoughts

I’m still in Kiev, Ukraine right now and I had the opportunity to attend RubyC 2017 conference over the weekend.

Despite having written Ruby professionally for a few years now, this was my first Ruby related conference. The tickets were only $100 so I figured that it would be a great opportunity to attend a software development conference as well as doing something productive and career related over the weekend.

Both Ruby and Ruby on Rails is over 10 years old at this point and one can make the argument that both the programming language and the web framework are both stable and mature. Due to it, the language has been “evolving” so to speak for the last few years and not too many ground breaking changes and/or features have been introduced. Also, the reason Ruby became popular at all is due to the rising (and eventual dominance) of Ruby on Rails. Ruby on Rails is essentially the “elephant” in the room. In fact, this was emphasized in many of the talks that were presented at the conference.

Pouches for speakers to sit for open talk session

One of the talks that I found to be the most thought provoking was “Ruby 4.0: To Infinity and Beyond” by Bozhidar Batso. He’s apparently the author of RuboCop which I found to be impressive. I love that library  as it helps me write cleaner code and makes me adhere to the basic programming and syntactical that I set for myself.

One thing Bozhidar Batso mentioned was that not much has changed in the last few version of Ruby. He had a few slides where he listed the major list of changes from Ruby 2.0 – 2.4 (I think he started from 2.0) and he did have a point in that each release since Ruby 2.0 has been incremental. In fact, the only change that I could think of that has been made from Ruby 2.3 – 2.4 (and this was listed in Bozhidar’s slide) was the unification of Fixnum and Bignum into the Integer class which generated a lot of deprecation warnings in some gems. Aside from that, nothing major sticks out in my mind.

Bozhidar also mentioned that Ruby is the only programming language where certain features and changes made are driven by the web framework that dominates the language, in our case Ruby on Rails. He mentioned how insane this is and a web framework shouldn’t influence the design of the programming language that it’s written in. He had a point there, but this made me notice that there was a lot of, “WE NEED AN ALTERNATIVE TO RAILS” mentality not only in the speakers but also by a lot of the audience. For example, when a statement about some negative aspects of ActiveRecord was mentioned, there were a few cheers made by the audience.

This is something I do not understand. The fact that as soon as something gets popular, we humans have a natural tendency to immediately start hating on it. This doesn’t just happen in technology stacks but even in coffee chains in Starbucks. How many times have you heard Americans say that they hate Starbucks and the coffee served is terrible? I personally think Starbucks coffee is pretty good, especially if you get it fresh in the morning. It’s strong and consistent.

Same goes for Ruby on Rails. As soon as it became the default go-to web framework for Ruby, there have been many talks about the need to replace it and that it’s inappropriate that something so dominant. During the conference, the Hanami web framework was proposed as something that could give Rails some competition.

Personally, I like Ruby on Rails. I think it’s well designed, easy to work with, and the most productive web framework in the market right now. Is it perfect? No, of course not. But is it a good tool for building web applications? Yes, it’s excellent.

There was an open talk session where the audience had an opportunity to ask the speakers any questions they had. One of the speakers mentioned that despite other speakers demoting Ruby on Rails and promoting something else, if he was the one paying for the software project, he would go with Ruby on Rails every time due to its emphasis on productivity and set of sane default configurations that it comes with. I completely agree with this. If I’m paying other developers to write a web application, I’m going to go with whatever is most productive and gets the job done in a timely manner with reasonable code quality. Also, due to its convention over configuration philosophy, new developers on the team can get acquainted with the codebase very quickly. Despite being over 10 years old, Ruby on Rails still hits on these points better than other technology stacks out there.

The speaker who gave the answer in terms of, “If I’m putting up my own money…”made me think of a training curriculum that all software developers should be required to go through. I think all software developers should have to go through a phase in their career where they have to manage a project from beginning to completion and through maintenance cycles where the team members are switched once every few months. Essentially, the training regimen should replicate a professional work environment as much as possible. I think a lot of software developers put too much emphasis on the engineering aspects of software development rather than the pragmatic side of it. Maybe, the training regiment should also include a portion where the participant loses money if he/she doesn’t complete the training regiment successfully. I’m willing to bet that a lot of participants will opt for tried and true technologies like Ruby on Rails than to Hanami or “enter the cool new shiny programming language/framework of the week” if their own money on was on the line.

Easy way to speed up your automated tests

Just a note before we start, this will be a Ruby on Rails centric post with code samples in written in Ruby. However, the concepts in this post can be applied to any tech stack, whether that would be Laravel, Django, Phoenix, and even mobile platforms like iOS and Android.

Most software developers are knowledgable enough to know that interacting with a database can be expensive. For example, one expensive query on a large dataset can seriously hamper your application’s performance. In the case of Ruby on Rails, this may include eager loading associations and avoiding ActiveRecord altogether and writing raw SQL queries. However, in many of the codebases I work on, I see that many developers do not adhere to this principle when writing automated tests.

For example, let’s say that we’re working on a Rails project for managing a list of books, the authors, and publishers. We have three models: Book, Author, and Publisher. Book belongs to Author and Publisher, and both Publisher and Author has many books. Below are the three hypothetical models.

Book

Author

Publisher

And now, for the purposes of writing our tests, let’s say that we’re using the FactoryGirl gem have three factories set up for each of the models defined above.

Book Factory

Author Factory

Publisher Factory

Okay, all of our models and factories are set up now. We are finally ready to write our tests!

First common mistake: Creating unnecessary records

I’ll give an example of a BooksController with the index method and then provide a “typical” test that I see often. This is the “bad” test.

Simplified BookController

BookControllerTest

Here, we have a pretty simple BooksController where we load up all of the books in the index method. And in our BooksControllerTest, we are creating 10 books and then testing the index route of the BooksController. This test will pass.

However… this test is not optimally written. Our Book factory has two belongs_to associations: Author and Publisher. In the setup block of our BooksControllerTest, where we loop 10 times to create 10 books:

This line of code will create not only 10 books, but a new set of authors and publisher each time the loop is executed. This line of code is devious as it looks like it’ll only insert 10 books into your test database. But in reality, it’s inserting 30 records (1 author and 1 publisher for each book), which is 3 times more records than the test needs.

These are unnecessary database writes that may seem innocent when your test suite is small, but it can seriously slow down your overall test suite as you write more tests.

The optimal way to write the BooksControllerTest should be

Modifying your tests this way, where you specify the author and the publisher that each individual book will belong to will ensure that you do not create unnecessary records (in this case, new set of authors and publishers) in our database, significantly improving performance.

In one of the projects I’ve worked on, just implementing this reduced the time needed to run the test suite from something like 13 minutes down to 7 minutes. You can see how this simple change can speed up the test suite by a lot.

Second common mistake: Writing to the database to check validations

In our example, all of our models validates the presence of the name field. Let’s write a test to make sure our models are adhering to this validation. I’ll show an example with the author model.

Above are two simple validation tests that check for the presence of the name field in the Author model. The above tests will pass, however they are not efficient. The reason for this is the same as the first common mistake which is unnecessary writes to the database.

You don’t have to actually write to the database to check the model validations. You can simply build a new instance of the model and then check the validity from there. Let’s rewrite this test to run faster.

Calling the build method on FactoryGirl will instantiate a random Author model rather than creating a new author and writing that author to the database. Also, rather than writing to the database to check the validity of the instance of the model, you can just call valid? on the model to see if the model is valid or not. This approach saves unnecessary writes to the database which in turn speeds up your test suite.

Closing note…

You can see that neither of the two examples above are difficult concepts to grasp. It’s just avoiding unnecessary database operations in your tests. These simple adjustments can make drastic performance improvements to the speed of your test suite.

Also as I mentioned at the beginning of this post, while this post was Rails centric, the same concepts can and should be applied to whatever language/framework you’re using.

Do not hold singletons in App level in Android

The first Android project I worked on was a freelance project that I joined midway. That app had singletons in the top App level and used the top level App.java file to store important variables. Since I was completely new to Android development at the time, I thought that holding an instance of the top level App object and using it to “hold” variables as singleton was an acceptable pattern. Oh how wrong I was.

Just to illustrate, this is what I mean by holding variables in top App level and an instance of it.

Here’s your average AndroidManifest.xml

And then App.java

Now, on line 11 – 13, where I hold the instance of App in a static variable and instantiate UserCacher and TokenRefresher and hold the instance of those variables in a static variable?

Yeah… don’t do that. It’s a terrible idea to do so. Here’s a brief explanation from a fellow Android developer who gave me a kind code review that helped me learn a bit more about how Android OS works.

In Android development, we have something called Context. Yeah, that thing that you can get by calling getContext(), getApplicationContext() so that you can call your typical Android system methods on. A context in Android development is like an area in which all instances of objects live in. When that instance of that context dies, all associated components of that context are removed from memory by Android’s garbage collection system. When you hold an instance of the App.java in a static variable like I did in line 11, it means that my ApplicationContext never dies, which eventually leaks memory, causing your app to crash.

Continuing on that front, do not store instances of non-simple objects in a static variable as they are not garbage collected. Stuff like this is fine

This stuff is fine since Strings are simple and won’t add much overhead to matter in your app’s performance. But do not do this with anything else like POJOs, Contexts, Views, and etc as it will cause memory leaks.

Puma config in development vs on Heroku

So that puma web server for ruby, the web server that’s built for speed and concurrency has a weird issue with its configuration on development environment vs on Heroku.

For those of who might not know, this is the puma web server I’m talking about

https://github.com/puma/puma

Yeah, the one that’s apparently the standard that comes with Rails 5 now.

One of the projects I’m consulting for (yes, it’s a Rails project) uses puma as its web server. And it has a puma.rb file that’s configured as recommended by Heroku. The file at config/puma.rb looks like

Now, you see on line 8 and 9 there? Despite the ruby code checking for the nil condition and defaulting to port 3000 and an environment of development if those environment variables are nil, this does not work in development mode if we run it with foreman with a Procfile. For some reason, the port for puma in development mode defaults to 5000 instead of 3000.

Now, if we put an = sign in front of the port and environment declarations like this

Then it works on development and the port for puma defaults to 3000. However, putting those = signs will break the Heroku server.

After wrestling with it for an hour, I simply decided to set the environment variables of PORT and RACK_ENV to 3000 and development accordingly on my development environment so that at least the application runs without crashing on Heroku.

It’s a super weird issue and I’m not sure why it’s working well on development and then goes haywire on Heroku. At any rate, for those who are running into the same issue, I hope this post was helpful.

Speeding up RecyclerViews

I recently had to deal with an issue where the scroll speed of a list of items in a RecyclerView was scrolling very slow. The view was usable, but you could notice the stutters and lag when using the application. I’ll go over a few things I attempted to speed up the RecyclerViews.

EDIT: There were some feedback about this article when I posted on the androiddev subreddit here. I wrote a follow up post about the solution I chose in this follow up post.

Before I get too deep into this post however, I have to mention that the main reason my RecyclerView was so slow as due to me displaying EditText elements in the RecyclerView. Render EditText elements are expensive, and since RecyclerViews “recycle” views as the user scrolls, the “onBindViewHolder” method is constantly called as the user scrolls, which causes the app to continuously re-render the already expensive EditText fields. So with that, I’ll start with the first tip…

1. Do not display EditText fields or any input fields in the ViewHolder

This was the first mistake that was made in the codebase. I wasn’t the original developer who began this project (although I took over the project at an early stage of development), but the previous developer made the decision to utilize RecyclerViews to render out various different ViewHolders dependent on the data that we received from the API. This resulted in more elegant code and probably more memory efficient application thanks to the nature of how RecyclerViews work, but resulted in a terrible user experience since the application had to continuously inflate the expensive EditText fields onto the screen. Therefore, RecyclerViews should not be utilized for any type of situations where you want to display a list of input fields.

The solution that I implemented was to remove the RecyclerView and simply loop through the input field data I received from the API, and dynamically inflate and add the input fields to the LinearLayout in my XML.

2. Make your onBindViewHolder as light as possible

RecyclerViews “recycle” views, meaning if there are a 100 rows, it doesn’t hold all 100 rows in memory. Instead, as the user scrolls, the RecyclerView removes the rows that aren’t displayed on screen, and then runs the code that inflates those rows again when the user scrolls back to the appropriate position.

The method that gets called to inflate the appropriate row is onBindViewHolder. Thus, this method is called constantly as the user scrolls through the screen, and therefore the code in this method should be as light as possible. The less efficient the code in the onBindViewHolder method is, the more performance hit you’ll take on your RecyclerView.

3. Prefetch the items in your RecyclerView

First thing if you haven’t, upgrade your support library to the latest version to at least v25.0. The reason being is that the Android team implemented something called prefetching in the RecyclerViews starting from v25.0 of the Support Library.

View story at Medium.com

Prefetching is explained in detail in the above Medium article, but the basic premise of the prefetch works like this. As the user scrolls through the items in your RecyclerView, rather than displaying the items as the user scrolls, the RecyclerView will prefetch the items up ahead as the user scrolls so that the item rows are ready to be displayed before it displays on the user’s screen.

The only disadvantage of this is that there’s a risk where you prefetch items that the user never scrolls to, thus wasting CPU cycle, but I think the benefits of prefetching items far outweigh the costs.

4. Preload all data that you need before you load them into your adapter

This is probably common sense but you want to make all your API calls and database queries for all your data before loading them up in yourRecyclerView.Adapter. This is to make your onBindViewHolder as light as possible. Think about it. If you’re making database queries constantly as the user scrolls through your RecyclerView, you’re taking an unnecessary performance hit. Just load up all your data and hold it in memory and then load it up on your RecyclerView.Adapter to avoid unnecessary performance hits.

5. Set setHasFixedSize(true) on your RecyclerView

If your design allows for it, in your RecyclerView, set setHasFixedSize(true). It’ll look something like this.

From the Google Docs:

https://developer.android.com/training/custom-views/optimizing-view.html

Another very expensive operation is traversing layouts. Any time a view calls requestLayout(), the Android UI system needs to traverse the entire view hierarchy to find out how big each view needs to be. If it finds conflicting measurements, it may need to traverse the hierarchy multiple times. UI designers sometimes create deep hierarchies of nested ViewGroup objects in order to get the UI to behave properly. These deep view hierarchies cause performance problems. Make your view hierarchies as shallow as possible.

Basically, whenever new items are inserted, moved, or removed, the size of the RecyclerView might change and in turn the size of any other view in the view hierarchy might change. This is expensive if this happens frequently. Avoid this unnecessary layout passes by setting setHasFixedSize(true) on your RecyclerView.

6. Set setHasStableIds(true) to your Adapter

There’s a method called setHasStableIds that you can call on your adapter. If you have a slow RecyclerView, try setting this to true like mAdapter.setHasStableIds(true). This is an optional optimization technique you can try to see if it speeds up your RecyclerView.

What this does is that it tells your Adapter that when you provide a ViewHolder, its id is unique and will not change. This prevents not-ideal situations where you might accidentally link the id to your item’s position. This way it doesn’t have to handle re-ordering of the entire adapter because it can tell if item X at position Y is the same as before and do less work.

7. If you’re using DataBinder, free your data binds up on onViewRecycled

This is a tip I got from reading this blog post

https://blog.workable.com/recyclerview-achieved-60-fps-workables-android-app-tips/

DataBinder is apparently a “thing” these days and if you’re using that, it’s a good idea to free up some unneeded resources. With DataBinding, it’s a good idea to remove onPropertyChangedCallbacks from our ViewModel and then clear the ViewModel itself from the binding.

 

I learned a lot about how to optimize the performance of my RecyclerViews during this little “exercise” in an attempt to speed up my client’s RecyclerView, even though I ended up replacing the RecyclerView with a more appropriate solution of simply inflating custom views onto an existing LinearLayout.

Hopefully this post can be of some help to those who are dealing with a slow RecyclerView.

SugarORM write WHERE IN (?) and WHERE NOT IN (?) statements

On my current freelance Android project, I chose SugarORM as the ORM of choice, mostly for the simplicity and ease of getting started with it. Unfortunately, like a lot of open source Android libraries, the documentation for it is pretty modest at best.

Recently, I had to try to write your standard WHERE IN ? and WHERE NOT IN ? statements where the conditions themselves would vary depending on the data that I received from the API. The methods of doing this was not anywhere in the SugarORM documentation, so I thought the best way of doing this would be writing a simple conditional. Unfortunately, this seemingly simple task wasn’t easy and it took me about an hour to make the query work.

Apparently, other developers have ran into similar problems, but since searching through the internets didn’t yield me with a working solution, I’m going to write the solution here in the hopes of saving other developers some valuable time.

So let’s say that you have some sort of Collection like an ArrayList, List, Array, and etc where you would like to use the conditions in that as a conditional in the WHERE IN (?) statement. You would do something like this.

Let’s say that you have a User model that looks like this

[code language=”java”]
public class User extends SugarRecord {
public String name;
}
[/code]

You would write a WHERE IN SQL statement with SugarORM like this

[code language=”java”]
ArrayList<String> conditionsList = new ArrayList<>();

conditionsList.add("joe");
conditionsList.add("karen");
conditionsList.add("chris");

StringBuilder queryBuilder = new StringBuilder();

for (int i = 0; i < conditionsList.size(); i++) {
if (i == 0) {
queryBuilder.append("(");
}

queryBuilder.append("’" + conditionsList.get(i) + "’");

if (i != conditionsList.size() – 1) {
queryBuilder.append(",");
}

if (i == conditionsList.size() – 1) {
queryBuilder.append(")");
}
}

List<User> userList = User.findWithQuery(User.class, "Select * from USER Where name IN " + queryBuilder.toString());
[/code]

The above snippet should get you the data that you are looking for.

Java nested classes – Static vs Non-static

I was working on a client project where I’m utilizing SugarORM as the ORM of the choice. One of the POJOs had few nested classes that I wanted to cache and query using SugarORM.

The SugarORM methods to perform standard CRUD operations on the objects were not working. Through some Googling, I realized that you had to make the nested classes static classes in order for the SugarORM methods to work. So to give a quick example

[code language=”java”]
public class Foo extends SugarRecord {

public Foo() {}

public class NestedFoo extends SugarRecord {

public NestedFoo() {}
}
}
[/code]

In the above example, SugarORM methods will work for Foo, but won’t work for NestedFoo. To make the SugarORM work for NestedFoo, we need to make the NestedFoo into a static class, like this.

[code language=”java”]
public class Foo extends SugarRecord {

public Foo() {}

public static class NestedFoo extends SugarRecord {

public NestedFoo() {}
}
}
[/code]

This brings up the question, what is the difference between static nested classes vs non-static nested classes in Java?

In Java, nested classes are divided into two categories: Static and Non-Static. Non-static nested classes are also simply called inner classes. These inner classes can only exist within an instance of the outer class. So for example, if the NestedFoo class above was non-static, that NestedFoo class will only be able to exist within an instance of the Foo class. Inner classes also have full access to all methods within the instance of the >Foo class.

Static nested classes do not have access to the instance of its parent class. So in our example, if the NestedFoo was a static class, it would not have access to the non-static methods or even an instance of the parent Foo class. In fact, nested static classes, if one wants to instantiate them separately, would be instantiated like this

[code language=”java”]
Foo.NestedFoo nestedFoo = new Foo.NestedFoo();
[/code]

while non-static nested classes would be instantiated like this

[code language=”java”]
Foo foo = new Foo();
Foo.NestedFoo nestedFoo = foo.new NestedFoo();
[/code]

Now back to the topic of SugarORM. For nested classes, why does SugarORM only work with static classes? To be honest, I have no idea. I’ll probably have to dig into the source code of SugarORM to be absolutely sure, but my guess at this point is the following:

  1. If the nested class is a normal inner class and non-static, then it can only exist in the presence of an instance of the outer Foo class. The outer Foo class already extends from SugarORM in my case, so something could be conflicting there.
  2. Again, if the nested class is non-static, it can only exist within the instance of the outer Foo class. It also has access to all of the non-static methods to the instance of the outer Foo class, so in a way, it’s kind of like extending a class. I wonder if something can potentially conflict if you extend an inner class.
  3. From learning about the primary differences between a static vs non-static nested classes, it seems like static nested classes really are just normal classes excepted nested. One advantage of this is that the nested static classes do have access to static methods in the outer parent class, and if you only use this nested class within the context of the parent class, then it’s a much better way of organizing your code. And because the only relationship between the parent class and the nested class is that the nested class has access to static methods in the parent outer class, then extending the nested class should have no ill-side-effects compared to extending a nested non-static class, therefore allowing SugarORM library to do its magic.

Again, the above are just educated guesses. Maybe one day I’ll dig into the source code of SugarORM to find out for sure, but for now, the above will do for me.

Lack of good documentation in the Android community

This is a off-topic post that came out of the SearchView implementation post I wrote here.

This is something I’ve noticed consistently while working on Android apps. The Android community seems to not put too much importance on documentation. When you look through popular Android libraries like DBFlow (a popular ORM for Android), and look at the README or the Wiki, there’s literally zero information on how to use the library. The most I’ve seen most open source projects do is provide a sample app that displays how the library can be used. While this is definitely helpful, it’s not the same as looking through the documentation to quickly get a sense of how the library can be used and integrated into your app.

I found this to be extremely common in the Android community and as someone who’s coming primarily from a Ruby background where documentation for many popular gems is excellent, I find Android development extremely frustrating. Android development on a technical level is not that difficult. It’s just Java at the end of the day and frankly it feels eerily similar to writing front end web applications using JavaScript frameworks like AngularJS and EmberJS with the only major difference being Java (Android) vs JavaScript (web). But the lack of documentation makes it unnecessarily difficult and raises the bar for new developers wanting to learn Android. It’s almost as if seasoned Android developers are doing this on purpose to protect their jobs or something.

When I was working on implementing the custom SearchView, I even remember coming across an answer that went something like, “I had this problem, but I figured it out by looking through the Android source code”. Dot dot dot… I mean… sure, I guess the source code being open for inspection is one of the benefits of open source, but c’mon who has the time to look through the Android source code??? It’s one thing if the problem is obscure enough that it warrants looking through the Android source code, but if it’s caused by due to lackluster documentation, then it’s a problem that can be more easily solved by us developers being more disciplined about documenting the software we produce. I once had to look through the Ruby on Rails source code to debug something, so I’m not saying looking through the source code of a framework to debug something is not totally unreasonable.

We as a community need to do a better job of documenting our software, myself included. I’m certainly not perfect, and I’ve been lazy before when writing those README.md files on the freelance projects I work on, but being more disciplined as a group will easily save hundreds if not thousands of our precious time for our fellow developers.