问:
Should curly braces appear on their own line?
Should curly braces be on their own line or not? What do you think about it?

```<code>if (you.hasAnswer()) {
    you.postAnswer();
} else {
    you.doSomething();
}
</code>```

or should it be

```<code>if (you.hasAnswer())
{
    you.postAnswer();
}
else
{
    you.doSomething();
}
</code>```

or even

```<code>if (you.hasAnswer())
    you.postAnswer();
else
    you.doSomething();
</code>```

Please be constructive! Explain why, share experiences, back it up with facts and references.

答:
I prefer

```<code>if (you.hasAnswer())
{
    you.postAnswer();
}
else
{
    you.doSomething();
}
</code>```

over

```<code>if (you.hasAnswer()) {
    you.postAnswer();
} else {
    you.doSomething();
}
</code>```

because the line you.postAnswer(); is much easier to read and find at first glance. In the second way, it gets blended in with the line above it (you.hasAnswer()) making my eyes have to focus more to read it.

Body:
I prefer

if (you.hasAnswer())
{
    you.postAnswer();
}
else
{
    you.doSomething();
}

over

if (you.hasAnswer()) {
    you.postAnswer();
} else {
    you.doSomething();
}

because the line you.postAnswer(); is much easier to read and find at first glance. In the second way, it gets blended in with the line above it (you.hasAnswer()) making my eyes have to focus more to read it.


问:
Reverse engineering: what is it really good for?
I have some innocent/beginner questions:

What is reverse engineering good for?

As a programmer, should I learn the art of reverse engineering?

What are the benefits to a programmer who is experienced with it?

答:
I am giving just a real world example from my experience.

Once our company took over a project from another company. About half a year into the project we realized that a subproject was without code. When we asked the former company to deliver the code, they politely replied that they couldn't find the code for the subproject. We needed the code because we wanted to change something in that subproject.

I had to reverse engineer the subproject.

First I decompiled the assembly (yes, it is a .NET project). The result of the decompiled assembly is bland and confusing code without names of local variables and a complicated control structure. This is because compilation discards important information which cannot be decompiled.

Then I tried to figure out where to change that code. To do this I streamlined the code to behave the same but in a more concise way. I also guessed the names of the variables from its behaviour. I single stepped  through the code many times till I figured out what it is doing.

I didn't reverse engineer everything, only the part we had to change. It was not too bad, about 200 lines of VB code. It took around five days of working time.

ContentLicense: CC BY-SA 3.0


问:
Why do developers need to keep up to date with technologies and methodologies?
I am always given the advice that developers need to stay up to date with the latest in technology - things like webrtc, updates on html5 and css3 and new js libraries, software methodologies like TDD, DDD, and BDD.

The question is why? Why do we need to constantly update ourselves? Can't we just stick with what we know and become better with it?

答: Because "sticking with what you know" represents a failure to "get better at it." You don't have to adopt every new practice and framework that comes along but you should at least have an informed opinion on the popular ones. In web development just asking the question would look horrible to an interviewer. Web dev is littered with the career-corpses of people who wanted to stop learning new stuff after 2000 and that's as it should be because they make more work for the rest of us. Stay away from dev if it doesn't interest you. It's a lousy $/hour ratio if the part where you learn new stuff feels like work.</p>


问:
Are there deprecated practices for multithread and multiprocessor programming that I should no longer use?
In the early days of FORTRAN and BASIC, essentially all programs were written with GOTO statements.  The result was spaghetti code and the solution was structured programming.

Similarly, pointers can have difficult to control characteristics in our programs.  C++ started with plenty of pointers, but use of references are recommended.  Libraries like STL can reduce some of our dependency.  There are also idioms to create smart pointers that have better characteristics, and some version of C++ permit references and managed code.

Programming practices like inheritance and polymorphism use a lot of pointers behind the scenes (just as for, while, do structured programming generates code filled with branch instructions).  Languages like Java eliminate pointers and use garbage collection to manage dynamically allocated data instead of depending on programmers to match all their new and delete statements.

In my reading, I have seen examples of multi-process and multi-thread programming that don't seem to use semaphores.  Do they use the same thing with different names or do they have new ways of structuring protection of resources from concurrent use?

For example, a specific example of a system for multithread programming with multicore processors is OpenMP.  It represents a critical region as follows, without the use of semaphores, which seem not to be included in the environment.

```<code>th_id = omp_get_thread_num();
#pragma omp critical
{
  cout << "Hello World from thread " << th_id << '\n';
}
</code>```

This example is an excerpt from: http://en.wikipedia.org/wiki/OpenMP

Alternatively, similar protection of threads from each other using semaphores with functions wait() and signal() might look like this:

```<code>wait(sem);
th_id = get_thread_num();
cout << "Hello World from thread " << th_id << '\n';
signal(sem);
</code>```

In this example, things are pretty simple, and just a simple review is enough to show the wait() and signal() calls are matched and even with a lot of concurrency, thread safety is provided.  But other algorithms are more complicated and use multiple semaphores (both binary and counting) spread across multiple functions with complex conditions that can be called by many threads.  The consequences of creating deadlock or failing to make things thread safe can be hard to manage.

Do these systems like OpenMP eliminate the problems with semaphores?

Do they move the problem somewhere else?

How do I transform my favorite semaphore using algorithm to not use semaphores anymore?

答:
Yes, but you're not likely to run into some of them.

In the old days, it was common to use blocking methods (barrier synchronization) because writing good mutexes was hard to do right. You can still see traces of this in things as recent  Using modern concurrency libraries gives you a much richer, and thoroughly-tested, set of tools for parallelization and inter-process coordination.

Likewise, an older practice was to write torturous code such that you could figure out how to parallelize it manually. This form of (potentially harmful, if you get it wrong) optimization has also largely gone out the window with the advent of compilers that do this for you, unwinding loops if necessary, predictively following branches, etc. This is not new technology, however, being at least 15 years on the market. Taking advantage of things like thread pools also circumvents some really tricksy code of yesteryear.

So perhaps the deprecated practice is writing concurrency code yourself, instead of using modern, well-tested libraries.


问:
Should I prefer properties with or without private fields?
The codebase I'm working in now has the convention of using private fields and public properties. For example, most classes have their members defined like this:

```<code>// Fields
private double _foo;
private double _bar;
private double _baz;

// Properties
public double Foo
{
    get{ return _foo; }
    set{ _foo = value; }
}

public double Bar
{
    get{ return _bar; }
    set{ _bar = value; }
}

public double Baz
{
    get{ return _baz; }
}
</code>```

I know these can be rewritten without their internal private properties:

```<code>public double Foo{ get; set; }
public double Bar{ get; set; }
public double Baz{ get; private set; }
</code>```

I'd like some input on this:

Is there a good reason to prefer the older, more explicit style over the
newer, more concise one?

Should I write any new classes using the
concise style, or should I try to match the older code for
consistency? Is consistency worth enough in this case to justify the older format?

答:
There are a couple instances where the so-called "older" style is still required:

A: Immutable types using language-provided immutability. The readonly modifier in C# freezes that value after construction. There's no way to mimic this with automatically-implemented properties (yet).

```<code>public sealed class FooBarBazInator
{
    private readonly double foo;

    public FooBarBazInator(double foo)
    {
        this.foo = foo;
    }

    public double Foo
    {
        get
        {
            return this.foo;
        }
    }
}
</code>```

B: Your getters/setters have any logic whatsoever. WPF and Silverlight (and similar) code that are data-bound to your classes will implement INotifyPropertyChanged like so:

```<code>public class FooBarBazInator : INotifyPropertyChanged
{
    private double foo;

    public event PropertyChangedEventHandler PropertyChanged;

    public double Foo
    {
        get
        {
            return this.foo;
        }

        set
        {
            this.foo = value;
            this.RaisePropertyChanged("Foo");
        }
    }

    private void RaisePropertyChanged(string propertyName)
    {
        var propertyChanged = this.PropertyChanged;

        if (propertyChanged != null)
        {
            propertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
</code>```

Other than those, I'd say use the new style. Keeps your code concise and offers less surface area for bugs to creep in. Plus, if it ever needs to change to include logic, it won't be signature-incompatible.

Body:
There are a couple instances where the so-called "older" style is still required:

A: Immutable types using language-provided immutability. The readonly modifier in C# freezes that value after construction. There's no way to mimic this with automatically-implemented properties (yet).

public sealed class FooBarBazInator
{
    private readonly double foo;

    public FooBarBazInator(double foo)
    {
        this.foo = foo;
    }

    public double Foo
    {
        get
        {
            return this.foo;
        }
    }
}

B: Your getters/setters have any logic whatsoever. WPF and Silverlight (and similar) code that are data-bound to your classes will implement INotifyPropertyChanged like so:

public class FooBarBazInator : INotifyPropertyChanged
{
    private double foo;

    public event PropertyChangedEventHandler PropertyChanged;

    public double Foo
    {
        get
        {
            return this.foo;
        }

        set
        {
            this.foo = value;
            this.RaisePropertyChanged("Foo");
        }
    }

    private void RaisePropertyChanged(string propertyName)
    {
        var propertyChanged = this.PropertyChanged;

        if (propertyChanged != null)
        {
            propertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

Other than those, I'd say use the new style. Keeps your code concise and offers less surface area for bugs to creep in. Plus, if it ever needs to change to include logic, it won't be signature-incompatible.


答:
I would say that having explicit backing field is just useless cruft: it makes your code longer and harder to read. It also adds potential of error:

```<code>public double Bar
{
    get { return _baz; }
    set { _bar = value; }
}
</code>```

I think an error like this could happen quite easily and would be quite hard to spot.

And if you want consistency, do it the other way: change code that uses backing fields into code that uses automatic properties. This is especially easy if you use a refactoring tool like ReSharper (and if you don't use something like that, I think you should start).

Of course, there are still cases where having backing field is necessary, but I think that's not relevant to this question.

Title: Should I prefer properties with or without private fields?

Body:
The codebase I'm working in now has the convention of using private fields and public properties. For example, most classes have their members defined like this:

```<code>// Fields
private double _foo;
private double _bar;
private double _baz;

// Properties
public double Foo
{
    get{ return _foo; }
    set{ _foo = value; }
}

public double Bar
{
    get{ return _bar; }
    set{ _bar = value; }
}

public double Baz
{
    get{ return _baz; }
}
</code>```

I know these can be rewritten without their internal private properties:

```<code>public double Foo{ get; set; }
public double Bar{ get; set; }
public double Baz{ get; private set; }
</code>```

I'd like some input on this:

Is there a good reason to prefer the older, more explicit style over the
newer, more concise one?

Should I write any new classes using the
concise style, or should I try to match the older code for
consistency? Is consistency worth enough in this case to justify the older format?

Body:
I would say that having explicit backing field is just useless cruft: it makes your code longer and harder to read. It also adds potential of error:

public double Bar
{
    get { return _baz; }
    set { _bar = value; }
}

I think an error like this could happen quite easily and would be quite hard to spot.

And if you want consistency, do it the other way: change code that uses backing fields into code that uses automatic properties. This is especially easy if you use a refactoring tool like ReSharper (and if you don't use something like that, I think you should start).

Of course, there are still cases where having backing field is necessary, but I think that's not relevant to this question.


答:
Is there a good reason to prefer the older, more explicit style over the newer, more concise one?

Not really. Though I would argue that any time you had a pass through property like that, you should've just used a public field to begin with.

Should I write any new classes using the concise style, or should I try to match the older code for consistency? Is consistency worth enough in this case to justify the older format?

Assuming you ignored the above advice and have passthrough properties, I would not aim to match the style. Ideally, you would go back and refactor the old style into the new style to be consistent, but the chance of people misreading that code is slim.


问:
printf - source of bugs?
I'm using a lot of printf for tracing/logging purposes in my code, I've found that it's a source of programming error. I always found the insertion operator (<<) to be somewhat of a odd thing but I'm beginning to think that by using it instead I could avoid some of these bugs.

Anyone ever had a similar revelation or I'm just grasping at straws here?

Some take away points

My current line of thinking is that type-safety outweighs any benefit
of using printf. The real problem is the format string and the use of
non type-safe variadic functions.

Maybe I won't be using << and the stl output stream variants but I will certainly look into using a type-safe mechanism which is very similar.

A lot of the tracing/logging is conditional but I'd like to always run the code to not miss bugs in tests just because it's a rarely taken branch.

答:
There are many groups - for example google - that don't like streams.

http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Streams

(Pop open the triangle thingy so you can see the discussion.)  I think the google C++ style guide has LOTS of very sensible advice.

I think the tradeoff is that streams are safer but printf is clearer to read (and easier to get exactly the formatting you want).

Title: printf - source of bugs?


问:
Can a single simple language such as Clojure replace Html + JavaScript + CSS + Flash + Java Applets ...?
Please do not dismiss the idea right away. I know that it is hard to compete with a mainstream approach that already works (mostly), so my question is partly "academic".

I also am aware that ClojureScript exists and is very cool, but it is a patch on an existing ugly thing, a useful abstraction.

Disclaimer: I am a programmer but not a web developer, and this is why I am soliciting other's feedback. Being a developer and using the web every day and reading up on various topic and viewing the html source of a page from time to time I think I have some idea about web development.

Anyhow, the problems as I see them:

The web started out quick and dirty and noob-friendly, but now it takes a great deal of skills to make a good modern interactive web page, and you just have to be good at it in order to be competitive today. This often means that quick and dirty "learn web in 21 days" just does not cut it at all.

Html started out quick and dirty, as a noob-friendly protocol. It is currently a mess.

JavaScript language is not without its flaws, but ok.

CSS appears to be a decent attempt to clean things up. It is worth keeping, at least the idea of it - that you can style the appearance in a separate file.

Putting it all together - JavaScript + Html + CSS becomes rather dirty. There have been good ideas/tools that mitigate the problem such as: AJAX libraries abstract away the specific flavors of the JavaScript. Powerful libraries such as JQuery, Node.js, etc. allow doing cool things in JavaScript as imperfect as it is. Google Web Kit does a very good job of translating a GUI design into a web page. Web MVC frameworks such as ASP.Net, RoR, Django abstract things away and do a lot of leg work for you, HOWEVER, these are all abstractions on top of a crappy base.

The demand for what the web could do today is ever-increasing; Google's ChromeBook is a manifestation of that. You run a browser full screen and everything that you might want to do - keyboard/mouse interactions, sound, video, games, text, images, power point presentations - everything is happening inside of it. Thanks for the fast browsers and fast computers and "the cloud", but it could be a lot better!

From a graphics point of view, a browser is just a rectangular canvas that you can paint anything on. Currently the browser executable weighs many megabytes because it has to know how to parse Html, JavaScript, CSS and display all of it.

If you start from scratch and realize that it is pretty much just a canvas to be painted, then I think the browser can be much smaller and simpler. The price to pay is having to write a valid program for everything in a funky syntax such as Lisp or Clojure, even for the simplest of things such as displaying a label. That used to be the cool part of the html - if you wanted just to type the paragraph, you would type it verbatim. This rarely happens anymore. If all you want is to just type the paragraph of text, you still have to think about inline or CSS styling, placement. The following piece of HTML (found on the front page of this site)

```<code>programming-languages learning
</code>```

is not that much easier to craft than some alternative Lispy syntax (and I have not put that much thought into it):

```<code>(create-link :target "/questions/tagged/programming-languages" :class "post-tag" :title "show questions tagged 'programming-languages'" :rel "tag" :content (text "programming-languages"))
</code>```

This might not be a valid Clojure syntax; I sort of made it up. It does not have to try to mimic html - in fact that is the point of starting from scratch. The huge advantage here would be that (text ...) and (create-link ...) are not part of the core language that a browser would have to understand. The browser would only need to understand a "safe" Clojure (one that cannot wipe your hard drive clean) and be able to draw and play music and listen to keyboard and mouse and similar things, and everything else - drawing text, playing a video, displaying a combo box and interacting with it would be all done in a carefully designed library.

Why did I choose Clojure? It is a tiny language that can accomplish a lot, plus the philosophy of building complicated programs out of simple building blocks is very attractive.

I do think that being able to support a single powerful language such as Clojure would be enough to accomplish everything that Html and Html5 and CSS and JavaScripts and Silverlight and Flash can accomplish.

Somewhat of a tangential discussion - I think the same is true for LaTeX - it could be redone with Clojure as an underlying language, and a source file would be a full-blown program that spits out a PDF or a ps as it executes.

I understand that starting from scratch is VERY HARD because a modern browser has lots and lots of useful features. Starting with a clean base can pay off though.

What are your thoughts on this crazy idea? I realize that the answers would probably be subjective due to the nature of this question, but I still am curious what you think of this.

答:
Browsers have one thing going for them that pretty much overwhelms all other considerations.

Market Share.

In short, you don't have to install them.  They're already on the user's machine.  Don't underestimate this singular benefit.

Things have gotten much better with HTML5; you can pretty much write a rich client in it, if you want to, and there are many frameworks available that make this process easier.

If you don't like the browser's native languages, you can use things like CoffeeScript and Less to clean them up.  Javascript is the new machine language anyway.  That's what makes things like ClojureScript work.

There are a number of tools such as Websharper that allow web development in a single language.

Body:
Please do not dismiss the idea right away. I know that it is hard to compete with a mainstream approach that already works (mostly), so my question is partly "academic".

I also am aware that ClojureScript exists and is very cool, but it is a patch on an existing ugly thing, a useful abstraction.

Disclaimer: I am a programmer but not a web developer, and this is why I am soliciting other's feedback. Being a developer and using the web every day and reading up on various topic and viewing the html source of a page from time to time I think I have some idea about web development.

Anyhow, the problems as I see them:

The web started out quick and dirty and noob-friendly, but now it takes a great deal of skills to make a good modern interactive web page, and you just have to be good at it in order to be competitive today. This often means that quick and dirty "learn web in 21 days" just does not cut it at all.

Html started out quick and dirty, as a noob-friendly protocol. It is currently a mess.

JavaScript language is not without its flaws, but ok.

CSS appears to be a decent attempt to clean things up. It is worth keeping, at least the idea of it - that you can style the appearance in a separate file.

Putting it all together - JavaScript + Html + CSS becomes rather dirty. There have been good ideas/tools that mitigate the problem such as: AJAX libraries abstract away the specific flavors of the JavaScript. Powerful libraries such as JQuery, Node.js, etc. allow doing cool things in JavaScript as imperfect as it is. Google Web Kit does a very good job of translating a GUI design into a web page. Web MVC frameworks such as ASP.Net, RoR, Django abstract things away and do a lot of leg work for you, HOWEVER, these are all abstractions on top of a crappy base.

The demand for what the web could do today is ever-increasing; Google's ChromeBook is a manifestation of that. You run a browser full screen and everything that you might want to do - keyboard/mouse interactions, sound, video, games, text, images, power point presentations - everything is happening inside of it. Thanks for the fast browsers and fast computers and "the cloud", but it could be a lot better!

From a graphics point of view, a browser is just a rectangular canvas that you can paint anything on. Currently the browser executable weighs many megabytes because it has to know how to parse Html, JavaScript, CSS and display all of it.

If you start from scratch and realize that it is pretty much just a canvas to be painted, then I think the browser can be much smaller and simpler. The price to pay is having to write a valid program for everything in a funky syntax such as Lisp or Clojure, even for the simplest of things such as displaying a label. That used to be the cool part of the html - if you wanted just to type the paragraph, you would type it verbatim. This rarely happens anymore. If all you want is to just type the paragraph of text, you still have to think about inline or CSS styling, placement. The following piece of HTML (found on the front page of this site)

```<code><a href="/questions/tagged/programming-languages" class="post-tag" title="show questions tagged 'programming-languages'" rel="tag">programming-languages</a> <a href="/questions/tagged/learning" class="post-tag" title="show questions tagged 'learning'" rel="tag">learning</a>
</code>```

is not that much easier to craft than some alternative Lispy syntax (and I have not put that much thought into it):

```<code>(create-link :target "/questions/tagged/programming-languages" :class "post-tag" :title "show questions tagged 'programming-languages'" :rel "tag" :content (text "programming-languages"))
</code>```

This might not be a valid Clojure syntax; I sort of made it up. It does not have to try to mimic html - in fact that is the point of starting from scratch. The huge advantage here would be that (text ...) and (create-link ...) are not part of the core language that a browser would have to understand. The browser would only need to understand a "safe" Clojure (one that cannot wipe your hard drive clean) and be able to draw and play music and listen to keyboard and mouse and similar things, and everything else - drawing text, playing a video, displaying a combo box and interacting with it would be all done in a carefully designed library.

Why did I choose Clojure? It is a tiny language that can accomplish a lot, plus the philosophy of building complicated programs out of simple building blocks is very attractive.

I do think that being able to support a single powerful language such as Clojure would be enough to accomplish everything that Html and Html5 and CSS and JavaScripts and Silverlight and Flash can accomplish.

Somewhat of a tangential discussion - I think the same is true for LaTeX - it could be redone with Clojure as an underlying language, and a source file would be a full-blown program that spits out a PDF or a ps as it executes.

I understand that starting from scratch is VERY HARD because a modern browser has lots and lots of useful features. Starting with a clean base can pay off though.

What are your thoughts on this crazy idea? I realize that the answers would probably be subjective due to the nature of this question, but I still am curious what you think of this.


答:
You are doing a lot of useless work, beside the fact that stl is evil or not, debug your code with a series of printf only add 1 more level of possible failures.

Just use a debugger and read something about Exceptions and how to catch and throw them; try to not be more verbose than you actually need to be.

PS

printf is used in C, for the C++ you have std::cout

Title: printf - source of bugs?

Body:
I'm using a lot of printf for tracing/logging purposes in my code, I've found that it's a source of programming error. I always found the insertion operator (<<) to be somewhat of a odd thing but I'm beginning to think that by using it instead I could avoid some of these bugs.

Anyone ever had a similar revelation or I'm just grasping at straws here?

Some take away points

My current line of thinking is that type-safety outweighs any benefit
of using printf. The real problem is the format string and the use of
non type-safe variadic functions.

Maybe I won't be using << and the stl output stream variants but I will certainly look into using a type-safe mechanism which is very similar.

A lot of the tracing/logging is conditional but I'd like to always run the code to not miss bugs in tests just because it's a rarely taken branch.


答:
Your problem is most likely coming from the mixing of two very different standard output managers, each of which has it's own agenda for that poor little STDOUT. You get no guarantees about how they are implemented, and it is perfectly possible that they set conflicting file descriptor options, both try to do different things to it, etc. Also, the insertion operators have one major over printf: printf will let you do this:

```<code>printf("%d", SomeObject);
</code>```

Whereas << will not.

Note: For debugging, you don't use printf or cout. You use fprintf(stderr, ...) and cerr.

Title: printf - source of bugs?

Body:
Your problem is most likely coming from the mixing of two very different standard output managers, each of which has it's own agenda for that poor little STDOUT. You get no guarantees about how they are implemented, and it is perfectly possible that they set conflicting file descriptor options, both try to do different things to it, etc. Also, the insertion operators have one major over printf: printf will let you do this:

printf("%d", SomeObject);

Whereas << will not.

Note: For debugging, you don't use printf or cout. You use fprintf(stderr, ...) and cerr.


答:
Mixing C-style printf() (or puts() or putchar() or ...) output with C++-style std::cout << ... output can be unsafe. If I recall correctly, they can have separate buffering mechanisms, so the output might not appear in the intended order. (As AProgrammer mentions in a comment, sync_with_stdio addresses this).

printf() is fundamentally type-unsafe. The type expected for an argument is determined by the format string ("%d" requires an int or something that promotes to int, "%s" requires a char* which must point to a correctly terminated C-style string, etc.), but passing the wrong type of argument results in undefined behavior, not a diagnosable error. Some compilers, such as gcc, do a reasonably good job of warning about type mismatches, but they can do so only if the format string is a literal or is otherwise known at compile time (which is the most common case) -- and such warnings are not required by the language. If you pass the wrong type of argument, arbitrarily bad things can happen.

C++'s stream I/O, on the other hand, is much more type-safe, since the << operator is overloaded for many different types. std::cout << x doesn't have to specify the type of x; the compiler will generate the right code for whatever type x has.

On the other hand, printf's formatting options are IMHO much more convenient. If I want to print a floating-point value with 3 digits after the decimal point, I can use "%.3f" -- and it has no effect on other arguments, even within the same printf call. C++'s setprecision, on the other hand, affects the state of the stream, and can mess up later output if you're not very careful to restore the stream to its previous state. (This is my personal pet peeve; if I'm missing some clean way to avoid it, please comment.)

Both have advantages and disadvantages. The availability of printf is particularly useful if you happen to have a C background and you're more familiar with it, or if you're importing C source code into a C++ program. std::cout << ... is more idiomatic for C++, and doesn't require as much care to avoid type mismatches. Both are valid C++ (the C++ standard includes most of the C standard library by reference).

It's probably best to use std::cout << ... for the sake of other C++ programmers who may work on your code, but you can use either one -- especially in trace code that you're going to throw away.

And of course it's worth spending some time learning how to use debuggers (but that might not be feasible in some environments).

Title: printf - source of bugs?


问:
front end development test - html/css/jquery/javascript
We are continually revamping our front end developer test that we do in-house after a candidate has passed an online test. The online test has questions such as:

How does a for loop start?

What is the correct way to write a JavaScript array?

Write the css selector for the 3rd list item within an ordered list
with the id "myList"

For var shoppingList = ["milk", "dumplings", "bread"]; - how would
you return dumplings into a variable named groceryItem?

FizzBuzz

So we cover the basics, and try to get an insight into their knowledge.

But, in house, we really want to test their problem solving skills, their logic approach, etc. And I don't think we've found a good way to do that for front end developers. For UI guys, it's easier - we give them a design challenge and a white board and see if they ask for more information, how they approach the problem, etc.

But we haven't found a way to replicate this approach with web developers (for the record, I am one of the web developers on the team)

Thoughts on how to approach?

答:
Switch it up, get the interviewee talking about past experience...

What will really help separate the wheat from the chaff is questions that drill deeper and require context to answer. Past experience is the best context but even theoretical answers show at the minimum some level of understanding.

Ask about process/tools:

What toolchain do you use to troubleshoot designs?

Using alert() as a print statement is all good but the turnaround for debugging is slow and it won't provide any help when it comes to making AJAX calls. Many experienced developers leverage tools like Firebug and Google Developer Tools because they show a much more in-depth analysis of what may be causing the problem.

I haven't used Firebug in quite a while but the Developer Tools built into Chrome allow you to inspect any element on the page by right-clicking on it which saves a ton of time that would be spent searching the source. It highlights elements on the page when you mouseover elements in the code.

How do you assess and improve page-loading performance?

Extremely important, especially since google added page load times to their ranking metrics. Being able to analyze load times and pinpoint potential bottlenecks is extremely important. There is no single hard/fast rule, there are about 100 and more experienced designers will be aware of many.

What program do you prefer to write code?

More experienced developers prefer more control over the source so they will probably use an enhanced plaintext editor (ex Notepad++) whereas a more green developer may still be dependent on the structure and documentation provided by a larger environment (ex Dreamweaver).

Ask questions about design

Would you use a table-based, relative, or absolute based layout structure?

A person who would say table probably has outdated knowledge of design. Relative and absolute are both good on their own for specific uses but mixing them both can be even better. A person who can articulate why with detail probably has a lot of experience dealing with more difficult design decisions.

How would you implement a rollover effect on an image button?

This is a very low level question. The 'right' answer is to use a css hover attribute but somebody who has weak design knowledge will prefer to implement a dual show/hide function in Javascript.

What are sprites and why would you use them?

Sprites can be a pain to implement initially but they can drastically cut down on the number of HTTP requests required to load a page. Somebody with solid knowledge of how HTML pages are loaded/assembled should be able to go into great detail about this topic.

Ask questions about APIs

Have you ever used an API?

As HTML and Javascript become more powerful, there will be a push to do more and more work on the client. It makes sense because it cuts down on cost on the server-side. Anybody who has done any sort of significant front-end development has most likely worked with an API. Whether it's Google Analytics, Twitter, Disqus, or just AJAX. I would consider knowledge of how to leverage API's to be vital to front-end development.

Have you ever designed a client-side API, what did it accomplish?

Yes, there are purely client-side APIs all over. jQuery, Prototype, and Underscore are the big 3 but there are many thousands of smaller API libraries and/or plugins that serve a specific purpose. If you're talking to an experienced dev, they may have grown beyond the 'look for a library' to the 'scratch an itch and write it yourself' stage. There are good reasons to choose one that has already been written, and there are good reasons to write your own, it all depends on the context.

Have you worked with AJAX, if so what format was the response and how was it handled?

Getting into more advanced territory but somebody who knows their stuff will be able to elaborate.

A AJAX request won't respond, how do you find the problem?

Usually, falls along the lines of checking the Javascript console to see if an error (usually 500) was returned and/or checking the HTTP header of the received packet.

JSONP, what is it and why is it useful?

See if they understand what cross-site-scripting protection is and how to get around it in a 'safe' manner.

Client-Side or Server-Side questions

Validation, do it on the front-end or back-end?

Kind of a trick question but the answer should be both. Verify that the fields are not empty and match the constraints. They should also be further sanitized and sanity-checked on the server.

What is an example of something that can't be done on the front-end?

Shows a better understanding of the limitations. For instance, email can't be done on the client because it requires a SMTP/POP/IMAP server to send/receive messages.

What is a REST API and why is it useful?

Shows deeper knowledge of HTML. Many people, especially those that don't understand them, talk about REST APIs like they're rocket science. Somebody who has worked with one should be able to present some simple examples of usage.

One biggie that I didn't cover, and probably shouldn't be limited to one question, is the issue of how to improve performance in situations where you're either traversing or modifying the DOM.

I could probably keep going all day but that should provide a good start. There is just so much ground to cover on the client-side alone. Not to mention that front-end developers also need to know enough to interact with designers, back-end developers, and possibly a multitude of external APIs.


问:
Can I change operator precedence and associativity in C++?
As the title says, I find it useful to be able to overload operators.  Is it possible to also change the way the operators are parsed by specifying the precedence and associativity of overridden operators?</p>

答:
No, you can't do that and that's a good thing. Operator overloading already has enough potential to make code unreadable without being able to change precedence or associativity.

If you even want to do that you are probably abusing operator overloading and should use normal functions instead.


答:
No.  While it may at first sight seem to make sense, if you think a little more, it becomes muddy to the point that it's a bad idea.

First note that the language isn't defined by using a precedence grammar, but a more classic BNF. I'm not sure that the behavior of sizeof or ?: is describable simply with a notion of priority and associativity.

But the major issue is that you are changing the priority and associativity of overloaded operators, not defining the priority and associativity of new operators used only for your types. Do you want your changes to be applicable for all uses, or just for your overload? You'll probably agree that the first option is a sure receipt for trouble. The other isn't much better. How to you know it's your overload which should be considered before doing overload resolution, which need parsing and thus associativity and priority to be known.

Title: Can I change operator precedence and associativity in C++?

Body: As the title says, I find it useful to be able to overload operators.  Is it possible to also change the way the operators are parsed by specifying the precedence and associativity of overridden operators?</p>


问:
SQL Server 2000 vs 2008 Express?
Due to not wanting to pay licenses my company is still using SQL Server 2000 for new projects.

This is very limiting for multiple reasons.

I'm wondering what are the limitations of using SQL Server Express 2008?

Is there any reason NOT to use it to power ASP.Net MVC3 websites?

答:
Let me explain the risks of developing in Express 2008 if you might ever run up on those limits. You will not be able to easily convert back to the SQL Server 2000 license if you use any newer features. If you don't use any newer features, they why not use SQL Server 2000? If  you use the Express version and after a few months it runs into those limits, are you then going to have the money you don't have now to buy a new version? Are you then going to have the time to get it in place or the time to convert backwards?

If you use the Express version and it hits the limits quickly and you were told to use 2000, then you will probably get fired.

If you think you cannot solve the problems you have with the feratures of 2000 (you didn't say where you thought 2000 was inadequate), then make a business case to upgrade. But don't forget to factor in the cost of upgrading existing systems and the cost of getting dbas trained on the new software if the upgrade will need to replace some or all of the existing databases.

Database sepcialists understand the cost and risk of moving data to a new version which is one reason why they tend to be very conservative about doing so. While I agree that it is past time to leave SQL Server 2000, you will have to build a very strong business case to take the risk of breaking something working so that you can play with new features you may or may not actually need. Database upgrades are inherently risky, if you want to upgrade then the onus is on you to prove the need.

Title: SQL Server 2000 vs 2008 Express?


答:
No.  Besides making code unreadable, it would make the language more ambiguous and deeply context-dependent because you would not be able to associate parameters with function calls until after you know all the operators available.

Consider the expression

```<code>a1 + a2 * a3
</code>```

where all a* vars have type A and you have overloadings

```<code>A operator+(A, A) // low precedence
A operator*(A, A) // high precedence
B operator+(A, A) // high precedence
A operator*(B, A) // low precedence
</code>```

This could be interpreted two different ways

```<code>operator+(a1, operator*(a2, a3))
</code>```

or

```<code>operator*(operator+(a1, a2), a3)
</code>```

With global precedence and associativity rules, the compiler can commit to the first interpretation during parse, but with overridable associativity/precedence, there's no way to figure out how to decompose tokens into function calls until you know all the available operator signatures.

This doesn't make the language impossible to parse (although there are more programs that have to be rejected as untypable) but it would make it slower to compile, and harder to read.

Body:
No.  Besides making code unreadable, it would make the language more ambiguous and deeply context-dependent because you would not be able to associate parameters with function calls until after you know all the operators available.

Consider the expression

a1 + a2 * a3

where all a* vars have type A and you have overloadings

A operator+(A, A) // low precedence
A operator*(A, A) // high precedence
B operator+(A, A) // high precedence
A operator*(B, A) // low precedence

This could be interpreted two different ways

operator+(a1, operator*(a2, a3))

or

operator*(operator+(a1, a2), a3)

With global precedence and associativity rules, the compiler can commit to the first interpretation during parse, but with overridable associativity/precedence, there's no way to figure out how to decompose tokens into function calls until you know all the available operator signatures.

This doesn't make the language impossible to parse (although there are more programs that have to be rejected as untypable) but it would make it slower to compile, and harder to read.


问:
Using captured non-local variables in C++ closures
On this wikipedia page I have found the following sentence regarding closures in C++11:

C++11 closures can capture non-local variables by copy or by reference, but without extending their lifetime.

Does this mean that an existing closure might refer to a non-local variable that has already been de-allocated? In such a case, is there any special care / best practice that one has to follow when using captured non-local variables inside a C++ closure?

答:
Does this mean that an existing closure might refer to a non-local
  variable that has already been de-allocated?

Yes. Extending an object's life-time which was allocated on the stack beyond the execution of the outer function seems to be somewhere between unreasonable and impossible. Also, the compiler won't try to check whether such an extension is needed and magically allocate the object on the heap or something like this. As a programmer you have to be explicit about what is supposed to happen with respect to allocation. If you want to use the free store (aka heap), use the free store. There is nothing magical going on with lambdas. If you make your closure object store the address of some other object that used to live on the stack and you try to access it after it's gone, the behaviour is undefined.

any special care / best practice that one has to follow when using
  captured non-local variables inside a C++ closure?

Just make sure that your lambda does not capture by reference if the lambda object (or a copy of it) outlives the scope it (or the original) was created in. For example, using a lambda which captures by reference as argument to some of the algorithms you find in the algorithm header is perfectly fine.


问:
Does "don't reinvent the wheel" ignore the limits of human memory?
One thing working in Haskell and F# has taught me is that someone in a university smarter than me has probably already found an abstraction for what I'm doing.  Likewise in C# and object-oriented programming, there's probably a library for "it", whatever it is that I'm doing.

There's such an emphasis on reusing abstractions in programming that I often feel a dilemma between: 1) just coding something short and dirty myself or 2) spending the same time to find someone else's more robust library/solution and just using that.

Like recently one of the coders here wrote up a (de)serializer for CSV files, and I couldn't help but think that something like that is probably very easy to find online, if it doesn't already come with the .NET standard APIs.

I don't blame him though, several times working in .NET I've patched together a solution based on what I know, only to realize that there was some method call or object or something  ,often in the same library, that did what I wanted and I just didn't know about it.

Is this just a sign of inexperience, or is there always an element of trade-off between writing new and reusing old?  What I hate the most is when I run across a solution that I already knew about and forgot.  I feel like one person just isn't capable of digesting the sheer quantities of code that comes prepackaged with most languages these days.

答:
First, you need to learn to identify "components" that are generic/reusable enough that a library or 3rd party solution is likely to already exist. Once you do that, realize that, even if you are a good developer, the collective experience of countless developers spending countless hours on the same problem is likely to have produced a solution better than you'll ever be able to do. That doesn't mean you should never "reinvent the wheel", but if you choose to do so, you better have a DAMN good justification for doing so.

There's such an emphasis on reusing abstractions in programming that I often feel a dilemma between: 1) just coding something short and dirty myself or 2) spending the same time to find someone else's more robust library/solution and just using that.

It's worth mentioning that even if it takes you the same amount of time to find an existing library/solution as it does to write it yourself, remember that doing it yourself also means you'll have to maintain it forever. You're not just re-inventing the wheel, but also the entire pit crew to keep it running. Of course, some libraries are buggy or poorly maintained, but these are things you should keep in mind when picking a 3rd party solution.

ContentLicense: CC BY-SA 2.5


问:
Is it a must for every programmer to learn regular expressions?
I am new to programming, and at an interview I got a question on regular expressions; needless to say I couldn't answer. So I was wondering whether I should learn regular expression? Is it a must for every programmer of all fields? Or it is a must for programming for some particular fields?

Related questions:

Why are regular expressions so morbidly attractive?

When you should NOT use Regular Expressions?

答:
Rob Pike doesn't think so:

Regular expressions are hard to write, hard to write well, and can be
  expensive relative to other technologies. Standard lexing and parsing
  techniques are so easy to write, so general, and so adaptable there's
  no reason to use regular expressions.

Another way to look at it is that lexers and parsing are matching
  statically-defined patterns, but regular expressions' strength is that
  they provide a way to express patterns dynamically. They're great in
  text editors and search tools, but when you know at compile time
  whatall the things are you're looking for, regular expressions bring
  far more generality and flexibility than you need.

Encouraging regular expressions as a panacea for all text processing
  problems is not only lazy and poor engineering, it also reinforces
  their use by people who shouldn't be using them at all.

It's worth noting that Pike acknowledges they have a place, of course, and IMHO, regular expressions are a pretty powerful tool, one that's absolutely rewarded the time I've spent learning to use, and from that standpoint, I'd absolutely recommend learning them. But it's possible the real issue is that they're a band-aid which has let me get away with knowing less about lexing and parsing than I should. :)


答:
printf can cause bugs due to the lack of type safety.  There are a few ways of addressing that without switching to iostream's << operator and more complicated formatting:

Some compilers (such as GCC and Clang) can optionally check your printf format strings against the printf arguments and can display warnings such as the following if they don't match.
```warning: conversion specifies type 'int' but the argument has type 'char *'```

The typesafeprintf script can preprocess your printf-style calls to make them type-safe.

Libraries such as Boost.Format and FastFormat let you use printf-like format strings (Boost.Format's in particular are almost identical to printf) while keeping iostreams' type safety and type extensibility.

Title: printf - source of bugs?

Body:
printf can cause bugs due to the lack of type safety.  There are a few ways of addressing that without switching to iostream's << operator and more complicated formatting:

Some compilers (such as GCC and Clang) can optionally check your printf format strings against the printf arguments and can display warnings such as the following if they don't match.

warning: conversion specifies type 'int' but the argument has type 'char *'

The typesafeprintf script can preprocess your printf-style calls to make them type-safe.

Libraries such as Boost.Format and FastFormat let you use printf-like format strings (Boost.Format's in particular are almost identical to printf) while keeping iostreams' type safety and type extensibility.


答:
printf, particularly in cases where you might care about performance (such as sprintf and fprintf) is a really strange hack. It constantly amazes me that people who pound on C++ due to miniscule performance overhead related to virtual functions will then go on to defend C's io.

Yes, in order to figure out the format of our output, something that we can know 100% at compile time, let's parse a fricken format string at runtime inside a massively weird jump table using inscrutable format codes!

Of course these format codes couldn't be made to match the types they represent, that would be too easy... and you're reminded every time you lookup whether it's %llg or %lg that this (strongly typed) language makes you figure out types manually to print/scan something, AND was designed for pre-32bit processors.

I'll admit that C++'s handling of format width and precision is bulky and could use some syntactic sugar, but that doesn't mean you have to defend the bizarre hack that is C's main io system. The absolute basics are pretty easy in either language (although you should probably be using something like a custom error function/error stream for debug code anyways), the moderate cases are regex-like in C (easy to write, hard to parse/debug), and the complex cases impossible in C.

(If you use the standard containers at all, write yourself some quick templated operator<< overloads that allow you to do things like std::cout << my_list << "\n"; for debug, where my_list is of type list<vector<pair<int,string> > >.)

Title: printf - source of bugs?


问:
Extend functionallity of a class: inheritance or java's dynamic proxy
Currently I have three classes and respective interfaces and respective builders:

Tree: the data structure (implemented in SimpleTree)

ProbabilityTree: is a Tree with added functionality to randomly select child nodes and to adjust the probability of selecting a node (implemented in ProbabilityTreeImpl).

DynamicTree: is a ProbabilityTree which dynamically constructs nodes when a requested node doesn't exist yet.

The client code needs Trees that support both random selection of nodes, as provided by ProbabilityTree, and the tree dynamically growing when yet unexisting nodes are requested, as provided by DynamicTree.

NOTE: Currently all three trees are immutable after having been build; for DynamicTree this means clients cannot add or remove nodes, but the tree itself can automatically change.

NOTE: See Github gist with the five Java classes for the code.

There are at least two issues with this design:

DynamicTree is derived from ProbabilityTree, while conceptionally these two capabilities are unrelated (i.e. orthogonal).

Using inheritance to add functionally is often considered "bad design" (correct me if I'm wrong here).

An alternative design would be to decouple ProbabilityTree and DynamicTree using something similar to the decorator and/or adapter pattern.  Using Java's dynamic Proxy might enable "decorators" that extend the interface and that can decorate other Trees with extended interfaces; i.e.:

```<code>TreeDecorator implements InvocationHandler, ... {
    Tree adapted;
    ...
    Object invoke(Method method, Object[] args) {
        if( «this class can/should handle method» ) {
            return method.invoke(this, args);
        } else if ( «this.adapted can/should handle method» ){
            return method.invoke(adapted, args);
        }
    };
}
</code>```

Again there are some issue's:

Using Proxy makes the code more difficult to understand.

What shall I do? Use inheritance to extend functionallity, use dynamic proxy, or something else?

答:
I can think of 3 reasonable options, depending on what you really need (right now), and how complex your code is.

(What you currently call DynamicTree, I call DynamicProbabilityTree)

If the only thing you really need is a DynamicProbabilityTree, and you feel like your code is simple enough to fit in one class, put all your code inside DynamicProbablityTree, and get rid of your other classes.

If the only thing you really need is a DynamicProbabilityTree, but you feel like you code is too complex to fit into one class, keep your code for the tree structure in SimpleTree, and put the dynamic and probability code in DynamicProbabilityTree. I would recommend that DynamicProbabilityTree contain and delegate to a Tree instead of inheriting; inheriting would also work.

If you really need a SimpleTree, ProbabilityTree (that is not dynamic), DynamicTree (that does not do probability), and DynamicProbabilityTree, use the Decorator pattern.


问:
Why is using System.out.println() so bad?
Of course, it is very good use to use a logging framework for the error messages or warnings. But sometimes I use System.out.println() if I want to try something new in a short time.

Is it really so bad using System.out.println() for some quick test?

答: System.out is just a wrapped BufferedOutputStream.  This is likely similar to any logging framework you will use, the frameworks just provide more functionality in the form of configuration and destination of your log output

ContentLicense: CC BY-SA 4.0


答:
All stdout is buffered, and thus it is possible that your program will crash after you called println(), but before it reaches the screen.

With that being said, this scenario is really unlikely. Go ahead and use it, but just keep that minor limitation in the back of your mind.

Title: Why is using System.out.println() so bad?

Body:
Of course, it is very good use to use a logging framework for the error messages or warnings. But sometimes I use System.out.println() if I want to try something new in a short time.

Is it really so bad using System.out.println() for some quick test?


问:
What alternatives are there for cross cutting concerns other than aspect oriented programming?
Aspect oriented programming promises to deal with cross cutting concerns, but I'm not completely sold on it yet. Have there been any other attempts to deal with this problem?</p>

答:
Two other options that I haven't seen explored yet:

Functional Programming with Monads and Arrows

In FP you represent a cross-cutting concern like anything else: as something you pass in on a function call.  Since doing that explicitly gets tedious, you can use Monads (or maybe Arrows) to hide away the extra information being passed along.

The most common AOP example is logging.  With Monads, you would create a "Logger" monad that keeps a list of messages.  Any functions you perform through the LoggerMonad have the ability to post a log message.  With Arrows, you would model the entire data flow of the application, and would work a logging routine into the model where appropriate.  I think.  Arrows are pretty complex.

Entity/Component-Based Programming

Something I've been researching and experimenting with for a game engine.  Instead of "objects" like in OOP, you decompose everything into packets of data (components) and services that operate over a type of component.  Components are grouped together by common IDs, like in a relational database, and groups of linked components are the Entities.  To add logging in such a system, you would add a new logging service the triggers based on which components are passed through it.

Both methods allows for one to easily work a cross-cutting change in very easily, but both are high-level architectural models.  So you would probably need to be using them from the beginning.  The Component model can, theoretically, be worked into an existing OOP system.  I guess monads could be too if your language is powerful enough.


答:
As is often the case, the answer is “it depends”. If your application already has a logging framework in place, then you may as well use it. It cannot be less capable than println(), and you may benefit from other features it provides—stack traces, extra context, better formatting, and so on. There is also the distinct possibility that logging frameworks offer better error recovery, ensuring that your logs are successfully written even in the event of a catastrophic failure.

So the question becomes when to add a logging system in the first place. This is a judgement call: you don’t want to add it too early, only to find out you really have no need for it. You also don’t want to add it too late, and do excessive work converting from your ad-hoc solution.

If you discover that you’re doing a lot of logging with println(), then your codebase is trying to tell you that it’s experiencing growing pains. At that point, it’s worth it to invest in proper logging.


问:
Algorithm Analysis: Frequencies of Execution
I am currently reading the Analysis of Algorithms section in Algorithms, 4th Edition and I'm trying to understand how the author calculated (N^2)/2 and (N^3)/6 frequencies of execution in the code snippet below (here is the full code):

```<code>public class ThreeSum
{
    public static int count(int[] a) {
            int N = a.length;
            int cnt = 0;
            for (int i = 0; i < N; i++) { // <---------------- 1
                for (int j = i+1; j < N; j++) { // <---------- N
                    for (int k = j+1; k < N; k++) { // <------ N^2/2
                        if (a[i] + a[j] + a[k] == 0) { // <--- N^3/6
                            cnt++;  // <---------------------- x
                        }
                    }
                }
            }
            return cnt;
        }
}
</code>```

Why divide N^2 by 2? Why divide N^3 by 6?

答: It's a part of using "partial sums" to determine the frequencies of execution. The specific section is "Useful Shortcuts" where it shows what eventuality exists for a given starting term order in a sequence.</p>


答:
It's not bad at all. The notion may stem from the fact that it's very simple and not as sophisticated as using a dedicated logging framework in your application.

However, this is not to say that it's an invalid approach. I've used it many times to check application flow after some black magic voodoo programming hijinks.


问:
Can an open source solution match or surpass Team Foundation Server's features?
Team Foundation Server offers a version control system, but with many more side features, such as bug tracking, user stories, project planning, and it is all integrated into visual studio.
Someone put a more complete list of features over here:

Over the past year I have been working with Mercurial and from the moment I typed "hg init" I was in love. My new colleagues are convinced that even though other scm solutions are probably better, TFS provides a better complete package for teams.

What I would like to know is whether it is better to just use TFS, or to go the open source route and select various solutions and integrate them to get a better result, and if its even possible to get that level of integration?

So in summation: Can it be done and is it better to go for various OSS tools?

答:
Sometimes certain software solutions want to do everything and that drives their doom.

Mercurial, Git and others are just focused on being good VCSs, and they are probably the best ones around (mind the advantages that you get from having a distributed version control system).

IMHO, if you want:

The best bug tracking you go with Jira, Redmine, ...

The best wiki you go with Confluence, dokuwiki, ...

The best agile tool you go with GreenHopper, Agilo, ...

The best DVCS repository management you go with Rhodecode, Stash

The best online DVCS repository management you go with Bitbucket, Github, ...

The best SCM/VCS you go with Mercurial, Git, ...

It is harder to find one thing that gets all things right than all the right things.

And BTW, as a SCM/VCS, Mercurial is undoubtedly a better tool than TFS for the sole fact of being distributed (and if you don't agree, you are ugly and stupid —Linus Torvalds).

Read the following article to finish convincing yourself and your team: http://hginit.com/00.html (Subversion is centralized like TFS)


问:
Choosing the right programmer among a class of undergrads
I am a CS undergrad but I landed a programming job last year and I like it a lot. We are currently 3 programmer in the development section of the company and we have to work with pretty much anything were asked to do. We deal with many different languages and learn them as needed for some quick jobs etc etc.

We want to hire a 4th programmer and I'm asked to suggest some students in my class, a year younger, since I failed a class. I don't really know any of these guys except my teammates which I wouldn't suggest. We don't really want to interview them all so I thought we could make a little challenge to help us choose who to interview. We're in need of someone who understand the business even though they're new to it, and likes to learn new stuff and code. Any idea on a programming challenge or a kind of letter saying why we should take them?

TL;DR: We need a new undergrad programmer, we want the best to come to us without interviewing them all. Any challenge or test you could suggest?

答: Say that the barrier to interviewing is to solve X problems from Project Euler (http://projecteuler.net/) and at the interview ask to see their answers, and perhaps let them do the FizzBuzz program while you watch.</p>


问:
Macintosh OS10.8 user experience with 'identified developer' downloads?
I work on a Windows/Mac cross platform application that is sometimes downloaded from web sites.  It is sometimes re-branded by and sold by third parties.

I'm the 'windows guy', my Mac counterpart is on vacation.

I'm getting some questions from a customers about what the Mac user experience will be if we sign the Mac installer with an Apple Developer certificate in our build system with our company name.  For some reason this customer doesn't want to sign the app themselves, but doesn't want our company name to pop up in front of the user.

Assuming the user's OS 10.8 Gatekeeper is set to allow downloads from both the Apple App Store and from 'identified developers', does the user see any warning dialog that provides certificate information similar to he Windows User Access Control prompts?

In my tests it looks like internet downloaded Apple signed apps are just trusted by OS10.8, and will run without anything resembling a Windows UAC prompt.  The user experience seems to be:

1) Download application from internet signed by an 'Apple identified developer'.

2) Click the application on web browser download list or using finder.

3) Application installer runs with no warning or caution dialogs.

Is this correct?

Also, is there some way on OS10.8 for the user to view in human readable form the 'identified developer' certificate information of a signed file?

答:
To your first question:

The user experience seems to be:

1) Download application from internet signed by an 'Apple identified
  developer'.

2) Click the application on web browser download list or using finder.

3) Application installer runs with no warning or caution dialogs.

Is this correct?

Yes. That seems about right --provided you are registered with Apple and your developer ID has been approved for signing "trusted" applications. For more details on the user experience please refer to this guide. If you are not registered with Apple, then your users will get a warning (if they have not disabled GateKeeper) saying that the application is not verified and poses a risk to the system etc… (examples on the guide page I cited).

Edit: Also note that this experience would be for the defaults Apple ships with OS X 10.8 (as of today). It is possible for people/corporations to design their custom signature policies (e.g., only allow code from my own AppStore). For more details please see this document.

Now for your second question,

Also, is there some way on OS10.8 for the user to view in human
  readable form the 'identified developer' certificate information of a
  signed file?

To view the sign information please use the codesign tool. Example,

```<code>monstertruck monstertruck $ cd /Applications/iTunes.app/Contents/MacOS
monstertruck /Applications/iTunes.app/Contents/MacOS $ codesign --display --verbose iTunes
Executable=/Applications/iTunes.app/Contents/MacOS/iTunes
Identifier=com.apple.iTunes
Format=bundle with Mach-O universal (i386 x86_64)
CodeDirectory v=20100 size=101125 flags=0x0(none) hashes=5048+5 location=embedded
Signature size=4064
Info.plist entries=36
Sealed Resources rules=13 files=348
Internal requirements count=1 size=184
</code>```

More details on how to sign code and view code signatures can be found here.

Body:
To your first question:

The user experience seems to be:

1) Download application from internet signed by an 'Apple identified
  developer'.

2) Click the application on web browser download list or using finder.

3) Application installer runs with no warning or caution dialogs.

Is this correct?

Yes. That seems about right --provided you are registered with Apple and your developer ID has been approved for signing "trusted" applications. For more details on the user experience please refer to this guide. If you are not registered with Apple, then your users will get a warning (if they have not disabled GateKeeper) saying that the application is not verified and poses a risk to the system etc… (examples on the guide page I cited).

Edit: Also note that this experience would be for the defaults Apple ships with OS X 10.8 (as of today). It is possible for people/corporations to design their custom signature policies (e.g., only allow code from my own AppStore). For more details please see this document.

Now for your second question,

Also, is there some way on OS10.8 for the user to view in human
  readable form the 'identified developer' certificate information of a
  signed file?

To view the sign information please use the codesign tool. Example,

monstertruck monstertruck $ cd /Applications/iTunes.app/Contents/MacOS
monstertruck /Applications/iTunes.app/Contents/MacOS $ codesign --display --verbose iTunes
Executable=/Applications/iTunes.app/Contents/MacOS/iTunes
Identifier=com.apple.iTunes
Format=bundle with Mach-O universal (i386 x86_64)
CodeDirectory v=20100 size=101125 flags=0x0(none) hashes=5048+5 location=embedded
Signature size=4064
Info.plist entries=36
Sealed Resources rules=13 files=348
Internal requirements count=1 size=184

More details on how to sign code and view code signatures can be found here.


答:
I have often the problem that System.out.print uses the "system default" codepage, which is often UTF-8 under Linux, but some crapped MS stuff under Windows.

This may lead to unicode characters that are or are not correctly printed to the screen, depending on where the program runs.

I therefore prefer a custom PrintWriter over System.out


答:
It is bad if you are working on a non-trivial program and you

Are using System.out as a crutch instead of automated unit testing (JUnit)

Spend lots of time creating and deleting or commenting/uncommenting System.out statements


问:
Pair programming remotely with Visual Studio?
What tools exist to facilitate pair programming with Visual Studio when the programmers are not in the same physical location? At the moment we are thinking voice (Skype?) plus remote desktop (VNC? TeamViewer?), but it would be good to know of other suggestions and experiences. Also, is there anything more integrated with Visual Studio?

A bit more background: we are two experienced developers with who have collaborated well for a long time on a large mature project (ASP.NET, Windows Forms and SQL Server). However we are not usually working on the same part of the code base at the same time. We intend to spend some weeks doing substantial refactoring and it would be ideal if we were able to do this work with a pair-programming approach.

答:
Have you tried VS Anywhere?

Is what you are looking for, allows you to share code and designers from Visual Studio and worlwide,

Is free for students, open source projects and non-commercial use

Works with VS2010 and VS2012

take a look https://vsanywhere.com

Regards


答:
As revealed in the comments, the real question being asked is, Why do static code analysis tools flag uses of System.out.println?

The reason is that sending messages to stdout is usually inappropriate in a production environment. If you're coding a library, the library should return information to its caller, not print to stdout. If you're coding a GUI app, the information should be presented to the user, not to where stdout happens to be pointing (which might be nowhere). If you're coding a server (or something that runs in a server-side container) you should be using whatever logging facility the framework has provided. And so forth.

But if you're using println for debugging or development, or you're writing a program and reads stdin and writes to stdout, println is perfectly fine. There's nothing wrong with it for those kinds of cases.


答:
printf is, in my own opinion, a far more flexible output tool for dealing with variables than any of the CPP stream outputs. For example:

```<code>printf ( "%d in ANSI = %c\n", j, j ); /* Perfectly valid... if a char ISN'T printing right, I'd just check the integer value to make sure it was okay. */
</code>```

However, where you may want to use the CPP << operator is when you overload it for a particular method... for example to get a dump of an object that holds the data of a particular person, PersonData....

```<code>ostream &operator<<(ostream &stream, PersonData obj)
{
 stream << "\nName: " << name << endl;
 stream << " Number: " << phoneNumber << endl;
 stream << " Age: " << age << endl;
 return stream;
}
</code>```

For that, it would be far more effective to say (assuming a is an object of PersonData)

```<code>std::cout << a;
</code>```

than:

```<code>printf ( "Name: %s\n Number: %s\n Age: %d\n", a.name, a.number, a.age );
</code>```

The former is far more in-line with the principle of encapsulation (No need to know the specifics, private member variables), and is also easier to read.

Title: printf - source of bugs?

Body:
printf is, in my own opinion, a far more flexible output tool for dealing with variables than any of the CPP stream outputs. For example:

printf ( "%d in ANSI = %c\n", j, j ); /* Perfectly valid... if a char ISN'T printing right, I'd just check the integer value to make sure it was okay. */

However, where you may want to use the CPP << operator is when you overload it for a particular method... for example to get a dump of an object that holds the data of a particular person, PersonData....

ostream &operator<<(ostream &stream, PersonData obj)
{
 stream << "\nName: " << name << endl;
 stream << " Number: " << phoneNumber << endl;
 stream << " Age: " << age << endl;
 return stream;
}

For that, it would be far more effective to say (assuming a is an object of PersonData)

std::cout << a;

than:

printf ( "Name: %s\n Number: %s\n Age: %d\n", a.name, a.number, a.age );

The former is far more in-line with the principle of encapsulation (No need to know the specifics, private member variables), and is also easier to read.


问:
Use constructor or setter method?
I am working on a UI code where I have an Action class, something like this -

```<code>public class MyAction extends Action {
    public MyAction() {
        setText("My Action Text");
        setToolTip("My Action Tool tip");
        setImage("Some Image");
    }
}
</code>```

When this Action class was created, it was pretty much assumed that the Action class won't be customizable (in a sense - its text, tooltip or image will be not be changed anywhere in the code). Now, we are in need of changing the action text at some location in code. So, I suggested my co-worker to remove the hardcoded action text from the constructor and accept it as an argument, so that everybody is forced to pass the action text. Something like this code below -

```<code>public class MyAction extends Action {
    public MyAction(String actionText) {
        setText(actionText);
        setTooltip("My Action tool tip");
        setImage("My Image");
    }
}
</code>```

He, however, thinks that since setText() method belongs to base class it can be flexibly used to pass the action text wherever action instance is created. That way, there is no need to change the existing MyAction class. So his code would look something like this.

```<code>MyAction action = new MyAction(); //this creates action instance with the hardcoded text
action.setText("User required new action text"); //overwrite the existing text.
</code>```

I am not sure if that is a correct way to deal with problem. I think in above mentioned case user is anyway going to change the text, so why not force him while constructing the action? The only benefit I see with the original code is that user can create Action class without much thinking about setting text.

答:
Just like kevin cline said in his answer, I think the way to go is to create a fluent API. I would just like to add that the fluent API works better when you have more than one property you may use.

It will make your code more readable, and from my point of view more easy and, aham, "sexy" to write.

In your case it would go like this (sorry for any typo, it has been a year since I wrote my last java program):

```<code> public class MyAction extends Action {
    private String _text     = "";
    private String _tooltip  = "";
    private String _imageUrl = "";

    public MyAction()
    {
       // nothing to do here.
    }

    public MyAction text(string value)
    {
       this._text = value;
       return this;
    }

    public MyAction tooltip(string value)
    {
       this._tooltip = value;
       return this;
    }

    public MyAction image(string value)
    {
       this._imageUrl = value;
       return this;
    }
}
</code>```

And the usage would be like this:

```<code>MyAction action = new MyAction()
    .text("My Action Text")
    .tooltip("My Action Tool tip")
    .image("Some Image");
</code>```

Title: Use constructor or setter method?

Body:
Just like kevin cline said in his answer, I think the way to go is to create a fluent API. I would just like to add that the fluent API works better when you have more than one property you may use.

It will make your code more readable, and from my point of view more easy and, aham, "sexy" to write.

In your case it would go like this (sorry for any typo, it has been a year since I wrote my last java program):

 public class MyAction extends Action {
    private String _text     = "";
    private String _tooltip  = "";
    private String _imageUrl = "";

    public MyAction()
    {
       // nothing to do here.
    }

    public MyAction text(string value)
    {
       this._text = value;
       return this;
    }

    public MyAction tooltip(string value)
    {
       this._tooltip = value;
       return this;
    }

    public MyAction image(string value)
    {
       this._imageUrl = value;
       return this;
    }
}

And the usage would be like this:

MyAction action = new MyAction()
    .text("My Action Text")
    .tooltip("My Action Tool tip")
    .image("Some Image");


答:
Welcome to the world of programming.  This issue will be the subject of many disagreements between you and your future colleagues.  You have two options:

Roll your own.

Build something on top of someone else's solution.

I think there are times where both solutions are appropriate.  For instance, I would prefer to avoid rolling my own CSV parser of ORM if I can avoid it mostly because it's pretty tedious work.  On the other hand, libraries are often restricted.  I would say that for every project I've worked on, I've encountered libraries that would solve my problem perfectly if not for this one shortcoming.  Or sometimes a library is exactly what you need when you first start out doing something, but is more harm than help once you need to make changes.

In general though, I'd advise against trying to find "correct" answers because they don't exist.  When in doubt, just go with your gut.  I once heard someone say that experience is defined by how many stupid mistakes you make.  So usually, you'll either learn something or make something that works.  Either way, it isn't all bad.

Title: Does "don't reinvent the wheel" ignore the limits of human memory?

Body:
One thing working in Haskell and F# has taught me is that someone in a university smarter than me has probably already found an abstraction for what I'm doing.  Likewise in C# and object-oriented programming, there's probably a library for "it", whatever it is that I'm doing.

There's such an emphasis on reusing abstractions in programming that I often feel a dilemma between: 1) just coding something short and dirty myself or 2) spending the same time to find someone else's more robust library/solution and just using that.

Like recently one of the coders here wrote up a (de)serializer for CSV files, and I couldn't help but think that something like that is probably very easy to find online, if it doesn't already come with the .NET standard APIs.

I don't blame him though, several times working in .NET I've patched together a solution based on what I know, only to realize that there was some method call or object or something  ,often in the same library, that did what I wanted and I just didn't know about it.

Is this just a sign of inexperience, or is there always an element of trade-off between writing new and reusing old?  What I hate the most is when I run across a solution that I already knew about and forgot.  I feel like one person just isn't capable of digesting the sheer quantities of code that comes prepackaged with most languages these days.


问:
Expected behavior when an request for a collection will have zero items
Let's say you are given the following...

```<code>List<Thing> theThings = fubar.Things.All();
</code>```

If there were nothing to return, what would you expect fubar.Things.All() to return?

Edit:
Thanks for the opinions. I'll wait a bit and accept the entry with the most ups.

I agree with the responses so far, particularly those suggesting an empty collection. A vendor provided an API with several calls similar to the example above. A vendor who did $4.6 million in revenue via their API(s) last year, BTW. They do something I fundamentally disagree with -- they throw an exception.

答:
The two solutions they mean different things.

If there are just zero of the thing you are returning, you ALWAYS return an empty collection!  Take the case of a directory listing.  If there are no files in the directory you return an empty collection of files.

On the other hand, if the directory doesn't exist, that's not really appropriate. "I can't return anything" means something compeltely different.  In that case you should either return null or throw an exception depending on the situation, don't just return an empty collection like nothing was wrong.


问:
Could implicit static methods cause problems?
This is a purely hypothetical question.

Say I create a class method that contains no references to instance variables or other resources.  For example (C#):

```<code>protected string FormatColumn(string value, int width)
{
    return value.Trim().PadLeft(width);
}
</code>```

As far as I can see, there is absolutely no reason why this method could not be declared static:

It only uses method-scope variables.

It doesn't override a base class method.

It's not virtual or abstract.

My questions are:

Is there any benefit to calling a static method over an instance method?

If so, why doesn't the compiler implicitly convert this to a static method?

I'm certain I've missed some key point here.  Any ideas?

答:
You should read this article about Code Analysis rule #CA1822, which states:

Members that do not access instance data or call instance methods can
  be marked as static (Shared in Visual Basic). After you mark the
  methods as static, the compiler will emit nonvirtual call sites to
  these members. Emitting nonvirtual call sites will prevent a check at
  runtime for each call that makes sure that the current object pointer
  is non-null. This can achieve a measurable performance gain for
  performance-sensitive code. In some cases, the failure to access the
  current object instance represents a correctness issue.


问:
Don't Use "Static" in C#?
I submitted an application I wrote to some other architects for code review. One of them almost immediately wrote me back and said "Don't use static. You can't write automated tests with static classes and methods. static is to be avoided."

I checked and fully 1/4 of my classes are marked static. I use static when I am not going to create an instance of a class because the class is a single global class used throughout the code.

He went on to mention something involving mocking, IOC/DI techniques that can't be used with static code. He says it is unfortunate when 3rd party libraries are static because of their un-testability.

Is this other architect correct?

update: here is an example:

APIManager - this class keeps dictionaries of 3rd party APIs I am calling along with the next allowed time. It enforces API usage limits that a lot of 3rd parties have in their terms of service. I use it anywhere I am calling a 3rd party service by calling Thread.Sleep(APIManager.GetWait("ProviderXYZ")); before making the call. Everything in here is thread safe and it works great with the TPL in C#.

答:
He is too general about it. He is correct, it hinders testing. However, static classes and methods have their place and it really depends on the context. Without code examples you can't really tell.

I use static when I am not going to create an instance of a class because the class is a single global class used throughout the code.

This can be severe code smell. What are you using the classes for? To hold data? To access a database? Then he is correct. You should look in to dependency injection in that case, as such a static class is effectively an implicit singleton.

If you are using them for extension methods or helpers that don't change the state and just operate on the parameters you provide, those usually are fine.

OwnerDisplayName: Josh Brown

Title: Don't Use "Static" in C#?

OwnerDisplayName: Femaref


答: It depends on whether the static classes maintain state or not.  Personally, I have no problem with stateless functions thrown together in a static class.</p>

Title: Don't Use "Static" in C#?

Body:
I submitted an application I wrote to some other architects for code review. One of them almost immediately wrote me back and said "Don't use static. You can't write automated tests with static classes and methods. static is to be avoided."

I checked and fully 1/4 of my classes are marked static. I use static when I am not going to create an instance of a class because the class is a single global class used throughout the code.

He went on to mention something involving mocking, IOC/DI techniques that can't be used with static code. He says it is unfortunate when 3rd party libraries are static because of their un-testability.

Is this other architect correct?

update: here is an example:

APIManager - this class keeps dictionaries of 3rd party APIs I am calling along with the next allowed time. It enforces API usage limits that a lot of 3rd parties have in their terms of service. I use it anywhere I am calling a 3rd party service by calling Thread.Sleep(APIManager.GetWait("ProviderXYZ")); before making the call. Everything in here is thread safe and it works great with the TPL in C#.

OwnerDisplayName: Larsenal


答:
One of the advantages that you get from IoC/DI is that most interactions between classes are negotiated between interfaces. This makes unit testing easy because the interfaces can be mocked automatically or semi-automatically, and therefore each of the parts can be tested for inputs and outputs.  Furthermore, beyond testabilty, putting interfaces between everything allows you to have the most modular code possible -- you can easily replace one implementation without quite so much worry that you're screwing up dependencies.

Because C# doesn't have metaclasses, a class can't implement an interface using static features, so static features of classes end screw up any effort to implement a pure IoC/DI object model.  That is to say, you can't create a mock to test them, and you have to create real dependencies.

If your company/project is invested heavily in doing IoC, this of course is a reasonable concern, and the pain you're going through is for the gain of all.  From an architectural standpoint, however, I personally don't think that any model should be followed to the grave.  There are some things that make sense to implement using static methods -- the singleton design strategy, for instance.  I'm less inclined towards static classes myself because I think they tend to start to lose the advantages of OO, but there are times when a library class is probably a more natural expression of something than an engine.

Commenter reminds me of extension methods, which of course have to be in static classes in C#.  That's legit, and is an example of how pure IoC doesn't work super well in C#, at least if you're trying to take advantage of the breadth of the language.

Title: Don't Use "Static" in C#?

OwnerDisplayName: jwrush


答:
I checked and fully 1/4 of my classes are marked "static". I use
  static when I am not going to create an instance of a class because
  the class is a single global class used throughout the code.

The best thing to do is to try and unit-test your code. Try designing tests that are repeatable, independent, simple and test only one method at a time. Try running your tests in different randomised order. Can you get stable "green" build?

If yes, that's a valid point to defend your code. If, however, you have difficulties, then maybe you should go for instance-based methods.

Title: Don't Use "Static" in C#?

OwnerDisplayName: oleksii


答:
Static classes are sometimes misused and should be:

a singleton (where the non-static class has a static member and a public static Instance variable to retrieve/create it only once.

a method in another class (where the state matters). If you have a member that is using no data from that class, probably it should not be part of that class.

It also might be a so called 'utility' function, and part of a utility class. Utility classes are classes that contain only static methods and serve as helper functions without any context.

Title: Don't Use "Static" in C#?

OwnerDisplayName: Michel Keijzers


答:
I have been using static properties for things that are common to all instances of a class. And I have been using static methods to get groups of class objects. I am by no means an expert but this has been working for me so far.

PHP example:

```<code>class vendorData {
  private static $data_table = 'vendor_data'; // static property
  private $id; // instance property
  private $name; // instance property

  public function __construct($vendor_id) {
    if(!self::validId($vendor_id) ) { // static method
      return false; // id doesn't exist
    }
    $this->id = $vendor_id; // id has been validated
    $this->getProperties(); // object method
  }

  private static function validId($vendor_id) {
    // send db query to find if the id exists
    // return true/false;
  }

  private function getProperties() { // object method
    $sql = "SELECT * FROM `{self::$data_table}` // using static property
        WHERE `id` = {$this->id}"; // using object instance property
    // get resultset
    foreach($result as $property => $value) {
      $this->$property = $value; // object instance properties all set
    }
  }

  // and here
  public static function getBy($property,$value) { // static method to return object array
    $sql = "SELECT `id` FROM `{self::$data_table}` // using static property
      WHERE `$property` = '$value'";
    // send query, get $ids array
    $obj_array = array();
    foreach($ids as $id) {
      // create array of current class objects using special static keyword
      // meaning of static here is different than in property/method declarations
      $obj_array[$id] = new static($id);
    }
    return $obj_array;
  }
}
</code>```

Title: Don't Use "Static" in C#?

Body:
I have been using static properties for things that are common to all instances of a class. And I have been using static methods to get groups of class objects. I am by no means an expert but this has been working for me so far.

PHP example:

class vendorData {
  private static $data_table = 'vendor_data'; // static property
  private $id; // instance property
  private $name; // instance property

  public function __construct($vendor_id) {
    if(!self::validId($vendor_id) ) { // static method
      return false; // id doesn't exist
    }
    $this->id = $vendor_id; // id has been validated
    $this->getProperties(); // object method
  }

  private static function validId($vendor_id) {
    // send db query to find if the id exists
    // return true/false;
  }

  private function getProperties() { // object method
    $sql = "SELECT * FROM `{self::$data_table}` // using static property
        WHERE `id` = {$this->id}"; // using object instance property
    // get resultset
    foreach($result as $property => $value) {
      $this->$property = $value; // object instance properties all set
    }
  }

  // and here
  public static function getBy($property,$value) { // static method to return object array
    $sql = "SELECT `id` FROM `{self::$data_table}` // using static property
      WHERE `$property` = '$value'";
    // send query, get $ids array
    $obj_array = array();
    foreach($ids as $id) {
      // create array of current class objects using special static keyword
      // meaning of static here is different than in property/method declarations
      $obj_array[$id] = new static($id);
    }
    return $obj_array;
  }
}

OwnerDisplayName: Buttle Butkus


答: I'll say the principles they have are ok but the statement (don't use statics) may be wrong. How much is your code coverage? if the number is high and you are comfortable with the unit testing of your app, then you are ok. If not, then I would suggest review the code. You may find static classes are the reason or not, it will depend on a lot of things.</p>

Title: Don't Use "Static" in C#?

OwnerDisplayName: ivowiblo


问:
Language-agnostic libs every programmer should consider learning?
Assuming the language provides it, what are some things to do or libraries to use that every programmer should know?

My list would be

Regular Expressions

Named Pipes

standard IO (std in/out/error)

Executing outside executables (like imagemagik and your own scripts)

How to grab an HTTP page as a string (mostly for updates and grabbing configs from servers)

I have a similar questions about tools. Also I am looking for specific answers. I don't want answers that can be done in different ways (such as learn how to synchronize threads).

I know how to do the above in 3+ languages. There always seems to be things programmers don't know how to do which can make their lives easier. For a long time I didn't know what regular expression was (although I did hear of it) and I was surprised how many people who tried to make a toolchain or complex app and did not know how to (or that you could) get the stdout from an exe they launched (they checked for errors in a very weird way or just didn't and hope it produce the expected results).

What do you think is useful, not well known and should be something every senior (or starting out) programmer should know?

答: Data structures and algorithms.  No matter what language you're using, chances are good you will have a hash table, vector, etc.  And algorithms can be translated from language to language.</p>


答:
The answers already posted cover a lot of really good points, but there is one that seems to be missing:

Static fields are never garbage collected.

This is really important if you have an app with a lot of memory constraints, and this pattern can be very common when people try to implement a cache.

Static functions are not nearly as bad, but everyone else has covered this in enough detail already.

Title: Don't Use "Static" in C#?


答:
This is an opinion rather than sure solid facts, I present it here as it may be of help.  here it goes:

One main concern with statics is thread safety. Static fields within the static classes (rather than static methods themselves) may cause the unexpected results when multiple threads are in action.

Is there any benefit to calling a static method over an instance method?

Yes, assuming the method uses an instance variable of some sort such as a counter for example, If you do this you are sure that the variables used within the instance method will be allocated separately for each object. You may choose to lock your object and the results would be guaranteed to be correct when multiple threads access it.

why doesn't the compiler implicitly convert this to a static method?

I really don't know for sure what the compiler does, but if it does not turn such methods to static methods, one reason for that may be because of thread safety. This is because, the compiler will have to tweak the code with locks to make it return the correct result. Locks slows down the execution in mulch-threaded processing.

Edit: Fixed a type as suggested by @WinstonEwert's comment.

Title: Could implicit static methods cause problems?

Body:
This is a purely hypothetical question.

Say I create a class method that contains no references to instance variables or other resources.  For example (C#):

```<code>protected string FormatColumn(string value, int width)
{
    return value.Trim().PadLeft(width);
}
</code>```

As far as I can see, there is absolutely no reason why this method could not be declared static:

It only uses method-scope variables.

It doesn't override a base class method.

It's not virtual or abstract.

My questions are:

Is there any benefit to calling a static method over an instance method?

If so, why doesn't the compiler implicitly convert this to a static method?

I'm certain I've missed some key point here.  Any ideas?