问:
Integer sign and compilation via C
I'm writing a compiler that uses the time-honored strategy of using a C compiler as the back end, and I'm trying to figure out exactly how to handle integer sign.

I'm using machine word integers as the default (translating into intptr_t and uintptr_t in the generated C), and while for myself I would prefer to make the default unsigned, I probably don't have much choice about making it signed just because that expectation is so widely ingrained.

I'm defining the result of integer overflow to be wraparound (at least by default, might add an option to throw an exception later), but in C, signed integer overflow is undefined behavior, so I can't just emit code that performs signed integer arithmetic. It seems to me there are two options:

Emit signed integers, but convert to unsigned for all arithmetic operations except division and right shift (these are the only ones where the difference matters, and also the only ones that can't overflow - edit: except for INT_MIN / -1; I had been considering that in the same category as division by zero, but of course it is strictly speaking an overflow).

Emit unsigned integers, but convert to signed for division (resisting the temptation to make division of negative numbers undefined behavior), right shift and comparison other than equality.

Emit signed integers anyway, use -fwrapv when using GCC as the backend, and hope other C compilers either don't take advantage of signed overflow being undefined, or provide a switch to disable such optimizations.

Does the third option work (e.g. are there any C compilers where you can't make signed overflow wrap)? If not, which of the first two is likely to involve less code and opportunity for error? Is there anything I'm missing?

答:
Why don't you just have your compiler generate code to check if an overflow is possible before performing arithmetic operations on signed integers?  This way you make sure you won't cause undefined behavior before you perform the operation.  You either perform the arithmetic, or throw an exception (or whatever.)

Something like this (taken from https://stackoverflow.com/a/3947943/168288):

```<code>int add(int lhs, int rhs)
{
 if (lhs >= 0) {
  if (INT_MAX - lhs < rhs) {
   /* overflow will occur */
   abort();
  }
 }
 else {
  if (rhs < INT_MIN - lhs) {
   /* overflow will occur */
   abort();
  }
 }
 return lhs + rhs;
}
</code>```

Also, your assumption that division can't overflow isn't true.  The expression INT_MIN / -1 causes an overflow.

Title: Integer sign and compilation via C

Body:
Why don't you just have your compiler generate code to check if an overflow is possible before performing arithmetic operations on signed integers?  This way you make sure you won't cause undefined behavior before you perform the operation.  You either perform the arithmetic, or throw an exception (or whatever.)

Something like this (taken from https://stackoverflow.com/a/3947943/168288):

int add(int lhs, int rhs)
{
 if (lhs >= 0) {
  if (INT_MAX - lhs < rhs) {
   /* overflow will occur */
   abort();
  }
 }
 else {
  if (rhs < INT_MIN - lhs) {
   /* overflow will occur */
   abort();
  }
 }
 return lhs + rhs;
}

Also, your assumption that division can't overflow isn't true.  The expression INT_MIN / -1 causes an overflow.


答:
Of the three options you posted, I'd vote for 2.

The first option is still invoking undefined behavior, in statements like this:

```<code>int result = (unsigned)1 - (unsigned)10;
</code>```

The third option is something akin to "let's do it anyhow and hope it works". Certainly, I wouldn't recommend it.

The second most probably does what you want (IIUC) and doesn't invoke undefined behavior.

ContentLicense: CC BY-SA 3.0

Title: Integer sign and compilation via C

Body:
I'm writing a compiler that uses the time-honored strategy of using a C compiler as the back end, and I'm trying to figure out exactly how to handle integer sign.

I'm using machine word integers as the default (translating into intptr_t and uintptr_t in the generated C), and while for myself I would prefer to make the default unsigned, I probably don't have much choice about making it signed just because that expectation is so widely ingrained.

I'm defining the result of integer overflow to be wraparound (at least by default, might add an option to throw an exception later), but in C, signed integer overflow is undefined behavior, so I can't just emit code that performs signed integer arithmetic. It seems to me there are two options:

Emit signed integers, but convert to unsigned for all arithmetic operations except division and right shift (these are the only ones where the difference matters, and also the only ones that can't overflow - edit: except for INT_MIN / -1; I had been considering that in the same category as division by zero, but of course it is strictly speaking an overflow).

Emit unsigned integers, but convert to signed for division (resisting the temptation to make division of negative numbers undefined behavior), right shift and comparison other than equality.

Emit signed integers anyway, use -fwrapv when using GCC as the backend, and hope other C compilers either don't take advantage of signed overflow being undefined, or provide a switch to disable such optimizations.

Does the third option work (e.g. are there any C compilers where you can't make signed overflow wrap)? If not, which of the first two is likely to involve less code and opportunity for error? Is there anything I'm missing?

Body:
Of the three options you posted, I'd vote for 2.

The first option is still invoking undefined behavior, in statements like this:

int result = (unsigned)1 - (unsigned)10;

The third option is something akin to "let's do it anyhow and hope it works". Certainly, I wouldn't recommend it.

The second most probably does what you want (IIUC) and doesn't invoke undefined behavior.


问:
Noobie wants to use source control, how would you guide them?
Let's say you know of an anonymous noobie that wants to be lead upon the path of righteousness.  This noobie wants to use some sort of source control tools simply for the experience of using source control tools (and possibly for whatever benefits they bring along with them).

To constrain things further (and to make this possibly even more noobie-tastic), let's say they're stuck in windows developing in visual studio.

How would you guide your neophyte?

答:
Everyone here mentioned a lot of IDE tools to use for source control. But from what I've seen generally the largest problem with source control is organization. The directory structure can make your life 10 times easier with a project that multiple people are working on. People take the branching feature for granted but don't realize that without the proper structure branching can be a pain. Setting up source control on another computer can be a pain if the user doesn't choose the same exact path as the original user. There are so many gotchas with source control that experienced developers take for granted I would have loved for someone to warn me of these situations before I had to learn the hard way. Most of them can be solved with a good directory structure. Here's an example.

```
$/{ProjectName}
    /Main
        /Branches
        /Trunk
            /Docs (documentation)
            /External (external dll's referenced outside the project)
            /Scripts (build scripts, install scripts, +)
            /Source (all source code)
            /Tests (unit tests, stress tests, etc)
            /Tools (tools for building or installing example: nant, ilmerge)
```

Of course for a new programmer there are many features here that are "excessive" but having the structure in place and realizing that it makes a difference are a big help.

ContentLicense: CC BY-SA 2.5

Body:
Everyone here mentioned a lot of IDE tools to use for source control. But from what I've seen generally the largest problem with source control is organization. The directory structure can make your life 10 times easier with a project that multiple people are working on. People take the branching feature for granted but don't realize that without the proper structure branching can be a pain. Setting up source control on another computer can be a pain if the user doesn't choose the same exact path as the original user. There are so many gotchas with source control that experienced developers take for granted I would have loved for someone to warn me of these situations before I had to learn the hard way. Most of them can be solved with a good directory structure. Here's an example.

$/{ProjectName}
    /Main
        /Branches
        /Trunk
            /Docs (documentation)
            /External (external dll's referenced outside the project)
            /Scripts (build scripts, install scripts, +)
            /Source (all source code)
            /Tests (unit tests, stress tests, etc)
            /Tools (tools for building or installing example: nant, ilmerge)

Of course for a new programmer there are many features here that are "excessive" but having the structure in place and realizing that it makes a difference are a big help.


问:
Don't structure data all the way down
In the blog post Don't structure data all the way down, the author discusses different ways to structure a circle datatype and how to implement the parameters to a Radius function.

```<code>area({circle, {point,0,0}, 17.4})
</code>```

Kind of messy. What about a function to build a circle for us? Then we could do this:

```<code>area(make_circle(0, 0, 17.4))
</code>```

We could also have a shorter version of make_circle that only takes a radius, defaulting the center point to 0,0. Okay, stop, we're engineering ourselves to death. All we need is a simple function to compute the area of a circle:

```<code>area(R) -> math:pi() * R * R.
</code>```

He is talking about the functions in the Erlang language, which is functional and not object oriented (OO).  My question is, does this argument hold for OO languages, and does it hold for functional languages?

答:
I guess the gist of it is "don't over-engineer". The OOP equivalent of his argument would use a class Circle, a bit like this one (canonical yet hypothetical class-based OOP language assumed):

```<code>public class Circle {
    private Point center;
    private double radius;
    public Circle(Point, radius) { ... }
    public Circle(radius) { ... }
    public double getArea() { return radius * radius * Math.PI; }
}
</code>```

...when in fact, all you need is:

```<code>public double getCircleArea(double radius) { return radius * radius * Math.PI; }
</code>```

Of course, "over-engineering is bad" is an easy statement to make, and under-engineering is equally bad. The trick is to find exactly the right level of abstraction, and learning this takes experience.

Object-oriented programming is especially vulnerable to the over-engineering trap though, because it offers so many neat ways of adding layers of abstraction; most of the time, adding yet another abstraction on top of your stack feels like the right thing to do, even though too often it's not.

Title: Don't structure data all the way down

Body:
I guess the gist of it is "don't over-engineer". The OOP equivalent of his argument would use a class Circle, a bit like this one (canonical yet hypothetical class-based OOP language assumed):

public class Circle {
    private Point center;
    private double radius;
    public Circle(Point, radius) { ... }
    public Circle(radius) { ... }
    public double getArea() { return radius * radius * Math.PI; }
}

...when in fact, all you need is:

public double getCircleArea(double radius) { return radius * radius * Math.PI; }

Of course, "over-engineering is bad" is an easy statement to make, and under-engineering is equally bad. The trick is to find exactly the right level of abstraction, and learning this takes experience.

Object-oriented programming is especially vulnerable to the over-engineering trap though, because it offers so many neat ways of adding layers of abstraction; most of the time, adding yet another abstraction on top of your stack feels like the right thing to do, even though too often it's not.


答:
The point I see in that circle area example is that your functions should not require parameters that they don't use.

A circle area function only needs to know the radius, so it should only take the radius as a parameter.  This principle can be extended from simple functions to any size chunk of code.  Your classes should not depend on other code they do not need.  Likewise your dlls should only require other dlls that they actually need.

Minimizing the dependencies and data your code requires makes it inherently easier to use and easier to reuse.  It also makes unit-testing much easier.

Title: Don't structure data all the way down

Body:
In the blog post Don't structure data all the way down, the author discusses different ways to structure a circle datatype and how to implement the parameters to a Radius function.

```<code>area({circle, {point,0,0}, 17.4})
</code>```

Kind of messy. What about a function to build a circle for us? Then we could do this:

```<code>area(make_circle(0, 0, 17.4))
</code>```

We could also have a shorter version of make_circle that only takes a radius, defaulting the center point to 0,0. Okay, stop, we're engineering ourselves to death. All we need is a simple function to compute the area of a circle:

```<code>area(R) -> math:pi() * R * R.
</code>```

He is talking about the functions in the Erlang language, which is functional and not object oriented (OO).  My question is, does this argument hold for OO languages, and does it hold for functional languages?


答:
Do you have to be 100% standard compliant?

It's very good to assume nothing that the standard doesn't guarantee, and it doesn't guarantee anything about signed integer overflow.

But in practice, most systems handle signed integer overflow very simply (MAX_INT+1=MIN_INT).

So if you know the target platform, and don't have to support any arbitrary platform that supports C, you can just use signed integers as they are.

An alternative, which is technically the same thing, is to make signed integer overflow undefined in the language you're compiling, just as it is in C.

Title: Integer sign and compilation via C


问:
Replace Type Code with Class (From Refactoring [Fowler])
This strategy involves replacing the likes of this:

```<code>public class Politician
{
    public const int Infidelity = 0;
    public const int Embezzlement = 1;
    public const int FlipFlopping = 2;
    public const int Murder = 3;
    public const int BabyKissing = 4;

    public int MostNotableGrievance { get; set; }
}
</code>```

With:

```<code>public class Politician
{
    public MostNotableGrievance MostNotableGrievance { get; set; }
}

public class MostNotableGrievance
{
    public static readonly MostNotableGrievance Infidelity = new MostNotableGrievance(0);
    public static readonly MostNotableGrievance Embezzlement = new MostNotableGrievance(1);
    public static readonly MostNotableGrievance FlipFlopping = new MostNotableGrievance(2);
    public static readonly MostNotableGrievance Murder = new MostNotableGrievance(3);
    public static readonly MostNotableGrievance BabyKissing = new MostNotableGrievance(4);

    public int Code { get; private set; }

    private MostNotableGrievance(int code)
    {
        Code = code;
    }
}
</code>```

Why exactly is this preferable to making the type an enumeration, like so:

```<code>public class Politician
{
    public MostNotableGrievance MostNotableGrievance { get; set; }
}

public enum MostNotableGrievance
{
    Infidelity = 0,
    Embezzlement = 1,
    FlipFlopping = 2,
    Murder = 3,
    BabyKissing = 4
}
</code>```

There is no behavior associated with the type and if there was you would be using a different type of refactoring anyways, for example, 'Replace Type Code with Subclasses' + 'Replace Conditional with Polymorphism'.

However, the author does explain why he frowns on this method (in Java?):

Numeric type codes, or enumerations, are a common feature of C-based
  languages. With symbolic names they can be quite readable. The problem
  is that the symbolic name is only an alias; the compiler still sees
  the underlying number. The compiler type checks using the number 177
  not the symbolic name. Any method that takes the type code as an
  argument expects a number, and there is nothing to force a symbolic
  name to be used. This can reduce readability and be a source of bugs.

But when trying to apply this statement to C#, this statement doesn't appear to be true: it won't accept a number because an enumeration is actually considered to be a class. So the following code:

```<code>public class Test
{
    public void Do()
    {
        var temp = new Politician { MostNotableGrievance = 1 };
    }
}
</code>```

Will not compile. So can this refactoring be considered unecessary in newer high-level languages, like C#, or am I not considering something?

答:
Another example that might help you can be found in Effective Java (item 30, if you want to look it up). It is valid for C# as well.

Suppose you use int constants to model different animals, say snakes and dogs.

```<code>int SNAKE_PYTHON=0;
int SNAKE_RATTLE=1;
int SNAKE_COBRA=2;

int DOG_TERRIER=0;
int DOG_PITBULL=1;
</code>```

Assume these are constants and maybe even defined in different classes. This may seem fine to you and it might actually work out. But consider this line of code:

```<code>snake.setType(DOG_TERRIER);
</code>```

Clearly, this is an error. The compiler will not complain and the code will execute. But your snake won't turn into a dog. That is because compiler only sees:

```<code>snake.setType(0);
</code>```

Your snake is actually a python (and not a terrier). This feature is called type safety and it is actually the reason why you're example code

```<code>var temp = new Politician { MostNotableGrievance = 1 };
</code>```

won't compile. MostNotableGrievance is a MostNotableGrievance not an integer. With enums you can express this in the type system. And that is why Martin Fowler and I think that enumerations are great.

Body:
Another example that might help you can be found in Effective Java (item 30, if you want to look it up). It is valid for C# as well.

Suppose you use int constants to model different animals, say snakes and dogs.

int SNAKE_PYTHON=0;
int SNAKE_RATTLE=1;
int SNAKE_COBRA=2;

int DOG_TERRIER=0;
int DOG_PITBULL=1;

Assume these are constants and maybe even defined in different classes. This may seem fine to you and it might actually work out. But consider this line of code:

snake.setType(DOG_TERRIER);

Clearly, this is an error. The compiler will not complain and the code will execute. But your snake won't turn into a dog. That is because compiler only sees:

snake.setType(0);

Your snake is actually a python (and not a terrier). This feature is called type safety and it is actually the reason why you're example code

var temp = new Politician { MostNotableGrievance = 1 };

won't compile. MostNotableGrievance is a MostNotableGrievance not an integer. With enums you can express this in the type system. And that is why Martin Fowler and I think that enumerations are great.


问:
Development Patterns for dealing with Data Import / Export
I have a ASP.NET web based application that allows the end user to export data to a flat file format. (essentially taking a point-in-time backup of their work)

At a later date they can re-upload (import) that data back into the web application.

The actual format of the backup is pretty trivial. An object graph is serialized using the WCF DataContractSerializer to xml, and then the resultant xml document is compressed. Importing, unzips it and deserializes the data.

There's one small problem I see with this approach. versioning... as time moves on and the data structures change (properties / child-collections are added/removed or renamed) then previously exported versions of a users data will no longer map to the object graph in the application.

Are there any specifici patterns or practices that address this issue? or any other reading material you could recommend.

答:
Have you considered adding a version to your export and then doing a version comparison during import?

If versions don't match, you can either fail import or warn the user that import is likely to fail, I don't see any other reasonable way of solving this.


问:
How important is the ability to touch-type?
Did you learn to touch-type when you were already working as a programmer?  If so how did it affect your productivity?  Or are you still unable to touch type and do you think it holds you back?

According to Steve Yegge it is essential,

Personally I did not notice much difference, possibly because I was spending less than 25% of my work time actually typing (I was working on a large legacy project at the time and I was spending more time on reading and debugging existing code.)

答: Keyboard, IDE, mouse, programming language, ... all should disappear when coding. Touch typing is the only trick that worked for me to make the keyboard disappear. I am still struggling to make the rest of 'em disappear!


答:
Touch-typing is a must have skill for a programmer. I think that most programmers thrive for high words per minute number, and I believe this is where the problem is. I'll try to justify this below:

I can touch-type, but I don't chase high WPM while programming, mainly because it gives me more time to think about what I'm doing.

Being able to use refactoring shortcuts within IDE is equally important. E.g. Automatic property, rename or extract method shortcuts will save you a lot of the time.

Effective use of code snippets and template is more important. E.g. by typing Tst you can make your IDE to generate a test template for you

High WPM while pair programming might make it harder for another person to follow you.

To summarise I think that touch-typing is a must-have skill for a competent programmer, however, just like any tool, it shouldn't have a negative impact on your productivity.

Title: How important is the ability to touch-type?

Body:
Did you learn to touch-type when you were already working as a programmer?  If so how did it affect your productivity?  Or are you still unable to touch type and do you think it holds you back?

According to Steve Yegge it is essential,

Personally I did not notice much difference, possibly because I was spending less than 25% of my work time actually typing (I was working on a large legacy project at the time and I was spending more time on reading and debugging existing code.)


问:
Will adopting a DVCS mean there will be a positive impact on development speed?
I was wondering how safe is to say that —because developers are free to version and have better and more organic workflows— code will be delivered faster.

A big factor here is team size of course, and I'd say the team is big enough to see this benefit (10-15 core devs, and maybe 5 to 15 more contributors to the common codebase).

Edit: How development speed can be affected:

Merging hell could be one of the cases that slow down people (DVCSs are much better at merging).

Better workflows that can pretty much only work work more naturally on a DVCS

Integration Manager

Dictator & Lieutenants

Ability to use version control (i.e. committing) without inflicting potentially unstable changes to everybody

I just want to know if anyone has seen such things help the overall speed of teams/projects as a whole.

答:
In our line of work, it's sometimes difficult to see the human element.  I believe DVCS has the potential to speed up a workflow, but a large number of developers are either unable or unwilling to learn it well enough to use it to its full potential.

In my experience, around 1 in 10 developers already get it, another 2 in 10 would learn and use it to potential after the company switched, and when you explain the benefits of DVCS to the other 70%, they respond something like, "Why would anyone ever want to do that?"  If forced to use it, they will make the experience as close to their familiar CVCS workflow as possible, thereby negating most of the benefits.


问:
What kind of problems does MapReduce solve?
I have been reading about MapReduce for a while -- but what I can't understand is how someone would make a decision to use (or not use) MapReduce.

I mean, what are the problem patterns that signal that MapReduce could be used.

答: Say you are searching a cluster of servers and one is unable to respond at that moment.  What mapReduce will do is since it could not access that tree node to the larger Map is it will reschedule it for later and perform either the Map or the Reduce then.  Essentially it tries to guarantee all information is available with the unpredictability of software and hardware in environments.</p>


问:
What is your approach to multi-paradigm programming?
I have been learning some Ruby recently and I had the following experience.
I had written a small tool of about 200 lines of code and, as an inexperienced Ruby programmer, I had used several loops to build arrays from other arrays.
E.g.

```<code>gs = ... # Some array of input data.
l  = gs.size
i  = 0
r  = Array.new
while (i < l) do
  if (cond(gs[i]))
    r.push(gs[i])
  end
  i = i + 1
end

# r contains the result now.
</code>```

Then I discovered that I can do it in a functional style:

```<code>gs = ... # Some array
r  = gs.select { |g| cond(g) }

# r contains the result now.
</code>```

So I immediately replaced most of my loops in the code with constructs like each, select, take_while, drop_while, and so on. I have decided to use a functional style in Ruby whenever possible and try to avoid an imperative style.

As another example, in C++ I tend to use classes and methods everywhere and use functions only for small utility tasks that are private to the implementation of some class. So I tend to think object-oriented when working in C++ and avoid
a procedural style almost completely.

More in general, when working on a given project in a given language, I tend to pick one paradigm and stick to it throughout the project: I find this makes my code more uniform, easier to read and to debug, which, IMO, is very important, especially for production code.

Yet, I often think that maybe I should explore more and try out different possibilities offered by a language, e.g. use different paradigms and try out different solutions. For me this involves some overhead both while coding (should I make it procedural or object-oriented? imperative or functional?) and when reviewing or debugging code (what did I want to do here?) because of the increased complexity.

So my question is: do you also tend to select a preferred programming paradigm
when coding and stick to it, or do you tend to explore more and mix different paradigms?

If you mix different paradigms, do you have the feeling that there is some overhead in terms of how fast you can write and debug code (added complexity, switching between different mindsets) or is it just a matter of learning how to do it and then you can even be more productive?

Or do you mix different paradigms in a more structured way, e.g. you apply each paradigm to a specific class of problems (e.g. functional for queries, object-oriented for architectural aspects, and so on)?

答:
do you also tend to select a preferred programming paradigm when
  coding and stick to it, or do you tend to explore more and mix
  different paradigms?

Constantly exploring alternative solutions makes you a better programmer. You must be aware of available tools, it doesn't mean that you have to use them each time.

Mixing paradigms is fine as long as it doesn't have a negative impact on quality of your code.

If you mix different paradigms, do you have the feeling that there is
  some overhead in terms of how fast you can write and debug code (added
  complexity, switching between different mindsets) or is it just a
  matter of learning how to do it and then you can even be more
  productive?

If this is your project and nobody else will work on it, then it's absolutely fine. It might cost you later, but the good thing is that it won't affect anybody else.

Generally, I think that teams will try not to use multi-paradigm as it is likely to have a negative impact on team's productivity. On other hand, experimenting, such as going from one paradigm to another is a great way to learn.

Or do you mix different paradigms in a more structured way, e.g. you
  apply each paradigm to a specific class of problems (e.g. functional
  for queries, object-oriented for architectural aspects, and so on)?

No matter what you do, you need to plan for it and think what effect it might have in future. Therefore, yes, whatever you decide to do, it must be structured and planned for.

My team has agreed on code guidelines and we have always been using these guidelines with very little if any paradigm-shifts. We also have tools that enforce these guidelines. In your specific example, ReSharper would suggest us to convert a foreach statement into a more readable LINQ statement.

To summarise, I think that exploring paradigm-shifts is a great way to learn, but it should be strictly controlled in a work environment.


问:
Sharing API's between different Programming languages?
I was just wondering how API's can be shared between different Programming languages.

I mean, MS have .Net which uses VB.net C# and various other technologies.

I doubt .Net is written for each programming language.

How are structs and classes shared between languages?

Also the same for Unity3D - Javascript shares API's with C# and BOO.

How?

答: They're based on the Common Language Infrastructure, or CLI. It's basically a virtual machine where all of these languages compile to the same bytecode and read out assemblies which are in terms of the CLI. This provides an abstraction over the source and target language.</p>


答:
This WPI - Applications of Map Reduce (ppt) may be of interest to  you. It discusses different applications of MR, and as one of the discussed cases, it shows how Using 100 EC2 instances and 24 hours, the New York Times was able to convert 4TB of scanned articles to 1.5TB of PDF documents.

Another set of examples where MR helped in speeding performance is at: Aster - SQL Map Reduce shows some case studies of SQL-Map Reduce technology including Fraud Detection, Transformations, and others.

Title: What kind of problems does MapReduce solve?

Body:
I have been reading about MapReduce for a while -- but what I can't understand is how someone would make a decision to use (or not use) MapReduce.

I mean, what are the problem patterns that signal that MapReduce could be used.


问:
For what reasons should I keep "using" section clean in C#?
Once when I was refactoring my code, I went up the IDE to the using section of my C# class, and cleaned unused namespaces and duplicate namespaces, and sorted them all.

My pair (pair programming) asked me the reason. I had no idea why I did that. I did it out of my habit to keep all of my code clean and tidy. I mean, I told him that having a cleaner code is a good idea in general, but of course that reason was not a good justification, as I won't even bother to spend my time in the using section of any C# code page.

Since many times you move a class or an enum (or a type in general) from one namespace to another namespace, and this adds new using statements to your code (either manually by going up the code window and writing the using statement yourself, or through the editor using Alt+Ctrl+F10 combination), and since these new using statements would be added to the end of using section, which makes them not sorted alphabetically, and since compiler never complaints about any of these problems, why should we care to make this section clean and tidy? What reasons might we have?

答:
It's just removing noise from the signal. Less noise means it's easier to receive the signal, i.e. understand the intent of the code.

As a generator of noise it's a pretty minor one though.


答:
It improves readability of your code.

Normally it makes little sense to follow this guideline if you have just few using statements

It makes more sense to separate using statements into sections.

For example:

```<code>    using System.Web;

    using MyPlatform.FooX;
    using MyPlatform.FooY;

    using MyFramework.Helpers;
    using MyFramework.Extentions;
</code>```

If I look at the class, then I can instantly see that given class is using System.Web assembly, as well as our platform and framework. This gives me a rough idea of its dependencies and complexity.

You can then take this a step further and order the statements, but I think that it makes using statements less readable, so I wouldn't recommend this.

```<code>using MyFramework.Extentions;
using MyFramework.Helpers;

using System.Web;

using MyPlatform.FooX;
using MyPlatform.FooY;
</code>```

Title: For what reasons should I keep "using" section clean in C#?

Body:
Once when I was refactoring my code, I went up the IDE to the using section of my C# class, and cleaned unused namespaces and duplicate namespaces, and sorted them all.

My pair (pair programming) asked me the reason. I had no idea why I did that. I did it out of my habit to keep all of my code clean and tidy. I mean, I told him that having a cleaner code is a good idea in general, but of course that reason was not a good justification, as I won't even bother to spend my time in the using section of any C# code page.

Since many times you move a class or an enum (or a type in general) from one namespace to another namespace, and this adds new using statements to your code (either manually by going up the code window and writing the using statement yourself, or through the editor using Alt+Ctrl+F10 combination), and since these new using statements would be added to the end of using section, which makes them not sorted alphabetically, and since compiler never complaints about any of these problems, why should we care to make this section clean and tidy? What reasons might we have?

Body:
It improves readability of your code.

Normally it makes little sense to follow this guideline if you have just few using statements

It makes more sense to separate using statements into sections.

For example:

    using System.Web;

    using MyPlatform.FooX;
    using MyPlatform.FooY;

    using MyFramework.Helpers;
    using MyFramework.Extentions;

If I look at the class, then I can instantly see that given class is using System.Web assembly, as well as our platform and framework. This gives me a rough idea of its dependencies and complexity.

You can then take this a step further and order the statements, but I think that it makes using statements less readable, so I wouldn't recommend this.

using MyFramework.Extentions;
using MyFramework.Helpers;

using System.Web;

using MyPlatform.FooX;
using MyPlatform.FooY;


答: There are two basic approaches.  One is to compile to virtual machine bytecode, so you basically need a compiler for every targeted language.  The other is to create what's called a language "binding" using a native interface.  Most languages have a way to link with native code, so you make an implementation in C, for example, then make a wrapper API in the target language that translates the calls and data structures to the C API.</p>

Title: Sharing API's between different Programming languages?

Body:
I was just wondering how API's can be shared between different Programming languages.

I mean, MS have .Net which uses VB.net C# and various other technologies.

I doubt .Net is written for each programming language.

How are structs and classes shared between languages?

Also the same for Unity3D - Javascript shares API's with C# and BOO.

How?


问:
Object Oriented Programming Concepts and Interviews
I'm an Object Oriented Programming fanatic. I have always believed in modelling solutions in terms of objects. It is something that comes to me naturally. I work with a services start up that essentially works on application development using OOP languages. So I tend to test understanding of OOP in the candidate being interviewed.

To my shock, I found very very few developers who really understood OOP. Most candidates brainlessly spit out definitions they mugged up from some academic book on object oriented programming but they don't know squat about what they are saying. Needless to say I reject these candidates. However, over the course of time, I ended up rejecting almost 98% of the candidates. Now this gets me thinking if I'm being over critical about their OOP skills. I still believe OOP is fundamental and every programmer MUST GET it. Language knowledge and experience is secondary.

Do you think I'm being over critical or do I just get to interview bad programmers unfortunately?

EDIT:

I usually interview programmers with 2 to 5 years of experience. The position that I usually interview for is Ruby/Ruby on Rails application developer.

答:
It's important to find out what other skills the interviewee has to offer

By working in a large software development team I have learned more in three months then I have learned in 2 years at a smaller company. I think experience should be measured in successful projects, rather than years.

Reasonable university graduates are likely to answer the majority of your OO related questions, but they are likely to have no or very little industrial experience to offer.

Because of these points, I think that you may be overcritical with your interviewees.


问:
Does your programming knowledge decrease if you don't practice?
I'm a novice programmer. I study languages such as C, C++, Python and Java (mainly focusing on C++). I'm what you'd call "young and inexperienced" and I admit that because I can't claim otherwise.

As a student, I have many other problems besides programming. I practice programming as often as I can, and especially because my teacher gives me a lot more exercises than the rest of the class (it's a very low level), so oftentimes I spend weeks doing something else such as school projects or sports, or traveling, anything besides programming.

Don't get me wrong though, I love programming. I love to build functional code, to watch as a program comes alive at the push of a button, and to learn as much as I can. The thing is, I simply don't have much time for it.

Straight to the question, now: does your programming knowledge decrease as time passes and you don't practice? You may ask "how much time do you mean?". I don't mean a specific amount of time, but for reference you could take a month-two or even a year as an example.

By knowledge I mean anything from syntax to language functionality.

答: Learning to program is learning how to problem-solve more then anything else. I've been in the situation where I hadn't programmed for over 10 years. Yes, the syntax details I had and have to look up regularly but the problem solving skill was still there.</p>


答:
As with all brain activities, knowledge start to fade after literally seconds.
That continues over seconds and minutes (short term). Some is transferred by the hippocampus to long-term memory, where the fading process is much slower.

An analogy that I like more than the muscle is "the sponge".  Learning and using is like adding water which makes the sponge nice and plump and 'heavy'.  Stop adding water and it'll start to dry up and lose weight.  Neurologists may like this analogy ;)

Some things that can counter that are:

Repetition. Do any task enough times and you'll remember it.

Nemonics.  Whether visual, aural or whatever these can be really helpful.

Flexibility.  Rather than knowledge itself, the ability to take on new tasks is key and is helped by frequently doing completely new activities.

Exercise.  Well known to help the brain and with memory.

Making notes.  Not (so much) for future reference but because the actual process of making them helps lock the knowledge in ones mind.

Title: Does your programming knowledge decrease if you don't practice?

Body:
I'm a novice programmer. I study languages such as C, C++, Python and Java (mainly focusing on C++). I'm what you'd call "young and inexperienced" and I admit that because I can't claim otherwise.

As a student, I have many other problems besides programming. I practice programming as often as I can, and especially because my teacher gives me a lot more exercises than the rest of the class (it's a very low level), so oftentimes I spend weeks doing something else such as school projects or sports, or traveling, anything besides programming.

Don't get me wrong though, I love programming. I love to build functional code, to watch as a program comes alive at the push of a button, and to learn as much as I can. The thing is, I simply don't have much time for it.

Straight to the question, now: does your programming knowledge decrease as time passes and you don't practice? You may ask "how much time do you mean?". I don't mean a specific amount of time, but for reference you could take a month-two or even a year as an example.

By knowledge I mean anything from syntax to language functionality.


问:
Tools for Operating on Large Amounts of Text Data
I need to handle and process  ~5 million news articles, an amount small enough to fit on a commodity desktop but too large to process serially.  Thus far, I have been using Python/pickle for serialization, but this is easily getting out of hand.  However, I do not have a server much less a cluster immediately available for distributed storage.

What tools can I use to store, query, and operate on this size of a dataset?  The majority of operations I need to do can be formulated as Map operations; the only exception is that the Natural Language Processing portion which is handled by calling Stanford's CoreNLP software suite (it needs a few seconds to load some large parameter files).

答:
Many people speak highly of Solr. It specializes in searching large quantities of text, and should be usable from Python.

I suppose you could also do something custom with Hadoop. It directly supports map reduce operations, though it might be easier to work in Java than Python with Hadoop.


答:
Out of all the interview questions you've read about out there, I'm pretty sure that only a few were an actual OO problem and in their case it was probably a simple matter of proving facts about OOP.

Call it a personal sentiment, but the developers out there that are more concerned with software design probably feel disappointed that they'll never have to take an abstract specification and refine it into a solution of objects communicating with the notion of satisfying the specification requirements.

For most of the candidates out there, they'll be abusing to what the interviewing system has been reduced to and will generally focus on preparing data structure and algorithm implementations.

Title: Object Oriented Programming Concepts and Interviews

Body:
I'm an Object Oriented Programming fanatic. I have always believed in modelling solutions in terms of objects. It is something that comes to me naturally. I work with a services start up that essentially works on application development using OOP languages. So I tend to test understanding of OOP in the candidate being interviewed.

To my shock, I found very very few developers who really understood OOP. Most candidates brainlessly spit out definitions they mugged up from some academic book on object oriented programming but they don't know squat about what they are saying. Needless to say I reject these candidates. However, over the course of time, I ended up rejecting almost 98% of the candidates. Now this gets me thinking if I'm being over critical about their OOP skills. I still believe OOP is fundamental and every programmer MUST GET it. Language knowledge and experience is secondary.

Do you think I'm being over critical or do I just get to interview bad programmers unfortunately?

EDIT:

I usually interview programmers with 2 to 5 years of experience. The position that I usually interview for is Ruby/Ruby on Rails application developer.


问:
Recommendations for teaching junior programmers good coding style
I am a big fan of good coding style, producing clean, clear code that runs well and is easy to use and integrate into larger systems. I believe that we programmers are essentially craftspeople who should take pride in our work, every line. I am not fond of code that is inconsistently formatted, cluttered with commented out experimental code, and rife with unhelpful or misleading function and variable names. But I sometimes find it hard to argue with code like this that basically works.

If you think that coding style matters, I am looking for recommendations for ways of teaching good, professional coding style to the junior programmers under me. I want them to take pride in their work, but my concern is that they appear to become satisfied when their code just barely works, and seem to have no interest in producing what professionals like me would consider professional code. On the other hand, if you think coding style is not particularly valuable, I welcome your comments and am open to reconsidering my standards and tolerances.

I know the usual arguments in favor of good code: comprehensibility, ease of maintenance, etc., but I would also like to hear some rebuttals to arguments like "it works, what more do you want?"

In our industry we can use the compiler to hide a multitude of sins. Clean code and messy code can both lead to identically functioning programs, so does cleanliness matter, and if so, why?

[While there are several existing questions on coding style, I didn't find any that related to teaching methods and ways to instill good coding style in junior programmers.]

答: I think the best way to encourage this behaviour from young developers is to practice it yourself and be a role model for them. If possible, you should pair program with them often and put emphasis on code quality when you program with them. While pairing, you can explain and justify good coding choices as you make them. You can explore the "worse" options and explain why they aren't a good solution in the long run. Being a part of this kind of development in a hands on way is probably one of the best ways to teach new developers about the importance of code quality. If everyone on your team thinks code quality is important, they will learn to respect it as well.


答:
The actual problem is that people disagree what exactly is clean code. Once you've written perfect code with every detail exactly correct, the next person is still going to think it's crap. Every programmer is looking at different parts of the code and finding things he doesn't like while simultaniously ignoring all the good parts. This is necessary part of the programming, since programmers need to find the bad stuff before it goes to version control for the first time. So programmers can easily regognize bad code. It's just that it's different for every programmer.

In a team, this feature is going to cause problems, if there is too strict rules for conventions, or if people have to maintain and work with code written by other persons. Best solution is to keep conventions, but not enforcing them. And then make sure everyone knows who is responsible of each part of the code.

Now teaching junior programmers is tricky. Most attempts end up in junior programmer thinking that his last code was somehow bad and the teaching session is required because of it. Like it's a punishment for some error that happened before.

Title: Recommendations for teaching junior programmers good coding style

Body:
I am a big fan of good coding style, producing clean, clear code that runs well and is easy to use and integrate into larger systems. I believe that we programmers are essentially craftspeople who should take pride in our work, every line. I am not fond of code that is inconsistently formatted, cluttered with commented out experimental code, and rife with unhelpful or misleading function and variable names. But I sometimes find it hard to argue with code like this that basically works.

If you think that coding style matters, I am looking for recommendations for ways of teaching good, professional coding style to the junior programmers under me. I want them to take pride in their work, but my concern is that they appear to become satisfied when their code just barely works, and seem to have no interest in producing what professionals like me would consider professional code. On the other hand, if you think coding style is not particularly valuable, I welcome your comments and am open to reconsidering my standards and tolerances.

I know the usual arguments in favor of good code: comprehensibility, ease of maintenance, etc., but I would also like to hear some rebuttals to arguments like "it works, what more do you want?"

In our industry we can use the compiler to hide a multitude of sins. Clean code and messy code can both lead to identically functioning programs, so does cleanliness matter, and if so, why?

[While there are several existing questions on coding style, I didn't find any that related to teaching methods and ways to instill good coding style in junior programmers.]


答:
All programmers should always do code reviews with a senior programmer before committing/merging their code changes.

This gives the senior programmers a chance to come to a consensus regarding which styles they want to enforce (and recognize which ones are just a matter of preference) among themselves.

It gives junior programmers a chance to learn what practices are expected from their team right from the get-go. Within a couple of months, 90% of the code they write will already be following those practices before the code review.

Also, most IDEs have tools you can configure to enforce the vast majority of coding style preferences with handsome little squiggly underlines and options to automatically correct the style throughout a file. Junior programmers will pick up on that pretty fast.


问:
Populate fields or return object
What is better to do in this type of scenario: populate fields or return an object?

The situation is like this: I'm doing calculations to find the prices (inc tax, ex tax, discounted etc) of a product. Is there any advice or are there any guidelines on how to handle a return value?

Populate fields:

```<code>public class ProductPrice
{
    public int BasePrice;
    public int IncTax;
    public int ExTax;
    // ...

    public void GetPricesForProduct(int ProductID)
    { /* Populate fields based on results */ }
}
</code>```

Return object:

```<code>public class PriceCalculator
{
    public ProductPrice GetPricesForProduct(int ProductID)
    { /* Populate object fields and return object */ }
}
public class ProductPrice
{
    public int BasePrice;
    public int IncTax;
    public int ExTax;
}
</code>```

I'm not sure I really like the first method, because the void return type doesn't make it clear what happens when the method executes. However, returning an object results in a class which has no functionality.

答:
Thinking about how prices work and what may happen in the future I would recommend:-

A single "productPrice" class.

The class should have a one or more getPrice methods

```<code>public int getPrice(getPrice.Type priceType) {}

public int getPrice(getPrice.Type priceType, int offerCode) {}

public int getPrice(getPrice.Type priceType, int discount) {}
</code>```

Where 'priceType' is an ennum defining the type of price you want.

In a large real-life situation you may offer different prices depending a vast number of variables:-

Channel -- eg. Web price, may differ from mail order.

Special Offers -- customers who attended a trade fair, who visited a particular web site may be givein a offer code which gets them a special price.

Turnover -- customers who buy  a lot get  a better price.

New Customers -- introductory offers for new customers.

Location -- Marketing may be targeting a particular region or city.

Market Segment -- Marketing may be pushing to increase sales to a specific type of customer.

Title: Populate fields or return object

Body:
Thinking about how prices work and what may happen in the future I would recommend:-

A single "productPrice" class.

The class should have a one or more getPrice methods

public int getPrice(getPrice.Type priceType) {}

public int getPrice(getPrice.Type priceType, int offerCode) {}

public int getPrice(getPrice.Type priceType, int discount) {}

Where 'priceType' is an ennum defining the type of price you want.

In a large real-life situation you may offer different prices depending a vast number of variables:-

Channel -- eg. Web price, may differ from mail order.

Special Offers -- customers who attended a trade fair, who visited a particular web site may be givein a offer code which gets them a special price.

Turnover -- customers who buy  a lot get  a better price.

New Customers -- introductory offers for new customers.

Location -- Marketing may be targeting a particular region or city.

Market Segment -- Marketing may be pushing to increase sales to a specific type of customer.


问:
Question on design of current pagination implementations
I have checked pagination implementations on asp.net mvc specifically and i really feel that there is something less efficient in implementations.

First of all all implementations use pagination values like below.

```<code>public ActionResult MostPopulars(int pageIndex,int pageSize)
{

}
</code>```

The thing that i feel wrong is pageIndex and pageSize totally should be member of Pagination class otherwise this way looks so much functional way. Also it simplify unnecesary paramater pass in tiers of application.

Second thing is that they use below interface.

```<code>public interface IPagedList<T> : IList<T>
{
    int PageCount { get; }
    int TotalItemCount { get; }
    int PageIndex { get; }
    int PageNumber { get; }
    int PageSize { get; }
    bool HasPreviousPage { get; }
    bool HasNextPage { get; }
    bool IsFirstPage { get; }
    bool IsLastPage { get; }
}
</code>```

If i want to routing my pagination to different action so i have to create new view model for encapsulate action name in it or even controller name. Another solution can be that sending this interfaced model to view then specify action and controller hard coded in pager method as parameter but i am losing totally re-usability of my view because it is strictly depends on just one action.

Another thing is that they use below code in view

```<code>Html.Pager(Model.PageSize, Model.PageNumber, Model.TotalItemCount)
</code>```

If the model is IPagedList why they don't provide an overload method like @Html.Pager(Model) or even better one is @Html.Pager(). You know that we know model type in this way. Before i was doing mistake because i was using Model.PageIndex instead of Model.PageNumber.

Another big issue is they strongly rely on IQueryable interface. How they know that i use IQueryable in my data layer ? I would expected that they work simply with collections that is keep pagination implementation persistence ignorant.

What is wrong about my improvement ideas over their pagination implementations ?
What is their reason to not implement their paginations in this way ?

答:
Given that what the client asks for a the page number and what the client is most likely to vary is the page size I think:

```<code>public ActionResult MostPopulars(int pageIndex,int pageSize)
</code>```

Is a pretty sensible way of doing this. I have seen variations where an ennum of (first, next, prev, last) was used but really its just an awkward way of saying "pageIndex".

I would reiterate that page size will and should vary a lot, depending on the viewer involved you should get different defaults for mobiles, portables and big screen workstations, plus, in many cases it is sensible to let the end user choose how many items constitute a page.

I know this results in a lot of parameter passing within an MVC framework, but the whole concept of paging breaks MVC -- your business logic needs to know about presentation in order for the paging to work so its always going to be messy.

Body:
Given that what the client asks for a the page number and what the client is most likely to vary is the page size I think:

public ActionResult MostPopulars(int pageIndex,int pageSize)

Is a pretty sensible way of doing this. I have seen variations where an ennum of (first, next, prev, last) was used but really its just an awkward way of saying "pageIndex".

I would reiterate that page size will and should vary a lot, depending on the viewer involved you should get different defaults for mobiles, portables and big screen workstations, plus, in many cases it is sensible to let the end user choose how many items constitute a page.

I know this results in a lot of parameter passing within an MVC framework, but the whole concept of paging breaks MVC -- your business logic needs to know about presentation in order for the paging to work so its always going to be messy.


问:
Should I use a code repository if I am the only one working on a project?

Possible Duplicate:

  Version control for independent developers?

I am not sure if I should use a code repository when I am the only one working on a project.

答:
Yes.  You never know when more people might be brought on to the project.  Also, repos allow you to rollback when you accidentally add something that doesn't work.

You could use git for version control on your own machine without the need for a centralized repo.  However, as long as you're using git, you might as well set up a repo on on GitHub.  It only takes a few minutes if you're already on there.  If you're not on GitHub, you should take the time to become familiar with it.  It's a useful tool.

Edit

As @DanRedux pointed out, it also allows you to easily fork projects and explore other paths.

OwnerDisplayName: Tim Pote


答: I agree with Tim, yes, you should use some version control system. But I would use something simple where you don't need to setup a server. I use Git for all my projects, even if they are simple and small (at first…). To setup a Git repository all you need to do is git init, so it's really easy. Of course, if you have not used Git up to now it might not be the right choice for you…

Title: Should I use a code repository if I am the only one working on a project?

Body:
Possible Duplicate:

  Version control for independent developers?

I am not sure if I should use a code repository when I am the only one working on a project.

OwnerDisplayName: siegi


答:
Actually, there is little reason NOT to use a code repository. Just the fact that I can easily roll back to any prior version has covered my rear end so many times when I accidentally introduced regression bugs - despite my automated tests.

If you need a recommendation - try Mercurial. It's really simple, yet very powerful. I would avoid Git because of its unnecessary complexity. Of course, this is only my personal opinion. So choose whatever suits you best.

OwnerDisplayName: Christian Schlichtherle


答:
A code repository is a history, and having a history never hurts. I've goofed things up in a bash shell script ~/bin directory, and having revision control bailed me out. Think of it also as a different kind of source code backup, as long as the repository is being backed up. I've restored our town's tax collection software from CVS, when migrating to a new Linux platform, and everything built after the checking out of the repository.

I would use the same software you use at work, or something more modern, like git.

OwnerDisplayName: octopusgrabbus


答: Definitely! Purely for the reason that it will allow you to roll your code back to previous versions etc. Version control is worth it. There's only so much "ctrl + z" one can do!</p>


答:
Well, nowadays with the third generation of Source control, it's not that hard to start using them specially git or mercurial, I cannot think on any downside of why you should not use any of them.

Also If you do not want to set a remote environment you can use sites like Github, bitbucket, CodeGoogle to keep your source up, and grab it whenever you want.

I have to disagree with @Christian git is actually a very simple and straighforward solution, well documented and very powerful. Personally I have used mercurial few times and short term so I can't have a strong opinion about it.

TL;DR the answer is Yes, Ja, Si, Oui!

OwnerDisplayName: Necronet


答:
The benefits of having your code in a VCS are well documented.  Regression/rollback testing, the ability to add people in the future, comment history of changes, etc.

But for very small "projects" that consists of only a few files or don't need versioned releases, you may be able to get away with absolutely bottom-of-the-barrel version control using RCS.  RCS is the per-file Revision Control System that CVS was originally built on top of.  If your goal is just get the benefits I noted above, then RCS will do, without requiring a centralized repository OR a steep learning curve.

I still use RCS to maintain a revision history of server configuration files, or individual shell scripts that don't have much use outside their particular areas.  Once you start needing to package a number of files up together into a "release" version of something, you've outgrown RCS.  But it still has its place.

My $0.02.

OwnerDisplayName: ghoti


答:
“Perfection is achieved not when there is nothing left to add, but when there is nothing left to take away” – Antoine de Saint-Exupery

Whenever you can remove something that is not necessary and does not add understanding, do so (readability is worth extra code).


答:
It seems like something as simple to enforce as a coding standard is only going to be handled by:

Hire people who agree with you.

Code Review

Use applications that can automate this stuff.

Make is as much a part of doing your job as showing up. There have to be consequences for not doing your job.

Personally, I would be leary of a manager that made this too much of a priority. Focus on what is important and don't get nitpicky. You should be able to justify why, but there are times to just pick a standard (Who knows why a 4 space indent is better than 5 other than you're just being mental.).

Get some team consensus on standards. This will improve the quality and level of adherance. Don't waste too much time on a debate. Eventually a leader makes a decision based on the amount of input.


答:
Make a good impression

Take some of the well-known books, e.g. Clean Code, Code Complete, Coders at Work, The Clean Coder: A Code of Conduct for Professional Programmers etc. (see here for full lists) and give them a couple of days to read one - at work, in a private office.  Space those out, say 1 book a month or a quarter.  They will see from the effort that what you're personally saying is really important, not just "the company line" to take with a grain of salt.  Obviously make sure you've got management in line with this - you don't want them saying in passing "huh? what's person X up to? holed away in there with the door closed?"

Along with continual, more formal training classes in the latest technologies.

Also, as things are done "the right way" gave big encouragement and even rewards.  Otherwise it can be more of a negative, punishing, rather than positive, rewarding environment.  Most folks want to do and want to be known for doing "a good job" if they have the tools to do it.

Practice what you preach, Preach what you practice

Talk about code, talk about the good principles, talk about new tools, become 'known' for it.

Provide / support /suggest screencasts, videos, peepcodes and whatever online tutorials and classes you can find.

Support and suggest appropriate local user groups, including those on sites like http://www.meetup.com

If you are in office (i.e. not virtual) a well-stock bookshelf of the actual books you would like people to use is good.  Find a way to make this be "not just dusty bookshelf in the corner" but placing it really prominently, Moving the books around,etc.  Use your imagination too.  Maybe every programmer gets one book as 'homework' a month and you have a monthly meeting where they get to 'present their findings' !

This will make far more of an impression that any 10 minute conversation alone and it will remove you from the 'criticizer' role and allow them to learn how to fish for themselves (rather than giving them fish, you know the deal).  Some junior folks also find it intimidating to have a senior folk always explain stuff, when sometimes all they really want is some time to study, practice and absorb it.

Instill a culture of learning and excellence

Basically you want to create "a culture of learning and excellence" so that you can Practice what you Teach and inspire others to do the same.

This should be in conjunction with code reviews to see if/how the principles apply to the actual work being done.  Conversely, code reviews done without the above can feel like whipping sessions to the student no matter how well intentioned by the teacher.


问:
How do I get my open-source idea started?
I have an idea for an open source project. It's about building developing tools for software developers. Yet I have never  joined a development team and now I don't know much about these teams except the fact that they exist ;)

My questions are:

Is there c# open source projects team? Where?

How can I offer my idea / code

If the groups exist ... should I be the project manager in the sense of offering the scope , versions etc. or let others do it?

I know that java and other languages are better starting point for open-source but... I feel more comfortable with C# and the vs developing environment.

答:
I have an idea for an open source project. It's about building
  developing tools for software developers. Yet I have never joined a
  development team and now I don't know much about these teams

Presumably, your idea relates to building software that would be useful for open source developers, right? (You're not likely to get much help from the OSS community otherwise.) But then you say that you don't know much about how OSS development works. That's a pretty big disconnect -- you might want to put that idea on the back burner and start contributing to an existing project for a while. Think of it as market research.

Is there c# open source projects team? Where?

In the beginning, the team is you and the guy in your bathroom mirror. Sure, there are OSS projects written in C#, but the people who maintain and contribute to them may already have their hands full.

How can I offer my idea / code

First, learn about the different OSS license options and figure out which one you want to use. Then put the code up on github.com or some other hosting site so that it's available to anyone who wants it.

If the groups exist ... should I be the project manager in the sense
  of offering the scope , versions etc. or let others do it?

It sounds a little like you're expecting to join up with a roving band of C# programmers who are constantly searching for things to do. That of course isn't how it works. Instead, you start working, and at some point you make what you've done available to the rest of the world. If it's useful, people will find it and start using it, and a few of those people might decide to help you improve it.

If you make it easy for people to contribute, the chance that they'll help you is that much greater. If nobody sees the value in your tool, you won't get much help. As the project owner and the major contributor, you get to make the final decisions about the project (although anyone is free to make a copy and take development in a different direction). So part of your task is to build something useful, part is to tell the world about it, and part is to stay true to your vision for the project while at the same time doing your best to accommodate contributors whose needs are different from yours.


答: Yes for anything bigger than a small script.  One of the benefits is being able to charge forward with a new design and strong refactoring of your code base without worrying that you will obliterate the original copy or that will be a large pain to merge your changes into the original code base if you determine that your changes are ready to be rolled in.</p>


问:
What's your favourite quote about programming?
What's your favourite quote about programming?

One quote per answer, and please check for duplicates before posting!

答:
"It worked on MY computer!"
    -anon

"Programs must be written for people to read, and only incidentally for machines to execute."
    - Abelson and Sussman, from "The structure and interpretation of computer programs"

LastEditorDisplayName: Roger Pate


问:
Extend the API or use the same name as a class in the API?
I have been running into this problem more and more: I am not happy with the current API, and end up making my own class that does what I wish the API did; however, I don't extend the 'super class' as I don't feel it fully fits. I can't imagine that this is good practice, so should I just extend the 'super class' or should I name the class slightly different than what I feel the original class should have done?

For example, in Java you end up writing ten lines of code just to read a file into a List, with each entry being one of the file.

So again, in cases like this, should the class be renamed to something similar, or should it go ahead and just extend the class the include the behavior you wanted? It almost seems wrong to me to extend the API classes, but at the same time, by not doing so, you are defeating the point of inheritance in OOP.

答:
You shouldn't inherit from File, or any other class to add additional features to it. Your new class is not a File, but rather a set of utility methods to the class File. In other words, there wouldn't be any methods you could pass in NewSuperFile into that would make that method behave differently.

In C# you can create Extension methods. So in this case you wouldn't need to inherit from a class to add additional methods to it, syntactically.

In Java the typical paradigm is to create a ClassUtils class. In this instance you should create either an IOUtils, or FileUtils.

```<code>public class FileUtils {
    /**
     * Read the file one line at a time, and return an array of lines
     * @return List<String>
     */
    public static List<String> readFile(File file) throws IOException {
            List<String> lines = new ArrayList<>();
            try (InputStream in = Files.newInputStream(file);
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(in))) {
            String line;
            while ((line = reader.readLine()) != null) {
                lines.add(line);
            }
        }
        return lines;
    }
}
</code>```

Body:
You shouldn't inherit from File, or any other class to add additional features to it. Your new class is not a File, but rather a set of utility methods to the class File. In other words, there wouldn't be any methods you could pass in NewSuperFile into that would make that method behave differently.

In C# you can create Extension methods. So in this case you wouldn't need to inherit from a class to add additional methods to it, syntactically.

In Java the typical paradigm is to create a ClassUtils class. In this instance you should create either an IOUtils, or FileUtils.

public class FileUtils {
    /**
     * Read the file one line at a time, and return an array of lines
     * @return List<String>
     */
    public static List<String> readFile(File file) throws IOException {
            List<String> lines = new ArrayList<>();
            try (InputStream in = Files.newInputStream(file);
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(in))) {
            String line;
            while ((line = reader.readLine()) != null) {
                lines.add(line);
            }
        }
        return lines;
    }
}


答: If if it is important to you use something like checkstyle and put it in a pre-commit hook.  If the checkstyle fails, the code can not be committed.  Checkstyle is pretty good at giving feedback messages.  People will figure out why their code did not meet the standard and what they need to do to make it through.</p>


答:
Do Code reviews

Especially point out problems occurring from bad coding style or prevented by good coding style.

Do a lot of talking why this is important.

Depending on how junior your coworkers are, do realize you have to learn to write code before you can write beatifull code.


答:
I am the only developer at my company. I use SVN for anything that is currently in production or might possibly be in production someday. Ten reasons why I use it:

BACKUP. If my HD fails, I don't want to lose all my code!

Makes it easy to roll back to previous versions of the code in case I completely stuff something up (makes you feel braver when doing large refactors too)

Makes it easy to setup a continuous build that runs my unit tests everytime I check in

The continuous builds also create a "staging" version of my application for anyone else in the company to look at (or for testing, or UAT, or demos)

Gives a good history for the boss (and me) to see what I've been working on

When new programmers come onboard I can easily point them towards the code

Lets me tag a "current production release" version of the code, in case I need to deploy an urgent fix without introducing the new features that I'm working on

Makes it easier to manage a re-usable code library that is shared across multiple solutions (I'm in the c# world)

Keeps me up to date with everything in the SVN world (hey, the latest version of tortoise SVN automatically prompts you to update if you do a commit that is out-of-date, cool!). The great thing about working on your own is that it's much easier to test out a lot more things - you don't have to worry about breaking the code/build/tests/framework for anyone else.

If I'm off sick (or holiday, whatever) the code isn't stuck on my machine, the boss can get it out of SVN.

Also serves to reminds me that I'm a software engineer not just coding scum :)


答:
For single developers the question simplifies to "Should I take backups of the source code if I am the only one working on a project".   You most likely want to.

The additional benefits pale in comparison with this, but you will most likely find some of them very useful anyway.  The advantages just show up much later in the process.

The second most useful feature is the ability to build the bits shipping to customers in a clean room environment.  This ensures that the build is reproduceable which is very important when you need to maintain them later.


问:
REST vs RESTful vs "normal" web service - the same or not?
I've read a couple of definitions and discussion on REST and/or RESTful applications, but I still do not understand the real meaning of it.

I usually work with the apps which either fetch data via GET or send data via POST to some web service (usually a PHP script) which then either get data from the database or do writing into the database.

Now, is this a RESTful app? If not, what would be a RESTful app? What is difference between RESTful concept and the concept I worked so far with? Please explain via an example.

Also, someone is talking about the REST and someone about RESTful apps. I found that the REST term refers to the theoretical concept, while RESTful is used when we talk about the specific app. Is this right or there are real differences between REST and RESTful apps?

答:
REST stands for Representational State Transfer.  If your software conforms to the REST Constraints then it is considered to be RESTful.

Right, now that I've shamelessly ripped from Wikipedia, what does this really mean? It effectively means using the inbuilt HTTP commands such as GET, POST, PUT, DELETE and a few other rarer ones to communicate back and forth between a client and server.

What you're doing sounds like its a RESTFul app.  However, there's a large difference between well designed and piles o' junk RESTFul web services.  For example the PHP code at the other end of the GET might execute state change, which would be considered wrong since a GET is seen as a read only operation. There are subtle differences between how POST (new) and PUT (replace) are used as well.

The Wikipedia article on this is actually really good, so I'll stop here.


问:
My coworker created a 96 columns SQL table
Here we are in 2010, software engineers with 4 or 5 years or experience, still designing tables with 96 fracking columns.

I told him it's gonna be a nightmare.

I showed him that we have to use ordinals to interface MySQL with C#.

I explained that tables with more columns than rows are a huge smell.

Still, I get the "It's going to be simpler this way".

What should I do?

EDIT *

This table contains data from sensors.

We have sensor 1 with

Dynamic_D1X

Dynamic_D1Y

[...]

Dynamic_D6X

Dynamic_D6Y

[...]

EDIT2 *

Well, I finally left that job. It is a sign when the other programmer goes dark for months at the time, it is another sign when management does not realise this is a problem

答:
It completely depends.

Normalized / unnormalized DB designs both have their advantages and disadvantages.

My first DB design was a normalized thing of beauty.  It was flexible and extensible.  It was also an incredible PITA for anyone except myself to deal with on the code level, and it was a mild PITA for me.

My next attempt was a flat structure, and it was (a) a lot faster and (b) a lot easier to code with.  And it won't be a huge chore to normalize more later.

So it may be a smell but some other DB design will have its own delightful array of smells.


答:
The key attributes of a RESTful applications are:
All communication is via http GET,POST,PUT,DELETE AND all items are addressed via a standard URL of the form http://your.site.com/salesapp/salesperson/0000001/details i.e. only a pure URL with no parameters etc. the URL identifies the thing the GET,POST,PUT,DELETE identifies what you want to do to it.

The main reason for doing this is that you automatically have a stateless service which can be load balanced, failed over etc. etc.

The sheer simplicity of the scheme makes for a very clean interface, totally decoupling the client from any particular back-end implementation.

Title: REST vs RESTful vs "normal" web service - the same or not?

Body:
I've read a couple of definitions and discussion on REST and/or RESTful applications, but I still do not understand the real meaning of it.

I usually work with the apps which either fetch data via GET or send data via POST to some web service (usually a PHP script) which then either get data from the database or do writing into the database.

Now, is this a RESTful app? If not, what would be a RESTful app? What is difference between RESTful concept and the concept I worked so far with? Please explain via an example.

Also, someone is talking about the REST and someone about RESTful apps. I found that the REST term refers to the theoretical concept, while RESTful is used when we talk about the specific app. Is this right or there are real differences between REST and RESTful apps?


答:
I am in this boat. Not only do I use source control, I build all the software on a completely separate box.

This makes sure that all the source code created on my machine has actually been checked in to source control. Plus I have a another backup of everything.

The cost of another machine is around £300 in the UK, so IMO you can't justify not doing this!


答:
RESTful means that the interface is a set of objects, that can be read and updated (and possibly deleted). That is there are no multi-parameter queries (only parameter is the object you want to read) and there is only one type of operation that changes anything on the server, upload of new state.

These limitations ensure that all requests are idempotent (sending them multiple times does not have any extra effect to sending them once). This is important, because network may fail anytime and not deliver any request or response and with idempotent requests you just send it again and don't have to do complicated recovery.


答:
I would add your new helper-methods to the superclass only if

it does not introduce new dependencies (i.e. an additional lib/dll is required)

does not change the semantic of existing methods in that superclass: Liskov substitution principle

else i would create a new class.

Title: Extend the API or use the same name as a class in the API?

Body:
I have been running into this problem more and more: I am not happy with the current API, and end up making my own class that does what I wish the API did; however, I don't extend the 'super class' as I don't feel it fully fits. I can't imagine that this is good practice, so should I just extend the 'super class' or should I name the class slightly different than what I feel the original class should have done?

For example, in Java you end up writing ten lines of code just to read a file into a List, with each entry being one of the file.

So again, in cases like this, should the class be renamed to something similar, or should it go ahead and just extend the class the include the behavior you wanted? It almost seems wrong to me to extend the API classes, but at the same time, by not doing so, you are defeating the point of inheritance in OOP.


问:
Where to put Spring configuration file?
I want to integrate Spring framework in my project especially into server side.

So, I don't want to put it within WEB-INF folder of war file.

Should I put an applicationContext.xml it into each layer (means each project since divided in distinct projects? (Services, Domain, and DAO)

What is the good practice ?

答:
The Maven file structure may help with this

In essence the Spring configuration files (that can have any name by the way, not just the generic applicationContext.xml) are treated as classpath resources and filed under src/main/resources. During the build process, these are then copied into the WEB-INF/classes directory which is the normal place for these files to end up.

Variations include an additional spring directory (e.g. src/main/resources/spring) to separate the Spring contexts from other resources dedicated to application frameworks. You may wish to split the application contexts into dedicated layers such as:

```<code>example-servlet.xml
example-data.xml
example-security.xml
</code>```

and so on.

What about different environments like dev/test/production?

Typically, your Spring configuration should pick up the environment configuration from its, ahem, environment. Usually this means using JNDI, JDBC, environment variables or external properties files to provide the necessary configuration. I list those in order of preference since JNDI is generally easier to administer than external properties files in a controlled production cluster.

In the case of integration testing you may need to use a "test-only" Spring configuration file. This would contain special contexts that use test beans or configuration. These would be present under src/test/resources and may have a test- prefix to make sure that developers are aware of their purpose. A typical use would be to provide a non-JNDI DataSource perhaps targeting a HSQLDB database during the build automated tests and would be referenced within the test case.

However, in general the majority of your Spring context files should not need specialised modification as they move between tiers. It should be the case that the same build artifact (e.g. WAR file) is used in dev/test/production just with different credentials.

Title: Where to put Spring configuration file?

Body:
The Maven file structure may help with this

In essence the Spring configuration files (that can have any name by the way, not just the generic applicationContext.xml) are treated as classpath resources and filed under src/main/resources. During the build process, these are then copied into the WEB-INF/classes directory which is the normal place for these files to end up.

Variations include an additional spring directory (e.g. src/main/resources/spring) to separate the Spring contexts from other resources dedicated to application frameworks. You may wish to split the application contexts into dedicated layers such as:

example-servlet.xml
example-data.xml
example-security.xml

and so on.

What about different environments like dev/test/production?

Typically, your Spring configuration should pick up the environment configuration from its, ahem, environment. Usually this means using JNDI, JDBC, environment variables or external properties files to provide the necessary configuration. I list those in order of preference since JNDI is generally easier to administer than external properties files in a controlled production cluster.

In the case of integration testing you may need to use a "test-only" Spring configuration file. This would contain special contexts that use test beans or configuration. These would be present under src/test/resources and may have a test- prefix to make sure that developers are aware of their purpose. A typical use would be to provide a non-JNDI DataSource perhaps targeting a HSQLDB database during the build automated tests and would be referenced within the test case.

However, in general the majority of your Spring context files should not need specialised modification as they move between tiers. It should be the case that the same build artifact (e.g. WAR file) is used in dev/test/production just with different credentials.


问:
What kind of problems does MapReduce solve?
I have been reading about MapReduce for a while -- but what I can't understand is how someone would make a decision to use (or not use) MapReduce.

I mean, what are the problem patterns that signal that MapReduce could be used.

答:
Map/Reduce is a specific form of a specific kind of algorithm.  You use it to transform one huge data set into another data set.  (The result dataset may or may not be huge.)  If you don't want a static data output set as a result of static data input, then Map/Reduce is not appropriate.  Map/Reduce can easily tell you how many John Smiths are in the Manhattan phone book, but it is not well suited to build a web server.

The way Map/Reduce works is:

Map takes pairs of keys (k1) and values (v1) and maps them into a new set of keys (k2) and values (v2).

Reduce takes all the v2 values with the same k2 key and produces a new value (v3).

The result is that a list of  (k1, v1) pairs is transformed into a list of (v3)s. (Of course, the value "v3" can be a composite that includes k2, which could be defined to be equal to k1.)

So you use it:

If you have so much data to start with that running it all sequentially through one or two servers would take too long, and

You can conceive of the output data of being a list of values or key value pairs (generally not too hard when you remember "key" only means "unique label"), and

Whatever the relationship, you are sure that each piece of input data only impacts the output value for one output key.

If your data can all be processed sequentially by a single server, then since that is the dominant computing paradigm (the ones servers are built for and programmers are trained on), use a single server.

The map stage has to partition all the input data by output key.  It doesn't have to produce the output value associated with the output key (that's done by the reduce stage), but it does have to uniquely assign each input key value pair to contribute to at most one output key's value.  If the data is too interrelated then map reduce might not be able to handle the problem.  On the other hand, it may just be that you need to use multiple rounds of map/reduce.

If you can't figure out how to turn your data transformation into a map/reduce, then of course it's not a solution.

There is a real art to figuring out if a problem can be decomposed into something Map/Reduce can handle.  For example v1 and v2 might not be in the input or output data sets at all.  If you just want to count unique items in the input data, then k1 = k2 = an item and v1 = v2 = 1 or 0 or really anything.  Reduce just produces v3 as the sum of the number of k2's it was given.

So it's hard to say for sure that a data transformation cannot be done using Map/Reduce, but the above gives you some guideposts.


问:
Magic square check for N×N matrix with minimum complexity
Is there any algorithm that works better than O(n²) to verify whether a square matrix is a magic one (e.g. such as sum of all the rows, cols and diagonally are equal to each other)?

I did see someone mention a O(n) time on a website a few days ago but could not figure out how.

答:
It all depends on what n is. If you say that n is the number of ellements per row you cant check if the matrix is magic with less than O(n²). If you say n is the total number of ellements in the matrix you could easily create an algorithm that has the time complexity of O(n).

Here is some psevdo code with time complexity analys

```<code>columvalue = rows[0];                    O(1)
diagonalvalue1 = rows[0][0]              O(1)
diagonalvalue2 = rows[0][-1]             O(1)
magicNumber = sum(rows[0]);              O(c)
diagonal count = 1

for r in rows:                           O(r)*(
  diagonalvalue1 += r[0+diagonalcount]         O(1)
  diagonalvalue2 += r[-1-diagonalcount]        O(1)
  diagonalcount  += 1                          0(1)
  rowsum = 0                                   O(1)
  i = 0                                        O(1)
  for n in r:                                  0(c)*(
    rowsum += n                                     O(1)
    columvalue[i] += n                              O(1)
    i += 1                                          0(1)
                                                    )
  if rowsum != magicvalue:                     O(1)
    return False                               O(1)
                                               )

for c in columvalue:                     O(c)*(
  if c != magicvalue:                          O(1)
    return False                               O(1)
                                               )

return diagonalvalue1 == magicvalue and
       diagonalvalue2 == magicvalue       O(1)
</code>```

this will give us the time complexity of O(c) + O(r*c)
there c = number of colons and r = number of rows.
Since O(r*c) >= O(c) we can say that the time complexity is O(r*c) which are the
number of ellements in the matrix that are n and this gives us the complexity of
O(n)

Body:
It all depends on what n is. If you say that n is the number of ellements per row you cant check if the matrix is magic with less than O(n²). If you say n is the total number of ellements in the matrix you could easily create an algorithm that has the time complexity of O(n).

Here is some psevdo code with time complexity analys

columvalue = rows[0];                    O(1)
diagonalvalue1 = rows[0][0]              O(1)
diagonalvalue2 = rows[0][-1]             O(1)
magicNumber = sum(rows[0]);              O(c)
diagonal count = 1

for r in rows:                           O(r)*(
  diagonalvalue1 += r[0+diagonalcount]         O(1)
  diagonalvalue2 += r[-1-diagonalcount]        O(1)
  diagonalcount  += 1                          0(1)
  rowsum = 0                                   O(1)
  i = 0                                        O(1)
  for n in r:                                  0(c)*(
    rowsum += n                                     O(1)
    columvalue[i] += n                              O(1)
    i += 1                                          0(1)
                                                    )
  if rowsum != magicvalue:                     O(1)
    return False                               O(1)
                                               )

for c in columvalue:                     O(c)*(
  if c != magicvalue:                          O(1)
    return False                               O(1)
                                               )

return diagonalvalue1 == magicvalue and
       diagonalvalue2 == magicvalue       O(1)

this will give us the time complexity of O(c) + O(r*c)
there c = number of colons and r = number of rows.
Since O(r*c) >= O(c) we can say that the time complexity is O(r*c) which are the
number of ellements in the matrix that are n and this gives us the complexity of
O(n)


问:
How to model two similar tasks with the Use-case diagram
I am trying to draw a use-case diagram for a software project.

Two requirements for the software I am trying to model in use-case diagram are:

A customer (i.e. Client) should be able to cancel its previous request. In this case, the client must select the relevant request from their list of request.

A travel agent should be able to cancel a request. in this case, the agent must the client from the list of clients and the request from the list of request issued by that client.

How should I model this two requirements in a UML user-case diagram? I've ended up to something like this:

答: That's largely how I've done them in Software Engineering. The Use Case diagram is to show relationships between Agents and Use Cases so you've done it correctly as far as I know. One small nitpick, typically primary users go on the left and back end users are on the right though they can be on the same side if you want. It's more of a convention that a rule.</p>


答:
The use case diagram is correct, just move the client to the left hand side

Use cases shouldn't be concerned with how something will be implemented.  When I look at the use case I don't care how the requests are selected.

Title: How to model two similar tasks with the Use-case diagram

Body:
I am trying to draw a use-case diagram for a software project.

Two requirements for the software I am trying to model in use-case diagram are:

A customer (i.e. Client) should be able to cancel its previous request. In this case, the client must select the relevant request from their list of request.

A travel agent should be able to cancel a request. in this case, the agent must the client from the list of clients and the request from the list of request issued by that client.

How should I model this two requirements in a UML user-case diagram? I've ended up to something like this:


答:
One idea: show them what code could look like if deliberately made to be not easy to read and comprehend (http://www.ioccc.org/2011/konno/konno.c is a short nice example for instance). Ask them would you like to receive code like this to maintain?

Highlight the importance of

a computer language is not just a way of getting a computer to
  perform operations ... programs must be written for people to read,
  and only incidentally for machines to execute.

(quote from SICP)