Search This Blog

Showing posts with label MyThoughts. Show all posts
Showing posts with label MyThoughts. Show all posts

Friday, April 3, 2015

Simple Ways to become a best programmer...

1. Never ever duplicate code

Avoid duplicating code at all costs. If you have a common code segment used in a few different places, refactor it out into its own function. Code duplication causes confusion among your colleagues reading your code, it causes bugs down the line when the duplicated segment is fixed in one location and not the others and it bloats the size of your code-base and executable. With modern languages its become possible to get really good at this, for example here is a pattern that used to be hard to solve before delegates and lambdas came along:

/// <summary>
/// Some function with partially duplicated code
/// </summary>
void OriginalA()
{
DoThingsA();

// unique code

DoThingsB();
}

/// <summary>
/// Another function with partially duplicated code
/// </summary>
void OriginalB()
{
DoThingsA();

// unique code

DoThingsB();
}
But now we can refactor the shared part of both functions and rewrite using a delegate:

/// <summary>
/// Encapsulate shared functionality
/// </summary>
/// <param name="action">User defined action</param>
void UniqueWrapper(Action action)
{
DoThingsA();

action();

DoThingsB();
}

/// <summary>
/// New implmentation of A
/// </summary>
void NewA()
{
UniqueWrapper(() =>
{
// unique code
});
}

/// <summary>
/// New implementation of B
/// </summary>
void NewB()
{
UniqueWrapper(() =>
{
// unique code
});
}

2. Notice when you start distracting yourself

When you find yourself flicking to facebook or twitter instead of working on a problem its often a sign that you need to take a short break. Go grab a coffee away from your desk and talk to your colleagues for 5 minutes or so. Even though this seems counter intuitive, you will be more productive in the long run.

3. Don’t rush the solution out the door

When under pressure to produce a solution to a problem, or to fix a bug, its very easy to get carried away and find yourself rushing, or even missing out your usual crucial testing cycle completely. This can often result in more problems and will make you look less professional in the eyes of your boss and colleagues.

4. Test your finished code

You know what your code is supposed to do, and you’ve likely tested that it works, but you really need to prove it. Analyse all the potential edge cases and make a test which confirms that your code performs as expected under all possible conditions. If there are parameters, send values outside of the expected range. Send null values. If you can, show your code to a colleague and ask them to break it. Unit testing is a formalised approach to this.

5. Code review

Before you promote your code into source control, sit down with a colleague and explain exactly what your change does. Often just by doing this you’ll recognise mistakes in your own code without your colleague saying a word. It’s much, much more effective than just reviewing your own work.

6. Write less code

If you find yourself writing a lot of code to do something simple, you’re probably doing it wrong. A good example is the lowly boolean:

if (numMines > 0)
{
   enabled=true;
}
else
{
   enabled=false;
}
When you could just write:

enabled = numMines > 0;
The less code you write the better. Less to debug, less to refactor, less to go wrong. Use with moderation; readability is just as important, you don’t want to make your code less readable by doing this.

7. Strive for elegant code

Elegant code is highly readable and solves the problem at hand with the smallest amount of code and machine action possible. Its quite difficult to achieve elegant code in all circumstances but after programming for a while you start to get a feel for what it looks like. Elegant code cannot be improved by refactoring anything. It makes you happy to look at it. You are proud of it. For example here is what I consider to be an elegant way of computing the area of a convex polygon:

static public double GetConvexPolygonArea(Vector2[] vertices)
{
double area = 0;
for (int i = 0; i < vertices.Length; i++)
{
Vector2 P0 = vertices[i];
Vector2 P1 = vertices[(i + 1) % vertices.Length];

area += P0.Wedge(P1);
}

return area / 2;
}

8. Write self documenting code

Comments are a very important part of programming for obvious reasons, but self documenting code can be even better because it makes it possible to understand code just by reading it. Function and variable names can often be deftly chosen so that when put together with the language semantics the code becomes readable even to non programmers. For example:

void DamagePlayer(Player player, int damageAmount)
{
if (!player.m_IsInvincible && !player.m_IsDead)
{
player.InflictDamage( damageAmount );
}
}
Self documenting code is not a substitute for comments. Use comments to describe ‘why’, self documenting code describes ‘what’.

9. Don’t use magic numbers

Numbers just inserted into the code are bad practice because there is nothing to describe what they represent. This is compounded by duplication; where the same number is used in multiple different places in the code. One will get changed and the others missed leading to bugs. Always use a named constant to describe the value you want to represent, even if it is only used in one place.

10. Don’t do manual labour

Humans are very good at making mistakes when doing a series of actions. If you have a build deployment process which is more than one step long, you’re doing it wrong. Automate as much as possible, reduce the chance of human error. This is especially important with tasks which you perform a lot.

11. Avoid premature optimisation

When you start optimising part of your already functioning code you risk breaking the functionality. Optimisation should only be performed in response to performance analysis, hopefully carried out towards the end of a project. Optimising before this analysis stage wastes time and can introduce bugs.

Thursday, December 25, 2014

5 Exciting Reasons to Work for a Tech Startup in India

Today fresh graduates really have a choice whether to work in a startup or not. 10 years ago this was not a viable option for most people.

Becoming a tech entrepreneur yourself is a great career option too. But in this post we will look at the pros and cons of working in an early stage tech startup vs. working in a well established IT organization like Infosys, HCL or Accenture.

Now i am working in a startup.

From my experience, here are some of the reasons why you should work in a startup.

1. Massive Learning

The amount of things that you learn by working in a startup is probably twice or thrice than that of a big organization with 1,000+ employees. The startup I am working for had only 30 employees but we were getting a lot of things done at a breakneck speed. I was blown away by the possibility of how much a small team can create given such less time and resources.

There are less formalities, less boring meetings, less approvals and more ownership and freedom for what you are doing. Due to less friction, you end up doing more work and hence you learn more in a shorter period of time.

2. Work Satisfaction

Big corporates are famous for their dirty politics. I am not saying that everyone is bad in such firms, of course there are a lot of visionary leaders in big companies but your chances of bumping into a bad manager are relatively high.
Many times, you do a piece of work and someone else takes credit for it. You want to do something creative, but your manager doesn’t allow it because he/she is afraid that you would overshadow him.

Since startups have a small team, everyone knows what kind of work you do and you will get valued. (On the flip side the only way to look like a hard worker is by working hard!)

New ideas and initiatives are encouraged and there will not be a need to get formal approvals to do new things. As a developer if you think that adding a small tweak to the user interface will help your customers, you can just inform your team and go ahead with it. You may not get a monetary reward for it, but your customers will be happy and that would give you immense pleasure.

Whether you work in the development team, marketing team or customer support, there are plenty of opportunities to talk and meet with your customers. You will see how your work is adding value to your clients. This motivates you to go the extra mile to serve them. In the process you will learn what entrepreneurship is and what value creation really means. Yes, you are really making the world a better place by doing your part of the work.

3. People & Culture

Except a few, most of the startups have a great work culture. Startups do not waste energy in unnecessary things such as insisting on formal dress codes, having to follow up with minutes of meetings, minimum clock-in hours at the office, leave policy and so on.

All that matters is the work you do. How much value you add to the organization and hence to its customers. Mostly it wouldn’t be a big deal if you wear t-shirts, come late to the office, made a spelling mistake in your email, didn’t adhere to the HR policy while taking a leave and so on. I don’t say all startups are like that, but most startups don’t have time to make an issue about small things that do not matter.

In startups people around you are more like a family than co-workers. There are mostly no politics and deception because no one has time to play such games.

4. A Platform to become an Entrepreneur

If you have ever dreamed of becoming an entrepreneur, working in a startup is the best place to get started. Since startups are small and mostly transparent in what they do, you will learn a lot more about the business in a holistic manner.
If you join a very big organization, you most likely will have no idea about the needs of the customer, the price they are willing to pay for your solution and whether your work has really solved their problem.

You work, you get paid and the only thing your will learn is how to save yourself from getting blamed when something goes wrong. This will help you only if you want to climb the corporate ladder.

But for people like you & me who believe in doing the work, corporate politics is a dirty game to play and the chances of becoming a senior manager or VP in an organization with tens of thousands of employees is very less.
Again, I am not here to give a bad rap about big and well respected organizations. Apart from my own experience, I have a lot of friends working in such firms and it looks like I have a fair idea about how things are in such companies. I am sure you will agree with me on this.

In a startup, you will do a little bit of everything when some important things have to be done on time. I am working mostly in developing but when the need arose, I did a bit of design, a bit of customer support and a bit of installation too. Such experience is priceless when you want to start your own company some day.

Another big benefit of working in startups is that you will network with great people. You will become friends with the CEO and co-founders. If you add good value and move on, no one is going to get angry at you that you are leaving them and will be more than happy to help with when you run your own startup with their contacts, resources and experience.

5. Remuneration & Stock Options

There is a misconception that Indian startups don’t pay well. If you do your homework, you will find out that if you are well educated, intelligent, hardworking and have the right attitude, a 5 year work experience could get you double or triple the salary compared to a traditional IT company in India. If the take home salary is not that much, you will be compensated with stock options of equivalent value.

You will get stock options which is usually in the range of 0.05% to 0.5% with startups which are a few years old. For startups that are less than 1 year old, you may get 5% to 10% stock but in that case you will be more of a co-founder than an employee.

0.5% may not look like much. But imagine you are working in a company that is valued at 10 Crores when you join. 0.5% of that is 5 Lakhs. This may not look like much in the beginning. But startups grow very fast and within a few years your company can become a 100 crore company.

If the startup is acquired, your 5 Lakhs becomes 50 Lakhs and that could be more than enough to fund your own startup or take a mini-retirement.

Redbus.in had an exit at 800 crores approx. An employee who had a 0.5% stock would have cashed out 4 crores when Redbus was acquired by South African Naspers group. An employee who only had a 0.05% stock would still have cashed out 40 Lakhs! Such exits don’t happen often but you have to consider the possibilities.

The Downsides
 You cannot have a cake and eat it too. Roses come with thorns. For some people working in a startup is not the right thing

Here are the down sides:

-- There is a bit of risk that your startup could fail and your stock options will becomes worthless. But you would still come out with priceless learning and experience.
-- The amount of work involved in startups is higher. Sometimes you may have to work on weekends as well. Sometimes more than 12 hours on a weekday. Startups are for people who want to work hard, not for people who want to look like working hard and take home a paycheck every month.
-- You may not work in a fancy looking office building in a tech park. Your relatives may not have heard of the company you work for. You may not get opportunities to travel abroad. Sometimes you may not even have A/C in your office. Startups are for people who want to learn more and get more things done, not for people who want to settle in a job with comfort.

Conclusion
If the downsides do not bother you, I am sure by now you are excited to work in a startup!

Wednesday, December 24, 2014

Clean Code – Is my code always readable?

Did you ever have to go back to a fragment of code that you wrote a month or year ago? How did it feel? Was it easy or did you have to figure out how it worked from scratch? If you need more than just one look, there is a good chance that you are doing something wrong. And if you scratch you head an think: “What the heck was I thinking?”, you have definitely done it wrong. But what have gone wrong? Most probably the code works fine and at some point you knew it inside out. Why can’t you remember it now? Maybe your code wasn’t written clearly enough and in accordance with best coding practices? Here are a few tips on how to write easily readable code not just for yourself but also for other developers.

Example of using coding standards

Consider the following method in C#:

public string transform(List<DateTime> s)
{string d = null;
foreach (DateTime kc in s)
{if (kc > DateTime.Now)
{ d = d + kc + "\n"; }
else { d = d + "Delayed\n"; }}
return d;}

At first glance you have no idea what it actually does or what it can be used for. But after short refactoring we can get:

public string GetText(List<DateTime> arrivalTimes)
{
    var stringBuilder = new StringBuilder();
    foreach (DateTime arrivalTime in arrivalTimes)
    {
        if (arrivalTime > DateTime.Now)
        {
            stringBuilder.AppendLine(arrivalTime.ToString());
        }
        else
        {
            stringBuilder.AppendLine("Delayed");
        }
    }
    return stringBuilder.ToString();
}

Or if we apply the “?:” operator, we will get:

public string GetText(List<DateTime> arrivalTimes)
{
    var stringBuilder = new StringBuilder();
    foreach (DateTime arrivalTime in arrivalTimes)
    {
        string message = arrivalTime > DateTime.Now ? arrivalTime.ToString() : "Delayed";
        stringBuilder.AppendLine(message);
    }
    return stringBuilder.ToString();
}


What has actually happened to the code? Several modifications have been made to increase its readability:
1. The name of the method has been changed from one that really doesn’t say anything to one that is       a little bit more descriptive.
2. The way of naming the variables was changed:

  • “kc” was changed to arrivalTime,
  • “s” was changed to arrivalTimes,
  • “d” was changed to stringBuilder,

It also much easier to understand what each variable is responsible for and how it was used.

3. Parentheses have been standardized to one format.
4. Tabs have been added to increase readability, spacing, and nesting in braces.
5. The “?:” operator has been used to reduce the length of the code by 4 lines.
6. The StringBuilder class was added to avoid string concatenation  (“string” + “string”). Although some may argue that creating the StringBuilder instance will slow down the method due to its memory allocation, I would like to remind everyone that string concatenation creates a lot of allocation for Garbage Collector to clean up. It is considered that ~5 string concasts are equal to creating instances of StringBuilder, so if a list consists of 5 or more elements the performance of this method will actually increase. And for larger collections this method will work several times faster.

Useful links:

But how can you know what conventions you should use when writing a code? Where to look for all good practices? And where to find all (or most) of this knowledge? For C# coding conventions I recommend: http://msdn.microsoft.com/en-us/library/ff926074.aspx Although these examples are written in C# all the same principles apply to Java. For Java coding conventions I recommend: https://google-styleguide.googlecode.com/svn/trunk/javaguide.html And if you are interested in writing code that is not only useful but also readable, check out this website: http://code.tutsplus.com/tutorials/top-15-best-practices-for-writing-super-readable-code–net-8118

















Wednesday, December 10, 2014

Welcome to programming.

·         Programming is really hard. No matter how good you get at programming, the only thing which slows you down is your ability to learn & solve problems. This seems to become more true as you get better at it. This is a fantastic trait - you will never be bored programming. If you are, you're doing it wrong and you should abstract over the set of code you're rewriting.

·         No matter how frustrating your problems are, there is almost certainly a solution out there. As you get better at programming, you'll get better & more confident at getting unstuck yourself. This makes the sense of frustration get better, and will push you to solve ever harder problems. (They're no fun if they're easy!)

·         When we were kids, we were bad at everything but we didn't notice. As adults, we have very few opportunities to be bad at something. Embrace the feeling - it is totally normal, and you're doing something not everyone is capable of doing.

·         Use the internet. Every problem you have in the first year you learn to program is a problem 100 other people have had before you. And all the answers are recorded online. The sooner you become effective at googling for programming help, the happier you'll be. Don't ever take any code snippets you find online if you don't understand how they work.

·         The best way to get better at programming is to write lots of code, read lots of code. Just keep making stuff.

·         There's lots of programmers who are more clever than both of us. They've written lots of code already that you can read if you want. It's probably on github.

·         There is no 'best language'. Some languages & tools are better at solving some problems than others. As you learn different languages, don't try and port your old thinking to the new system. Instead learn how to program idiomatically in the new language.

·         Be playful. Be silly. Because geniuses always can’t find solutions. Being silly will always give you solution but you should pick the right solution. Programming is a giant lego set full of fun problems waiting to be solved. Spend time making toy programs just for the hell of it. It's much more fun than whatever assignments you're given.

·         When you're stuck, write your program on paper. I'm serious. It's magic. This is standard practice in programming competitions. (I think it works because when you don't have to think about syntax you have more brain to solve the actual problem).

Credits: Joseph Gentle



Restricting Custom People Picker to only one Sharepoint group programatically

Refer the following script files in your page,     <!-- For People Picker -->     <script type="text/javascript" src...