答:
To what end?

Why would you want one? Some people use it as a way to sell themselves to employers. Others do it to help enrich the community and share information. Maybe both. I think you need to ask why you want a website before you determine how important it is.

If you want to sell yourself to employers, then yes a site or blog can definitely be of help. If you want to share something with the community then yes, a blog is a great way to do that. But you should only contribute if you want to contribute. Don't feel compelled to have a blog just because all the other "good developers" have one. If you like to write and have something good to say, go for it. Otherwise don't bother.

Title: Is having your own website important?

Body:
How necessary or important is it? I try to keep a running list of blogs or sites to follow, but a lot of the time I pull up someone's profile and notice there isn't anything there. Is it really important?

I understand are different levels of programming (from C/C++ system programmers to Rails and even Haskell and J) and not everyone works in a language easily worked with for web based applications. Not everything is web-centric, however with the advent of many popular and sometimes free services I don't think it's unreasonable to expect a majority of programmers to have a personal site.


问:
How do you maintain a common library used by different clients?
I am part of a software deveopment team. Originally there were just 2 of us, and two applications. To ease our job we create a set of libraries, handling stuff like GUI, database access, calculation, business rules etc, so that we can reuse them in our applications without implementing them twice.

Now the team grew, 6 people and ~5 applications (and growing). The applications use the same library, which are great because we don't have to develop and maintain the same thing more than once. I and the other initial guy developed and are mostly responsible for the library, but other people have access to the code and occasionally update it to fix bugs and add improvements.

But soon we notice that the more we grow and the more people can modify the code, there is a risk that "improvements"/"bug fixes" that someone does can unintentionally break someone else's application which depends on the old behavior. On the other hand, assigning one guy to maintain the libraries and make sure modifications won't break anything is not practical because there are many applications, and possibly many improvement requests to be done, and he can't be sure of everything either.

How do teams normally manage situation like this? Perhaps by implementing rules on allowed modification? Defining behaviours that shouldn't be changed? There are a lot of libraries in the internet used by a lot of people, for example open-source/free to use libraries like Apache, Castle, etc. How do they make sure that changes won't break existing client codes?

答:
I like Thanos' answer. Additionally, at my work, we use git repositories to manage our code libraries. It puts the code under version control, essentially, so that if damaging changes are ever made and pushed out to everyone else, it's easy to roll it back, find the problem, fix it, and re-deploy.

But, fortunately, it will detect conflicts, or collisions in modified files, for you so that you can review each change (called the "delta") as it goes up to the repo.

To know more, you'd like Pro Git, which is free to read online.

ContentLicense: CC BY-SA 3.0


问:
Is this a correct situation to use a constant?
So my professor was giving back some feedback on a project I've been working on. He docked a few marks for this code:

```<code>if (comboVendor.SelectedIndex == 0) {
  createVendor cv = new createVendor();
  cv.ShowDialog();
  loadVendors();
}
</code>```

This is in a combobox "index changed" handler. It's used when the user wants to create a new vendor, my top option (index 0, that never changes) opens the "Create a new Vendor" dialog. So the content of my combo box ends up looking like this:

```<code>Create New Vendor...
Existing Vendor
Existing Vendor 2
Existing Vendor 3
</code>```

His problem is with the first line code:

```<code>if (comboVendor.SelectedIndex == 0)
</code>```

He claims that the 0 should be a constant, and actually docked me marks because of that. He claims I shouldn't use literals in my code at all.

The thing is, I don't understand why I would want to make that code in that situation a constant. That index will never change, nor is it something that you would need to tweak. It seems like a waste of memory to keep a single 0 in memory that's used for a very specific situation and never changes.

答:
[...] my top option (index 0, that never changes) opens the "Create a new Vendor" dialog".

That fact that you had to explain that proves why you should use a constant. If you introduced a constant like NEW_VENDOR_DIALOG, your code would be more self-explanatory. Besides, compilers optimize out constants, so there won't be a change in performance.

Write programs for programmers, not compilers. Unless you're specifically trying to micro-optimize, which it doesn't seem like you are.


答: I suggest that you add unit tests for this shared library. This will help you decide on the expected behavior and will alert you if this behavior ever changes due to a bug fix or a code improvement/refactor. I would not worry too much about different applications that use the library expecting different behavior from it if you spend the time to clearly define what that behavior is.</p>

Title: How do you maintain a common library used by different clients?

Body:
I am part of a software deveopment team. Originally there were just 2 of us, and two applications. To ease our job we create a set of libraries, handling stuff like GUI, database access, calculation, business rules etc, so that we can reuse them in our applications without implementing them twice.

Now the team grew, 6 people and ~5 applications (and growing). The applications use the same library, which are great because we don't have to develop and maintain the same thing more than once. I and the other initial guy developed and are mostly responsible for the library, but other people have access to the code and occasionally update it to fix bugs and add improvements.

But soon we notice that the more we grow and the more people can modify the code, there is a risk that "improvements"/"bug fixes" that someone does can unintentionally break someone else's application which depends on the old behavior. On the other hand, assigning one guy to maintain the libraries and make sure modifications won't break anything is not practical because there are many applications, and possibly many improvement requests to be done, and he can't be sure of everything either.

How do teams normally manage situation like this? Perhaps by implementing rules on allowed modification? Defining behaviours that shouldn't be changed? There are a lot of libraries in the internet used by a lot of people, for example open-source/free to use libraries like Apache, Castle, etc. How do they make sure that changes won't break existing client codes?


问:
Is there a formula to figure out the total execution time of sequential asynchronous processes?
I have a set of steps that need to run sequentially over a list of data. However each step only operates on a single piece of data at a time. Because of this, I can run the steps asynchronously.

For example I have two pieces of data, and two steps. When step one is done processing the first piece of data, it passes it to step two. Now step one processes the second piece of data while step two is processing the first piece of data. So forth and so on until all of the data  has been processed by each step.

In contrast, looping through the list of items and executing every sequentially in order turns into the equation:

```<code>total_time = (step1 + step2 + ... + stepN) * number_of_items
</code>```

Given that I know the execution time of each step for a single piece of data, and I know the number of items to be processed, is there a formula that will tell me the total execution time for processing all the data items asynchronously?

I have written a program (see below) that simulates this process. I'm not entirely sure that it is computing it correctly, but I believe it is close. This was my attempt at figuring out how to solve the problem. I'm including it here to show my understanding of the problem, which may be wrong.

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ConsoleApplication1 {
    class Step : Queue<object> {
        public Step(int totalExecutionTime)
        {
            _totalExecutionTime = totalExecutionTime;
            CurrentExecutionTime = _totalExecutionTime;
        }
        readonly int _totalExecutionTime;
        public Queue<object> NextStep { private get; set; }
        public int CurrentExecutionTime { get; private set; }
        public void RunTick()
        {
            if (Count == 0)
                return;
            if (CurrentExecutionTime == 0)
                CurrentExecutionTime = _totalExecutionTime;
            CurrentExecutionTime--;
            if (CurrentExecutionTime == 0 && NextStep != null)
                NextStep.Enqueue(Dequeue());
        }
    }
    class Program {
        static void Main(string[] args)
        {
            int totalItems = 10;
            int[] stepLengths = new int[] { 1,2,5,2,2 };
            if (File.Exists("output.txt"))
                File.Delete("output.txt");
            WriteLine("ASYNC: {0}", TotalTime(totalItems, stepLengths));
            WriteLine("SEQUENTIAL: {0}", stepLengths.Sum() * totalItems);
            Console.WriteLine("DONE");
            Console.ReadLine();
        }

        static int TotalTime2(int totalItems, int[] stepLengths)
        {
            throw new NotImplementedException();
        }

        private static int TotalTime(int totalItems, int[] stepLengths)
        {
            var steps = new List<Step>();
            Step prevStep = null;
            foreach(var stepLength in stepLengths) {
                var step = new Step(stepLength);
                steps.Add(step);
                if (prevStep != null)
                    prevStep.NextStep = step;
                prevStep = step;
            }
            var first = steps.First();
            for(int i = 0; i < totalItems; i++) {
                first.Enqueue(new object());
            }
            var last = steps.Last();
            var revSteps = steps.Reverse<Step>().ToList();
            var totalTime = 0;
            do
            {
                Display(steps, totalTime);
                revSteps.ForEach(s => s.RunTick());
                totalTime++;
            } while (last.Count < totalItems);
            if (last.CurrentExecutionTime > 0)
            {
                do
                {
                    Display(steps, totalTime);
                    revSteps.ForEach(s => s.RunTick());
                    totalTime++;
                } while (last.CurrentExecutionTime > 0);
            }
            Display(steps, totalTime);
            return totalTime;
        }

        static void Display(List<Step> steps, int totalTime)
        {
            Write("[");
            steps.ForEach(s => Write("{0},", s.CurrentExecutionTime.ToString().PadLeft(2)));
            WriteLine("]");
            Write("[");
            steps.ForEach(s => Write("{0},", s.Count.ToString().PadLeft(2)));
            WriteLine("] {0}", totalTime.ToString().PadLeft(5));
            WriteLine();
        }
        static void Write(string fmt, params object[] args)
        {
            Console.Write(fmt, args);
            using (var w = new StreamWriter("output.txt", true))
            {
                w.Write(fmt, args);
            }
        }

        static void WriteLine(string fmt, params object[] args)
        {
            Console.WriteLine(fmt, args);
            using (var w = new StreamWriter("output.txt", true))
            {
                w.WriteLine(fmt, args);
            }
        }

        static void WriteLine()
        {
            Console.WriteLine();
            using (var w = new StreamWriter("output.txt", true))
            {
                w.WriteLine();
            }
        }
    }
}
</code>```

答: Assuming that the processes are completely independent (no resource contention), and each process has an infinite input queue, processing all the items will take about as long as it takes the slowest process to handle all the data, plus the time for the first item to reach the slowest process, plus the time to complete the last item after it leaves the slowest process.</p>


问:
Documentation with images - what is the most git-friendly approach?
When documenting software I traditionally write a plain text file (like a README.txt) which works well, but unfortunately cannot contain images like HTML can.  Unfortunately images must be stored as separate files with a normal HTML document (using href=".../foo.png">) which give unnecessary clutter.

The "Save a single web-page" in Internet Explorer use MIME HTML (MHTML) to save all resources within a single file.  The requirement of having to use a browser to read it, is not a impediment these days.  Apparently Opera and Word support editing these documents directly.

We use git for our source code, hence the differences as seen by git between two edits of the same documents should not be large to avoid unnecessary disk usage and unusable diff's when looking at the document outside the MTHML editor.

What is the best mainstream HTML editor for producing git-friendly MHTML files?

答:
If, for some reason, you absolutely don't want external images, you could embed images in HTML as base64 (here is an online converter).

But I would personally rather have files as HTML (or better, Markdown) with images separated, and export/print to PDF if/when a single file is requested, that is easier to maintain.


答:
The actual correct way of doing this in C# is to not rely on the ordering of the ComboItems at all.

```<code>public partial class MyForm : Form
{
    private readonly object VENDOR_NEW = new object();

    public MyForm()
    {
        InitializeComponents();
        comboVendor.Items.Insert(0, VENDOR_NEW);
    }

    private void comboVendor_Format(object sender, ListControlConvertEventArgs e)
    {
        e.Value = (e.ListItem == VENDOR_NEW ? "Create New Vendor" : e.ListItem);
    }

    private void comboVendor_SelectedIndexChanged(object sender, EventArgs e)
    {
        if(comboVendor.SelectedItem == VENDOR_NEW)
        {
            //Special logic for selecting "create new vendor"
        }
        else
        {
            //Usual logic
        }
    }
}
</code>```

Title: Is this a correct situation to use a constant?

Body:
So my professor was giving back some feedback on a project I've been working on. He docked a few marks for this code:

```<code>if (comboVendor.SelectedIndex == 0) {
  createVendor cv = new createVendor();
  cv.ShowDialog();
  loadVendors();
}
</code>```

This is in a combobox "index changed" handler. It's used when the user wants to create a new vendor, my top option (index 0, that never changes) opens the "Create a new Vendor" dialog. So the content of my combo box ends up looking like this:

```<code>Create New Vendor...
Existing Vendor
Existing Vendor 2
Existing Vendor 3
</code>```

His problem is with the first line code:

```<code>if (comboVendor.SelectedIndex == 0)
</code>```

He claims that the 0 should be a constant, and actually docked me marks because of that. He claims I shouldn't use literals in my code at all.

The thing is, I don't understand why I would want to make that code in that situation a constant. That index will never change, nor is it something that you would need to tweak. It seems like a waste of memory to keep a single 0 in memory that's used for a very specific situation and never changes.

Body:
The actual correct way of doing this in C# is to not rely on the ordering of the ComboItems at all.

public partial class MyForm : Form
{
    private readonly object VENDOR_NEW = new object();

    public MyForm()
    {
        InitializeComponents();
        comboVendor.Items.Insert(0, VENDOR_NEW);
    }

    private void comboVendor_Format(object sender, ListControlConvertEventArgs e)
    {
        e.Value = (e.ListItem == VENDOR_NEW ? "Create New Vendor" : e.ListItem);
    }

    private void comboVendor_SelectedIndexChanged(object sender, EventArgs e)
    {
        if(comboVendor.SelectedItem == VENDOR_NEW)
        {
            //Special logic for selecting "create new vendor"
        }
        else
        {
            //Usual logic
        }
    }
}


问:
How to update display during large processing job
I have an ASP.NET C# application that needs to go off and iterate through a directory of .xml files and do some processing on the data inside them. This is easy enough, but i need to display the result after each .xml is processed, how can this be done?

What im really asking here is how do you process a lot of data in a loop that needs to be displayed back to the client even though the server processing has not fully completed. Is this even possible?

I could start the big process in a seperate thread and start a js timeout to postback and essentially poll the process but this doesn't sound great and would probably require using static variables to maintain state.

Would it be correct to use SessionState / ViewState / QueryString to persist the status of which file ive processed and do away with the loop altogether? Therefore seperate the large job into seperate requests?

答:
Contrary to @Mike's answer, you actually can maintain a "sort" of persistent connection with your clients.  With HTML5 and WebSockets (or Flash), you can.  However, there is a really simple way to do this if you don't mind a 3rd party service.

We just implemented a real-time chat system in a membership site using Pusher.com's service.  They provide a JavaScript library which maintains a persistent connection to their server, and then allow you to post messages to their server, which are instantly delivered to all of the JavaScript clients, allowing the display to update.

Check it out:  http://pusher.com/


问:
Naming Rules: Standards, Reserved, and what do they depend on?
I want to know the rules of naming (AlwaysCapitalize, _underscore, firstSmallLetter, etc...) for each of Namespaces, Classes, Interfaces, Exceptions, Data Members, Methods, Variables, etc....

also I would like to know:

Are they standards?

Do they differ According to the access modifiers? (public, private.....)

What about compiler and library reserved formats?

Also are they Language, IDE, or Framework relative?

I only know that these rules exist, but don't actually know any.

Any help would be appreciated.

EDIT: OK, if the question is really wide, then I have to narrow my question:

What are the naming rules of Classes, Interfaces, Data Members, and Methods in C# (and Java if possible).

Also, inspired by Renesis's comment, I've created a wiki to write Coding Conventions, here's the link:

http://codingconventions.referata.com/

答:
I'd suggest taking a look at stylecop ( or fxcop and its naming warnings ) and other similar tools.

Stylecop is a static C# code analyzer that enforces the naming conventions you want to find out. So by checking its rules you can see the information you want.


答:
I would say that you should not do long processing causing the user to wait for long time in an ASP.NET application to start with.

I suggest that you do the processing in batch and have the result stored on some kind of data store (file or database).

If the information changes frequently (say, you keep getting XML files), you could set a trigger/watcher on the directories to monitor arriving XML files, process the new ones and update the results (in batch). You could also build an ETL job for that.

Title: How to update display during large processing job

Body:
I have an ASP.NET C# application that needs to go off and iterate through a directory of .xml files and do some processing on the data inside them. This is easy enough, but i need to display the result after each .xml is processed, how can this be done?

What im really asking here is how do you process a lot of data in a loop that needs to be displayed back to the client even though the server processing has not fully completed. Is this even possible?

I could start the big process in a seperate thread and start a js timeout to postback and essentially poll the process but this doesn't sound great and would probably require using static variables to maintain state.

Would it be correct to use SessionState / ViewState / QueryString to persist the status of which file ive processed and do away with the loop altogether? Therefore seperate the large job into seperate requests?


答:
```<code>Are they standards?
</code>```

In general, they are coding conventions not standards. Following the conventions makes reading the code much easier.  Companies and projects may adopt particular conventions as their standard.

```<code>Do they differ According to the access modifiers? (public, private.....)
</code>```

This is dependent on the conventions in use.

```<code>What about compiler and library reserved formats?
</code>```

Compilers and libraries commonly use underscores at the beginning or end of identifiers.  Programmers should avoid such identifiers unless they fully understand the implications.

```<code>Also are they Language, IDE, or Framework relative?
</code>```

Different languages have different conventions.   Some languages have competing conventions.  Most frameworks will have a convention, but not all frameworks have the same convention.

IDEs may provide support for coding conventions.  Many have add-ins which will allow the use of style validation tools within the IDE>

EDIT: Java has a recommended coding style now available from Oracle.  I don't work with C#, so I don't know if there are competing standards to the MSDN C# coding standards.  These would be a good starting point for your own standards.

When working with existing code try to follow the same conventions as the current code.  Working with code that has been coded with a variety conventions can be very confusing.

You may find it useful to be familiar with a number of conventions.  You will likely encounter a number of them as you work with different code bases.  When working on new code select a set of code conventions and stick to them.

Title: Naming Rules: Standards, Reserved, and what do they depend on?

Body:
I want to know the rules of naming (AlwaysCapitalize, _underscore, firstSmallLetter, etc...) for each of Namespaces, Classes, Interfaces, Exceptions, Data Members, Methods, Variables, etc....

also I would like to know:

Are they standards?

Do they differ According to the access modifiers? (public, private.....)

What about compiler and library reserved formats?

Also are they Language, IDE, or Framework relative?

I only know that these rules exist, but don't actually know any.

Any help would be appreciated.

EDIT: OK, if the question is really wide, then I have to narrow my question:

What are the naming rules of Classes, Interfaces, Data Members, and Methods in C# (and Java if possible).

Also, inspired by Renesis's comment, I've created a wiki to write Coding Conventions, here's the link:

http://codingconventions.referata.com/

Body:
Are they standards?

In general, they are coding conventions not standards. Following the conventions makes reading the code much easier.  Companies and projects may adopt particular conventions as their standard.

Do they differ According to the access modifiers? (public, private.....)

This is dependent on the conventions in use.

What about compiler and library reserved formats?

Compilers and libraries commonly use underscores at the beginning or end of identifiers.  Programmers should avoid such identifiers unless they fully understand the implications.

Also are they Language, IDE, or Framework relative?

Different languages have different conventions.   Some languages have competing conventions.  Most frameworks will have a convention, but not all frameworks have the same convention.

IDEs may provide support for coding conventions.  Many have add-ins which will allow the use of style validation tools within the IDE>

EDIT: Java has a recommended coding style now available from Oracle.  I don't work with C#, so I don't know if there are competing standards to the MSDN C# coding standards.  These would be a good starting point for your own standards.

When working with existing code try to follow the same conventions as the current code.  Working with code that has been coded with a variety conventions can be very confusing.

You may find it useful to be familiar with a number of conventions.  You will likely encounter a number of them as you work with different code bases.  When working on new code select a set of code conventions and stick to them.


问:
Is having your own website important?
How necessary or important is it? I try to keep a running list of blogs or sites to follow, but a lot of the time I pull up someone's profile and notice there isn't anything there. Is it really important?

I understand are different levels of programming (from C/C++ system programmers to Rails and even Haskell and J) and not everyone works in a language easily worked with for web based applications. Not everything is web-centric, however with the advent of many popular and sometimes free services I don't think it's unreasonable to expect a majority of programmers to have a personal site.

答:
I don't see why you shouldn't have a blog.

I would recommend starting one for purely selfish reasons.  I use my site to keep track of things I've learned so I don't have to go look it up again.

If you don't want to add your site as spam on the internet, then don't crawl it on search engines, and just leave it for yourself.

No harm no foul.

ContentLicense: CC BY-SA 2.5

Title: Is having your own website important?


问:
What would you do if your client required you not to use object-oriented programming?
I am writing a program to simulate the activity of ants in a grid (PDF). The ant can move around, pick up things and drop things.

The problem is while the action of the ants and the positions of each ant can be tracked by class attributes easily (and we can easily create many instances of such ants) my client said that since he has a background in functional programming he would like the simulation to be made using functional programming.

To be clear, the original words from the client is "no class" only, but not "functional programming". So I assume he doesn't mean functional programming and I can do it imperatively. Additionally, I have no prior experience in functional programming.

However, I think it's beneficial to focus on this question being particularly about a functional programming requirement than just simply "do it imperatively."

How would you handle this situation? Would you try to persuade your client that using object-oriented programming is much cleaner, try to follow what he required and give him poor-quality code, or do something else?

答:
```<code>double dist(Point p1, Point p2)
{
  //return distance
}
</code>```

This function is functional as long as it doesn't read/write anything outside the function. If the function touched a class variable it would no longer be "functional". The advantage of functional style is there are no more bugs from changing or invalid state. A large amount of functions are just mathematical formulas. That's functional programming in a nutshell.

BTW you can combine a functional style within an object based or oriented design. For example the two "Point" variables are objects with state. And the function is still functional! Yay!!

Body:
double dist(Point p1, Point p2)
{
  //return distance
}

This function is functional as long as it doesn't read/write anything outside the function. If the function touched a class variable it would no longer be "functional". The advantage of functional style is there are no more bugs from changing or invalid state. A large amount of functions are just mathematical formulas. That's functional programming in a nutshell.

BTW you can combine a functional style within an object based or oriented design. For example the two "Point" variables are objects with state. And the function is still functional! Yay!!


问:
Functional Low-Level language that can use a webkit view

TL;DR:

I need to develop an app which should look kind of the same on desktop and as a website incarnation.

Since I am a web dev and have never developed for desktop, I want to use a language that can embed a webkit view so I can use the same HTML/JS front-end for both usages, and minimize the learning curve for GUI at least.

C++ and Java can both use webkit, however, I am looking for alternatives where functions are first-class citizens, because I prefer prototype-based languages by far.

Long Version

I am mainly a web developer; I'm at ease with js/as3/php/python.

Lately however, I had ideas that need other languages to get done. Namely, I have an idea for a software that is part custom-database and part GUI. So I began tackling desktop oriented languages such as Java and C++.

I discovered Java is basically super-easy and C++ kind of ok (though it gets complex when I try to use GTK and the docs are sparse and dispersed). I can use this; one thing bugs me though: As fond as I am of PHP as a project and as a community, I've grown a dislike for imperative languages and find myself much more at home with ECMA-style languages. I was happy in web dev lately with the rise of node.js and how I could begin developing server-side functionality with javascript.

My question

I need a language that has the following features:

Functional. By "functional", I mean a large definition. This includes any language where functions are first-class citizens (where "actions" are more important than "actors").

Portable: I picked C++/GTK or Java because of easy portability and no license restrictions. So portability here means os-independent (with realistic limits) as well as open license.

Can use a webkit view:(like in GTK,or in Java) or similar; I intend to leverage my knowledge of web apps to build a beautiful, usable, gui in html5. The same interface will be used in the online version of the app. Therefore, I need the language to have a way to embed and interact with HTML5

Can use JS: ideally, through V8, although rhino or a similar tool is ok. If a window js object could be exposed to the js code (so I can use standard libs such as jQuery), it would be perfect.

Low-level: I need the database part to be fast. Could code my db in C and my GUI in whatever-language-it-will-be, but ideally, I'd like to use one toolset for both

Less important, but: if the language could be a derivative of ECMA script, so I can leverage my js skills, it would be cool.

My Current Options

Titanium, which has all the above features and uses js as it's primary code; However, I dislike being tied to a particular SDK and I'd rather use independent open-source libs that I can read.

Your suggestion?

答:
While it is significantly different that Java, C++, JS, whatever else I propose Clojure, a Lisp dialect. It is functional in the true sense. It also is dynamic. Since it is running on the JVM you should be able to use a webkit view since you have access to Java libraries.

The syntax probably looks pretty foreign but it is rather simplistic really and does satisfy your requirements.

Rhino, an open source implementation of Javascript in Java. You can use it and still have access to Java libraries though I am not entirely sold on some of the examples. The site shows that reflection is required to create a Java array from Rhino which feels clunky in my opinion but that is only my opinion. Again though like Clojure you get access to Java libraries which will fulfill the webkit view desire.


问:
When would one give up backward compatibility in favor of new and improved interface implementation?
I have been working at the same software company for more than ten years. As a result, I have implemented a large code base using various object-oriented programming languages.  I was a beginner programmer when I first started my career and I didn't know much about good interface and class design principles. I would like to think that my design skills have improved over time, but I now face more and more difficulties in improving my earlier code because of backward compatibility concerns. My code is used by a large number of customers as part of the products that my company sells.

So my question is: when should one stop trying to keep backward compatibility of old interfaces and bite the bullet in favor of implementing a brand new design?

I think there comes a point where keeping backward compatibility becomes such a big burden that useful changes to interfaces become impossible. Has anyone experienced similar concerns, who can provide some feedback?

答:
The short answer is Never!

Experience shows that dropping backward compatibility at the very least annoys customers and users, and, at worse loses them completely.

If you are asking your users to rewrite code, after they have finished the customary cursing of you and all your descendants, they will think "If I have to re-write anyway maybe I should just switch to that nice ACME library I have been reading so much about?".

The trick is to either enhance the current interface in such a way that does not break backward compatibility, or, to offer a completely new shiny and obviously superior interface while maintaining the older interface. At some point there will be features in the new interface that just won't be possible in the older interface, but, this just gives people an incentive to move, without forcing the issue.

Edit to clarify this further.

What you as a programmer think is -

"I will improve this API and make the system as good as possible and everyone will admire me".

What the users of your API will think is -

"A***e he thinks my time and schedule are not important. I have to stop what I am doing and refactor all my code for no other reason than to satisfy his ego. If I have to refactor then I am going to switch to another API just to stick it too him."

ContentLicense: CC BY-SA 4.0


问:
Estimation of Effort and Schedule for a project with almost no familiar elements
To the best of my understanding the schedule for the project is derived using the effort estimates for the individual tasks (in person hours), and the number of relevant resources used   for the particular task.

As discussed in this question, we are starting a project using a new platform, featuring a brand new API and feature-set. How do we estimate the schedule of the tasks involved in the project, knowing only the top level task breakdown? Also, if some efforts are allocated to the tasks, the estimations would have a wide probability distribution. What is the best way to communicate the same to management?

答: I usually give an R&D (Research and Development) estimate for unfamiliar territory. In this, I promise an actual estimate upon the elapsing of the R&D time limit. I spend the R&D time creating prototypes and proof of concepts, and then finally my overall architecture. By that time, you should be familiar enough to make a good estimate. Giving an estimate without communicating that you will have to spend time in R&D is asking for upset employers. They may not like this response, but I promise you they will hate the alternative-- i.e. you make a timeline that you have no idea that you can meet and you inevitably fail to meet it. </p>


答:
In general I agree with James Anderson. In my experience there are, however, additional aspects that may warrant consideration and that may point towards an option that does indeed allow evolving interfaces.

This example is from one of the teams I am working with. They ship a product on a regular basis, at least once per month sometimes even weekly. Customers are encourage to upgrade as new features and new platforms are only supported on newer versions. Upgrading is easy and customers can even skip versions in between. Downgrading is not supported. In addition versions are only supported for 3 years. After that there is a grace period of one year when maintenance fees double.

As a result the vast majority - about 95% of the customers - are upgrading on a regular basis, at least once a year. This also means that you can gradually introduce new interfaces.

How about old interfaces? The technique this team uses is declaring old interfaces as 'end-of-life'. Then there is a 12 month period in which the new interface is available and the old interface has not bee retired yet. The new interfaces offer better features than the old interface so there are two incentives: Old interface end-of-life and new interface being much better.

The concrete old interface in this case was a platform specific technology that is in the process of gradually being replaced by a service interface based on standard mainstream technology.

Of course this change doesn't happen over night and it takes many years until completion. But it allowed stopping investment in the old technology and instead investing into the new technology. Customer are given assistance and have a path forward. Most of them are welcoming the move towards newer technology as well.

Keep in mind, though, that this particular approach may not work in your scenario. It certainly does work for the team that I'm working with.

Title: When would one give up backward compatibility in favor of new and improved interface implementation?

Body:
I have been working at the same software company for more than ten years. As a result, I have implemented a large code base using various object-oriented programming languages.  I was a beginner programmer when I first started my career and I didn't know much about good interface and class design principles. I would like to think that my design skills have improved over time, but I now face more and more difficulties in improving my earlier code because of backward compatibility concerns. My code is used by a large number of customers as part of the products that my company sells.

So my question is: when should one stop trying to keep backward compatibility of old interfaces and bite the bullet in favor of implementing a brand new design?

I think there comes a point where keeping backward compatibility becomes such a big burden that useful changes to interfaces become impossible. Has anyone experienced similar concerns, who can provide some feedback?


答:
While 'when' is a good question, I think 'how' is even more relevant. It can be difficult to make a breaking transition in a way that doesn't make users frustrated or unhappy. Some items for consideration:

Communicate with your clients/customers well ahead of any transition. Explain why and how it will be implemented. Citing security, performance, stability, and future flexibility as reasons are all valid.

If you're making a clean break anyway, solicit feedback.

If there are any 3rd party developers, make sure that you include their input as well in so much as it makes sense.

If it's possible, provide a compatibility layer.

Provide a comprehensive upgrade guide.

Make the upgrade as easy and painless as possible. Minimize your users' pain, even if it means a little more work for you.

If you charge, offer a discount for upgrades to the new version.

Add at least a few new and useful features in a new version to incentivize the upgrade. This is especially important in making the upgrade more appealing to managers.

If you do make a break, make it the last time you need one. That means some comprehensive planning in advance and making sure that everything is set up properly.

If you have a UI, go easy on changes to it. Think refresh rather than redesign. For non-technical users, drastic UI changes from one version to another can be a big cause for frustration.

Your new version should be noticeably more stable and performant than the old. Don't give your users a reason to resent the upgrade. Don't release a new version without extensive testing beforehand (unit, integration, and beta testing).

Maintain the old version simultaneously for an extended period of time. If you do decide to phase it out and discontinue support, give at least 6-12 months notice, more if you can.

Can you afford to maintain two versions at once in terms of both finances and manpower? (Also, from a business perspective, you shouldn't stop support of the old version until you can afford to lose the remaining clients that are clinging to the old version and don't want to upgrade. That point should be when your costs of maintaining it outweigh your profits from it.)

Commit to doing security updates for a period of time after the old version has been discontinued if necessary.

Again, communication is huge all throughout the process. Don't leave your users/clients/customers feeling abandoned at any point. Their loyalty and passion is the foundation of your business. Make sure that you respond to their questions on your blog or in your forums. The social factor should not be underestimated.

As for the 'when', you will probably have a better idea for your application than anyone else.  In general, however, it might be time for a clean break when your technical debt and architecture completely inhibit stability, prevent reasonable performance, and make the development of new features overwhelming or needlessly difficult.

All that said, don't take this step lightly. Even done right, breaking backward compatibility is a big deal. You should strongly consider increasing your test coverage and refactoring first and if at all possible before considering a break.


问:
What should I put in comments while commiting to the Source Control?
I am a lone developer and maintain a SVN server for source control. So far, I haven't followed anything specific while committing my changes.

I was just reviewing my previous commits, and couldn't make any sense of my comments.

What do you put in comments while committing your checkins?

答:
I generally put the purpose of the check-in at the top.  This may be the name of a feature request, ticket number, etc.

I then follow it up with the list of the files affected and the specific changes required in each file.  This is particularly helpful when one is looking at the revision history of a file as opposed to the project/folder.

Something like

```<code>Ticket 101 fix web service exception when uploading widget

Bug was caused by users uploading incomplete widgets (widgets without wonkers)

webservice.cs:
  improved post validation for incomplete widgets
  added default exception handler to ProcessWidget
widget.cs:  handled the SqlException when inserting widgets without wonkers
</code>```

Body:
I generally put the purpose of the check-in at the top.  This may be the name of a feature request, ticket number, etc.

I then follow it up with the list of the files affected and the specific changes required in each file.  This is particularly helpful when one is looking at the revision history of a file as opposed to the project/folder.

Something like

Ticket 101 fix web service exception when uploading widget

Bug was caused by users uploading incomplete widgets (widgets without wonkers)

webservice.cs:
  improved post validation for incomplete widgets
  added default exception handler to ProcessWidget
widget.cs:  handled the SqlException when inserting widgets without wonkers


答:
You already got some good answers here, so I would just like to add a pointer to a very nice article from Joel Spolsky concerning this topic. He is discussing the plans of giving up backwards compatibility in IE 8, which is essentially the same as your problem:

http://www.joelonsoftware.com/items/2008/03/17.html


问:
Learning C# in a unified manner
Microsoft technologies keep getting better but they do so on the expense of adding one more abstraction layer every time. In the early stages we used to play with C# code and SQL procedures to perform CRUD operations. Then generics came along with ADO.NET, DataSets, Entities. Next, LINQ came offering LINQ to SQL, to XML, to Entities, to Objects. To get more easier and more confusing, EF 4.1 came. C# just kept evolving and adding new abstractions layers again and again.

The end result is that I am so confused that I don't know which one is which and when to use which one. When I try to follow books, some teach EF while some are stuck with ADO.NET. Seriously I have no clue whatsoever why we have evolved so much for data manipulation

To be honest, all I know is the C# syntax and some basic stuff. Data manipulation is out of the window and so are the advanced features.

Is there a unified manner to learn C# ? I don't want to use Entity Framework and LINQ when I don't understand them or what they offer. I just want to have a thorough understanding from Level 0 to Level 10.

Also, I am thinking of learning PHP simultaneously because I feel learning some other language will might help me understand C# better. Is this the right thing?

答:
Here is my advice:

Learn LINQ - Linq is useful in many situations and for different purposes.

Don't learn EF in detail as long as you don't really need it. Of course, you should know what it is good for, but unless you are going to create a new database application with a bunch of domain model classes, you won't need it.

Learning PHP will be good for understanding PHP better, but probably not so much C# (but who knows what you will find there). There are other languages which may be better suited than PHP if you want to see things from a different angle - I suggest that you try a functional language like Lisp, Scheme, Haskell, F#, or a weakly typed language like Python.

Title: Learning C# in a unified manner


问:
A good tool for browser automation/client-side Web scripting
I'm interested in adopting a tool/scripting language to automate some daily tasks connected with fighting forum spammers.  A brief overview of these tasks: analyze new registrations and posts on a phpBB forum, and delete or deactivate spammers using a website/community that collects such spam reports.

Typically such automation is integrated into the phpBB installation itself, which certainly has its advantages.  My approach has the advantage of independent operation, etc.

One way to think about this is in terms of browser automation.  I've used iOpus iMacros for Firefox (the free version) in the past to respond to individual spammers, but current attacks are highly distributed.  My "logic" for pigeonholing spammers vs. nonspammers seems beyond the easy reach of the free version of iMacros.

From a more technical perspective one can think about dispensing with the browser altogether and programming GET/POST requests directed to my forum and other Web-based resources.

I'm familiar with some scripting languages like Ruby and Lua, but I could be persuaded that a compiled application is better suited for these tasks.  However in my experience the dynamic flexibility of interpreted environments is very useful in prototyping and debugging the application logic.  So I'm leaning in the direction of scripting languages.

Among browsers I favor Firefox and Chrome. I use both Windows and Linux platforms, and if the tool can adapt to an Android platform, it would make a neat demonstration of skills, yes?

Thanks in advance for your suggestions!

答: I have used Watir for all the automated testing at a big electronics company and found it really great to work with, especially because the excellent Ruby language is used.</p>


问:
Elegant ways to handle if(if else) else
This is a minor niggle, but every time I have to code something like this, the repetition bothers me, but I'm not sure that any of the solutions aren't worse.

if(FileExists(file))
{
    contents = OpenFile(file); // <-- prevents inclusion in if
    if(SomeTest(contents))
    {
        DoSomething(contents);
    }
    else
    {
        DefaultAction();
    }
}
else
{
    DefaultAction();
}
```

Is there a name for this kind of logic?

Am I a tad too OCD?

I'm open to evil code suggestions, if only for curiosity's sake...

答:
I saw a lot of examples with "return" which I use too but sometimes I want to avoid creating new functions and use a loop instead:

while (1) {
    if (FileExists(file)) {
        contents = OpenFile(file);
        if (SomeTest(contents)) {
           DoSomething(contents);
           break;
        }
    }
    DefaultAction();
    break;
}
```

If you want to write less lines or you hate infinite loops as me, you can change the loop type to "do ... while(0)" and avoid the last "break".

Title: Elegant ways to handle if(if else) else

Body:
I saw a lot of examples with "return" which I use too but sometimes I want to avoid creating new functions and use a loop instead:

while (1) {
    if (FileExists(file)) {
        contents = OpenFile(file);
        if (SomeTest(contents)) {
           DoSomething(contents);
           break;
        }
    }
    DefaultAction();
    break;
}

If you want to write less lines or you hate infinite loops as me, you can change the loop type to "do ... while(0)" and avoid the last "break".


答:
EF, LINQ, ADO.NET etc. are all tools you will use in some cases, and throw away in others. Just like in a toolbox of a craftsman, you'll find not one, but dozens of screwdrivers of different sizes and shapes. Why not using one screwdriver for everything? Because it doesn't work this way.

This also means that an experienced developer needs to be familiar with all those tools. It also means that you have two approaches:

Start to learn everything at once,

Start to learn something you understand better, then learn another tools, etc.

I'm pretty sure most of the developers would prefer the second approach, but I also believe that for some, the first one will work better. You can also mix both: go see what EF is about while just starting to learn ADO.NET for example. After all, before choosing the one you understand better, you must first try them all a little.

After learning those technologies for a while, you'll also be able to detect which ones will be useful for you, personally. I know that in my daily work I don't need EF at all. Not because it's bad, but just because my work doesn't require it. I then can concentrate my learning efforts on other technologies I use every day. Maybe in your daily work, EF will be your favorite tool, and you'll never need ADO.NET. In the same way, I may have just an idea what Workflow Foundation (WF) is, while some other developers are required to have a deep knowledge of this technology if they want to find a job in their sector.

Also, I am thinking of learning PHP simultaneously. Because I feel learning some other language will might help me understand C# better. Is this the right thing?

I would not do that. Especially with PHP. I wouldn't even learn C# and some normal language, like Python, at the same time: chances are it will make more confusion than help. F# could be an interesting choice if you're interested in LINQ and how to write code in a LINQy way, but I still recommend postpone the learning of F# until you know C# enough.

If this particular question interests you, you can search for other questions on Programmers.SE, specifically about learning several languages at the same time.

Title: Learning C# in a unified manner

Body:
Microsoft technologies keep getting better but they do so on the expense of adding one more abstraction layer every time. In the early stages we used to play with C# code and SQL procedures to perform CRUD operations. Then generics came along with ADO.NET, DataSets, Entities. Next, LINQ came offering LINQ to SQL, to XML, to Entities, to Objects. To get more easier and more confusing, EF 4.1 came. C# just kept evolving and adding new abstractions layers again and again.

The end result is that I am so confused that I don't know which one is which and when to use which one. When I try to follow books, some teach EF while some are stuck with ADO.NET. Seriously I have no clue whatsoever why we have evolved so much for data manipulation

To be honest, all I know is the C# syntax and some basic stuff. Data manipulation is out of the window and so are the advanced features.

Is there a unified manner to learn C# ? I don't want to use Entity Framework and LINQ when I don't understand them or what they offer. I just want to have a thorough understanding from Level 0 to Level 10.

Also, I am thinking of learning PHP simultaneously because I feel learning some other language will might help me understand C# better. Is this the right thing?


答:
I think if you learn PHP in parallel to C#, you will see the common values in programming languages and that is a very supportive action you can take. And when you start learning PHP you will notice that there are several frameworks there too. And all the techniques that you listed are some tools you can use in your projects when you need them. But the main branch of a language and in general what a programming language is, is your main knowledge about the craft, so make it stronger while you can.

For example you can try to use C# new language features like functional programming, anonymous objects(maybe you know them already). From there you can hop to more dynamic languages like Javascript, Lisp etc.

Title: Learning C# in a unified manner


答:
Your question is rather difficult to answer in detail because the answer would cover lengthy discussion of the many points you raised but I will try to cover the core concepts here. I will start by:

Also, I am thinking of learning PHP simultaneously. Because I feel learning some other language will might help me understand C# better. Is this the right thing?

Well, if you are a person with average IQ, it is hard to learn PHP and Microsoft Stack (C#, EF, LINQ, ADO), ...etc + different frameworks, ..., all together at the same time. The above statement is my opinion and is not scientific fact of course.

So, first, determine what you want to do with all of this. Are you building a system for yourself, do you want a job as a professional developer, etc. This is very important.

Next, I assume that you should start by focusing on ONE technology stack (or event 1 tool).

Assuming you go with Microsoft, you then have to pick an application model (eg.  Silverlight, WPF, ASP.NET or Windows Forms). This is very important too because each of those technologies have its own framework and you need to be familiar with other related technology to the selected application model (e.g. HTML is needed for ASP.NET but not for WPF).

Now we come to the database part. You either pick no-sql, XML only or SQL RDBMS (like most do)

Let's say you go with SQL RDBMS, you still have a combination of choices to make regarding how to access this data from your code:

ADO.NET (with or without LINQ)

EF with LINQ

Use of a 3rd party ORM (I will not get into this here because it is a very lengthy subject)

ADO.NET worked for the early days of .NET and represents an important foundation for data access, so learning it is important.

You say:

I don't want to use Entity Framework and LINQ when I don't understand them and what do they offer.

If your goal is to be a professional developer with Microsoft Technologies, you need to know LINQ (and I suggest you add EF as well) to some extent even if you don't directly use them in your current project. Knowing these technologies will open a wider market than knowing ADO.NET only.

"At Microsoft’s November 2009 Professional Developer Conference, the legendary Don
Box, a Distinguished Engineer at Microsoft, said, “If you’re a .NET developer Entity
Framework is where we’re going. We’re there. Get on board, it’s time."

...

"The ADO.NET Entity Framework has shifted into becoming Microsoft’s core data
access platform for building .NET applications" - From the book: Programming Entity Framework by Julia Lerman.

The EF with LINQ allows you to program using your business objects instead of programming against data tables directly. Some of the Other benefits are listed here:

Entity Framework Features

New Features in Entity Framework 4.0 (V2)

Title: Learning C# in a unified manner


答:
My advice is that you learn LINQ for 2 good reasons.

Although LINQ is only a tool, and is not appropriate for all purposes, it is a very powerful tool with many possible applications.  Obviously it is useful for LINQ to Entities EF type db access but it can also do neat things like this file text aggregation.

Secondly, in learning LINQ you will expose yourself to many of the powerful new C# features and .NET language extensions such as Implicitly typed variables, Anonymous types, Object initializers, Lambda expressions, Delegates, First Class functions, Generics, Iterators using yield and Extension methods.  Much of the features that have progressed C# significantly as a language and .Net as a platform either directly support or are indirectly involved with LINQ.  If you want to get deeply into C# that would be the sensible direction to take.

Jon Skeet's book C# in depth is excellent and covers these things, although definitely not the 1st C# book you should read (and probably not the second one either)

Title: Learning C# in a unified manner


问:
How to load text files into memory-mapped files
I have a number of large text files that I need to manipulate in a highly performant manner. I've decided to look into using Memory Mapped files in C# (.NET 4). However, I can't find any examples of or guidance on how to read/write to a memory mapped file that, underneath, is bound to a text file. Can anyone shed some light on this and, possibly, provide me with some examples?

If it helps, I’ll be reading text in whole lines, then altering the line and replacing it with content that may be shorter or longer than the original. After all of the manipulations are done, I want to save it back to disk as a text file.

答:
I do not think you will gain much, if anything, in performance, by using memory-mapped files instead of performing normal text-file processing. From the moment that you change the length of a single line even by just one byte, the remainder of the file will need to be read, shifted by one byte, and written back to disk. From the point of view of I/O, this is equivalent to normal text-file processing: Read a line, modify it, write it, repeat. And the headache of having to do by yourself all the text processing is probably not worth the hassle.

Have you established an acceptable performance metric for your system?

Have you tried the normal text file processing approach and found it to exceed that metric before starting to look for a more efficient solution?


问:
How do I go from being able to write code to being a good developer?
I'm frustrated by the lack of concrete explanations on how to go from being able to script (bash, awk) and write simple applications (c, php, python) to designing and developing larger, more complicated software. It seems that on one side there are programming language books and on the other side there are the software engineering/project management books designed for teams of programmers.

I've read plenty of both. I've read the XP/Agile classics and have a decent theoretical understanding of the software development process. I like to read other people's code and can follow it fairly well. But when I have an idea for a project or want to go from "here's the problem/need" to "here's the solution", my mind draws a blank and I don't know where to begin.

Do I just hack it out? Are there any structured workflows for individual developers that don't work in teams or for a big software house? I really don't have any desire to get a PMP or work for a software company. I'm just looking for an effective, efficient, practical workflow.

答:
Well, in my opinion, as in any profession, to be a good professional all what it takes -- besides theoretical formation -- is experience.

As a doctor cannot be good with only the classes taken in med school, or a lawyer cannot know all the political side of being an attourney with only its degree, being a good developer needs experience and time.

Experience doesn't come by reading third party code. If you get a med student, he/she would be able to point out a lot of procedures, deseases, medicines etc., but the actual application of these things (when to apply one procedure, what desease to diagnose etc.) only comes with supervision and experience.

Since you don't want to work for a large company (or any company for that matter), I suggest you start by developing small applications, one step at a time. Developing software by yourself takes a lot of time, belive me.

Other thing that I suggest to you to become a good software developer/engineer, is to contribute to open source software. A lot of guys have make a good amount of money (and experience, btw) by helping develop open source software and giving consultations afterwards. They have made a name for themselves with their contributions to open source.

Anyway, I think there isn't a shortcut to gaining experience, and it must be pursued with discipline and patience.

OwnerDisplayName: Bill

OwnerDisplayName: Eduardo Melo


答:
In my opinion, you become a good developer by having experience and working with multiple ways of doing things. You've stated that you have a problem going from "here's my idea" to "here's my solution". That's something more towards software development methodologies as well as being an experienced developer.

Using a software development methodology is more than "just hacking out code", and these methodologies provide structured workflows. There Agile family provides good structure for smaller development teams (or individuals) that you can follow to help you get from the "idea" phase to the "finished product" phase.

There's a few things that I've learned over the years from others and through working on various projects, such as:

Make everything testable, this will make your life much much easier;

You cannot expect to have a perfect design and be able to design enterprise applications/the next biggest game title/insert more here, without having experience in doing so;

It is difficult to design good software if you have not had experience doing so and learned from others;

You will never have a perfect design the first time, even as an experienced developer - things change and therefore; your design might too;

Write things down: Writing/drawing/whiteboarding/painting/whatever it is you feel comfortable with, it makes life easier if you have things written down. Such as GUI designs, class diagrams, etc. In my experience, just going to "hack something together" has the potential to fail catastrophically;

Don't reinvent the wheel, you shouldn't have to. If you're trying to implement your own HashMap then you're probably doing something wrong. Research things, and think before you write code.

Hope some of that helps.

Title: How do I go from being able to write code to being a good developer?

Body:
I'm frustrated by the lack of concrete explanations on how to go from being able to script (bash, awk) and write simple applications (c, php, python) to designing and developing larger, more complicated software. It seems that on one side there are programming language books and on the other side there are the software engineering/project management books designed for teams of programmers.

I've read plenty of both. I've read the XP/Agile classics and have a decent theoretical understanding of the software development process. I like to read other people's code and can follow it fairly well. But when I have an idea for a project or want to go from "here's the problem/need" to "here's the solution", my mind draws a blank and I don't know where to begin.

Do I just hack it out? Are there any structured workflows for individual developers that don't work in teams or for a big software house? I really don't have any desire to get a PMP or work for a software company. I'm just looking for an effective, efficient, practical workflow.

OwnerDisplayName: Deco


答:
You are confused? The situation is much worse in the Java world, where a different web framework is in fashion at every month.

My advice: you don't need to learn C#, you already know it. Employers rarely seek super language skills nowadays. The emphasis shifted towards the tools and frameworks, to the IT (MS or Java) "ecosystem". Don't bother with PHP.

Try to cover the whole of the application development stack, ui/server side/databases. Unless you live in the US I'd recommend a horizontal approach: try to learn many things, but not too deeply. Set yourself 3 month long 'projects', and always focus on
one thing at a time. Don't rush, don't panic :)

Pick the most popular technologies first, what you can see in the job ads the most. But don't learn new languages (script/dynamic, functional) just now, those can wait a few years. Learning new languages is a gold mine from a professional point of view, unfortunately in the job market a solid technology/tool portfolio is more important.

Title: Learning C# in a unified manner


问:
How relevant are Brainbench scores when evaluating candidates?
I've seen many companies using certification services such as Brainbench when evaluating candidates. Most times they use it as a secondary screen prior to interview or as a validation to choose between candidates.

What is your experience with Brainbench scores? Did you try the tests yourself, and if so do you feel the score is meaningful enough to be used as part of a hiring process?

Difficult choice.

Consensus seems to be that BB cert are not very good as a certification.  The biggest argument was around the fact that some of the questions are too precise to form a good evaluation.  This view can probably be tempered somewhat but still, to hold someone's future solely on the results of this evaluation would be irresponsible.

That said, I still think it is possible to use them properly to gain additional objective knowledge on a candidate's level of expertise provided the test is done in a controlled environment ensuring that all taking it stand on equal footing.

Thus I went with the answer that best reflected this view keeping in mind that it is still just an hour long 50ish multiple choice question to evaluate skills and knowledge that take years to acquire.  To be taken with a grain of salt !

In short, the tests have value but whether or not they are worth the money is another debate.

Thanks all for your time.

答:
I think BB certs make good sense as part of a hiring process - provided you can guarantee that the guy passing these is indeed the one you're interviewing (at BB it is easy to screw up identity and make someone pass the test for you).

My first encounter with BB was at interview when they gave me OO concepts test. Since it was at their office, and since the BB session was established at their account, this procedure left no chance to trick exam results. Based on my further experience with BB I believe this is the only reliable way to certify a candidate.

I did not receive my results back then because these were delivered to guys who interviewed me, but anyway exam questions and overall BB approach got me curious enough to give it more try...

I tried all the free exams that made me interested, 5 or 6 or maybe 7 (it was few years ago, I don't remember how many) - Java SE and EE, RDBMS, business writing, typing.

Scores I received felt quite relevant: I got Master's in areas where I felt my knowledge was solid, average scores where I was not so good, and could not certify at exam for typing which has proven that I am not a professional. Also, Java SE score at BB felt pretty consistent with one I've got at SCJP - which in turn felt pretty accurately reflecting my strengths and weaknesses.

My overall impression of BB is that as interviewer I would feel comfortable using these certifications as part of candidate screening - provided that these were taken in a way that guarantees that candidate identity was not screwed.


答:
Honestly, from the few people I've interviewed with Brainbench "qualifications", I would say that the 20-minute multiple-choice test that I built myself, on eSkills, was a more effective filter. And that wasn't much of a filter at all, it just saved me phone-interviewing people who were going to embarrass themselves.

The only way that I use Brainbench as a filter is to filter out CVs where people try to pass it off as a professional qualification like an MCPD. That seems dishonest to me.

Title: How relevant are Brainbench scores when evaluating candidates?

Body:
I've seen many companies using certification services such as Brainbench when evaluating candidates. Most times they use it as a secondary screen prior to interview or as a validation to choose between candidates.

What is your experience with Brainbench scores? Did you try the tests yourself, and if so do you feel the score is meaningful enough to be used as part of a hiring process?

Difficult choice.

Consensus seems to be that BB cert are not very good as a certification.  The biggest argument was around the fact that some of the questions are too precise to form a good evaluation.  This view can probably be tempered somewhat but still, to hold someone's future solely on the results of this evaluation would be irresponsible.

That said, I still think it is possible to use them properly to gain additional objective knowledge on a candidate's level of expertise provided the test is done in a controlled environment ensuring that all taking it stand on equal footing.

Thus I went with the answer that best reflected this view keeping in mind that it is still just an hour long 50ish multiple choice question to evaluate skills and knowledge that take years to acquire.  To be taken with a grain of salt !

In short, the tests have value but whether or not they are worth the money is another debate.

Thanks all for your time.


答:
Another possibility if you don't like to see too many the else's is to drop the use of else altogether and throw in an extra return statement.  Else is kind of superfluous unless you require more complex logic to determine if there are more than just two action possibilities.

Thus your example might become:

void DoABunchOfStuff()
{
    if(FileExists(file))
    {
        DoSomethingWithFileContent(file);
        return;
    }

    DefaultAction();
}

void DoSomethingWithFileContent(file)
{
    var contents = GetFileContents(file)

    if(SomeTest(contents))
    {
        DoSomething(contents);
        return;
    }

    DefaultAction();
}

AReturnType GetFileContents(file)
{
    return OpenFile(file);
}
```

Personally I don't mind using the else clause as it states explicitly how the logic is supposed to work, and so improves readability of your code.  Some code beautification tools however prefer to simplify to a single if statement to discourage nesting logic.

Title: Elegant ways to handle if(if else) else

Body:
This is a minor niggle, but every time I have to code something like this, the repetition bothers me, but I'm not sure that any of the solutions aren't worse.

if(FileExists(file))
{
    contents = OpenFile(file); // <-- prevents inclusion in if
    if(SomeTest(contents))
    {
        DoSomething(contents);
    }
    else
    {
        DefaultAction();
    }
}
else
{
    DefaultAction();
}
```

Is there a name for this kind of logic?

Am I a tad too OCD?

I'm open to evil code suggestions, if only for curiosity's sake...

Body:
Another possibility if you don't like to see too many the else's is to drop the use of else altogether and throw in an extra return statement.  Else is kind of superfluous unless you require more complex logic to determine if there are more than just two action possibilities.

Thus your example might become:

void DoABunchOfStuff()
{
    if(FileExists(file))
    {
        DoSomethingWithFileContent(file);
        return;
    }

    DefaultAction();
}

void DoSomethingWithFileContent(file)
{
    var contents = GetFileContents(file)

    if(SomeTest(contents))
    {
        DoSomething(contents);
        return;
    }

    DefaultAction();
}

AReturnType GetFileContents(file)
{
    return OpenFile(file);
}

Personally I don't mind using the else clause as it states explicitly how the logic is supposed to work, and so improves readability of your code.  Some code beautification tools however prefer to simplify to a single if statement to discourage nesting logic.


问:
How do you define, organize, and document your data?
Please feel free to suggest a better name or way of explaining this question - I wasn't quite sure what to call it.

The situation is one that may just come under the heading of "be organized" but I often find myself passing around either big blobs of data or many smaller sub-blobs (blob in the non-technical meaning of the word =o), to be used in various parts of my web apps.

For example, building a small task manager that allows someone to create a task that ends up being represented like this:

With a title, initial date, user, client, etc. (simple attributes).

Zero or more temporal expressions that represent "schedules" for when the task must be done - periodically, by day of week, by day of month, etc.

A tree-list of sub-tasks that can be nested to any level.

This is all easy enough to represent in the database with a few tables.

It's also easy enough to pack into a series of arrays and pass around (for example, passing an array of a task template, subtasks, and schedule data via JSON to a jQuery object that will build a tasklist on the client side.

Between creating, updating, displaying, etc., the tasks, tasklists, etc., there are any number of places where I might find myself passing a big collection of data from one place to another (especially working with AJAX with much client-side processing), and it often looks pretty much the same - just a big array that says "here is the data for your task and related 'stuff'".

How do you (or would you) keep this organized?  For example, below is an array that has been pulled out of a "Task Template" object, and will be passed via JSON to a JS object that will dynamically build and display a list of tasks on the client side.

I guess the question is whether and how you define the structure of such an 'object' outside the database, code, etc., and how you document it.

For example, while the nested subtasks are pretty explanatory (and duplicate data, available only for convenience), it's not readily apparent that the "SubTasks" array MUST have each subtask appear in the array AFTER (higher index than) it's parent subtask, and BEFORE (ie: with lower index than) any child subtasks, so that they arra can be processed in order with the assurance that each subtask can be appended to it's already existing parent subtask.

There are a number of rules like that here, and if a "relatively" similar array is used in 9 different places, documenting in comments/class documentation, etc sort of ends up sucking.

```<code> [43] => Array
    (
        [Meta] => Array
            (
                [SubTaskCount] => 6
                [TemporalExpressionCount] => 3
                [NumInstances] => 0
                [OutOfSync] => 0
            )

        [Fields] => Array
            (
                [UserID] => 1
                [ClientID] => 1
                [StatusID] => 1
                [Title] => Keep Testing
                [Body] => How are you?  Because I am a potato.
                [UserName] => Wheatley
                [ClientName] => Wheatley Laboratories
                [BodyHTML] => Etc.
            )

        [Sched] => Array
            (
                [TemporalExpressions] => Array
                    (
                        [0] => Array // Every Monday every month
                            (
                                [type] => dw
                                [ExpressionID] => 1
                                [ord] => 0
                                [day] => 1
                                [month] => 0
                            )

                        [1] => Array  // Every Tuesday every month
                            (
                                [type] => dw
                                [ExpressionID] => 2
                                [ord] => 0
                                [day] => 3
                                [month] => 0
                            )

                        [2] => Array  // The last of every month
                            (
                                [type] => dm
                                [ExpressionID] => 3
                                [day] => -1
                                [month] => 0
                            )

                    )

                [TaskInstances] => Array
                    (
                       // This would have data on "complete" status of tasks by date...
                    )

                [InitialDate] => 2011-12-02
                [DueTime] => 14:55:00
                [SchedDates] => Array
                    (
                        [1322812800] => 2011-12-02
                        [1323072000] => 2011-12-05
                        [1323244800] => 2011-12-07
                        [1323417600] => 2011-12-09
                        [1323676800] => 2011-12-12
                        // ... List of dates between externally defined date range parameters...
                    )

            )

        [SubTasks] => Array
            (
                [1355] => Array
                    (
                        [SubTaskID] => 1355
                        [ParentST] =>
                        [RootT] => 43
                        [UserID] => 1
                        [Title] => New Subtask Title
                        [Body] =>
                        [DueDiff] => 0
                        [UserName] => Eli
                    )

                [1356] => Array
                    (
                        [SubTaskID] => 1356
                        [ParentST] => 1355
                        [RootT] => 43
                        [UserID] => 1
                        [Title] => New Subtask Title
                        [Body] =>
                        [DueDiff] => 0
                        [UserName] => Eli
                    )

                [1357] => Array
                    (
                        [SubTaskID] => 1357
                        [ParentST] => 1355
                        [RootT] => 43
                        [UserID] => 1
                        [Title] => New Subtask Title
                        [Body] =>
                        [DueDiff] => 0
                        [UserName] => Eli
                    )

                [1358] => Array
                    (
                        [SubTaskID] => 1358
                        [ParentST] => 1355
                        [RootT] => 43
                        [UserID] => 1
                        [Title] => New Subtask Title
                        [Body] =>
                        [DueDiff] => 0
                        [UserName] => Eli
                    )

                [1359] => Array
                    (
                        [SubTaskID] => 1359
                        [ParentST] =>
                        [RootT] => 43
                        [UserID] => 1
                        [Title] => New Subtask Title
                        [Body] =>
                        [DueDiff] => 0
                        [UserName] => Eli
                    )

                [1360] => Array
                    (
                        [SubTaskID] => 1360
                        [ParentST] =>
                        [RootT] => 43
                        [UserID] => 1
                        [Title] => New Subtask Title
                        [Body] =>
                        [DueDiff] => 0
                        [UserName] => Eli
                    )

            )

        [SubTasksNested] => Array
            (
                [1360] => Array
                    (
                        [SubTaskID] => 1360
                        [ParentST] =>
                        [RootT] => 43
                        [UserID] => 1
                        [Title] => New Subtask Title
                        [Body] =>
                        [DueDiff] => 0
                        [UserName] => Eli
                    )

                [1359] => Array
                    (
                        [SubTaskID] => 1359
                        [ParentST] =>
                        [RootT] => 43
                        [UserID] => 1
                        [Title] => New Subtask Title
                        [Body] =>
                        [DueDiff] => 0
                        [UserName] => Eli
                    )

                [1355] => Array
                    (
                        [SubTaskID] => 1355
                        [ParentST] =>
                        [RootT] => 43
                        [UserID] => 1
                        [Title] => New Subtask Title
                        [Body] =>
                        [DueDiff] => 0
                        [UserName] => Eli
                        [SubTasks] => Array
                            (
                                [1358] => Array
                                    (
                                        [SubTaskID] => 1358
                                        [ParentST] => 1355
                                        [RootT] => 43
                                        [UserID] => 1
                                        [Title] => New Subtask Title
                                        [Body] =>
                                        [DueDiff] => 0
                                        [UserName] => Eli
                                    )

                                [1357] => Array
                                    (
                                        [SubTaskID] => 1357
                                        [ParentST] => 1355
                                        [RootT] => 43
                                        [UserID] => 1
                                        [Title] => New Subtask Title
                                        [Body] =>
                                        [DueDiff] => 0
                                        [UserName] => Eli
                                    )

                                [1356] => Array
                                    (
                                        [SubTaskID] => 1356
                                        [ParentST] => 1355
                                        [RootT] => 43
                                        [UserID] => 1
                                        [Title] => New Subtask Title
                                        [Body] =>
                                        [DueDiff] => 0
                                        [UserName] => Eli
                                    )

                            )

                    )

            )

        [TemplateID] => 43
    )
</code>```

答:
Object-oriented classes are the answer. Classes' fields are strongly defined (i.e. a Foo instance must have bar, baz fields) and class code can enforce (and indirectly document) data constraints (i.e. the constructor can refuse bad construction parameters).

Often, serialization is then harder, but that's an unavoidable trade-off; associative arrays are trivially serializable because of their simplicity; OO-style classes often cannot be trivially serialized.


问:
Why is Mercurial considered to be easier than Git?
When looking at comparisons, it seems to me that there could be a 1:1 mapping between their feature sets. Yet, an often cited statement is that "Mercurial is easier". What is the basis of this statement? (if any)</p>

答:
Because it is.

Git exposes far more of it's guts than mercurial. You can happily use mercurial within a few minutes of picking it up but I find git still very hard to grapple with after a couple of months of wrestling with it (I have done very little over the last couple of months other than try to learn git). I am using both from the command line and mostly on Linux so this is not just an aversion to the command line interface.

One simple example is the relatively few flags and command line arguments needed for mercurial compared to git.  The staging area and the behavior of the add command in git also adds more complexity than is necessary. The trio of reset, checkout and revert and their multiple permutations adds enormous complexity, which was quite unnecessary when you witness the straightforward nature of revert and update on mercurial.

I agree with the above comment also about Hginit, it definitely made mercurial much easier to comprehend. Well written and very easy to understand. None of the documentation written for git comes close. I for one, find most of what is written by Scott Chacone (who has singlehandedly written most of the documentation/books about git) particularly confusing.


答:
You can start by enhancing other people's code.  Take some project you've got and add a feature to it.  You'll have to decide what the feature is going to do, and how it should do it.  Working within the framework of the existing code, design your solution.

And don't be afraid to hack stuff out.  A lot of new development is done by refining (or preferably rewriting) quick-and-dirty prototypes.  Go ahead and use every worst practice and antipattern in the book, just crank out something that does what you want.  Then, go back and design it properly.  Usually, I find myself thinking "You know, a better way to do this would be..." while I'm hard-coding some configuration parameters in my 800-line three-procedure monstrosity.

I know it's currently out of vogue, but the techniques of structured analysis really helped me get a handle on software design.  Play around with making a few bubble charts and DFDs to get a feel for decomposing problems and designing different parts of a system to work together.


问:
Commented short fancy code vs. uncommented longer easy-to-understand code - which is preferred?
Sometimes an algorithm can be written in two ways:

The short, fancy way; or

The longer, easy-to-understand way.

For example, here is a longer, easier way of copying a string source to dest in C:

```<code>*dest = *source;
while (*source != '\0') {
    source++;
    dest++;
    *dest = *source;
} (true);
</code>```

And here is a short, fancy way.

```<code>// Copy string source to dest
while (*dest++ = *source++);
</code>```

I've always heard and read that fancy code should be avoided, and I tend to agree. But what if we take comments into account? Assume that, as in the examples above, we have an uncommented, longer and supposedly easier-to-understand code, and a well-commented, short, fancy code? Is the non-fancy code still preferred?

EDIT: Many have commented on variable names, so I've modified the example code as to not make that a factor when preferring on over the other. I tried to remove the double assignment in the first example, but that only made the code less readable.

Perhaps this wasn't the best of examples because many find the 'fancy' code more readable and understandable than the longer code. The idea was to have one longer code which was much easier to understand than a very short but complicated code.

EDIT2: Here's a new examle I got from SO:

Commented fancy version:

```<code>//direct formula for xoring all numbers from 1 to N
int Sum = (N & (N % 2 ? 0 : ~0) | ( ((N & 2)>>1) ^ (N & 1) ) );
</code>```

Non-commented long version:

```<code>int Sum = 0;
for (int i = 1; i < N; ++i)
{
   Sum ^= i; //or Sum = Sum ^ i;
}
</code>```

答:
```<code>Keep it simple, stupid!
</code>```

Make sure any other programmer can understand what your code does—and even better if it's at a glance (this is where good names and comments come into their own).

Fancy bit-twiddling kung-fu and inlined assembly is all great in the name of (perhaps unnecessary and premature) optimisation, but when even you can't understand the code you wrote when you come across a bug in it two months later... What was the point? You'll cost yourself time and effort.

I often refer to the Zen of Python in these situations. In particular:

```<code>Explicit is better than implicit.
Simple is better than complex.
</code>```

Body:
Keep it simple, stupid!

Make sure any other programmer can understand what your code does—and even better if it's at a glance (this is where good names and comments come into their own).

Fancy bit-twiddling kung-fu and inlined assembly is all great in the name of (perhaps unnecessary and premature) optimisation, but when even you can't understand the code you wrote when you come across a bug in it two months later... What was the point? You'll cost yourself time and effort.

I often refer to the Zen of Python in these situations. In particular:

Explicit is better than implicit.
Simple is better than complex.


问:
How can I convince cowboy programmers to use source control?
I work on a small team of devs, 4 guys.  They have all used source control.  Most of them can't stand source control and instead choose not to use it. I strongly believe source control is a necessary part of professional development. Several issues make it very difficult to convince them to use source control:

The team is not used to using TFS.  I've had 2 training sessions, but was only allotted 1 hour which is insufficient.

Team members directly modify code on the
server.  This keeps code out of sync.  Requiring comparison just to be sure you are working with the latest code.  And complex merge problems arise

Time estimates offered by developers exclude time required to fix any of these problems.  So, if I say nono it will take 10x longer...I have to constantly explain these issues and risk myself because now management may perceive me as "slow".

The physical files on the server differ in unknown ways over ~100 files.  Merging requires knowledge of the project at hand and, therefore, developer cooperation which I am not able to obtain.

Other projects are falling out of sync.  Developers continue to have a distrust of source control and therefore compound the issue by not using source control.

Developers argue that using source control is wasteful because merging is error prone and difficult.  This is a difficult point to argue, because when source control is being so badly mis-used and source control continually bypassed, it is error prone indeed.  Therefore, the evidence "speaks for itself" in their view.

Developers argue that directly modifying server code, bypassing TFS saves time.  This is also difficult to argue.  Because the merge required to synchronize the code to start with is time consuming.  Multiply this by the 10+ projects we manage.

Permanent files are often stored in the same directory as the web project.  So publishing (full publish) erases these files that are not in source control.  This also drives distrust for source control.  Because "publishing breaks the project".  Fixing this (moving stored files out of the solution subfolders) takes a great deal of time and debugging as these locations are not set in web.config and often exist across multiple code points.

So, the culture persists itself.  Bad practice begets more bad practice.  Bad solutions drive new hacks to "fix" much deeper, much more time consuming problems.  Servers, hard drive space are extremely difficult to come by.  Yet, user expectations are rising.

What can be done in this situation?

答:
Quote:

The team is not used to using TFS

TFS turns out to be Microsoft Team Foundation Server.

My first instinct says: "this is the latest release of Microsoft Visual SourceSafe"

I would be on the side of you coworkers and go really against this.


问:
What is the best way to insert range of values into a datastructure
If I have a datastructure which is the fastest way I could insert values into it in a specified range?

For example if I had a method:

```<code>myDatastructure var=new myDataStructure();
var.insert(2,1000);
</code>```

it would mean that I get a most optimised way of getting a datastructure holding values from 2 to 1000 in each of index sequentially.

答: If you have a C++11 STL, you could use the std::iota() function to insert sequentially increasing values into any container that supports iterators. As for choosing a type of container, C arrays or std:arrays should be the fastest as they require no additional memory allocations while inserting elements.


问:
What are approaches to learning multiple technologies at the same time?
I want to learn multiple technologies. Currently I have knowledge of core Java, C, and PHP. I want to know the approach which should be followed to learn multiple things. I know if you know the core concepts of the behavior of programming language, any programming language can be learned. I want to make command on such language in a way that I can talk with them. I am doing lots of coding and surfing but I think there is an approach by which we can communicate or talk with programming language.</p>

答:
If by "technologies" you mean languages, then what you really need to learn is language theory and compiler design.  Once you know how a lexer identifies tokens, how the parser builds an AST and how the code generator turns the AST into assembly language, you're pretty much set to figure out any procedural language.

If you truly mean different technologies (like relational databases, web development, map/reduce frameworks and sensor networks) then I'd recommend you take them one at a time, and create a sandbox project using each one.


答:
The fastest way to do this is to not do it.  Here's an outline of a class that looks like a read-only array of consecutive integers.

```<code>class range {
private:
  int low, high;
public:
  typedef int iterator;
  range(int low, int high) { this.low = low; this.high = high; }
  iterator begin() { return low; }
  iterator end() { return high + 1; }
  int operator[](int index) { return low + index; }
}
...
range r(1, 1000);
for (r::iterator i = r.begin(); i != r.end(); ++i) { ... }
</code>```

If you need a writable collection, then the answer depends on how you want to modify it after creation.

Title: What is the best way to insert range of values into a datastructure

Body:
If I have a datastructure which is the fastest way I could insert values into it in a specified range?

For example if I had a method:

```<code>myDatastructure var=new myDataStructure();
var.insert(2,1000);
</code>```

it would mean that I get a most optimised way of getting a datastructure holding values from 2 to 1000 in each of index sequentially.

Body:
The fastest way to do this is to not do it.  Here's an outline of a class that looks like a read-only array of consecutive integers.

class range {
private:
  int low, high;
public:
  typedef int iterator;
  range(int low, int high) { this.low = low; this.high = high; }
  iterator begin() { return low; }
  iterator end() { return high + 1; }
  int operator[](int index) { return low + index; }
}
...
range r(1, 1000);
for (r::iterator i = r.begin(); i != r.end(); ++i) { ... }

If you need a writable collection, then the answer depends on how you want to modify it after creation.


答:
I would suggest that you:

Immerse yourself totally in one new language at a time.

For me, fluttering between new languages means that I don't learn any one well.

Plan out what you want to learn and how long you want to spend learning it.

Long enough to get a good feel for the language, but not so long that you're itching to get onto the next.

Choose languages from a number of different paradigms. Imperative, declarative, procedural, object-oriented, functional and even logic all have their place depending on what you want to do.

Choose languages with different features. Static/dynamic, weak/strong type system, high/low level, modern/traditional.

Only with exposure to a good range will you learn the benefits and challenges of each.

Try to learn not only the language, but also the idioms and conventions of that language.

This takes time, but if you only have a hammer, you're more likely to treat everything as a nail, and it is well worth having a full toolbox.

Try to have in mind a project that you want to try and implement in that language.

Play to the languages strengths. Don't try to write a text processing utility in assembler, unless you're feeling masochistic.

Make the project tough but not overly ambitious. You want a challenge that you can learn from, but you don't want something so difficult that you get put off.

Last year, one blogger decided to Learn 12 New Programming Languages in 12 Months. His language choices included:

Clojure (a Lisp dialect for the JVM), Factor (a stack based language), Go (described as a cross between C++ and Python), Haskell (a purely functional strongly typed language), Erlang (a fault tolerant, real-time concurrent language), Scheme (another Lisp dialect), Fantom (which claims to be portable across the JVM, .NET CLR, and JavaScript in the browser), Scala (a JVM based language which combines OO and functional paradigms), OCaml (another statically typed, OO/functional language), Ruby (popular with Rails), Lua (a small, portable scripting language) and Prolog (a declarative logic language).

It was a tall order, and he only got around to learning four languages in that year (Clojure, Objective-C, Fantom and Lua) but the planning probably gave him a good overview of what was out there and I'll be interested to see if he has managed to find the time to learn the 8 more langauges he set as his goal this year.

The easiest option for structuring your learning mulotiple languages might be a book like Seven Languages in Seven Weeks: A Pragmatic Guide to Learning Programming Languages. This covers an interesting selection of languages (Ruby, Io, Prolog, Scala, Erlang, Clojure & Haskell) which have a range of language features, and should help many programmers who have only been exposed to the usual mono-cultures of curly brackets languages.

Title: What are approaches to learning multiple technologies at the same time?

Body: I want to learn multiple technologies. Currently I have knowledge of core Java, C, and PHP. I want to know the approach which should be followed to learn multiple things. I know if you know the core concepts of the behavior of programming language, any programming language can be learned. I want to make command on such language in a way that I can talk with them. I am doing lots of coding and surfing but I think there is an approach by which we can communicate or talk with programming language.</p>