Programmers

Why CS teachers should stop teaching Java applets

May 3, 2013 by Andrew Thompson. 20 comments

Post to Twitter Post to Facebook Post to Reddit Post to LinkedIn Post to StumbleUpon Post to Digg Post to Delicious Post to Technorati

As a veteran of applet development (see credentials below), I think it is high time to make a call that teachers should stop teaching applets in general, & especially AWT based applets. Applets are an advanced and specialized type of app. that has little place in the real world around us (most things that are done by applets can instead be better achieved using Javascript and HTML 5).

It saddens me to see new students ‘tossed in at the deep end’ to learn how to make an applet.

The reasons are multiple, but first, I’ll look a little at the history of applets and why applets were ever considered a good idea for teaching small, simple projects.

Applet vs. Frame

The simplest applet is:

import java.applet.Applet;
import java.awt.Label;

public class HelloWorldApplet extends Applet {

  @Override
  public void init() {
    add(new Label("Hello World!"));
  }
}

Looks simple, right? This hints at the primary reason that applets were taught.

It only takes a handful of code lines to see the end result.

But an applet gets a size & position on screen from the HTML that loads it. So an applet also requires a little HTML E.G.

<html>
<body>
<applet 
  code=HelloWorldApplet
  width=400
  height=200>
</applet>
</body>
</html>

This makes the total for a working applet 17 LOC. Not looking quite so simple now. Worse, many developers think ‘any old mark-up will do’ when that is very much not the case. Missing opening or closing elements make the HTML invalid and how a browser will interpret it is anyone’s guess.

Compare that to an application that behaves in as smooth a manner:

import java.awt.Label;
import java.awt.Frame;

public class HelloWorldApplication {

public static void main(String[] args) { Frame f = new Frame(); f.add(new Label("Hello World!")); f.pack(); f.setVisible(true); } }

So, while it takes just 9 lines of code for the simplest of applets (even including the @Override notation), while 12 LOC for the application doing the same thing, add the HTML and it becomes 17 lines for applet/HTML vs. just 12 LOC for the application.

AWT vs Swing

Time moves on, and the Swing component toolkit was introduced as a replacement for AWT. Nobody uses AWT anymore. Most Java GUI developers started using Swing, and those that have used AWT have largely forgotten the finer details.

This is relevant to the student in terms of getting help when they get stuck. It does not matter who we are, when approaching new areas of CS, we all tend to reach for whatever resources might help us understand the new technology. For a student the best resources are firstly the text books and class notes, but those typically only go so far at explaining, and the rest is from things like the JavaDocs, the Java Tutorial, searching the net, or asking for clarification on forums.

Those last two are particularly relevant in that:

  • There is a slew of extremely poor AWT based code available on the net.
  • There may also be some poor Swing based code out there, but usually there is a Swing programmer nearby that can point out the deficiencies in it.

Industry uses Swing and that is all that Swing programmers know and remember. AWT is obsolete, and a dead end in career or learning.

So let’s now look at the proper way to write a Swing applet & application. The Java Tutorial warns us that all Swing code should be started and updated on the Event Dispatch Thread, which (ironically) is an AWT based Thread.

A simple Swing applet might then be:

import javax.swing.JApplet;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import java.lang.reflect.InvocationTargetException;

public class HelloWorldApplet extends JApplet {

@Override public void init() {

@Override
Runnable r = new Runnable() {
  public void run() {
    add(new JLabel("Hello World!"));
  }
};
try {
  SwingUtilities.invokeAndWait(r);
} catch(InterruptedException ie) {
  ie.printStackTrace();
} catch (InvocationTargetException ite) {
  ite.printStackTrace();
}

} }

This is slightly verbose (25 LOC) for strict clarity, but could be reduced to:

import javax.swing.*;

public class HelloWorldApplet extends JApplet {

@Override public void init() { Runnable r = new Runnable() {

  @Override
  public void run() {
    add(new JLabel("Hello World!"));
  }
};
try {
  SwingUtilities.invokeAndWait(r);
} catch(Exception e) {
  e.printStackTrace();
}

} }

It could be further shortened (from 20 LOC) by declaring the Runnable inside the SwingUtilities method call, but I find that notation to be confusing & prefer to separate the Runnable into a clearly defined instance.

And now the Swing equivalent application, using the same ‘short guidelines’.

import javax.swing.*;

public class HelloWorldApplication {

public static void main(String[] args) { Runnable r = new Runnable() {

  @Override
  public void run() {
    JFrame f = new JFrame();
    f.add(new JLabel("Hello World!"));
    f.pack();
    f.setVisible(true);
  }
};
SwingUtilities.invokeLater(r);

} }

Just 18 LOC in total.

Not very much coding to see our simple message on screen, in a free floating Swing component.

Embedded vs. not embedded

Security

Why won’t the applet load my input file?

By default, Java applets run in a security sand-box that prohibits many actions which might be damaging to other applets, the browser or the user’s machine.

While the security sand-box is of great benefit to end-users, it makes the life of the developer difficult. And it has just become that much more difficult in Java 7 update 21.

In Java 7 Update 21 Security Improvements in Detail Markus Eisele notes:

With the introduced changes it is most likely that no end-user is able to run your application when they are either self-signed or unsigned.

While that warning is a little extreme, I agree with the underlying point being made. A user (or in this case you, the teacher) will need to OK some very scary dialogs, and possibly lower the default Java security to an unsafe level, before being able to view an applet.

Error reporting

My applet is broken but shows no errors! Where are they?

The System.err stream used for displaying stack traces appears on the command line (or in the IDE) when running an application. When a stack trace occurs in an applet it is sent to the Java Console, which is (by default) not configured to be shown.

Class caching

I changed my applet but the browser shows the same!

Many times I have responded to applet problems where the questioner swears they have changed the code & recompiled it, yet the browser is still showing the old values. The solution is relatively simple when you know how – flush the class cache from the Java Console. To someone learning, it is typically a complete mystery.

Embedded conclusion

Those 3 problems alone have probably earned me a quarter of the reputation points I’ve so far gained for applets on Stack Overflow. They pose huge problems when developing and debugging applets.

Conclusion

The question really comes down to:

Are you teaching Java/CS or how to deploy applets?

If the former, use JFrame based applications and side-step all the problems that are inherent to an embedded app. And don’t even consider teaching AWT components – they are obsolete & Swing takes only a few more LOC to get something on-screen.

Author Credentials

So who am I?

Post to Twitter Post to Facebook Post to Reddit Post to LinkedIn Post to StumbleUpon Post to Digg Post to Delicious Post to Technorati

What programming concepts I should master to have a deep understanding of my craft?

March 4, 2013 by LachlanB. 10 comments

Post to Twitter Post to Facebook Post to Reddit Post to LinkedIn Post to StumbleUpon Post to Digg Post to Delicious Post to Technorati

So you’ve been working as a programmer for a couple of years, and you want to become a good programmer. But not just a good programmer, you want to be a GREAT programmer. You want to paint with ALL the colors. Hell, you want to paint with all the dimensions. You want to be the GURU of programming – not just some nerd that’s stuck in corner that knows every namespace in the .NET API and can punch out a website in a day – you want to be a Michelangelo. A Picasso. Programming isn’t a science, it’s an art. You want to be respected.

Boy that’s a big ask.

So how do you get started?

By now you’ve hopefully realized that what makes good programmers great isn’t necessarily their technical skills. Your technical skills can be AWESOME, but if you don’t know what your customer wants, they amount to diddly squat. Of course if you know what your customer wants but don’t have the technical skills to back it up, you’re also up the creek. So what are the technical things you want to learn?

* How to write “DRY” code. DRY stands for “Don’t Repeat Yourself”. Copy and paste coders are not real coders. If you find yourself writing the same (or similar enough) lines of code more than once, it needs to be cleaned up so that you don’t have duplicate code all over the place. This will actually keep your codebase smaller, easier to maintain and reduce your bug count. People call this refactoring and it’s a daily part of our job. It’s not an optional extra for the end of a project.

* How to keep it simple. Once you’ve got the hang of refactoring and cleaning up your code as you go, you’re going to have to learn the next principle of keeping it simple. Too often once programmers have got it into their head that they need to not repeat themselves, EVER, and so many code bases grow to be an abstracted monstrosity. I’ve seen huge heaving code bases that take minutes to compile, but the application itself hardly does anything. Keeping things simple above all else is your goal.

* Learn the principle of YAGNI. You Ain’t Gonna Need It. All too often as programmers we want to make sure that we cover all our bases. The customer has asked that the application is to do X. If that’s the case, then they’ll probably want it to do Y and Z too. We might as well spend another 3 days putting that in, after all they’re going to ask for it anyway. Once again, you end up with a much bigger codebase and app than you need, and half of the code in there isn’t being used. Keep it simple!

This can be a very difficult concept to master. Making your solution flexible, customisable and forseeing future requirements is a very important part of our job. This is where I think that programming can be shown to be an art – there’s no hard and fast rule here. Ultimately it’s up to the programmer(s) discretion over how flexible a solution is – it involves constant judgement calls and a weighing up of the pros and cons. Normally the questions that you want to ask yourself are:

“How much extra work will it be to make this more flexible?” vs

“How much time do we have?” vs

“Will they really need it?” vs

“is this making the code worse or better?”

These kind of questions are very difficult to answer on your own. Two heads are so much better than one! Often just talking through the problem and the solution with another guy can help you work out the right approach yourself. Even picking up the phone to call another programmer to see what they think can save you a lot of pain.

* How to constructively review other people’s code. Code reviews can send a shiver down the spine of the most experienced programmer. They can be harrowing, aggravating and an ultimate waste of time. They can also be a delight, an opportunity to learn from others and to improve your skills! The most important aspect of code reviews is not what technical details you are looking out for, but the attitude and expectations that people approach the review with. If you’re dying to bag out someone’s code and make them feel bad, if you’re on the witch-hunt to see how many bugs you can find, then you’re going to be in trouble. People will resent these code reviews, nobody will want to help anybody else and most importantly, your code will not get any better!

The approach that you want is for everybody to go in with the mentality that “we’re here to learn from everybody else and to improve the code”.

* Design patterns. Reading the classic book on design patterns can give you a lightbulk moment – “oh, THAT’S how I solve that messy coding problem”. The danger that most people have is overapplying design patterns and you end up with a bigger mess than you started. Once you’ve learnt how to use a hammer everything starts looking like a nail. So don’t overzealously use them for the sake of it.

* Keep up to date with frameworks & libraries. You don’t have to use them, but you need to know what they do and their pro’s & con’s. A great example of this is SignalR – before this came along I would have been adamant that there is just no way that you can easily do realtime notifications within your web application. Turns out that before signalr there were libraries like pubnub who do this kind of thing with ease – but I had no idea! If I hadn’t kept up to date I could have been the one spouting rubbish (well, more often than usual, anyway). Keeping up to date with libraries and frameworks will also show you how if something seems way too hard to do then there’s probably (hopefully) a much easier way of doing things. Don’t write your own service bus layer when there’s MSMQ.

* How to comment your code. If you’re not commenting code then you’re making your life more difficult. When you come back to that function you wrote 6 months ago you’re not going to have a clue why you wrote it in such a convoluted way. Hey, it turns out that you did it that way for a reason! And BTW you shouldn’t simplify this mess because you’ll actually break it!

You also want to learn how to write down that complicated algorithm in a flowchart or just write it out in english. Don’t expect that someone will spend 2 days trying to reverse engineer your code. Don’t expect that people in the business will learn/remember/understand that complicated logic that they asked you to do. You’re going to end up pulling out this flowchart in at least 3 meetings in the future whenever people say “So what happens when x happens and then y?”

* How to write unit tests. Writing tests is a great way to ensure that your code will continue to work, even when some dufus comes along and modifies the database schema without telling you. Okay, well your code definitely won’t work, but now you can catch it the very day that someone renames a column. Instead of catching it three weeks later and finding out that your application hasn’t been calculating numbers properly. You’ll also want to learn what TDD is and see if it’s a good fit for you.

* What dependency injection / IOC is. A contentious argument for sure, but one you want to be well informed of. It’ll also give you a massive leg-up on when you see your first project that uses DI. If you don’t know what’s going on, you’d swear the code is backwards and insideout.

* How continuous integration is your saviour. I can’t imagine working on a project these days without CI. If I didn’t have a build running everytime someone checked in some code I would be quite terrified. It’s your safety net, your progress indicator and your one-click deploy solution all in one.

* Know what’s going on under the hood. For example, calling a web service – what’s it actually doing? If it’s WCF it’s creating a SOAP service call – you should check out the actual data that is sent over the wire sometime. It’s massive. If I hadn’t peeked under the hood I would have had no idea just how much bandwidth it needs. When it comes to programming, nothing just happens magically.

* Learn the gist of quite a few programming languages. You’d be surprised what you can learn from other areas. If you don’t know how simple python is nor how easy a web application is in ruby on rails, then you’re only seeing one side of the coin. If you’re coming in from strictly typed languages then javascript is a bizarre world in itself! I’m a c# developer and I’ve found that java guys think very differently. So do PHP people.

* Peter Rowell has a great post on how to debug. I agree with everything he says – real programmers don’t guess, they debug. If you think or hope something is working, you’re probably wrong. You need to SEE it working and prove that it’s working. I can’t tell you the number of times I’ve looked at code and said “there, that will work” only to run it and see that it doesn’t. Actually while you’re at it, read his other answers. There’s a voice of experience.

* Make fun of the losers. You also need to learn which programming languages you can successfully make fun of without someone actually punching you in the face.

So what about the non technical stuff? These are the hard ones.

* How to justify your project to management. Management will continually conveniently forget what the point of your project is. You need to be able to explain it in 30 seconds, and then if given the opportunity explain it in 360 seconds. How it benefits the business and why. If you can’t articulate it, nobody else will be able to, and pretty soon people will be asking “why is that guy here?”

* How to explain to management what you’re doing and why. This is different to justifying your project. Some bosses like to know what you’re doing every day – when s/he does, you better have a good answer. “Working on code” is not a good answer. “Adding feature X that will solve problem Y” is a much better answer.

* How to clarify and write down what the customers wants (“requirements”). This is an art in and of itself. If you can do this, your programming job will be A BREEZE. You know all those arguments and problems that you had with people outside of IT? They can be resolved by writing down what people say. Write it down in front of them, during the meeting. Learn from technical BA’s – they are a Godsend.

* How to estimate. People will ask you for an estimate, be prepared. If you don’t know what you’re doing, multiply your estimate by three.  This is not to pad it out – this is to make it more accurate.

* How to plan your project. Remember, only 30% of your time on a project should be coding. That’s thirty percent.

* How to differentiate between a bug, an issue and a feature request. They are all different.

* How to direct other programmers without getting up their nose. You also want to know how to motivate them.

* How to get along with other programmers. We’re a strange breed. Getting along with us can be a challenge – you’re going to have to learn some ninja skills. I can recommend “how to make friends and influence people” by Dale Carnegie. A classic.

* How to work with maniacs, psychopaths and just plain crazy people. There’s a lot of them out there. You’re probably one of them yourself.

 

Phew.

 

So what’s the most important thing to learn?

How to GET STUFF DONE. All the theory in the world won’t help you if you can’t get stuff done. Everything above is a waste of time if you’re not getting stuff done. Can this be taught? There’s an interesting question.

Post to Twitter Post to Facebook Post to Reddit Post to LinkedIn Post to StumbleUpon Post to Digg Post to Delicious Post to Technorati

Happy Birthday, Programmers!

December 16, 2012 by Yannis Rizos. 3 comments

Post to Twitter Post to Facebook Post to Reddit Post to LinkedIn Post to StumbleUpon Post to Digg Post to Delicious Post to Technorati

Hey all! Today is our second anniversary since graduation, Happy Birthday!

No, I don’t have any cake for you, I think by now, we all know the cake is a lie. Instead, I’ve a not-that-long blog post, summarizing all the awesome things that happened this year. We’ve certainly come a long way since our humble beginnings, the community is stronger than ever and the site has been steadily growing for quite some time now.

So, without further ado, here’s what’s been going on this past year:

Community Events

Programmers’ second year had some truly exciting moments. First, Anna Lear joined the evil corporate machine and we found ourselves short of a moderator. This prompted our second community moderator election, a process that I was very proud to be part of. The elections run smoothly, with surprisingly little drama and participation, although a bit low, was increased comparing to our first election.

Then, after the dust from the election settled down, we had our first ever contest. An exciting month long event that brought us some awesome questions, and some of the best answers I’ve ever read on the site. You can read more about the contest in this blog post, and it’s never too late for your feedback.

Which, of course, brings us to this very blog. The blog had a rocky start, although it was first proposed in June 2011, we didn’t really seemed to be able to get enough people interested in contributing. We went through various Meta discussions, two calls for contributors, a lot of candidates in the elections commited to make the blog happen, and finally we launched and posted our first blog post almost a year after the blog was first proposed. Kudos to the awesome blog team and everyone else involved for making this happen!

Lastly, starting from late January we undertook the monumental task of cleaning up our most problematic tags. The Structured Tag Cleanup started with the most bothersome of our tags, career and continued with software-engineering and software-development. The clean up effort ended on early April, at which point we’ve gone through 1000+ questions. Those of you who were active at the time may remember that we got at least a couple of blatantly off topic career questions per day, cleaning up 600+ broken windows in the various career related tags took care of that problem almost instantly.

We kick off our third year with the Hat Dash, a network wide event starting on Wednesday, it’s going to be fun!!!

Sister sites

The Stack Exchange network has grown rapidly this past year, right now there are 92 graduate and beta sites and a lot more are very close to popping out of Area51. Here’s a brief list of new technology oriented sister sites that you might find interesting (in no particular order):

When Computer Science first appeared, a question was asked in our Meta about clarifying the boundaries between the two sites. Inspired by that question, and after a brief discussion with a CS moderator, Raphael, we decided to test those boundaries by re-asking CS’s highest voted algorithmic question on Programmers. The answers the question received on Programmers are surprisingly different than the ones it received on CS, which, at least to me, says that although the sites overlap a bit, they have distinctly different audiences:

And of course, although not a technology oriented site, The Workplace deserves an honourable mention. The site was initially proposed on Area51 to fill the gap for all those general career related questions we couldn’t really support on Programmers, and it was greeted with enthusiasm from Programmers’ regulars when it finally made it to beta. Even today, 8 months into beta most of the site’s high rep users are also Programmers’ regulars, and all four pro tempore moderators are significant contributors on our site. If you haven’t visited the site already, trust me, it’s awesome!

New features

There have been a ton of new features this year, with two very important changes for Programmers:

Network wide the more significant changes were:

Questions

I wanted to close this with a list of awesome questions from the past year. At first I wanted to bring some new attention to a few hidden gems, showcase posts from less popular tags, blah blah blah, but at the last moment I decided to go simply with the questions with the highest score. It might not be the best metric we have, but it’s the only metric that I felt would adequately represent the wider community. Here they are, our top twenty questions:

All in all, it’s been an awesome year! Keep on rockin’, Programmers!

Post to Twitter Post to Facebook Post to Reddit Post to LinkedIn Post to StumbleUpon Post to Digg Post to Delicious Post to Technorati

Maintaining Healthy Hands

November 20, 2012 by Morons. 3 comments

Post to Twitter Post to Facebook Post to Reddit Post to LinkedIn Post to StumbleUpon Post to Digg Post to Delicious Post to Technorati

Keeping your hands healthy and pain free is something every programmer should be thinking about, minor hand injuries will affect your productivity, a major injury could threaten you livelihood. Hand injury is common problem amongst programmers, so it’s not surprising that the question “How do you keep your hands in good condition?” was asked here on Programmers (though closed as off topic).

Dr. Alan Gotesman an orthopedic surgeon with training in hand, microvascular & upper extremity surgery and friend to the Programmers Community has agreed to answer this question for us.

By: Dr. Alan Gotesman

Repetitive Strain Injuries of the Hand

Prolonged repetitive hand movements, particularly in awkward positions, can lead to strain injuries. It is important to be aware of these injuries and prevent them as well as treat them when appropriate. Some of the conditions may not necessarily be caused by repetitive stress, but many can be aggravated by it.  The following are some of the more common hand conditions encountered by hand surgeons in the setting of repetitive stress.

Carpal Tunnel Syndrome

The carpal tunnel is a narrow, tunnel-like structure in the wrist. The bottom and sides of this tunnel are formed by wrist (carpal) bones. The top of the tunnel is covered by a strong band of connective tissue called the transverse carpal ligament.

The median nerve travels from the forearm into the hand through this tunnel in the wrist. The median nerve controls feeling in the palm side of the thumb, index finger, and long fingers. The nerve also controls the muscles around the base of the thumb. The tendons that bend the fingers and thumb also travel through the carpal tunnel. These tendons are called flexor tendons

Carpal tunnel syndrome occurs when the tissues surrounding the flexor tendons in the wrist swell and put pressure on the median nerve. These tissues are called the synovium. The synovium lubricates the tendons and makes it easier to move the fingers. This swelling of the synovium narrows the confined space of the carpal tunnel, and over time, crowds the nerve. The synovial swelling can be caused or aggravated by repetitive motion. Direct compression of the carpal tunnel as well as extreme positions can also aggravate the condition.

Symptoms of carpal tunnel consist of:

  • Numbness, tingling, and pain in the hand
  • An electric shock-like feeling mostly in the thumb, index, and long fingers
  • Strange sensations and pain traveling up the arm toward the shoulder

Prevention:

Prevention of symptoms should focus on proper hand positioning when performing activities, in particular typing. The wrist should be in a neutral position (not bent up or down) which is best done by a forearm rest. There should also be no direct compression on the wrist which can increase the pressure in the carpal tunnel. Occasionally, braces may be required to rest the wrist and if symptoms become severe enough, surgery may be necessary.

Tendonitis

Tendons are the connection between muscle and bones which allow us to move our joints. The wrist tendons slide through smooth sheaths as they pass by the wrist joint. These tendon sheaths, called the tenosynovium, allow the tendons to glide smoothly in a low-friction manner. When wrist tendonitis becomes a problem, the tendon sheath or tenosynovium, becomes thickened and constricts the gliding motion of the tendons. The inflammation also makes movements of the tendon painful and difficult.

The most common and consistent complaint of patients diagnosed with wrist tendonitis is pain over the area of inflammation. Swelling of the surrounding soft-tissues is also quite common. Repetitive stress can cause tendonitis by putting too much strain on the tendons.

Prevention:

Taking frequent breaks and not putting the wrist/hand in awkward positions can prevent these injuries. If symptoms appear, anti-inflammatories can be helpful as well as short periods of immobilization. Swelling can be brought down with ice and elevation. Cortisone injections can be helpful for symptoms that are not improving and surgery may be necessary if conservative modalities are failing.

Sprains

A sprain is an injury to a joint caused by a tearing/stretching of the ligaments. These are frequently acute injuries caused by trauma, however they can be chronic from repetitive stress across the joint causing stretching. Any joint can be affected, but the thumb can be particularly vulnerable as the ligament is often being stressed with daily activities. The increased frequency of texting, with the thumb primarily being used to depress the keys, has increased the incidence of this problem.

Symptoms consist of discomfort around the joint, particularly with any stress applied. There can be swelling in the area as well as tenderness directly over the affected joint. Extremes of motion can be painful as well.

Prevention:

Repeated stress across the joint, especially in one particular direction, should be avoided. If symptoms appear, alternative positions should be used and if possible, decrease the amount of activity. Custom splints can be helpful to support the particular ligament involved and decrease the stress across it. Anti-inflammatories can alleviate the pain and swelling. Infrequently, if symptoms persist, the ligament may need to be repaired or reconstructed.

Repetitive stress injuries of the hand can be disabling and appropriate measures to prevent them should be instituted. If symptoms persist, they should be evaluated further by a qualified hand surgeon for further treatment.

About The Author

Dr. Alan Gotesman is a board certified orthopedic surgeon with fellowship training in hand, microvascular & upper extremity surgery. He has a special interest in minimally invasive and arthroscopic surgery. He is in private practice in Rockland County.

Alan Gotesman MD
http://www.alangotesmanmd.com
Orangetown Orthopedics
99 Dutch Hill Road
Orangeburg, NY 10962
845-359-1877

Post to Twitter Post to Facebook Post to Reddit Post to LinkedIn Post to StumbleUpon Post to Digg Post to Delicious Post to Technorati

How we managed 24 software development trainees

July 17, 2012 by pierremengal. 3 comments

Post to Twitter Post to Facebook Post to Reddit Post to LinkedIn Post to StumbleUpon Post to Digg Post to Delicious Post to Technorati

Students programming in main room

Students programming in main room

Each year the Belgian Microsoft Innovation Center (MIC) runs a program to introduce future graduates in software development to local startup companies. The students come with their enthusiasm and eagerness to learn; the Startups arrive with innovative and exciting projects and the MIC provides the infrastructure and support. This year I had the pleasure to manage 24 students over 19 projects. I’ll explain how we did it.

In addition to the equipment necessary for project implementation (laptops, office, subscriptions, software, etc…) we organized many activities. The purpose of these activities was to increase significantly the level of our future developers’ professionalism while ensuring the proper conduct of the projects for our local businesses. These activities included among others: training, collective code reviews, coaching and each trainee had to give presentations.

Training

Controlling a claw built with Lego Mindstorms with his mind using Emotiv Headset

Controlling a claw built with Lego Mindstorms with his mind using Emotiv Headset

There was nothing very special about the training except the emphasis we gave to interactivity. One thing we noticed was that instead of covering new topics we were trying to complete the learning that students had achieved during their studies. Here are some of the topics we covered:

  • Coding guidelines
  • Source code controllers (We used Mercurial on BitBucket.org)
  • Unit Testing
  • Design Patterns
  • C # in depth (inspired by the book of the same name)
  • Agility in general
  • Scrum in detail
  • Effective Logging & debugging
  • Basic concepts of project management software such as backlog management

We believe that these issues need to be fully integrated into university/college curricula. This would allow us to focus on even more advanced subjects.

Collective Code Reviews

a Collective Code review session

a Collective Code review session

I regularly organized what we call a collective review of the code. This does not mean that everyone read all the code – that would be inefficient.

I read each trainee’s code and when I came across a problem, I would put a screenshot on a powerpoint slide. The next slide was a copy of the previous slide but with arrows showing the errors and a third slide was a screenshot of the code as I would have liked to have seen it. One type of error was added to the presentation once. For example, “poor management of exceptions” was examined only once even if it was a widespread problem found in most projects.

All the students would gather in the conference room to see the presentation. For each problem the first slide is shown so that the group could review it and identify potential problem with the code. Very often, one of the interns suggested the right solution straight away. The slide that highlighted the errors was then displayed and a discussion took place. Finally an example of corrected code was shown (third slide) so that everyone would get the benefit of the “lesson”.

Occasionally, good practice was suggested which always generated discussions and suggestions.

The learning method proved very effective. Students loved the performance aspect since it is very interactive and it always close to the problems they face.

Coaching

A student programming Nao

A student programming Nao

In addition to formal learning, intensive coaching has been implemented. At any time, I could intervene to help trainees to advance the project. I was fully dedicated to that during the whole period. They also had the opportunity to come and see me to ask technical questions whenever they could not find a solution online in less than 10 minutes (on Stack Overflow for example). Rather than handing out fish, the technique of coaching was to teach them how to fish. We placed an emphasis on developing the student’s capacity to learn while giving them the ideal conditions for the rapid acquisition of new knowledge. Coaching also included informal learning and covered all the things that are more difficult to cover during presentations to the group. Here are the different subjects which have been covered:

  • Continuous integration
  • Blogging
  • The use of a project tracking tool (we used Trello see below)
  • How to write an effective resume
  • How to interview
  • How to gain certifications (Microsoft ;))
  • The attitude to adopt in the business environment

The last point was particularly important to me. Throughout the internship, I stressed the one point that I think will make the difference between them and other developers: the ability to solve problems and not create new ones.

Project Monitoring

A team using Trello with the Microsoft Surface

A team using Trello with the Microsoft Surface

Managing the project was a very important part of the project. In fact, following 24 people in 19 projects is not an easy task. We naturally chose to set up Scrum and used a task management tool of the kanban type. Trello was chosen for its ease of use.

We formed four “virtual” teams based on project similarities, included in these “virtual” teams were two real teams of 2 or 3 people, Alongside our desire to maximize the output, we had a secondary objective to get the trainees to live Scrum and agility in general through real scenarios, some exactly as in a large company. So we had the daily scrum, the sprint review, the retrospective and a lighter version of the sprint planning.

Scrum has proven very effective in this type of program. We plan to integrate even more companies in the process. Although I took the role of “Product Owner” on this occasion we think it would bring more if the course tutors played this role, after training.

Trainee presentations

Students had the opportunity to prepare and make presentations to the group of students. These presentations were in addition to what was originally planned in the program and has allowed the students to practice the art of presentation but has also allowed them to share their new learning with the other trainees. Subjects covered were:

  • Introduction to HTML5
  • MEF (Managed Extensibility Framework)
  • Work with Blend interfaces
  • Introduction to Windows 8
  • Introduction to XNA
  • Introduction to ASP.NET MVC
  • Deploy a WCF service in Azure
  • Object Mocking
  • Get organized with GTD
  • The pattern MVVM
  • Introduction to Programming Kinect
  • Which company to choose?
  • Introduction to Silverlight
  • Debugging with Visual Studio.

We believe that a great developer must learn to communicate his knowledge and this exercise is therefore one of the things we will continue in the future. Indeed, in addition to these presentations, we encourage our trainees to develop a presentation video by making the appropriate equipment available. In business, those who are able to communicate well are often those to whom we entrust the most responsibility.

Conclusion

Programming the Kinect for Windows

Programming the Kinect for Windows

How will we know if this program will lead to better performance from the students in comparison with other internship models? That’s the question we asked ourselves last year.

This year we have developed a proficiency test that measured several dimensions that we believe a developer must master. As we predicted, the score at the start of the program was pretty bad. At the end of the course this score had, on average, doubled!

Despite this result, we cannot say today that our program will have had an effect significantly superior to another approach, simply because we did not have a control group. We hope to do this in 2013.

I sincerely hope that other companies will be inspired to create a similar program within their specialism. I am also very interested in any form of feedback or to hear of your experiences – you can contact me in the comments.

You can see a video introduction to the program here.

In addition, one of the project participated in the Imagine Cup 2012 and you can watch the video here.

 

Post to Twitter Post to Facebook Post to Reddit Post to LinkedIn Post to StumbleUpon Post to Digg Post to Delicious Post to Technorati

Approaching another programmer about their code quality

July 2, 2012 by Rachel. 7 comments

Post to Twitter Post to Facebook Post to Reddit Post to LinkedIn Post to StumbleUpon Post to Digg Post to Delicious Post to Technorati

Programmers have to work with large amounts of bad code. Sometimes its your own code, but other times its another programmer’s code. If you have to frequently work with another programmer’s bad code, you will eventually wish to approach them about their code quality, however how to do this without causing offense or resentment is not always easy. This article is about the approach I would take when wanting to casually talk with another programmer about their code quality.

Determine the problem

First off, determine what exactly the problem is, and verify that it is worth bringing up. Ask yourself:

  • Do you work with this person on a regular basis?
  • Will you be working with, and maintaining their code in the future?
  • Is this an actual problem that harms productivity, performance, or security, or is it simply a case that your preferences are different from theirs? For example, simply complaining that “your naming convention doesn’t match mine” is not a very good reason, however saying “your naming convention makes it hard to understand what is going on in the code” is a much better.

If you answered yes to all of those, then it sounds like you might have a good reason to approach someone about their code quality.

Gather your arguments

Once you’ve determined there is a valid reason for trying to change the way another programmer does things, get your arguments prepared. Identify why the code is harmful to the development environment, and figure out the ideal way of coding it instead. Pick some code samples illustrating the problem, and write your own way of coding the same piece. Determine what your arguments are for why your code is better than the existing code sample. Don’t use arguments such as “it’s best practice”, but instead explain why it’s a best practice (readability, maintainability, reusability, etc)

Approaching the other programmer

Now that you know your arguments for why you think your code is better than theirs, and have a clear idea of what the ideal code should look like, arrange a time to talk with the other programmer.

This could be a casual conversation, or it could be setting up an appointment to talk with them about your concerns. How you choose to approach your co-worker is based on your level of comfort with them, the organization’s environment, and both of your ranks within the organization. For example, if I wanted to talk to the programmer next to me, I might simply ask them if I could have a moment of time whenever they’re available to talk with me about a piece of code, however if it’s my boss, I might send him/her an email asking if I could setup a brief meeting with them to discuss some code I’ve been working on.

Some people might argue that approaching a boss is different than approaching a co-worker, however I feel they are both people and both deserve equal respect. The only real difference I see is that your boss’s time is usually more valuable to the company, so be aware of that when talking with him/her.

What to say

When you actually talk with the other programmer, I usually find a good way to start the conversation is to ask them to explain their code. Ask if there was a reason for their style of coding, or tell them you’ve never seen something coded that way, and ask them why they chose that method. Really listen to what they have to say during their explanation. It could be that their way is right, and you are wrong, in which case take notes and learn from it!

If you still think the code is bad and worth changing, show the other programmer how you would code the same piece of code, and tell them why you would code it that way over his/her way (better performance, fewer chances of errors, easier for other programmers to read/maintain, etc).

Focus on why your method of coding is better, and not why their method is worse. Nobody likes being accused of writing bad code, although in reality we were all new once and I’m sure we’ve all written some horrendous code at some point in our lifetime. Be sure to keep the conversation focused on the code, and avoid turning it personal by talking about the person who wrote the code. It is always best if you can show that you understand that sometimes bad code gets written, whether it was due to time constraints, inexperience, or simply a bad day.

In addition, don’t try and get them to change their old code (unless you are their boss and want them to spend time doing so). Your goal is to educate them so they stop making the same mistake in the future, not berate them over past mistakes and punish them by extra work.

Afterwards, see if he/she still supports their coding style over yours. If they are open to improvement, they will likely change their way of coding going forwards. But if they still prefer to use their coding style, you are not likely to change their opinion, so drop the subject and don’t bring it up again unless their code is actually harmful.

Conclusion

Remember, nobody can write perfect code, and good programmers are always looking for improvement. The world of programming is so big that its impossible to know everything. It’s very likely that the other programmer doesn’t know there is a problem with their code, and would appreciate the input, providing you do it in such a way that you are teaching them, and not insulting them.

So don’t be afraid to approach another programmer about their code quality. I know I would appreciate the conversation, and I think you would too.

Post to Twitter Post to Facebook Post to Reddit Post to LinkedIn Post to StumbleUpon Post to Digg Post to Delicious Post to Technorati

Code stinks! What do I do?

June 11, 2012 by ubermensch. 2 comments

Post to Twitter Post to Facebook Post to Reddit Post to LinkedIn Post to StumbleUpon Post to Digg Post to Delicious Post to Technorati

Introduction

A quick search for the words “bad code” and “code smell” on Programmers Stack Exchange fetches a lot of results. So this means that several people are having this problem. This article present a few ways to work with this problem from a non-technical 30000 feet perspective.

A few caveats

  • Nobody can write perfect software; you can improve it forever. There is always room for improvement.
  • Programs keep changing based on requirements and requirements based on market environment. Hence code is dynamic and prone to error.
  • Bad code is not directly proportional to programmer inefficiency. There are a lot of other factors that contribute to bad code.
  • This article is written from the perspective of enterprises engaged in the business of software.
  • In my opinion, there are a few hopeless cases where you just cannot tame it. A list of them is given at the end of the article.

What is bad code?

Though difficult to define, for the purpose of this article, we can define bad code as some piece of code that is: incomprehensible by reasonable standards,1 lacks in conceptual integrity, doesn’t have a definite structure and is a sign of more bigger problems. Technically, code smell.2

If a bad piece of code is not found, it can quickly turn into a code smell and transform into a black hole that could suck every good part of the program in.

The following are a few explicit instances of bad code

  • the person who wrote or maintains the code cannot explain it in a logical manner
  • changing one part of a program breaks another
  • improper documentation
  • lack of conceptual integrity
  • lack of standard conventions
  • lots of duplicated code
  • too many components to integrate and too many layers

Causes for bad code

The causes for bad code are many and the reasons are also multidimensional. So, causes may be viewed from three main perspectives:

Programmer-centric

  • Improper communication3
  • Lack of domain knowledge4
  • Lack of experience and understanding
  • Lack of experience in a particular tool-set or methodology

Design/Architecture-centric

  • Anti-patterns
  • Over-engineered code
  • Interface kludge
  • Lot of individual components to integrate
  • Improper layer/tier separation
  • Improper selection of technologies
  • Anemic models

Organization-centric

  • Outdated methodologies
  • Outdated tool-sets
  • Usage of legacy systems
  • Too much vendor lock-in
  • Wrong hiring policies

There are several other ways that bad code can be made, and each topic in this list deserves a separate article on its own. The following Wikipedia page provides some excellent links.

Ensuring the code is indeed bad

Before embarking on this journey, make sure that the code is indeed bad and it needs to be taken up. The following guidelines would help.

  • Do plenty of research and get to the root cause.
  • Analyze the code from multiple perspectives. Review it with another person.
  • See old versions of the code to know its evolution.
  • Always use objective standards.
  • Discard petty issues, obvious errors that could be easily corrected.
  • If possible, correlate between the code and the bugs created by the code.
  • Use standard code coverage tools to analyze the program.

Your Rank in the organization

A program is just not an entire technical pursuit. There are different priorities for the same program at different ranks and the same technique wouldn’t be a good fit for all.5 Thus your rank in the organization gives you the ability to leverage your resources purposefully. The higher the rank, the higher the resources and the bigger your influence albeit with higher responsibility. Enterprise hierarchy is one big tree you can’t always traverse successfully.

For the sake of simplicity, we assume three ranks in the hierarchy bottom-up.

  • Rank 1 – people who actually write code – programmers, developers, software engineers – scope limited to a module or a set of modules.
  • Rank 2 – people responsible for a project – Project leaders, senior developers, team leaders, software architects – scope covers the entire project in hand.
  • Rank 3 – people responsible for the delivery of the software to the customer and revenue to the organization – Project managers, Product managers, delivery managers – scope extends to the successful delivery of the project.

There is a correlation, though not directly proportional, between rank and the nature of problem. Most programmer-centric problems can be attributed to Rank 1, design-centric to Rank 2 and organization-centric to Rank 3.

A few suggestions to approach the problem:

  • Know your position and rank in the organization and approach problems that could be realistically solved by you. You may easily talk to a co-worker about refactoring but you can’t expect to implement it across teams if there are tight deadlines. Be pragmatic as what you could solve.
  • Talk to the right person. Know the scope and rank of the person you are talking to. You can’t discuss design or methodology change with a Rank1 programmer nor you could be talking variable naming conventions with your boss.
  • Take time off. A prior appointment would be good. Never ever discuss in a urgent, haste manner. Proceed on a case-by-case basis. Remember you are pitting for a future change and people doesn’t like change.
  • Always give time for reasoning and listen to the person you are talking to and never run into an argument on his style of programming.6
  • Despite your best efforts, if your underlying assumption about the code turns to be wrong, graciously accept it.

The following additional guidelines would help for different ranks

Rank 1 Communication

A person in this rank may not be fully aware of the entire software life-cycle. So you are limited about what things you could talk to but this is the rank where most of your suggestions would be accepted. Communication is the X-Factor at this rank.

  • Know the qualification, domain experience, expertise and the programming paradigm of the person. Paradigms (Object Oriented,Functional) and domain experience play a huge role in programming style and understanding. Ascertain the right area of concern.
  • Ask him to explain the code to you and share your thoughts about it. Show how your proposed method could be better. Use an objective method to stress the advantages arising out of the new method versus its disadvantages.
  • Put focus on ease of use, easy maintenance, long-term development of quality software and stress the importance of cascading effects
  • Don’t talk things beyond his reach. He is just hired to do programming not to run the organization.

Rank 2 Communication

Persons in this rank do have a lot of technical knowledge so you got to be spot on with your reasoning and facts. Also, keep all your discussions at the conceptual level. Changes at this level may take time to get implemented. Clarity is the X-Factor at this rank.

  • Ask the reasons for choosing the specific design or architecture; the constraints, advantages and trade-offs involved.
  • If the design is flawed, pinpoint it accurately. If it is a known anti-pattern, name it precisely. If there is a flaw in the business logic, describe it with the industry standards.
  • If the design, though technically sound, is too esoteric, try explaining how making it a bit simple would make it more easy.
  • Building a good design takes considerable time and energy. So try concentrating on improving the existing design to rectify the flaws rather than proposing a radically new design.

Rank 3 Communication

You are operating at a much higher level where revenue is the main priority. You must prove decisively that the present polices inadvertently lead to programmer inefficiency and thereby increasing cost. So, a lot of work needs to be put in. Remember, you are pitching for a future organizational change. Many a time, you may just not get over the line in this rank, since a lot of other factors are involved in decision-making but if you believe you could make a change, you must give a honest try. There is basically no X-Factor here though some knowledge of political science would definitely help.

  • Talk to your peers as how they feel and think about the present scenario and garner valuable support.
  • Do organizational research. Read the policies and procedures of the organization and compare them with the competitors.
  • Fix a prior appointment and have a formal agenda.
  • Never ever use subjective standards.
  • Support your views with research papers and authenticated articles.
  • Effectively use metaphors.
  • Prepare a neat presentation. Use some business buzzwords in it. Do not make it too technical. Nitty-gritty technical points can be taken up at a separate discussion.
  • Always present your views with a cost-revenue analysis and show a comparative study with your competitor.

To illustrate, if you are sure that the waterfall methodology of your company is creating delay in software delivery and thereby introducing more bugs due to cramped schedules, try doing the following.

  • Select a couple of completed projects.
  • Collect the following information regarding the projects.
  • Estimated schedules, proposed delivery, actual delivery, estimated budget and final cost
  • Number of man-hours spent
  • Number of changes proposed by the client and the hours required to complete them
  • Bug reports and the time taken to complete them.
  • Installation, maintenance and service costs.
  • Prepare an alternative schedule in an another methodology (say agile). Be conservative in your approach.
  • Now, estimate the hours that would have been saved by the new methodology.
  • Include the additional costs that would be incurred
  • Calculate the opportunity cost
  • Now put these things together and create a nice presentation. Quantify everything and convert it into costs or revenue such as “the new method would lead to a 10% decrease in man-hours that would cut project costs by 7%”
  • Initiate for a pilot project so that you could try the new methodology. You are running a big risk here but its worth taking.

Final remarks

A few hopeless (difficult to change) situations in my opinion:

  • Cramped schedules.
  • Programming thought as a linear function by the management and work allotted on the basis of pure division of labor.
  • No upfront design. Starting to code straight away.
  • Horses for courses policy. Hiring somebody to do the job.
  • Egocentric persons with lethargic attitude.
  • Right persons in the wrong jobs and wrong persons in the right job. DBA’s pushed into web interface programming and business analysts doing hands-on programming.
  • No clarity in rules of procedures.
  • Too much implicit communication.
  • Thinking too much.

There are chances that despite your best efforts, your suggestions may not be accepted. Always try to the best of your efforts and if it fails, just adopt an another method. Remember the Pareto principle; You might spend 20% discovering bad code and 80% try correcting it. Also, communicating bad code is 20% technology and 80% psychology.

Our problems are man-made, therefore they may be solved by man. And man can be as big as he wants. No problem of human destiny is beyond human beings.

  • John F. Kennedy, speech at The American University, Washington, D.C., June 10, 1963

Recommended Reading

Footnotes


  1. Reasonable standards mean the program must be understood by a programmer with the same expertise as the person who wrote it in the first place 

  2. Code smell is any symptom in the source code of a program that possibly indicates a deeper problem 

  3. Communication here means the ability to correctly understand the business requirements of the client and to explain it to fellow programmers. 

  4. Domain here refers to specialization. Domain may be computer-related such as systems programming, web programming, GUI application or business-related such as finance, human resource, production. 

  5. If you honestly believe you are hired by enterprises exclusively for your technical abilities, I suggest reading this article

  6. The only way to get the best of an argument is to avoid it from “How to win friends and influence People” by “Dale Carnegie” 

Post to Twitter Post to Facebook Post to Reddit Post to LinkedIn Post to StumbleUpon Post to Digg Post to Delicious Post to Technorati