5 Top Mistakes All Freelancers Should Avoid

5 Top Mistakes All Freelancers Should Avoid

And So The Story Goes

Chances are, if you’ve been freelancing for a while you’ve made your fair share of mistakes. If you’re a new freelancer, maybe you haven’t made all the same mistakes yet, but you probably will before long.

The thing is, even with all the technology, tutorials and web sites out in the world today, there is one thing that people can’t avoid – human error. And not one of us likes to admit it (to ourselves or to anyone else), but we all make mistakes. Some mistakes are small and insignificant; others can end up costing us a lot.

Heck, I don’t even like admitting if I mispell a word or make a typo. Oh no… a button on my keybord must hve gotten stuck. 😉

But, like it or not – admit it or not – we are bound to make mistakes. It’s part of our nature, it’s part of our growing process… And there is no way to avoid every single mistake if you’re trying to succeed.

That said, I’m still going to try to warn you about some of the biggest mistakes most people make. Hopefully, after reading this article, you’ll be able to avoid some of these large and costly mistakes and fill up your “mistake quota” with the little ones… like typos.

1. Know Your Worth

There are too many – way too many – freelancers out there who don’t know or recognize their own worth. I’m not sure why this is, but it is a mistake that freelancers from all over the globe are making, not just the ones here in the United States.

It’s tempting to enter into freelance and offer discounted prices, cheaper rates, and big savings to potential clients. After all, what client doesn’t want to save a little money?

I can answer that… None of them.

Not one single client that you ever meet will want to save money. What they want is more bang for their buck. Clients want to know that if they pay you $3,000 to design their new web site, that this new web site is the best possible web site they could have received for $3,000. They want to know that the quality of their new web site, the service that they received from you during and after this web site was designed, and everything in between, was absolutely worth the cost.

Clients have no idea how much their projects are worth. Most don’t know how much work goes into completing their project. The only thing that a client knows is how much he or she can spend (in other words, his or her budget) to get that project completed.

In a perfect world, the client’s budget will match or surpass your worth – making everyone happy. But sadly, not everyone lives in a perfect world. And when you find that client whose budget does not meet your worth, it’s up to you to decide whether or not that client can afford your services.

So, when you start lowering your prices and offering your discounts, are you really giving your clients what they want? Are you actually giving them more bang for their buck? Or are you, instead, lowering your bang to meet their buck?

Determining Your Worth

So, how do you determine your worth?

I’m so glad you asked, because I’m going to help you do that.

First, think over your skills and what you’re able to offer your client.

  • Did you go to school to learn the skills that you’re offering?
  • Do you continue to learn and expand on your skills that you went to school for?
  • How good are you at communicating?
  • How much experience do you have?
  • Are your skills highly sought after? What is the level of competition you might be facing? Are there a lot of people with your skills, or are you one of a few?
  • How are you with meeting deadlines?
  • Do you have a successful track record, and can you prove this track record through recommendations, testimonials or a portfolio?

Of course, determining your worth won’t determine the exact amount that you should charge for your services. But it’s a good start. There are some other factors that you should consider when trying to determine how much you should charge for your services:

  • Your costs to get the project done, such as electric bills, buying any needed software or hardware, buying basic supplies such as paper or ink, Internet costs, phone bills, etc.
  • Your costs to get paid. Every online payment system, such as Paypal, charges you money when you receive payments. Even if you have clients writing you checks, your bank may charge you money to cash that check. Credit card companies charge money to process credit card transactions. Freelancing sites such as Elance or oDesk have their own fees associated with their payment systems.
  • General operating costs to continue your freelancing endeavor. Some freelancing sites charge you for your membership, others charge you before you can even bid on a project. Time spent marketing yourself or searching for potential projects can take hours away from your work day.

And, of course, what good is working if you’re only getting paid enough to continue working? There are living expenses that your income needs to be able to cover – otherwise you’re not going to get very far.

  • Food
  • Rent or mortgage payments
  • Electricity and other bills

Don’t Get Stuck Charging too Little

I’m going to pause here to tell you a little story. It’s the story of a budding freelance writer who was unable to determine her worth and it nearly cost her dearly.

So, as a freelance writer, she realized that there was a high level of competition. There are a lot of writers out and about, and the majority of them have excellent spelling and grammar skills, can type fast, and can meet and surpass deadlines without blinking. She had a degree in writing, took several writing courses every year to help keep up on changing grammar rules, put together a portfolio… she was prepared.

But this level of competition had her scared. She didn’t know how to make herself stand out from the crowd of freelance writers who could do any project she could do (and had the experience to prove it). Obviously, her particular skills were not difficult to find – they were present in abundance around the globe – and she didn’t yet have the extensive portfolio or testimonials to back up her track record.

So she went the way of discounts. Like I said, it can be very tempting. Other freelance writers in her area were charging close to $6 or $10 per page; competitors from overseas were charging closer to $1 to $2 per page, or even per article.

Finally, she got her first freelance writing job, and she was ecstatic. She thought for sure that this was going to be the start of a successful career in freelance writing. She made plans to have a website built (which is actually how I met her – she had approached me to develop a website to promote her freelance writing services), and she believed that this project would be the first of many that would fill her portfolio.

Then, after working nearly 60 hours in one week, it was time for her to get paid… and that’s when she learned she couldn’t even afford to take the money her client had paid her. 60 hours of work, and she couldn’t afford to collect her payment. Why? Because she had earned a total of $20 for that project, and the cost to withdraw her money from her chosen payment system was $30.

She actually had to pay $10 for the privilege of working.Headache

She made the mistake of forgetting what her value was, didn’t think about what her costs would be, and allowed the threat of competition to force her into lowering her worth. So much so that she only charged $0.65 per page for this article. She had a bill on the way from me, and several other bills she couldn’t pay, no other projects, and she was stuck.

Do you think I gave her a discount? If you guessed yes, you’d be wrong. But I did feel bad, and I do have compassion. So I made some arrangements to help her out, breaking down her payments into manageable amounts rather than all at once, and allowed her an extra two weeks to pay that first installment.

Hey, I said I had compassion – but I, too, have bills to pay.

Part of my work with her website included building an invoice system, so she could post invoices and have her clients log into the site to view them and make payments online. So, while doing this, I got to see what she did when I posted the invoice. I saw her mistake right away. “Don’t do that,” I told her. This eventually led to a few discussions regarding where to cut costs, how clients determine their budgets, and how contractors should determine their prices. And, well, the majority of the advice I gave her is what I’ve posted here for you to learn from.

Use Those Discounts Wisely

That’s not to say that discounted prices don’t have their place in business. If lowering prices didn’t work for some things, then there wouldn’t be such things as the Blue Light Special! Absolutely, discounts can make a difference – but you need to use them wisely.

  • Offering discounts in exchange for referrals, links, or advertising is a good way to get a head start with your own marketing plans
  • Offer discounted services in bundles if you can – such as free logo design with every site design, or discounted site hosting with every site developed.
  • Offer limited discounts for the beginning of your contracts, such as 20% off the first 20% of the project for new customers.

No One Needs to Know Your Finances Except You

And finally, no one else needs to know what you charge other people. If you decide to donate some of your time to designing a new logo for a charity auction and charge $10 for that design, then the next company looking for logo design doesn’t need to know that.

All potential clients need to know is whether or not your previous clients got more bang for their buck. That’s it. You can quote the number of hours it took you to finish a project or how large the project was. But the only numbers that a potential client should know is what you are going to charge him or her. Not what you charged some one else.

This is especially important if you made the mistake of charging too little in the past. A lot of freelancers get stuck if they’ve handed out too many discounts trying to make a name for themselves. Most clients feel cheated if you quote them $150 when they know you did the same thing – or at least what they think is the same thing – for someone else at $75.

And why would you want your client to feel cheated?

Just don’t do it. What a client pays you is between you and your client, maybe your accountant, and no one else.

2. Know When to Shut Up

That’s right, I said it right in the middle of this long article about mistakes freelancers should avoid. Learn when to shut up.

This can be critical for you, especially if you’re new and aspiring to be the next great you.

Turning Down Clients

Part of knowing when to keep quiet is deciphering the difference between promising a client that you can deliver the moon on a silver platter and actually knowing that you’ll be able to deliver that moon on a silver platter. Some freelancers get scared that if they tell a client they can’t do something, that client will huff and puff and rip their arm off before taking their business elsewhere.

Clients are not the monsters that so many freelancers are scared of! Clients are people – be they business people, charitable people, marketing people, or just bubbly cheerleader people. More importantly, they are usually people who are scared of freelancers. People scared of getting cheated. People scared of not getting their money’s worth. People who are scared of falling victim to liars.

And most people who don’t want to get cheated out of their money will appreciate you for being honest with them and explaining your limits.

And I can promise you, it’s amazing what a client will do if he or she trusts you. Time for another story.

So, as many of you know, I work with and favor Drupal. I heart Drupal. Nay… I Drool for Drupal. It’s the first CMS I learned on, and three years into working with Drupal I still had never seen the admin screen of a WordPress site. Then one day, a few years ago, a potential client approached me, having been referred by one of my previous clients. Except this client wanted a new site set up in WordPress, complete with custom theme and a list of about five different plugins he had already looked up, plus any other plugins I might know of.

Well, I didn’t know of any. I had never worked with WordPress. People kept telling me that WordPress was easier than Drupal and that if I could work with Drupal then I could take on WordPress with no problems. But I don’t work backwards so well. And the thought of trying scared me.

But, this was a friend of a client whom I had loved working with, and I really didn’t want to disappoint either one of them. So I thought about it, and I hemmed and I hawed while I pondered and sighed… and finally I sent an apologetic email explaining my limitations. I explained that learning my way around WordPress would take longer than working within the system with which I was already more comfortable. I explained my reservations regarding the project, and confessed that my schedule at the time wouldn’t allow for the extra “learning time” that the project would entail.

And, I’m not saying that every client would have reacted this way… but he hired me anyway, despite my limitation, and decided to let me work in Drupal instead of WordPress.

Yes, he had been referred to me, but it was my honesty that impressed him more than anything. He could have gotten referred to anyone else – I even offered to refer him to some freelancing colleagues who worked primarily with WordPress – but my honesty showed him why his friend had hired me before, and why his friend had referred him to me. And it was my honesty that got me that job.

It may not always work out that way. Sometimes your honesty will cost you a project or two. But, in exchange, you will have gained their trust – and nothing is better for a freelancer’s career than trust.

Giving Away Too Much Information

Hehe, Okay… So this one I can’t really blame on the keyboard. But boy, if I could figure out a way to do so I would!

One of the biggest mistakes that cost me several projects when I started freelancing was explaining everything before getting that contract.

Correct or Incorrect

You see, clients have no idea what freelancers do. If a client wants a web site built, he hires someone (or a team of someones) and all he knows, all he cares about, is that eventually when he loads up the Internet he can find his web site online and working just as he wanted. He doesn’t know how many hours it took to design the logo; he doesn’t care how many hours it took to write the PHP and CSS for the layout. He doesn’t care, really, if the site was tested across multiple browsers as long as it’s working on the browser he’s using.

Unless that client has ever worked as a web designer, web developer, content writer or graphic designer, then for all that client knows, the designer he hired had a magic wand.

So, knowing this, I thought that it would be easier for me to justify some of my higher-than-average rates if I explained exactly what I was doing. So I would draw up a detailed plan of exactly what I was going to use – what modules I was going to use, what resources I had found regarding their requests, what issues were being tracked that might affect them, on and on.

I said everything. And my keyboard never once tried to shut me up. So guess what happened.

That’s right, my potential client took all the information I had just spent an hour or so typing out, and ran with it – either finding someone cheaper, or implementing my plan himself.

Bad keyboard.

Well, the good news is that it only took me about 4 or 5 times to figure out that the problem was me. If you teach a client (for free) to build his own web site, you’ll be kicking yourself.

Don’t get me wrong. If you’re selling consulting, so clients can take your ideas and do the work themselves, that’s a great business too (and an excellent way to leverage your time). But don’t teach people to do your job unless you’re getting paid for the higher value of this service.

So, when you’re talking to a potential client, be honest and answer his or her questions – and then shut up. Do not go overboard with your explanations by telling him or her things he or she doesn’t need to know. They will either glaze over, or, if they’re unethical, take your information and run. Don’t give away all your secrets and plans until after he or she has gone from “potential client” to “actual client“.

3. Know When You’re Working

What I mean is, throughout the day you’ll find yourself doing various tasks that are related – or that you think are related – to your business. But chances are good that some of them just aren’t working for you. There’s no use wasting time and energy on an activity that is not going to work for you.

Whether it be social media marketing, online marketing, Tweeting, writing articles, putting together a blog, working on a web site, or planning the corporate retreat, people think that to get their name out there it has to be everywhere. Their marketing strategy is little more than throwing their name into every ad listing, directory, classifieds section and Facebook status that they can manage.

But guess what? These strategies may not work for you. The freelancer down the road from you might get some of her best clients through Facebook via their ad system – but that doesn’t mean you’ll ever find a single one on Facebook, no matter how many ads you write or buy.

Yes, it’s true that every marketing campaign takes time to work. And there is something to be said for having patience. But after a while, a marketing plan that isn’t working just becomes a waste. And the more time you spend on wasted activities that aren’t working for your business, the less time you have to invest in the activities that are working. You can either spend your time fighting your weaknesses, or using and improving your natural strengths.

To find out how much time you spend on each activity, try tracking your time over a typical day or week. Write down every task you do for your business (not for clients) and how much time you spend on each task. Then, go back and evalutate each task’s effects on your freelancing business. Did it attract more clients? Help you with the clients you already have? Broaden your skills? Is your business better for the time spent on this task or worse? Was there any change?

As you can imagine, evaluating these results may lead you to some surprising discoveries about how you’re spending your time. That 10 minutes you spend Tweeting every 3 to 4 hours might prove to be better than the $600 you spend posting an ad on Facebook. Or, it might just be that the 10 minutes you spend Tweeting every 3 to 4 hours added up to 4 hours of wasted time every week – time that could have been spent doing something more effective.

4. Know When to Stop

There’s a well known fairy tale that working freelance means you’ll get to choose your own hours. And, for the most part, this can be true. But it won’t always feel like you’re choosing your hours.

Especially if you’ve just started working freelance.

Your clients need you. Their websites might need to be set up, or maybe their websites have stopped working. Their online presence needs to be marketed, their articles need to be written and / or edited. Their logos need to be designed, their store needs to be set up. Their advertising needs to work.

And your business needs you. Your reputation needs to be built. Your name needs to be known, new clients need to be contacted. Your services need to be marketed or advertised and your promises need to be kept. You need to do research to gain more clients, learning to stay up-to-date with the latest software and techniques.

But most of all, you need to take a break.

It is far too easy to work yourself into exhaustion when you’re working freelance. It starts with a plan to “quickly finish this up” and before you know it, you’ve been working 10 hours and you haven’t eaten lunch, you haven’t stretched and your puppy still needs to go for a walk.Take a Break

Then, just as you think you’re done working for the day, you receive an email from one of the potential clients you had contacted last week, and he’s inquiring for more information. You think to yourself, “It’ll only take a few minutes to answer this, and then I can be done.”
But it doesn’t take just a few minutes. Some of their questions might require a more in-depth answer, or maybe even a little research. Or maybe you are just having a hard time thinking of the right way to explain something. Whatever the case, after working for 10 hours, writing an email that you thought would take you ten minutes ended up taking you close to another hour.

Finally, sleep. Unless you have a smartphone with email support. Because now, three hours after you’ve drifted off into blissful slumber, your smartphone starts to explode with new emails. You check, thinking – even praying – that it’s nothing important, but you find that your client’s site has gone down… and do you have a backup?

Even if you decide to put this request off until morning, this client’s problem will be top-of-mind until you finally get to the computer and start working on fixing the problem. That might be an hour or two of worry and anxiety before even starting to work on the problem.

For some of you, your work will never seem to end. Unforeseen problems will pop up. Answers to problems will strike while you’re eating breakfast and some of your best ideas will strike in the middle of the night.

Yes, it is far too easy to work yourself into mental and physical exhaustion when you’re freelancing.

And because of this, it’s crucial that you give yourself a break every once in a while.

  • Stand up and stretch or go for a short walk every 3 to 4 hours – even if it’s only to the mailbox.
  • Set up some boundaries regarding your schedule and stick with them. If your plan is to work a maximum of 8 hours a day, then once you hit that 8 hours, stop. Yes, there will be days when you can’t simply “stop” because of a looming headline or a problem that has come up… but these should be the exception, not part of your daily routine.
  • If you’re not in front of the computer working, then distract yourself. Don’t continue to stress over work as you eat your lunch or while you’re going for a walk. It’s not really a break if you’re still stressed! When you stop working, that means you should stop mentally focusing on work as well. Go to a friend’s birthday party, go on a date, learn how to knit, or go duck hunting if you have to. Find something, anything, to do that will provide an adequate distraction so that you can forget about work, even if it’s only for a few minutes.
  • Do not interrupt your “me time” for work. What I mean by “me time” is any time during the day that you spend taking care of your basic needs, such as meals, bathing, getting the kids to school or mowing your lawn. It’s so tempting – and easy – to glance at that phone or tablet when you hear the chime signaling that you’ve received a new email. In fact, it’s so easy that you may not even notice you’re doing it.
  • Take a day off – and keep it off. Again, it’s easy to say to yourself, “I’ll take Thursday off,” but then Thursday comes around and guess what happens? Someone needs you. So what do you do? You either work, or you stress about work (or stress so much that you’re as tired as if you had worked). So what good has taking Thursday off done? None. Pick a day, at least one day, every week that will be your day off and stick with it. No work. No stressing about work. Just you and a well-earned break.

Taking these breaks at regular times will also help you to stave off distractions while you’re working, allowing you to concentrate and work more efficiently and finish faster. If you find yourself perusing the Internet at times when you should be working or constantly being distracted with Facebook notifications, then chances are you aren’t giving yourself a good break.Cell Distraction Control

For me, it’s cooking or baking. If I find myself dying to peruse the Food Network site in search of new recipes to try, I know that I am not mentally prepared to work at that moment… and it’s usually because I haven’t taken a break, or even stretched my legs, in hours.

And finally…

5. Don’t Fall Victim to Slow Business

As easy as it is to get sucked in and work yourself into exhaustion when your business is booming, it’s just as easy to slip out of working efficiently when business is slow.

Things like marketing and availability become even more critical when business is slow. But as you well know, marketing costs money. So it’s easy to decide not to renew that advertising campaign or to let your web site’s hosting plan expire.

If you’re really worried about your bills, you may even find yourself looking for part time work somewhere. Working as a cashier at the local Wal-Mart is a little less embarrassing if it’s paying your bills, right? And besides, you’ll tell yourself that it’s temporary, just until business picks back up for your real job in freelance.

But the problem with this is that while you’re counting out change and wishing people a great day at Wal-Mart, you’re not answering your phone when a potential client is finally calling you back. And while you’re no longer buying ads, other freelancers are reaching new clients using the very ad space you aren’t using. Finishing that project in time to meet the deadline becomes harder after working 6 hours at a retail store stocking shelves. And as you miss deadlines, your reputation begins to slip, too.

This causes a slippery slope of failure. If business is slow, and you allow it to slow you down, then business will get slower. If that potential client can’t get ahold of you because you’re at another job, or you can’t respond to his email in a reasonable time, your reputation will suffer. And before you know it, your business will get slower – forcing you to take on more hours at your temporary job to pay the bills, and leaving it even harder to make yourself available when a potential client comes around.

I do understand that the cost of postage for your direct mail marketing campaign is not going to go down simply because you don’t have enough work. Your mortgage payment isn’t going to get any lower just because your income took a dip. There are some business-related costs that might need to be cut to help you make ends meet. But don’t allow cutting your costs to cut into your business. Double up on other lower-cost but time-intensive marketing endeavors to bring in clients, and keep plugging ahead.

Economic downturns always eventually end. And if you let a downturn wreck your availability and reputation, you may not be there to take advantage of the upturn.

In Conclusion

Be sure to also ask freelancing friends for advice. It’s absolutely okay to learn from others’ mistakes. After all, you don’t have time to make them all, right?

Have you learned something the hard way? If so, please share below in the comments. Help your fellow freelancers avoid them!


[Source: http://www.dwuser.com/education/content/5-top-mistakes-all-freelancers-should-avoid/]

Advertisements

2012 in review – Tech Muffins & Musings Smoothie

The WordPress.com stats helper monkeys prepared a 2012 annual report for this blog.

Here’s an excerpt:

600 people reached the top of Mt. Everest in 2012. This blog got about 6,900 views in 2012. If every person who reached the top of Mt. Everest viewed this blog, it would have taken 12 years to get that many views.

Click here to see the complete report.

How to Override Android’s Back Key When Soft Keyboard is Open

There are various scenarios where we need to handle the Android powered handsets’ hardware “back” key to do some important stuff. One scenario that’s very common is to use it on your custom search view where pressing back key only leads to hide the keyboard and user has to tap it again to hide the search view.

Let’s consider this:

Here we have a search view with keyboard open. If user wants to cancel searching and go back, he can press the back key and here is what we get on back key press:

You can see that the keyboard has gone but the search view is still there. User has to press the back key another time to navigate back to original activity.

Apparently, there is no method in your activity which listens to hardware key events when software keyboard is open. onKeyDown() and onKeyUp() methods work only when keyboard is hidden and this happen because Android considers on-screen keyboard as a separate activity and behaves accordingly.

So what should one do to override it?

Answer is simple and the easiest way to do is to override onKeyPreIme() method which is inherited from View class. To override it, you need to create a custom view. we’ll do it With minimum of the effort. For the example above, we have an EditText which we have using for searching.

Now create a new class which extends from EditText class. Override all the constructors to avoid any possible app crash. Now we’ll override the onKeyPreIme() method and check for Back key:

@Override
public boolean onKeyPreIme(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        // User has pressed Back key. So hide the keyboard
        InputMethodManager mgr = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        mgr.hideSoftInputFromWindow(this.getWindowToken(), 0);
        // TODO: Hide your view as you do it in your activity
    }
    return false;
}

Replace your EditText with this brand new class and that’s all. Now whenever the soft keyboard is hidden through back key, you’ll be notified and you can do the required code to get things work your way.

Bonus Trick:

Here’s a bonus trick for you. If you have implemented menus in your activity, you might face a problem like this:

If you press menu key when the keyboard is opened, you ‘ll have your menus over the keyboard. Now isn’t that funny? But don’t worry, we don’t have to worry about this. What do we want here is that menus should not become visible when keyboard is opened. Piece of cake!! Update your above code to this:

@Override
public boolean onKeyPreIme(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        // User has pressed Back key. So hide the keyboard
        InputMethodManager mgr = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        mgr.hideSoftInputFromWindow(this.getWindowToken(), 0);
        // TODO: Hide your view as you do it in your activity
    } else if (keyCode == KeyEvent.KEYCODE_MENU) {
        // Eat the event
        return true;
    }
    return false;
}

And here you go!! Menus won’t show up on pressing menu key when the keyboard is visible.
Please share the post if you liked.

Creating an Alternate-Colored List View in Android

This post will help you make a list with alternate row in different colors. This is What your list will look like:

To accomplish this, first of all create a layout file and add a listview in it. We name this file “categories.xml“:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/RelativeLayout1">
    <ListView android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/listView1" />
</RelativeLayout>

Next, you need to create an activity. Let’s name this file “CategoriesActivity.java” and enter following code in oncreate() method:

setContentView(R.layout.categories);
ListView listView = (ListView) findViewById(R.id.listView1);
listView.setAdapter(new CategoriesListAdapter(this));

Next step it to create create a custom adapter for our list. In our code above, we’ve named it CategoriesListAdapter. Extend this class from BaseAdapter and implement the methods as usual.

Now, in CategoriesListAdapter.java, we’ll first declare and initialize a list of colors:

public class CategoriesListAdapter extends BaseAdapter {
    private final int[] bgColors = new int[] { R.color.list_bg_1, R.color.list_bg_2 };
}

You have to define these colors in an xml file e.g., colors.xml under res/color. Alternatively, you can use Android’s built-in colors like Color.YELLOW or Color.BLUE for which you don’t need to define these colors. But if you select the first method, your colors.xml will look like this:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="list_bg_1">#ffffff</color>
    <color name="list_bg_2">#fef2e8</color>
</resources>

Now the last step is to set these colors in getView() method. Use the following code snippet for this:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder;
    if (convertView == null) {
        convertView = inflater.inflate(R.layout.item_categorylist, null);
        holder = new CategoryContentsHolder();
        holder.title = (TextView) convertView.findViewById(R.id.txtCategoryName);
        convertView.setTag(holder);
    } else
        holder = (CategoryContentsHolder) convertView.getTag();
        int colorPosition = position % bgColors.length;
        convertView.setBackgroundResource(bgColors[colorPosition]);
        if (holder != null) {
            holder.name.setText(categoryStringArray[position]);
        }
        return convertView;
    }
}

class CategoryContentsHolder {
    TextView title;
}

That was all! The same way you can create a list with 3 or more color.

A Beginner’s Guide to Design Patterns with Java Examples

Ever wondered what design patterns are? In this article, I’ll explain why design patterns are important, and will provide some examples, in Java, of when and why they should be used.

What are Design Patterns?

Design patterns are optimized, reusable solutions to the programming problems that we encounter every day. A design pattern is not a class or a library that we can simply plug into our system; it’s much more than that. It is a template that has to be implemented in the correct situation. It’s not language-specific either. A good design pattern should be implementable in most—if not all—languages, depending on the capabilities of the language. Most importantly, any design pattern can be a double-edged sword— if implemented in the wrong place, it can be disastrous and create many problems for you. However, implemented in the right place, at the right time, it can be your savior.

There are three basic kinds of design patterns:

  • Structural
  • Creational
  • Behavioral

Structural patterns generally deal with relationships between entities, making it easier for these entities to work together.

Creational patterns provide instantiation mechanisms, making it easier to create objects in a way that suits the situation.

Behavioral patterns are used in communications between entities and make it easier and more flexible for these entities to communicate.

Why should we use them?

Design patterns are, by principle, well-thought out solutions to programming problems. Many programmers have encountered these problems before, and have used these ‘solutions’ to remedy them. If you encounter these problems, why recreate a solution when you can use an already proven answer?

Example

class StrategyExample {
    public static void main(String[] args) {
        Context context;

        // Two contexts following different strategies
        context = new Context(new ConcreteStrategyAdd());
        int resultA = context.executeStrategy(3,4);

        context = new Context(new ConcreteStrategySubtract());
        int resultB = context.executeStrategy(3,4);
    }
}

// The classes that implement a concrete strategy should implement this
// The context class uses this to call the concrete strategy
interface Strategy {
    int execute(int a, int b);
}

// Implements the algorithm using the strategy interface
class ConcreteStrategyAdd implements Strategy {

    public int execute(int a, int b) {
        System.out.println("Called ConcreteStrategyAdd's execute()");
        return a + b;  // Do an addition with a and b
    }
}

class ConcreteStrategySubtract implements Strategy {

    public int execute(int a, int b) {
        System.out.println("Called ConcreteStrategySubtract's execute()");
        return a - b;  // Do a subtraction with a and b
    }
}

// Configured with a ConcreteStrategy object and maintains a reference to a Strategy object
class Context {
    private Strategy strategy;

    // Constructor
    public Context(Strategy strategy) {
        this.strategy = strategy;
    }

    public int executeStrategy(int a, int b) {
        return strategy.execute(a, b);
    }
}

Pretty simple, right? Now, let’s take a closer look at the strategy pattern.

Strategy Pattern

The strategy pattern is a behavioral design pattern that allows you to decide which course of action a program should take, based on a specific context during runtime. You encapsulate two different algorithms inside two classes, and decide at runtime which strategy you want to go with.

In our example above, the strategy is based on whatever the context variable was at the time the class was instantiated. If you give it the context for ConcreteStrategyAdd, it will use ConcreteStrategyAdd, and vice versa.

Cute, but where can I use this?

Imagine that you’re currently developing a class which can either update or create a new user record. It still needs the same inputs (name, address, mobile number, etc.), but, depending on a given situation, it has to use different functions when updating and creating. Now, you could probably just use an if-else to accomplish this, however, what if you need to use this class in a different place? In that case, you’ll have to rewrite the same if-else statement all over again. Wouldn’t it be easier to just specify your context?

Class User {
    public void createOrUpdate(String name, String address, String mobile, String userId)
    {
        if(userId == null) {
            // it means the user doesn't exist yet, create a new record
        } else {
            // it means the user already exists, just update based on the given userid
        }
    }
}

Now, the “usual” strategy pattern involves encapsulating your algorithms inside another class, but in this case, another class would be wasteful. Remember that you don’t have to follow the template exactly. Variations work as long as the concept remains the same, and it solves the problem.

Adapter Pattern

The adapter pattern is a structural design pattern that allows you to repurpose a class with a different interface, allowing it to be used by a system which uses different calling methods.

This also lets you alter some of the inputs being received from the client class, making it into something compatible with the adaptee’s functions.

How can I use this?

Another term to reference an adapter class is a wrapper, which basically lets you “wrap” actions into a class and reuse these actions in the correct situations. A classic example might be when you’re creating a domain class for table classes. Instead of calling the different table classes and calling up their functions one by one, you could encapsulate all of these methods into one method using an adapter class. This would not only allow you to reuse whatever action you want, it also keeps you from having to rewrite the code if you need to use the same action in a different place.

Compare these two implementations:

Non-Adapter Approach

User user = new User();
user.createOrUpdate( //inputs );

Profile profile = new Profile();
profile.createOrUpdate( //inputs );

If we needed to do this again in a different place, or even reuse this code in a different project, we would have to type everything all over again.

Better

That’s opposed to doing something like this:

Account account = new Account();
account.createNew( //inputs );

In this situation, we have a wrapper class, which would be our Account class:

class Account()
{
    public void createNew( //inputs )
        User user = new User();
        user.createOrUpdate( //subset of inputs );

        Profile profile = new Profile();
        profile.createOrUpdate( //subset of inputs );
    }
}

This way, you can use your Account again whenever you need it—plus, you’d be able to wrap other classes under your account class as well.

Factory Method Pattern

The factory method pattern is a creational design pattern which does exactly as it sounds: it’s a class that acts as a factory of object instances.

The main goal of this pattern is to encapsulate the creational procedure that may span different classes into one single function. By providing the correct context to the factory method, it will be able to return the correct object.

When can I use this?

The best time to use the factory method pattern is when you have multiple different variations of a single entity. Let’s say you have a button class; this class has different variations, such as ImageButton, InputButton and FlashButton. Depending on the place, you may need to create different buttons—this is where you can use a factory to create the buttons for you!

Let’s begin by creating our three classes:

Interface Button {
    public String getHtml();
}

Class ImageButton implements Button {
    public String getHtml() {
        return "..."; //This should be whatever HTML you want for your image-based button
    }
}

Class InputButton implements Button {

    public String getHtml() {
        return "..."; //This should be whatever HTML you want for your normal button (<input type="button"... />);
    }
}

Class FlashButton implements Button {
    public String getHtml() {
        return "..."; //This should be whatever HTML you want for your flash-based button
    }
}

Now, we can create our factory class:

Class ButtonFactory
{
    public static Button createButton(String type)
    {
        try
        {
            Class buttonClass = Class.forName(type);
            java.lang.reflect.Constructor cons = buttonClass.getConstructor(classParm);
            return cons.newInstance(objectParm);
        } catch(Exception x) {
            System.out.println("The button type " + type + " is not recognized.");
        }
        return null;
    }
}

We can use this code like so:

String[] buttons = {"ImageButton", "InputButton", "FlashButton"};
for(int i=0; i<buttons.length; i++) {
    ButtonFactory.createButton(buttons[i]).getHtml();
}

The output should be the HTML of all your button types. This way, you would be able to specify which button to create depending on the situation and reuse the condition as well.

Decorator Pattern

The decorator pattern is a structural design pattern which enables us to add new or additional behavior to an object during runtime, depending on the situation.

The goal is to make it so that the extended functions can be applied to one specific instance, and, at the same time, still be able to create an original instance that doesn’t have the new functions. It also allows for combining multiple decorators for one instance, so that you’re not stuck with one decorator for each instance. This pattern is an alternative to subclassing, which refers to creating a class that inherits functionality from a parent class. As opposed to subclassing, which adds the behavior at compile time, “decorating” allows you to add new behavior during runtime, if the situation calls for it.

To implement the decorator pattern, we can follow these steps:

  1. Subclass the original “Component” class into a “Decorator” class
  2. In the Decorator class, add a Component pointer as a field
  3. Pass a Component to the Decorator constructor to initialize the Component pointer
  4. In the Decorator class, redirect all “Component” methods to the “Component” pointer, and
  5. In the Decorator class, override any Component method(s) whose behavior needs to be modified

Steps courtesy of http://en.wikipedia.org/wiki/Decorator_pattern

When can I use this?

The best place to use the decorator pattern is when you have an entity which needs to have new behavior only if the situation requires it. Once we’ve established our decorations, we can start programming them.

The following example illustrates the use of decorators using coffee making scenario. In this example, the scenario only includes cost and ingredients.

// The Coffee Interface defines the functionality of Coffee implemented by decorator
public interface Coffee {
    public double getCost(); // returns the cost of the coffee
    public String getIngredients(); // returns the ingredients of the coffee
}

// implementation of a simple coffee without any extra ingredients
public class SimpleCoffee implements Coffee {
    public double getCost() {
        return 1;
    }
    public String getIngredients() {
        return "Coffee";
    }
}

The following classes contain the decorators for all Coffee classes, including the decorator classes themselves:

// abstract decorator class - note that it implements Coffee interface
abstract public class CoffeeDecorator implements Coffee {
    protected final Coffee decoratedCoffee;
    protected String ingredientSeparator = ", ";

    public CoffeeDecorator(Coffee decoratedCoffee) {
        this.decoratedCoffee = decoratedCoffee;
    }

    public double getCost() { // implementing methods of the interface
        return decoratedCoffee.getCost();
    }

    public String getIngredients() {
        return decoratedCoffee.getIngredients();
    }
}

// Decorator Milk that mixes milk with coffee. Note it extends CoffeeDecorator
public class Milk extends CoffeeDecorator {
    public Milk(Coffee decoratedCoffee) {
        super(decoratedCoffee);
    }

    public double getCost() { // overriding methods defined in the abstract superclass
        return super.getCost() + 0.5;
    }

    public String getIngredients() {
        return super.getIngredients() + ingredientSeparator + "Milk";
    }
}

// Decorator Whip that mixes whip with coffee. Note it extends CoffeeDecorator
public class Whip extends CoffeeDecorator {
    public Whip(Coffee decoratedCoffee) {
        super(decoratedCoffee);
    }

    public double getCost() {
        return super.getCost() + 0.7;
    }

    public String getIngredients() {
        return super.getIngredients() + ingredientSeparator + "Whip";
    }
}

// Decorator Sprinkles that mixes sprinkles with coffee. Note it extends CoffeeDecorator
public class Sprinkles extends CoffeeDecorator {
    public Sprinkles(Coffee decoratedCoffee) {
        super(decoratedCoffee);
    }

    public double getCost() {
        return super.getCost() + 0.2;
    }

    public String getIngredients() {
        return super.getIngredients() + ingredientSeparator + "Sprinkles";
    }
}

Here’s a test program that creates a Coffee instance which is fully decorated (i.e., with milk, whip, sprinkles), and calculate cost of coffee and prints its ingredients:

public class DecoratorTest
{
    public static void main(String[] args)
    {
        Coffee c = new SimpleCoffee();
        System.out.println("Cost: " + c.getCost() + "; Ingredients: " + c.getIngredients());

        c = new Milk(c);
        System.out.println("Cost: " + c.getCost() + "; Ingredients: " + c.getIngredients());

        c = new Sprinkles(c);
        System.out.println("Cost: " + c.getCost() + "; Ingredients: " + c.getIngredients());

        c = new Whip(c);
        System.out.println("Cost: " + c.getCost() + "; Ingredients: " + c.getIngredients());

        // Note that you can also stack more than one decorator of the same type
        c = new Sprinkles(c);
        System.out.println("Cost: " + c.getCost() + "; Ingredients: " + c.getIngredients());
}
}

The output of this program is given below:

Cost: 1.0; Ingredients: Coffee
Cost: 1.5; Ingredients: Coffee, Milk
Cost: 1.7; Ingredients: Coffee, Milk, Sprinkles
Cost: 2.4; Ingredients: Coffee, Milk, Sprinkles, Whip
Cost: 2.6; Ingredients: Coffee, Milk, Sprinkles, Whip, Sprinkles

Example courtesy Wikipedia decorator pattern example

Singleton Pattern

The singleton design pattern is a creational design pattern which makes sure that you have one single instance of a particular class in the duration of your runtime, and provides a global point of access to the single instance.

This makes it easier to set up a point of “coordination” for other objects that use the singleton instance as well, since the singleton’s variables will always be the same for anything that calls it.

When can I use this?

This solution is thread-safe without requiring special language constructs, but it may lack the laziness of the one below. The INSTANCE is created as soon as the Singleton class is initialized. That might even be long before getInstance() is called. It might be (for example) when some static method of the class is used. If laziness is not needed or the instance needs to be created early in the application’s execution, or your class has no other static members or methods that could prompt early initialization (and thus creation of the instance), this (slightly) simpler solution can be used:

public class MySingleton {

    private static final MySingleton INSTANCE = new Singleton();

    // Private constructor prevents instantiation from other classes
    private MySingleton() {
    }

    public static MySingleton getInstance() {
        return INSTANCE;
    }
}

By doing this, we can access our MySingleton instance from different parts of our code, even in different classes. This data will persist throughout all getInstance calls.

Conclusion

There are many more design patterns to study; in this article, I’ve only highlighted some of the more prominent ones that I use when programming. If you’re interested in reading about the other design patterns, Wikipedia’s Design Patterns page has a plethora of information. If that’s not enough, you can always check out Design Patterns: Elements of Reusable Object-Oriented Software, which is considered to be one of the best design pattern books available.

One last thing: when you use these design patterns, always  make sure that you’re trying to solve the correct problem. As I mentioned previously, these design patterns are a double-edge sword: if used in the wrong context, they can potentially makes things worse; but if used correctly, they become indispensable.


Post inspired from: http://net.tutsplus.com/articles/general/a-beginners-guide-to-design-patterns/


I’ll highly appreciate your feedback on this article.