问:
Why did memory-managed languages like Java, Javascript, and C# retain the `new` keyword?
The new keyword in languages like Java, Javascript, and C# creates a new instance of a class.

This syntax seems to have been inherited from C++, where new is used specifically to allocate a new instance of a class on the heap, and return a pointer to the new instance.  In C++, this is not the only way to construct an object. You can also construct an object on the stack, without using new - and in fact, this way of constructing objects is much more common in C++.

So, coming from a C++ background, the new keyword in languages like Java, Javascript, and C# seemed natural and obvious to me.  Then I started to learn Python, which doesn't have the new keyword.  In Python, an instance is constructed simply by calling the constructor, like:

```<code>f = Foo()
</code>```

At first, this seemed a bit off to me, until it occurred to me that there's no reason for Python to have new, because everything is an object so there's no need to disambiguate between various constructor syntaxes.

But then I thought - what's really the point of new in Java?  Why should we say Object o = new Object();?  Why not just Object o = Object();?  In C++ there's definitely a need for new, since we need to distinguish between allocating on the heap and allocating on the stack, but in Java all objects are constructed on the heap, so why even have the new keyword?  The same question could be asked for Javascript.  In C#, which I'm much less familiar with, I think new may have some purpose in terms of distinguishing between object types and value types, but I'm not sure.

Regardless, it seems to me that many languages which came after C++ simply "inherited" the new keyword - without really needing it.  It's almost like a vestigial keyword.  We don't seem to need it for any reason, and yet it's there.

Question: Am I correct about this?  Or is there some compelling reason that new needs to be in C++-inspired memory-managed languages like Java, Javascript and C# but not Python?

答:
The reason why Python does not need it is because of its type system. Fundamentally, when you see foo = bar() in Python, it doesn't matter what whether bar() is a method that is being invoked, a class that is being instantiated, or a functor object; in Python, there is no fundamental difference between a functor and function (because methods are objects); and you could even argue that a class being instantiated is a special case of a functor. Thus, there is no reason to create an artifical difference in what is happening (especially since memory management is so extremely hidden in Python).

In a language with a different typing system, or in which methods and classes are not objects, there is the possibility of a stronger conceptual difference between creating an object and calling a function or functor. Thus, even if the compiler/interpreter does not need the new keyword, it is understandable that it might be maintained in languages that haven't broken all the boundaries that Python has.


问:
Refactoring code smells in ASP.NET Web Forms Code Behind Files: Is it risky? Is it wise? Is it a waste of time?
Given a long method with Pac-Man ifs, would it be wise to:

Break down code blocks into regions.

Then refactor code blocks into methods.

Or would it be best to leave it alone?

Would it be risky?

Would it be a waste of time?

In the absence of automated unit-tests, I'm trying to understand the risk-reward relationship associated with this manuever.

答:
0 . Work out what the logic of the if statements is.

Quite often when I'm looking at a set of pac-man ifs I find that if I just draw out something like a truth table of all the conditions involved I can work out a much better route to resolving the problem.

That way you can also assess whether there is a better method, how you might break it down further and ( and this is a big one with this kind of code ) whether there are any holes in the logic.

Having done that you can probably break it down into a couple of switch statements and a couple of methods and save the next poor mook who has to go through the code a whole lot of problems.

ContentLicense: CC BY-SA 2.5


问:
Is there any Windows installer maker with decent scripting capabilities?
I need to do complex dependency processing during the installation of our solution, install a few related programs from their own installers and also probably run a few simple tests to determine performance of the machine to choose the right parameters for our application.

I'm thinking something like Lua would be a great fit for this task, yet all scripting in installers I found so far is something like Pascal script of Inno Setup which leaves a lot to be desired and NSIS scripting language is nonexistent.

I guess I'm missing something really obvious here as my task is not unique and has probably been solved before.

答:
(Re)Learn pascal and use InnoSetup. You can have innosetup to execute other programs written in your favorite language (after innosetup has installed it) and get the results.

I personally work in PHP on windows. Innosetup drops a basic installation of the PHP interpreter and I call PHP programs.

ContentLicense: CC BY-SA 3.0


问:
How can I build a C# project (installer) for multiple environments
I would like to propose a solution to our companies problem with building consistent installers for different environments.  Our current process is to build an installer for test,  perform testing, update app config, build installer for production.

Unfortunately this has lead to issues in the past where the installer was not properly updated etc. What can I suggest as a best practice to mitigate this problem?

答:
Automate it

This is always the solution for "people are screwing up a continuous and repeatable process". Automate it.

Don't bother building a "test version" and testing it, AND THEN changing some config manually... AND THEN... building a "release" version (and waiting for it). Build both at the same time. It's the same as if you were doing a full debug/release build.

Take a look at the MSBuild Community Tasks and Jenkins CI.

Make your build system work for you. Modern build systems can do a fair bit very easily these days.

Test your release version

Seriously. What good is testing if you're not going to test what customers get? (this excludes automation that runs on instrumented builds, of course)


问:
How can I update a large legacy codebase to meet specific quality standards?
There is a lot of information about tools and techniques for improving legacy codebases, but I haven't come across any successful real world case studies.  Most advice is on the micro level, and while helpful, doesn't convince many people because of a lack of evidence it can help at the macro level.

I am looking specifically for incremental improvements that have been proven to be a success in the real world when updating a large legacy codebase to meet today's quality standards, and not a complete rewrite.

Before:

Large: greater than 1MLOC

Legacy: no automated tests

Poor quality: high complexity, high coupling, high escaped defects

After

Automated tests

Easier updates/maintenance

High quality: lowered complexity, decoupled code, few escaped defects

What kind of incremental steps have been proven in the real world to update a large legacy codebase successfully to meet above quality standards, without going through a total rewrite?

If possible, include an example company or case study of a large legacy project that has gone through a "successful" quality improvement process in your answer to back it up.

答:
Books like http://www.amazon.com/Working-Effectively-Legacy-Michael-Feathers/dp/0131177052 should be witness enough to how large, legacy poor quality code bases are common in the industry.

My guess at why you have not heard or seen, and, more importantly, you will never likely hear about them until you work on one of them yourself, is, nobody seems capable for various reasons, to come out clean and say that their code base was all the above without facing non-trivial repercussions.

This could explain the dearth of studies you speak of.  If you read enough books, for example, Peter van der Linden's Deep C Secrets, you will read about million dollar bugs where the part about which project had them will be missing.

NOTE: I wanted to make this a comment, but it was too long.  I understand this does not answer the question fully.

EDIT: C++11 & The long term viability of GCC is questioned -- if the developers refactor GCC and make it more toolable as LLVM/clang, it might provide a good example.  The discussion notes that the documentation is poor at some places pushing the entry barrier for new developers higher.


问:
Is it a basic principle, or highly desirable, to have class methods that return "$this" rather than a value?
I've really just begun to learn OOP. I started about a year ago and have written probably 15,000 lines of it. But I wrote it all with hardly any experience looking at other people's OOP.

Most of my class functions return a value or make a change to the class properties and return true/false. Some of the ones that return a value also save that value into a class property (after first checking if the class property is already set, which can avoid a database call).

Now I'm doing a lot of digging in Magento/Zend and I notice a lot of their class methods return "$this". As I understand it, unlike in regular functions, class methods that return $this act by reference not by value, so that you get back the same object you started with rather than a copy.

Is returning $this something that I should be doing much more of? Does it make the code easier to maintain and use? Is returning $this necessary in order to chain class methods?

答:
Returning $this returns an instance of the object that the method is a member of.  There are lots of cases where you'd want to do this, but until you understand exactly what I just said means and can identify a use case for it, you don't really need it.

Examples of when to use this:

A btree is an example in PHP of where you would return a child of $this, which isn't exactly the same thing but I think it has bearing on this discussion.

Writing your own constructor you would always return $this

To clarify about references, when you return $this you're passing out a reference to the object that the method running is part of.  I think PHP's rules for when it's operating on a reference vs a value is a little unclear sometimes, but in this case $this is always a reference. To be clear:  a reference is always 'the instance that you had' and never a copy, whereas a 'value' is a copy. These are two types of argument semantics


问:
What is the point of using lists over vectors, in C++?
I've run 3 different experiments involving C++ lists and vectors.

Those with vectors proved more efficient, even when a lot of insertions in the middle were involved.

Hence the question: in which case do lists make more sense than vectors?

If vectors seem more efficient in most cases, and considering how alike their members are, then which advantages are left for lists?

Generate N integers and put them in a container so that the container remains sorted. The insertion has been performed naively, by reading elements one by one and inserting the new one right before the first larger one.

With a list, time goes through the roof when dimension increases, compared to vectors.

Insert N integers at the end of the container.

For lists and vectors, time increased by the same order of magnitude, though it was 3 times faster with vectors.

Insert N integers in a container.

Start timer.

Sort the container using list.sort for lists, and std::sort for vectors.
Stop timer.

Again, time increases by the same order of magnitude, but it is in average 5 times faster with vectors.

I might continue to perform tests and figure out a couple of examples where lists would prove better.

But the joint experience of you guys reading this message might provide more productive answers.

You might have come across situations where lists were more convenient to use, or performed better?

答:
One factor I can think of is that as a vector grows, free memory will get fragmented as the vector deallocates its memory and allocates a larger block over and over. This will not be an issue with lists.

This is in addition to the fact that large number of push_backs without reserve will also cause a copy during each resize which makes it inefficient. Inserting in the middle similarly causes a move of all the elements to the right, and is even worse.

I dont know if this is a major concern though, but was the reason given to me at my work(mobile game development), to avoid vectors.


问:
What *are* the programming concepts I should master to have a deep understanding of my craft (programming)?
In order of importance, if its possible to do so and it may not be, what are the most important foundations of knowing how to program. Algorithms, iteration, recursion, etc?

Note that where I put etc. is where my question lies. I recently read an Internet post that said 9 out 10 programmers can't gasp program!

http://www.codinghorror.com/blog/2007/02/why-cant-programmers-program.html

I want to have a deep knowledge of what it is I am actually trying to accomplish when programming and an exhaustive comprehension of the basic tools at my disposal. Basically I want to be able to paint with all the colors of the wind.

答:
I'm afraid this is a pretty large question for anyone to answer conclusively or authoritatively, especially given that you want a prioritized list. There are lots of programmers out there, and they work on very different things - sure, fundamentals stay the same, but what you need to keep active in your memory can be really different, and indeed there are lots of tasks where you can stay pretty high-level without going deeper.

It seems though that you are genuinely concerned about how to be a better developer, and not just a jack-of-one-trade. I find that admirable, and I can share some of the things that have helped me learn how to program.

Pretty much all of programming boils down to algorithms and data structures. They, in turn, are examples of the larger question - how do we model things and processes from the real world into a representation such that a computer can understand. If you are just starting out, it might be useful to use a higher-level programming language (like Java, Python, whatever) to become familiar with implementing data structures and algorithms.

At a certain point, having played around with data structures and algorithms, you may start getting that gnawing question "but how do we go from telling the computer what to do, to the computer actually doing it?" Then you can look into how a computer actually computes - how memory and the CPU work together to execute instructions, how operating systems abstract the hardware so you can write a program that, say, opens a file, without coding to a particular low-level hard-drive interface.

This is probably a good point to start - how algorithms and data structures model problems from the real world, and how a computer actually performs computation. Knowing the latter is very useful in mastering lower-level languages like C, which utilize far fewer smoke and mirrors than OO and scripting languages :)


问:
About clean code
Example: I have a method that formats the output based on a parameter from an object. The question is, should I pass the object that holds the parameter to the method, or just the required param?

Still trying to grasp clean coding so I might be wrong, my take is that the 2nd approach is cleaner because it doesn't require you to pass the entire object, and is easy to test.

However, it makes calling the method ugly now since I have to check for the param every time when I call the method. And its used very very often.

In contrast, the first approach while not that easy to test, because I have to mock the requestObject, is much easier to use.

So which method should I go with? Or is there an even better approach?

```<code>// The output method with object as input
public function outputResponse($message, $requestObject) {
    if (isset($resquestObject->param['response_type']) && $requestObject->param['response_type'] == 'json') return json_ecode($message);
    return xmlOutput($message);
}

// So you call it like
$this->outputResponse($message, $requestObject);
</code>```

The other approach...

```<code>// The output method with just the param as input
public function outputResponse($message, $responseType) {
    if (responseType == 'json') return json_ecode($message);
    return xmlOutput($message);
}

// So you call it like
$responseType = (isset($resquestObject->param['response_type']) && $requestObject->param['response_type'] == 'json') ? 'json' : '';
$this->outputResponse($message, $responseType);
</code>```

答:
When you're making decisions like this it's best to weigh the pros and cons of the specific case.  In this case, since your example is a one line convenience function, use the most convenient way possible.  There's no reason to make a convenience function anything other than a super simple and easy to use interface.  As for testing, you don't even need to test it:  all that it is in and of itself is a conditional, your test can be against the $requestObject. It's not neccessary to test a single conditional usually, the more important thing is if $requestObject is set up correctly.

I'd also like to add that unless you see this same code repeated 3 times or more you might not even need to call out to your method, you might just do it inline.  I'm assuming since you've written it, it's something that happens a lot.

Title: About clean code


答:
A recent question, related in some way to this one, and Answer  had a link to This blog which discusses the same problem from a different angle.

Probably the most important concept for any developer is "humility"....Once you accept you don't know it all, you are open to explore solutions.  Most of the people who write blogs on programming are in the top percentile, and the problem is many have yet to control their narcissistic tendencies.... which is why they blog..... You need to learn to identify these bloggers and ignore there rants

The linked blog is really nothing more than a rant - In every industry complains that recent graduates are useless are common, that it takes years to get them useful and productive. Perhaps the problem is that these self proclaimed guru's actually expect too much and have forgotten that once they would not have been able to solve FizzBuzz. Not everyone can be in the top 10 percentile, by definition, half of programmers are below average......

Title: What *are* the programming concepts I should master to have a deep understanding of my craft (programming)?

Body:
In order of importance, if its possible to do so and it may not be, what are the most important foundations of knowing how to program. Algorithms, iteration, recursion, etc?

Note that where I put etc. is where my question lies. I recently read an Internet post that said 9 out 10 programmers can't gasp program!

http://www.codinghorror.com/blog/2007/02/why-cant-programmers-program.html

I want to have a deep knowledge of what it is I am actually trying to accomplish when programming and an exhaustive comprehension of the basic tools at my disposal. Basically I want to be able to paint with all the colors of the wind.


问:
What are some things you have read that inspired and guided you as a programmer?
For example, being a beginner, I find a lot of inspiration and direction from reading this post by Bryan Woods.</p>

答:
The book of five rings by Myomoto Musasashi.

Some highlights.

Don't have a a favorite tool. Learn to use every tool, learn when it is appropriate to use, learn its weaknesses and strengths.

Staff whose work is not perfect can be used in places where the quality of their workmanship is in public view. The pillars that support the floor under a  building do not have to have a perfect finish (they just have to work).

By doing one thing, do many things.
So if there is a choice between doing A and B, but B can be used to do many things next week, do B if you can afford it.


答:
Under the heading of "etc." comes something which can easily take 50% or more of your time.

Learn how to debug.

This means learning the Scientific Method. I mean really learning it. And then applying it with brutal self-honesty. Learn how to state precisely what you know is true, what you know is not true, and those things which you don't know. Any time you sloppily assign an item to the wrong category, you've just made your life a lot harder.

Learn to say "I think" instead of "I know". You only get to say "I know" when you "think" something is true (or false), and then you prove it!

Many bugs are trivial, but they can be hard to see because you "know" what the code should be ... except it's not. Find a freind to explain it to. Ask them to be an "expert idiot": someone who doesn't know your code, but who you know you can't blow BS past. Don
t be surprised if in the middle of a describing it to them you suddenly stop and say, "and so you can ... see ... see that ... sh*t. Thanks."

Nontrivial bugs require an arsenal of techniques. A classic that can quickly spotlight most non-timing related bugs is Wolf Fence in Alaska. There is a wolf somewhere in Alaska; build a fence cutting the state in half. Which side is the wolf on? Cut that side in half. Lather, rinse, repeat. Doing this 20 times at well-chosen places in the code reduces the area where the bug (wolf) can be to 1/1048576. Kill that wolf.

Tip: look for handwaves—physical, mental, or any other kind. As soon as you (or your colleague) flinch / divert / minimize attention paid to a portion of the code, go totally rabid. Because the area where you just know the bug can't be, even though you've spent hours / days looking for the d*mn thing and still can't find it ... that's the highest probability location for the bug.  Nobody gets a 'bye', nobody (including the machine, the OS, the compiler, or you) gets any sort of "due respect". There's a bug. Period. End of sentence. Now go kill the d*mn thing.

I know of no school that teaches debugging as a subject unto itself. IMNSHO, this may be the single most glaring piece of evidence that they (universities / professors) are not teaching you to be a programmer, they are, instead, teaching you to be ... like them? Harsh? Perhaps. True? Make up your own mind. Now prove it.


答:
The most important thing to know about being a programmer is that writing code is a grind, and a workmanlike "blue collar" attitude towards producing what you're being paid to produce will get you farther than any esoteric learnings.

Learn to get into the zone. By that I mean the mental state when you're focused only on your task and you can begin to keep a great many things in your head and how they interoperate all at once. Once you're in the habit of getting into the zone at will, start worrying about the rest.  Until you can pound out code like some kind of a code pounding out thingy, the rest is virtually useless.

EDIT:

If you don't believe this and you downvoted me I beleive that you do not know if you have the determination to do it for 20 years.   I know that I do because I accept this. ;)


答:
You are correct that $requestObject doesn't seem like it belongs as a parameter to outputResponse. outputResponse is supposed to be outputting response, not interpreting the meaning of request parameters. However, your second version is still doing that:

```<code>public function outputResponse($message, $responseType) {
    if (responseType == 'json') return json_ecode($message);
    return xmlOutput($message);
}
</code>```

See, it defaults to xml. But it should not. The fact that your requests default to XML is part of request parameter processing, so you've not entirely removed it from the function. It should really be:

```<code>public function outputResponse($message, $responseType) {
    switch($responseType) {
         case 'json':
               return json_encode($message);
         case 'xml':
               return json_encode($message);
         default:
               throw new BadInputError($responseType);
}
</code>```

On the other hand, you really shouldn't be duplicating the logic to decide the responseType all over the place either. At the version least, lets define a function for it:

```<code>public function determineRequestType($requestObject)
{
    if( isset($requestObject->param['response_type']) && $requestObject->param['response_type'] == 'json' )
         return 'json';
    else
         return 'xml';
}
</code>```

That gives you two fairly easily testable functions. You can test each task (figure out the output format, produce the output format independently. This leaves something like the following all over the place. It's a big improvement, but still more duplication than we want.

```<code>$this->outputResponse($message, determineRequestType($requestObject));
</code>```

We could write a function:

```<code>function produceResponse($message, $requestObject) {
     return $this->outputResponse($message, determineRequestType($requestObject));
}
</code>```

Which gives you the exact same interface you had before, but has the components broken up for easier testing. However, you are still repeating calls to produceResponse all over the place and that's suspect. So I'd look at doing something different.

I'm going to guess that what you've got is something like this many times over:

```<code>function handleFoobarRequest($requestObject)
{
     // pull parameters from requestObject
     // do whatever the request actually requests
     $message = // message constructed from request results
     $response = produceResponse($requestObject);
     write_response($response);
}
</code>```

What you should really do is rearrange the code so that its more like this:

```<code>function handleFoobarRequest($requestObject)
{
     // pull parameters from requestObject
     // do whatever the request actually requests
     $message = // message constructed from request results
     return $message;
}
</code>```

And whoever calls this function takes care of formatting it. That way there should only be one place that actually needs to make that call. Without knowing more about how your app is structured I don't know how exactly to do that in your case.

Title: About clean code

Body:
Example: I have a method that formats the output based on a parameter from an object. The question is, should I pass the object that holds the parameter to the method, or just the required param?

Still trying to grasp clean coding so I might be wrong, my take is that the 2nd approach is cleaner because it doesn't require you to pass the entire object, and is easy to test.

However, it makes calling the method ugly now since I have to check for the param every time when I call the method. And its used very very often.

In contrast, the first approach while not that easy to test, because I have to mock the requestObject, is much easier to use.

So which method should I go with? Or is there an even better approach?

```<code>// The output method with object as input
public function outputResponse($message, $requestObject) {
    if (isset($resquestObject->param['response_type']) && $requestObject->param['response_type'] == 'json') return json_ecode($message);
    return xmlOutput($message);
}

// So you call it like
$this->outputResponse($message, $requestObject);
</code>```

The other approach...

```<code>// The output method with just the param as input
public function outputResponse($message, $responseType) {
    if (responseType == 'json') return json_ecode($message);
    return xmlOutput($message);
}

// So you call it like
$responseType = (isset($resquestObject->param['response_type']) && $requestObject->param['response_type'] == 'json') ? 'json' : '';
$this->outputResponse($message, $responseType);
</code>```

Body:
You are correct that $requestObject doesn't seem like it belongs as a parameter to outputResponse. outputResponse is supposed to be outputting response, not interpreting the meaning of request parameters. However, your second version is still doing that:

public function outputResponse($message, $responseType) {
    if (responseType == 'json') return json_ecode($message);
    return xmlOutput($message);
}

See, it defaults to xml. But it should not. The fact that your requests default to XML is part of request parameter processing, so you've not entirely removed it from the function. It should really be:

public function outputResponse($message, $responseType) {
    switch($responseType) {
         case 'json':
               return json_encode($message);
         case 'xml':
               return json_encode($message);
         default:
               throw new BadInputError($responseType);
}

On the other hand, you really shouldn't be duplicating the logic to decide the responseType all over the place either. At the version least, lets define a function for it:

public function determineRequestType($requestObject)
{
    if( isset($requestObject->param['response_type']) && $requestObject->param['response_type'] == 'json' )
         return 'json';
    else
         return 'xml';
}

That gives you two fairly easily testable functions. You can test each task (figure out the output format, produce the output format independently. This leaves something like the following all over the place. It's a big improvement, but still more duplication than we want.

$this->outputResponse($message, determineRequestType($requestObject));

We could write a function:

function produceResponse($message, $requestObject) {
     return $this->outputResponse($message, determineRequestType($requestObject));
}

Which gives you the exact same interface you had before, but has the components broken up for easier testing. However, you are still repeating calls to produceResponse all over the place and that's suspect. So I'd look at doing something different.

I'm going to guess that what you've got is something like this many times over:

function handleFoobarRequest($requestObject)
{
     // pull parameters from requestObject
     // do whatever the request actually requests
     $message = // message constructed from request results
     $response = produceResponse($requestObject);
     write_response($response);
}

What you should really do is rearrange the code so that its more like this:

function handleFoobarRequest($requestObject)
{
     // pull parameters from requestObject
     // do whatever the request actually requests
     $message = // message constructed from request results
     return $message;
}

And whoever calls this function takes care of formatting it. That way there should only be one place that actually needs to make that call. Without knowing more about how your app is structured I don't know how exactly to do that in your case.


答:
You need to show how you were doing the inserts in your first test. Your second and third tests, vector will easily win.

A significant use of lists is when you have to support removing items while iterating. When the vector is modified, all iterators are (potentially) invalid. With a list, only an iterator to the removed element is invalid. All other iterators remain valid.

The typical order of use for containers is vector, deque, then list. The choice of container is usually based on push_back choose vector, pop_front choose deque, insert choose list.

Title: What is the point of using lists over vectors, in C++?

Body:
I've run 3 different experiments involving C++ lists and vectors.

Those with vectors proved more efficient, even when a lot of insertions in the middle were involved.

Hence the question: in which case do lists make more sense than vectors?

If vectors seem more efficient in most cases, and considering how alike their members are, then which advantages are left for lists?

Generate N integers and put them in a container so that the container remains sorted. The insertion has been performed naively, by reading elements one by one and inserting the new one right before the first larger one.

With a list, time goes through the roof when dimension increases, compared to vectors.

Insert N integers at the end of the container.

For lists and vectors, time increased by the same order of magnitude, though it was 3 times faster with vectors.

Insert N integers in a container.

Start timer.

Sort the container using list.sort for lists, and std::sort for vectors.
Stop timer.

Again, time increases by the same order of magnitude, but it is in average 5 times faster with vectors.

I might continue to perform tests and figure out a couple of examples where lists would prove better.

But the joint experience of you guys reading this message might provide more productive answers.

You might have come across situations where lists were more convenient to use, or performed better?


答:
This list is a start... you're asking a big question!

How to clarify and write down what the customers wants ("requirements"). This is an art in and of itself. If you can do this, your programming job will be much better.

How to estimate and project plan. People will ask you for an estimate, be prepared.

How to constructively review other people's code.

Design patterns. This is a big one. But don't overzealously use them for the sake of it.

Learn the difference between a bug, issue and feature requests

Keep up to date with frameworks/libraries. You don't have to use them, but you need to know what they do and their pro's/con's. If something seems way too hard then there's probably (hopefully) a much easier way of doing things.

How to document complicated algorithms in a flowchart or just write it out in english. Don't expect that someone will spend 2 days trying to reverse engineer your code.

How to organise your code structure so that anyone else can understand it

How to comment your code

How to write unit tests

Know what's going on under the hood. Eg calling a web service - what's it actually doing?

How to abstract away logic into classes.

How to refactor code

Learn the gist of quite a few programming languages. You'd be surprised what you can learn from other areas

How to tell other programmers what to write.

How to explain to management what you're doing and why.

Like Peter said, how to debug. I agree with everything he says, real programmers debug, not just guess.

How to work with maniacs. There's a lot of them out there.

How to GET STUFF DONE. All the theory in the world won't help you if you can't get stuff done.

I answered another question along similar lines (with similar content) here:

tips, guidelines, points to remember for rendering professional code?


答:
The short answer is that cases seem to be few and far between. There are probably a few though.

One would be when you need to store a small number of large objects -- especially, objects that are so large that it's impractical to allocate space for even a few extra of them. There's basically no way to stop a vector or deque from allocating space for extra objects -- it's how they're defined (i.e., they must allocate extra space to meet their complexity requirements). If you flat-out can't allow that extra space to be allocated, an std::list may be the only standard container that meets your needs.

Another would be when/if you'll store an iterator to an "interesting" point in a list for an extended period of time, and when you do insertions and/or deletions, you (nearly) always do it from a spot to which you already have an iterator, so you don't walk through the list to get to the point where you're going to do the insertion or deletion. Obviously the same applies if you work with more than one spot, but still plan on storing an iterator to each place you're likely to work with, so you most manipulate spots you can reach directly, and only rarely walk through the list to get to those spots.

For an example of the first, consider a web browser. It might keep a linked list of Tab objects, with each tab object representing on open tab in the browser. Each tab might be a few dozen megabytes of data (of more, especially if something like a video is involved). Your typical number of open tabs might easily be less than a dozen, and 100 is probably close to the upper extreme.

For an example of the second, consider a word processor that stores text as a linked list of chapters, each of which might contain a linked list of (say) paragraphs. When the user is editing, they're typically going to find a particular spot where they're going to edit, and then do a fair amount of work at that spot (or inside that paragraph, anyway). Yes, they'll move from one paragraph to another now and again, but in most cases it'll be a paragraph near where they were already working.

Once in a while (things like global search and replace) you end up walking through all the items in all the lists, but it's fairly uncommon, and even when you do, you're probably going to do enough work searching within an item in the list, that the time to traverse the list is nearly inconsequential.

Note that in a typical case, this is likely to fit the first criterion as well -- a chapter contains a fairly small number of paragraphs, each of which is likely to be fairly large (at least relative to the size of the pointers in the node, and such). Likewise, you have a relatively small number of chapters, each of which might be several kilobytes or so.

That said, I have to admit that both of these examples are probably a little contrived, and while a linked list might work perfectly well for either, it probably wouldn't provide a huge advantage in either case as well. In both cases, for example, allocating extra space in a vector for either some (empty) web pages/tabs or some empty chapters is unlikely to be any real problem.


问:
How does C++ handle multiple inheritance with a shared common ancestor?
I'm not a C++ guy, but I'm forced to think about this. Why is multiple inheritance possible in C++, but not in C#? (I know of the diamond problem, but that's not what I'm asking here). How does C++ resolve the ambiguity of identical method signatures inherited from multiple base classes? And why is the same design not incorporated into C#?</p>

答:
The answer is that it doesn't work correctly in C++ in the event of namespace clashes. See this.  To avoid namespace clashing you have to do all kinds of gyrations with pointers.  I worked at MS on the Visual Studio team and I at least in part the reason they developed delegation was to avoid namespace collision altogether.  Preiouvsly I had said that they also considered Interfaces to be part of the multiple inheritance solution, but I was mistaken. Interfaces are actuallly amazing and can be made to work in C++, FWIW.

Delegation specifically addresses namespace collision:  You can delegate to 5 classes and all 5 of them will export their methods to your scope as first class members.  On the outside looking in this IS multiple inheritance.


问:
Java or C++ for university CS courses?
I'm in the throes of getting myself enrolled in school to get a CS degree. The school I am looking at actually offers both Java- and C++-based for the introductory software development courses (object-oriented programming, design patterns, that sort of thing). It is student's choice which track to follow, but there is only time to follow one.

Knowing what you know now, if you had the choice, would you lay down your CS curriculum foundation in Java or C++?

My current debate currently looks like this:

A good friend (who has a PhD in AI) is touting Java as the better choice regardless of what I do, if only to open up more job opportunities later, though he might be biased since all of his work has been in Java (he loves it). I live in the Boston, MA, USA area and I see an equal amount of Java and C work.

On the flip side, although I haven't entirely yet settled on what I want to do with the degree when I'm done, my preference would be to develop for the Mac, which I am doing now albeit in a limited capacity. To that end, I'm getting some limited exposure to C++ already, but I've had none with Java, and looking at my projects at my day job I don't see a need to use it anytime soon, "soon" measured by at least two years.

I probably should note that I'm an adult going back to school after 20 years (I currently have no degree of any kind) so I'm looking to maximize the opportunity and time spent as best I can. I'm kind of leaning towards C++ but I'm still ambivalent, and some outside, objective advice would help here.

Or I could just be thinking too hard about it.

UPDATE: It turns out the language selection wasn't so clear cut as I originally surmised. While a couple of core courses focused on Java, some of the other core courses work in primarily C and Java, but also a few others thrown in for good measure. In fact, my rest of my semester is going to be in Objective-C after spending time in Java and Javascript. Last semester was C, Javascript, and PHP, plus a few others thrown in as assignments required. Since things were pretty much split down the middle overall, and I am still getting answers to this, I am now trying to work my curriculum such that I meet all of the requirements for the degree but to absorb as many languages as I can reasonably handle. So far, my grades have not suffered trying to do this.

答:
I can't believe people are advocating C++ as a first language! You will spend most of your time writing boiler plate and trying to get around the limitations and fish hooks in the language than actually learning how to program.

Java is a much simpler language and won't get in the way of your learning.

If you must learn C++, learn the concepts with Java and then go to C++, or better still, OBJ-C if you want to write Mac software. Java and OBJ-C aren't too dissimilar.

FYI I have spent 10 years as a commercial C++ developer.

Title: Java or C++ for university CS courses?


问:
MVC - sharing multiple models
I am building a java desktop application where I am attempting to implement MVC. The GUI interface has multiple views (think pop-up windows) from the main view. Each view has its associated model that it receives updates from.

I am running into scenarios where two views need to access a particular data field from one model. This requires that one model "knows about" the another. What are my options to solve this?

The data field is a table that is populated in one of the views and is then subsequently accessed in the main splash view.

I have tried passing the second model into the first's constructor from the controller, however I feel this is sloppy. Should a model listen to another model (Observer pattern)? Perhaps my question is too subjective....

答:
Single model and multiple views - I see no problem in your case. Have you tried to implement observer pattern? If not, try to write your classes according to class structure suggested by observer pattern. I think it will solve problem.

You can visit here to find more information about observer pattern.

Title: MVC - sharing multiple models


答:
YAGNI: "Always implement things when you actually need them, never when you just foresee that you need them."

In my experience, it is common for "programmers" to foresee many cases in the future and try to "improve" the code by adding codes to anticipate them! In most cases the code that they added will just bloat the code and add complexity to the code.


问:
Fernando J. Corbató's “Constrained languages”
For his 1990 Turing award speech, Fernando J. Corbató listed reasons why complex systems will inevitably fail. In his conclusion, he gives some suggestions for decreasing the probability of failure. He lists one idea as follows:

[U]se of constrained languages for design or synthesis is a powerful methodology. By not allowing a programmer or designer to express irrelevant ideas, the domain of possible errors becomes far more limited.

What does he mean by "constrained language?"

For a moment I considered constraint programming. However, constraint programming is about restricting the program's solution space. It is a tool that empowers a programmer. The feature Corbató is referring to seems to be something which actually restricts the programmer, or at least makes her more inclined to write terser code.

My second thought is that he is referring to conservative programming languages. Corbató received his Turing award for work done in the 1960s and 1970s. It's my understanding that he dealt with a lot of punch cards. I have never seen a punch card, so I certainly don't know how to program one, but I might guess that punch card programming is extremely liberal.  I suspect the notions of type checking, static analysis, and so forth simply didn't exist. So, is Corbató perhaps referring to the idea of languages that restrict the developer from making dumb mistakes?  This doesn't seem to be the case, either. Safety checking and data modeling have nothing to do with terseness, which is what he seems to be talking about when he mentiones "not allowing ... irrelevant ideas."

答:
A "Constrained Programming Language" is simply one that does not provide (easy) ways to do things that are irrelevant to the languages purpose.

Note that's "irrelevant", not "dumb", "stupid" or "incorrect".

A fair example of this might be ISO/ANSI SQL (before SQL-92), which had no way in the query language to  express many procedural-type programming artifacts such as recursion or loops.  (Though, it has them now, and the vendors added custom extensions for them previously anyway).

OwnerDisplayName: RBarryYoung


问:
Visitor stability vs instanceof flexibility
I am working on a GUI application which generates a configuration file. I have a class hierarchy for the configuration model and I use an object tree of that hierarchy in several different contexts. Currently, I use the Visitor pattern to avoid polluting my model classes with context specific code.

```<code>interface IConfigurationElement {
    void acceptVisitor(IConfigurationElementVisitor visitor);
}
</code>```

In an earlier version I used chains of instanceof conditions instead of the Visitor. Comparing the two approaches I see the following tradeofs.

Visitor

It is easier and safer to add new IConfigurationElement. Just add a new declaration to IConfigurationElementVisitor and the compiler generates errors for all visitor implementations. With instanceof chains you have to remember all the places you have to extend with the new configuration element. Basically instanceof violates the DRY principle as it duplicates logic in several places.

The visitor pattern is more efficient than a chain of instanceofconditions

instanceof

The great advantage of instanceof is its flexibility. For example instanceof  allows me to define special solutions for different subsets of IConfigurationElement implementations which need to be handled similarilly in some cases. In contrast, Visitor forces me to implement a method for each implementation class every time.

Is there a common solution for this kind of problem? Can I adapt the Visitor somehow, so I can provide a common solution for some cases?

答:
You could use visitor with instanceOf

interfaces:

```<code>interface Visitable {
  void accept(Object visitor);
}
interface AVisitor {
  void visitA(A a);
}
interface BVisitor {
  void visitB(B b);
}
interface CVisitor {
  void visitB(C c);
}
</code>```

Visitables:

```<code>class C implements Visitable {
  public void accept(Object visitor) {
    if (visitor instanceof CVisitor) {
      ((BVisitor)vistor).visitC(this);
    }
  }
}

class B implements Visitable {
  public void accept(Object visitor) {
    if (visitor instanceof BVisitor) {
      ((BVisitor)vistor).visitB(this);
    }
  }
}

class A extends B implements Visitable {
  public void accept(Object visitor) {
    super.accept(visitor);
    if (visitor instanceof AVisitor) {
      ((AVisitor)vistor).visitA(this);
    }
  }
}
</code>```

Visitors:

```<code>class PrintBs implements BVisitor {
  public void visitB(B b) {
    system.out.println(b);
  }
}

class PrintAs implements AVisitor {
  public void visitA(A a) {
    system.out.println(a);
  }
}

class PrintCs implements CVisitor {
  public void visitC(C c) {
    system.out.println(c);
  }
}
class PrintAsAndCs implements CVisitor, AVisitor{
  public void visitA(A a) {
    system.out.println(a);
  }
  public void visitC(C c) {
    system.out.println(c);
  }
}
</code>```

each class knows only about its related interfaces, so adding new vistors nor visitables requires changing everything in that category (visitor/visitable) (for visitor, it does not require changing anything, for visitable it requires creating new visitor interface, but again, no changing of existing objects).

This way, there is no chain of instanceof tests and visitor for subset does not need to even know about types outside this subset.

Question is what to do with situation where A extends B (and B is Visitable too), in that case, you could just add super.accept(visitor) into accept (thus it would be short chain of instanceof-s, but onlu as long as hierarchy is deep, and it should not be too deep to matter, abd you don't need to write it whole manually).

Body:
You could use visitor with instanceOf

interfaces:

interface Visitable {
  void accept(Object visitor);
}
interface AVisitor {
  void visitA(A a);
}
interface BVisitor {
  void visitB(B b);
}
interface CVisitor {
  void visitB(C c);
}

Visitables:

class C implements Visitable {
  public void accept(Object visitor) {
    if (visitor instanceof CVisitor) {
      ((BVisitor)vistor).visitC(this);
    }
  }
}

class B implements Visitable {
  public void accept(Object visitor) {
    if (visitor instanceof BVisitor) {
      ((BVisitor)vistor).visitB(this);
    }
  }
}

class A extends B implements Visitable {
  public void accept(Object visitor) {
    super.accept(visitor);
    if (visitor instanceof AVisitor) {
      ((AVisitor)vistor).visitA(this);
    }
  }
}

Visitors:

class PrintBs implements BVisitor {
  public void visitB(B b) {
    system.out.println(b);
  }
}

class PrintAs implements AVisitor {
  public void visitA(A a) {
    system.out.println(a);
  }
}

class PrintCs implements CVisitor {
  public void visitC(C c) {
    system.out.println(c);
  }
}
class PrintAsAndCs implements CVisitor, AVisitor{
  public void visitA(A a) {
    system.out.println(a);
  }
  public void visitC(C c) {
    system.out.println(c);
  }
}

each class knows only about its related interfaces, so adding new vistors nor visitables requires changing everything in that category (visitor/visitable) (for visitor, it does not require changing anything, for visitable it requires creating new visitor interface, but again, no changing of existing objects).

This way, there is no chain of instanceof tests and visitor for subset does not need to even know about types outside this subset.

Question is what to do with situation where A extends B (and B is Visitable too), in that case, you could just add super.accept(visitor) into accept (thus it would be short chain of instanceof-s, but onlu as long as hierarchy is deep, and it should not be too deep to matter, abd you don't need to write it whole manually).


问:
Egoless programming, is it possible or even desirable
Is it possible to have egoless programming or is it even desirable?

As a profession we do seem to want to show off the latest gizmo, technique or say “look at this awesome piece of code I’ve written”. Yet we can get very defensive when asked to submit items of work for code reviews or get negative comments from other programmers (hearing the term WTF, has never been a good sign).

Can we as a profession be able to sit down and analyse a piece of code, data or architecture for its merits or constraints and a calm and respectful manner, without causing offense or antagonising our colleagues, or are we just the archetypal Dilbert character, raging against the system?

答:
I think this relates to how you view your code.  Good programmers are constantly in the tug of war between viewing the results as "art" and as a "commodity" (or whatever words you want to stick in there).

When we see the code as simply something we're paid to produce, it's pretty easy to avoid ego-related issues.

When viewing the code as "art" we've created, the ego really tries to get in there.  After all, what artist produces things they don't like?

So, depending upon your view of your code, you may or may not have emotional attachment to your code.  Pay attention to the balancing act, and you'll do well.   We want to create code as if it's the highest quality art, but we want to release it as a cheap commodity.  Think from the appropriate angle at the proper times and you'll do well.


答:
Why is multiple inheritance possible in C++, but not in C#?

I think (without having hard reference), that in Java they wanted to limit the expressiveness of the language to make the language easier to learn and because code using multiple inheritance is more often too complex for its own good than not. And because full multiple inheritance is a lot more complicated to implement, so it simplified the virtual machine a lot too (multiple inheritance interacts especially badly with garbage collector, because it requires keeping pointers into the middle of object (at the beginning of the base))

And when designing C# I think they looked at Java, saw that full multiple inheritance indeed wasn't missed much and elected to keep things simple as well.

How does C++ resolve the ambiguity of identical method signatures inherited from multiple base classes?

It does not. There is a syntax to call base class method from specific base explicitly, but there is no way to override only one of the virtual methods and if you don't override the method in the subclass, it's not possible to call it without specifying the base class.

And why is the same design not incorporated into C#?

There is nothing to incorporate.

Since Giorgio mentioned interface extension methods in comments, I'll explain what mixins are and how they are implemented in various languages.

Interfaces in Java and C# are limited to declaring methods only. But the methods have to be implemented in each class that inherits the interface. There is however large class of interfaces, where it would be useful to provide default implementations of some methods in terms of others. Common example is comparable (in pseudo-language):

```<code>mixin IComparable {
    public bool operator<(IComparable r) = 0;
    public bool operator>(IComparable r) { return r < this; }
    public bool operator<=(IComparable r) { return !(r < this); }
    public bool operator>=(IComparable r) { return !(r > this); }
    public bool operator==(IComparable r) { return !(r < this) && !(r > this); }
    public bool operator!=(IComparable r) { return r < this || r > this; }
};
</code>```

Difference from full class is that this can't contain any data members. There are several options for implementing this. Obviously multiple inheritance is one. But multiple inheritance is rather complicated to implement. But it's not really needed here. Instead, many languages implement this by splitting the mixin in an interface, which is implemented by the class and a repository of method implementations, that are either injected into the class itself or an intermediate base class is generated and they are placed there. This is implemented in Ruby and D, will be implemented in Java 8 and can be implemented manually in C++ using the curiously recurring template pattern. The above, in CRTP form, looks like:

```<code>template <typename Derived>
class IComparable {
    const Derived &_d() const { return static_cast<const Derived &>(*this); }
public:
    bool operator>(const IComparable &r) const { r._d() < _d(); }
    bool operator<=(const IComparable &r) const { !(r._d() < _d(); }
    ...
};
</code>```

and is used like:

```<code>class Concrete : public IComparable<Concrete> { ... };
</code>```

This does not require anything to be declared virtual as regular base class would, so if the interface is used in templates leaves useful optimization options open. Note, that in C++ this would probably still be inherited as second parent, but in languages that don't allow multiple inheritance it's inserted into the single inheritance chain, so it's more like

```<code>template <typename Derived, typename Base>
class IComparable : public Base { ... };
class Concrete : public IComparable<Concrete, Base> { ... };
</code>```

The compiler implementation may or may not avoid the virtual dispatch.

A different implementation was selected in C#. In C# the implementations are static methods of completely separate class and the method call syntax is appropriately interpreted by compiler if a method of given name does not exist, but an "extension method" is defined. This has the advantage that extension methods can be added to already compiled class and the disadvantage that such methods can't be overriden e.g. to provide optimized version.

Title: How does C++ handle multiple inheritance with a shared common ancestor?

Body: I'm not a C++ guy, but I'm forced to think about this. Why is multiple inheritance possible in C++, but not in C#? (I know of the diamond problem, but that's not what I'm asking here). How does C++ resolve the ambiguity of identical method signatures inherited from multiple base classes? And why is the same design not incorporated into C#?</p>

Body:
Why is multiple inheritance possible in C++, but not in C#?

I think (without having hard reference), that in Java they wanted to limit the expressiveness of the language to make the language easier to learn and because code using multiple inheritance is more often too complex for its own good than not. And because full multiple inheritance is a lot more complicated to implement, so it simplified the virtual machine a lot too (multiple inheritance interacts especially badly with garbage collector, because it requires keeping pointers into the middle of object (at the beginning of the base))

And when designing C# I think they looked at Java, saw that full multiple inheritance indeed wasn't missed much and elected to keep things simple as well.

How does C++ resolve the ambiguity of identical method signatures inherited from multiple base classes?

It does not. There is a syntax to call base class method from specific base explicitly, but there is no way to override only one of the virtual methods and if you don't override the method in the subclass, it's not possible to call it without specifying the base class.

And why is the same design not incorporated into C#?

There is nothing to incorporate.

Since Giorgio mentioned interface extension methods in comments, I'll explain what mixins are and how they are implemented in various languages.

Interfaces in Java and C# are limited to declaring methods only. But the methods have to be implemented in each class that inherits the interface. There is however large class of interfaces, where it would be useful to provide default implementations of some methods in terms of others. Common example is comparable (in pseudo-language):

mixin IComparable {
    public bool operator<(IComparable r) = 0;
    public bool operator>(IComparable r) { return r < this; }
    public bool operator<=(IComparable r) { return !(r < this); }
    public bool operator>=(IComparable r) { return !(r > this); }
    public bool operator==(IComparable r) { return !(r < this) && !(r > this); }
    public bool operator!=(IComparable r) { return r < this || r > this; }
};

Difference from full class is that this can't contain any data members. There are several options for implementing this. Obviously multiple inheritance is one. But multiple inheritance is rather complicated to implement. But it's not really needed here. Instead, many languages implement this by splitting the mixin in an interface, which is implemented by the class and a repository of method implementations, that are either injected into the class itself or an intermediate base class is generated and they are placed there. This is implemented in Ruby and D, will be implemented in Java 8 and can be implemented manually in C++ using the curiously recurring template pattern. The above, in CRTP form, looks like:

template <typename Derived>
class IComparable {
    const Derived &_d() const { return static_cast<const Derived &>(*this); }
public:
    bool operator>(const IComparable &r) const { r._d() < _d(); }
    bool operator<=(const IComparable &r) const { !(r._d() < _d(); }
    ...
};

and is used like:

class Concrete : public IComparable<Concrete> { ... };

This does not require anything to be declared virtual as regular base class would, so if the interface is used in templates leaves useful optimization options open. Note, that in C++ this would probably still be inherited as second parent, but in languages that don't allow multiple inheritance it's inserted into the single inheritance chain, so it's more like

template <typename Derived, typename Base>
class IComparable : public Base { ... };
class Concrete : public IComparable<Concrete, Base> { ... };

The compiler implementation may or may not avoid the virtual dispatch.

A different implementation was selected in C#. In C# the implementations are static methods of completely separate class and the method call syntax is appropriately interpreted by compiler if a method of given name does not exist, but an "extension method" is defined. This has the advantage that extension methods can be added to already compiled class and the disadvantage that such methods can't be overriden e.g. to provide optimized version.


答: This sounds very similar to the notion of domain-specific languages to me. Just as @RBarryYoung pointed out, one example for this would be SQL (others would be HTML, CSS, etc.).

Title: Fernando J. Corbató's “Constrained languages”

Body:
For his 1990 Turing award speech, Fernando J. Corbató listed reasons why complex systems will inevitably fail. In his conclusion, he gives some suggestions for decreasing the probability of failure. He lists one idea as follows:

[U]se of constrained languages for design or synthesis is a powerful methodology. By not allowing a programmer or designer to express irrelevant ideas, the domain of possible errors becomes far more limited.

What does he mean by "constrained language?"

For a moment I considered constraint programming. However, constraint programming is about restricting the program's solution space. It is a tool that empowers a programmer. The feature Corbató is referring to seems to be something which actually restricts the programmer, or at least makes her more inclined to write terser code.

My second thought is that he is referring to conservative programming languages. Corbató received his Turing award for work done in the 1960s and 1970s. It's my understanding that he dealt with a lot of punch cards. I have never seen a punch card, so I certainly don't know how to program one, but I might guess that punch card programming is extremely liberal.  I suspect the notions of type checking, static analysis, and so forth simply didn't exist. So, is Corbató perhaps referring to the idea of languages that restrict the developer from making dumb mistakes?  This doesn't seem to be the case, either. Safety checking and data modeling have nothing to do with terseness, which is what he seems to be talking about when he mentiones "not allowing ... irrelevant ideas."


问:
QR Codes as Booking Confirmations for Conference?
A client of mine is holding a conference and we have the task of creating a booking system for them. However they have requested that we use QR codes so that on the door, a person can simply present their QR code, be scanned, and boom! they are signed in.

This isn't so much of a problem because I thought well I could use a long URL to connect to our DB and sign the person in, mark them as booked in/confirmed, and be done with it.

That's all very easy, the problem is then that what if the person scan's the QR code themselves? How do ensure that, only the people who are on the door of the conference have the power to scan the barcodes and sign people in?

I am limited really to php / jquery, if I knew XCODE I would write an App but I don't.

Thoughts I had:

Get the IP of the local WIFI, and only accept requests from that (however that does not stop the public from signing in)

Use some variable in $_SERVER[] that I could map as coming from a certain person's phone only.

答:
You need a piece of information that can only be got obtained the door.

Three ideas:

Have a sign-in QR code at the door (can be a universal one for everyone). When that URL is visited, set a cookie on their device which you then require before accepting the second, personalized URL. This has the problem of the QR code being shared with others once it's posted at the door.

Only give them half the QR code, and keep the other half at the door. You'd need to keep a different half for each attendee though

After they sign in with their own QR, generate another one on a secured machine at the door, which they have to scan to complete the sign-in


答: Possibly he means that a language which has fairly lower number of concepts to grasp. Check the diagrams here which shows the graphical representations of concepts in Coffescript, Ruby and C++. May be Tuner means that the fewer concepts you have in a language, the lesser chances of expressing irrelevant ideas.</p>


答:
You could link to a URL like http://localhost/... and have the machine that is scanning at the door also be the one that hosts the server for this.

This server would be a thin one, all it would need to do is do you db updating.

Title: QR Codes as Booking Confirmations for Conference?

Body:
A client of mine is holding a conference and we have the task of creating a booking system for them. However they have requested that we use QR codes so that on the door, a person can simply present their QR code, be scanned, and boom! they are signed in.

This isn't so much of a problem because I thought well I could use a long URL to connect to our DB and sign the person in, mark them as booked in/confirmed, and be done with it.

That's all very easy, the problem is then that what if the person scan's the QR code themselves? How do ensure that, only the people who are on the door of the conference have the power to scan the barcodes and sign people in?

I am limited really to php / jquery, if I knew XCODE I would write an App but I don't.

Thoughts I had:

Get the IP of the local WIFI, and only accept requests from that (however that does not stop the public from signing in)

Use some variable in $_SERVER[] that I could map as coming from a certain person's phone only.


问:
Do people who get paid to write code but score low on the "programmer competency matrix" have an ethical duty to find a different kind of job?
People advise me to "find a job doing something that you are good at", but the truth is that I don't believe I am good with anything other than just writing code.  I don't think that I can design or structure a program though.

Don't get me wrong, I'm not the kind of programmer who can't write a fizz buzz program; I'm more like the kind of programmer who can't do much besides getting the job done. It's not that I have a "do the bare minimum" attitude; it's that I'm painfully aware of my limitations as a programmer.

For example, implementing a quick sort algorithm is something that I could do only by relying on rote memorization (that is, if I ever find the motivation to spend a good chunk of my day trying to commit the entire algorithm to memory and not just go like "umm, I see, that makes sense, I can see the logic...").

When it comes to structuring and designing an application I feel I'm just as helpless. Since I am unable to see the right answer at the start I just make a judgement call which nine times out of ten I later regret.

I still manage to obtain job promotions and praise from my coworkers, so others don't necessarily share my opinions.  Objectively speaking though, I simply have neither the learning ability nor the sheer brain power to realistically aspire to be anything more than a 'slightly above average' programmer.

I wonder whether I actually have an ethical duty to make room for more talented people and find myself another kind of job, even if I'm fairly confident that I would not find another role I am better qualified for.  My question then is "Do average programmers have a place on a team?"

答:
No.

Bad carpenters don't quit carpentering they just concede they're not the greatest carpenters who ever lived whilst proceeding to submissively punch out mundane everyday chairs that they come to do rather well by sheer repetition.  There are lots of arses out there so we actually need mundane carpenters because the primadonna's all get bored with making cheap chairs and want to show off their talents via more impressive structures like -say- tables.

It's not a question of ethics, but rising to your best and being happy with being the best you can be.


答:
You should definitely automate your building process. In order to configure the environments on each deployment you could put them on a separate XML configuration and in the build process use the 'AfterCompile' feature of the csproj.

There's a nice tutorial on building such a multiple environments automated build here:

http://zbra.com.br/2012/06/14/dynamic-environment-configuration/

Title: How can I build a C# project (installer) for multiple environments

Body:
I would like to propose a solution to our companies problem with building consistent installers for different environments.  Our current process is to build an installer for test,  perform testing, update app config, build installer for production.

Unfortunately this has lead to issues in the past where the installer was not properly updated etc. What can I suggest as a best practice to mitigate this problem?


答:
Ego is simply a sense of self-worth.  The effect of emotions related to ego can be both positive and negative.

I will often feel proud (ego gets excited) when I accomplish something that was difficult, or find a clean simple solution to a complex problem, or learn to apply a new methodology to a problem.  Which I think is beneficial and gives me a self-sourced motivational kick.  The brain is wired to release feel-good chemicals when this happens.  You can become success addicted.

There are negative aspects of relying on your ego though, especially in team environments; that can have a counter-productive impact.  If you become to attached to some project, or solution, or technology, you will become defensive when it is threatened (by a new solution or technology, or person with ideas).  It's important to maintain objectivity, and not take an attack on your solution personally.

I've found the best way to deal with an ego threat, is to humbly attach myself to any new or alternative ideas or solutions.

There's always something new to learn, especially if you consider yourself the expert.

Title: Egoless programming, is it possible or even desirable

Body:
Is it possible to have egoless programming or is it even desirable?

As a profession we do seem to want to show off the latest gizmo, technique or say “look at this awesome piece of code I’ve written”. Yet we can get very defensive when asked to submit items of work for code reviews or get negative comments from other programmers (hearing the term WTF, has never been a good sign).

Can we as a profession be able to sit down and analyse a piece of code, data or architecture for its merits or constraints and a calm and respectful manner, without causing offense or antagonising our colleagues, or are we just the archetypal Dilbert character, raging against the system?


答:
First, you need to understand the era of computing when his speech was given (1990). Also, realize he's speaking to an academic audience and MIT is his home-base.

In that era, languages for writing languages (meta-languages) were a hot topic. The Art of the Meta-Object protocol is just out and is inspiring the design of new languages. However, all this luxury comes at a price: complexity.

To help reduce the complexity of systems and to allow checking these systems, meta-languages such as Z came out to make a testable specification. It is my guess he refers to these kind of languages.


问:
dechex(4000) - Why is it not signed?
Why does PHP's dechex(4000) not return a signed hexadecimal value?

It returns:

```<code>fa0
</code>```

As opposed to:

```<code>0xfa0
</code>```

And is signed the correct term to use in describing this problem?  Or is there a better term to describe the 0x portion?  Is that called a prefix?

答:
This is not about signedness.

fa0 and 0xfa0 represent the exact same number. However, without context, you probably wouldn't realize that the first represents a number in hexadecimal format. The 0x prefix is just a hint for you (or the computer) that it represents a hexadecimal number.

As for why it doesn't: Why should it? It's not necessary. If you were to process it and already know it represents a hexadecimal number, you would just ignore the 0x prefix. Thus, it may make processing slightly less cumbersome under some circumstances.

Signedness is about being able to represent both positive and negative values.

Title: dechex(4000) - Why is it not signed?


问:
Estimate of each localization's prospects on Mac App Store
I write utility programs (converters, compression tools, etc.) with simple UI’s, which I put for sale of for free download on the Mac App Store.

I write these programs in English, and usually add a French localization (which I do myself). By comparing the distribution of sales per country between a localized app and nonlocalized one, I can estimate how much the French localization boosts my sales. (The apps themselves are pretty generic and not country-specific, which makes the comparison possible.) For example, on nonlocalized app A, my sales in France are 2.5% of all sales, while on localized app B, sales in France amount to 10%. This means localization increased my overall revenue by 8.4%.[1]

My question is: does someone have an estimate of how much localization is worth for each language? (according to this metric, i.e. potential added revenue) This would be a great help to prioritize new localizations (which I cannot do myself).

[1] And not, that's not 8.5%.

答: Haha, good question! It's hard to estimate a percentage for each language, but you can think about apps with similar subjects with yours and look for charts about how it was received in each country. And about localizing apps efficiently, I want to suggest a tool I use, http://poeditor.com/. It has translation memory, which helps a lot when you have many projects, and lots of other features.</p>


问:
Why is it so difficult to know where to use interfaces,generics in program design?
I am attempting to learn c# from the head first series, in addition i also consult other books such as Pro C# by Andrew Tolson.

Now the thing is that i perfectly understand the interface,generics syntax and can also use it for the programs given in the exercises.

What i find difficult is using these concepts into my own programs. For example the other day i was making a twitter account managing client and despite my best efforts i was unable to use any of the aforementioned concepts in code. I was even having difficulty in making useful classes.

What are some guidelines I can use to decide what classes I need to create for my program, assuming I know the syntax of how to create a class, but not the idea of when to do so?

答:
If you want to develop a sense for when to use interfaces, generics, and design patterns, then you should read 'Head First Design Patterns'.

It's a very approachable book for somebody at your level with a desire to learn more.

Please don't misunderstand me. Troelsen's book is good too. Just think of 'Head First Design Patterns' as "Level 2". Also, don't let the fact that the code samples are written in Java scare you away. The underlying concepts apply equally to Java and C#.


问:
Refactoring code smells in ASP.NET Web Forms Code Behind Files: Is it risky? Is it wise? Is it a waste of time?
Given a long method with Pac-Man ifs, would it be wise to:

Break down code blocks into regions.

Then refactor code blocks into methods.

Or would it be best to leave it alone?

Would it be risky?

Would it be a waste of time?

In the absence of automated unit-tests, I'm trying to understand the risk-reward relationship associated with this manuever.

答:
Your plan, or clean up the logic on the ifs (in cases where the pacman structure is an inefficient order or view of the conditions) is usually the place to start IMHO.

As to if it is worth the effort:

do you expect to be changing this page much?

do you have trouble understanding what is going on in there to the point you are wary of modifying it?

do you think it is causing a performance or stability problem?

is there no real reason it was done this way in the first place?

would it be trivial to manually validate the correctness of the re-factor?

IMHO unless you have some strong "yes" answers to those questions re-factoring it is a questionable exercise when compared to the risk of botching it and the fact that you could be adding new value elsewhere with your time.


答:
I think you are taking a natural progression that all programmers go through. Explanation and examples of programming concepts are almost always presented in the simplest context possible. The goal is to focus on the concept and not get distracted by a lot of other concepts. Ever notice that many examples don't include error-handline? You get a try/catch at most.

The next step is to do something more complicated. Let's use your Twitter client as an example. You built it and it works and you see no 'need' for any of this. Very common. Now, see if you can make this same application handle managing a Facebook, Evernote or some other online service account. What parts are difficult to change? How do you avoid code duplication? Try and research some of the concepts you mentioned and see if you can find out "why" you would use them.

The next step, try and add another programmer to your project.

Title: Why is it so difficult to know where to use interfaces,generics in program design?

Body:
I am attempting to learn c# from the head first series, in addition i also consult other books such as Pro C# by Andrew Tolson.

Now the thing is that i perfectly understand the interface,generics syntax and can also use it for the programs given in the exercises.

What i find difficult is using these concepts into my own programs. For example the other day i was making a twitter account managing client and despite my best efforts i was unable to use any of the aforementioned concepts in code. I was even having difficulty in making useful classes.

What are some guidelines I can use to decide what classes I need to create for my program, assuming I know the syntax of how to create a class, but not the idea of when to do so?


问:
What defines "software developer" role
I am a junior software developer and I have been working for a company less than a year.

While I always thought being a software developer means to develop software and CODE something, my tasks are more in administration type of work, such as setting up Jenkins, SQL Replication and etc.

Are these type of jobs included in a Developer role, or a developer only develops software? Should I be talking to my manager about this? Is this a common way for companies to evaluate "developing" skills?

答:
It depends. It seems that different companies define this differently and for some it is an umbrella term for an array of technical functions. For some it is just a title. Asking the same question before, I got an answer similar to "Only developers have the capability to do this in our organization", I'd say maybe, but that does not necessarily make it development).

The theoretical answer is that a developer (comparing with coder/programmer) is a person who "solves problems" even if they do not have to do with "coding something".

You want to code more, so maybe ask your manager for more coding tasks or to do some of the things you do by coding? You mentioned operational stuff, so maybe some of them could be done by DevOps frameworks (check chef and puppet), which will make the functions more efficient and are close to development.

Title: What defines "software developer" role


答:
I find the term "Software Developer" to be synonymous with "Programmer". Thus a software developer is a person whose primary responsibility is to write code. In my first job, my title was "Developer", and my primary responsibility was to design and code software. But I think that there is no exact definition of the term. It is used differently by different people, thus the meaning becomes fuzzy.

But for a development team to work efficiently, you must have these things set up, CI servers, SQL replication, Deployment to test servers, monitoring of test servers, archiving of builds, etc. (Maybe not all of them applies in any situation).

These tasks will take up a large amount of time in a project's initial phase, but will take up a smaller amount of time once you have a nice setup running.

Unfortunately, developers would rather code than managing build servers. Therefore often, these boring tasks fall in the hands of junior developers, as the senior developers have more important tasks.

I have not experienced any company that uses these tasks as a means to evaluate skills.

If you are dissatisfied with your current responsibilities, I would suggest taking up the issue with your line manager.

Title: What defines "software developer" role

Body:
I am a junior software developer and I have been working for a company less than a year.

While I always thought being a software developer means to develop software and CODE something, my tasks are more in administration type of work, such as setting up Jenkins, SQL Replication and etc.

Are these type of jobs included in a Developer role, or a developer only develops software? Should I be talking to my manager about this? Is this a common way for companies to evaluate "developing" skills?


问:
Custom templating in a web application
I want to understand the pros and cons in generating dynamic web application controls.

The idea is to generate all the controls dynamically based on the database procedure output and populate the controls to a  say a grid structure / independent controls.

I know that creating user controls and populating to layout is one option.

Say, if we don't know what is the structure of controls the procedure is going to generate based on complex logic; what all should be considered in generating a layout structure?

Is what I am thinking of is not logical in web application sense?
Do I need to tackle the issue in a top down approach than a bottom up approach?

答:
I think the question of whether you choose to tackle such a problem from the top down vs. bottom up is largely dependent on what design principles you seek to move towards.

The biggest concerns that I have from your proposed design is that the application tiers (Eg. Presentation/GUI, Middle Tier, Database, etc...) are muddied.  There is nothing inherently wrong with a single tiered approach to application design, however if an Architectural Requirement or Assumption is provided that this must be a distributed multi-tier application then your design is already violating these principles.

If you are identifying the Database procedure as a seperate Component in a Component Oriented Architecture then you are now also introducing tight coupling.  This however would not be tight coupling if your Components are all to be designed with vertical integration in mind.  This is another architectural assumption you will need to check on.

Beyond that I have actually worked on such projects before that employed a similar design scheme and have seen the pros and cons of this design approach personally.  In my honest opinion the Cons outweigh the Pros here.  The pros here are that changes to layout and components on a screen become a schema change.  If you anticipate that power users will have the ability to deeply customize their screens then it is an ideal model, however if this is not the case then it can be constraining, especially when new requirements dictate specific UI features.

Look into component based web frameworks like ASP.NET or JSF to see if these might better serve your needs without violating MVC or other architectural principles.

EDIT:

It seems that your requirements indeed dictate that users will have the ability to create their own screens and forms.  In this case, the bottom up approach is best.

This can still work with a multi-tier architecture and MVC model, but it will be complicated.  The following are some key points to keep in mind during your design process:

Decoupling

Keep your screen builder modules seperate from other domain business logic and data access.  Keeping these decoupled allows the application to be more maintainable and scalable as features are added.

Model

The model in this case will be your application business logic, and data access as well as any domain model entities that you wish to declare.  The screen builder model is seperate from this.

View (Screen Builder MVC and other Views)

The View will consist of the hard coded view pages as well as the entire Screen Builder module.

What does this mean?

Basically your View contains a completely sepereate self contained MVC design for user dynamic screens.

Screen Builder Model: The data access to the stored procedure that returns the data on screen elements.  This is also the domain model of the data returned.

Screen Builder View: The code that generates the dynamic user generated view.

Screen Builder Controller: The stored procedure, and other controller related tasks that mitigate between fetching and translating the model, and building the view for the user.

Controller

The controller in this case will be your web application framework controller.

The following model affords you a decoupled multi-tier approach by approaching the design of the dynamic form generation as a seperate MVC component operating inside of the web based MVC design of your overall application.

Title: Custom templating in a web application


问:
How do freelancer web developers manage web hosting for customers?
I have built a number of websites for friends, family, etc. and I have put them all on a single shared web hosting account. Now that they are built, I want to get out of business of supporting them and paying for them (my friends are reimbursing me but I am paying for the actual bill) so I was thinking of having them create their own hosting accounts and slowly migrating the sites over.

It got me thinking how does any freelancer do this? Do they force their clients to setup their own hosting up front and let the programmer log into the customer account during development. What if there is a bug in the future and they need to go back in?

I was curious to see what model most people use who build websites for others as it seems like a tricky situation.

答: I create websites in ASP.NET so I need my customers to use a web hosting company that supports that technology. I tell my clients to sign up at the URL of a specific hosting account and exactly what plan to select and how much it cost. (No, I don't get a markup - it just makes my life easier this way). I tell them once they get their "Welcome Email" from the hosting company to forward it to me so that I have their FTP username and password and can setup their server. I, of course, also offer that if they'd rather, I could send them all of the web files and they can do the setup of the server and FTP the files over themself. Most of them are so very non-technical that just hearing the words 'server and FTP' is enough for them to say, 'no, that's okay, I'll let you do that." I then use FileZilla and transfer the files over. Easy.</p>


答:
You shouldn't put an URL in the QR code. It should only contain an ID that is represents their ticket. Then when you scan the persons QR code at the door, you check if that ID is valid and let them enter if it is.

Assuming your ID is sufficiently large, this would be near impossible to abuse.


问:
What's a nice explanation for pointers?
In your own studies (on your own, or for a class) did you have an "ah ha" moment when you finally, really understood pointers? Do you have an explanation you use for beginner programmers that seems particularly effective?

For example, when beginners first encounter pointers in C, they might just add &s and *s until it compiles (as I myself once did). Maybe it was a picture, or a really well motivated example, that made pointers "click" for you or your student. What was it, and what did you try before that didn't seem to work? Were any topics prerequisites (e.g. structs, or arrays)?

In other words, what was necessary to understand the meaning of &s and *, when you could use them with confidence? Learning the syntax and terminology or the use cases isn't enough, at some point the idea needs to be internalized.

Update: I really like the answers so far; please keep them coming. There are a lot of great perspectives here, but I think many are good explanations/slogans for ourselves after we've internalized the concept. I'm looking for the detailed contexts and circumstances when it dawned on you.

For example:

I only somewhat understood pointers
  syntactically in C. I heard two of my
  friends explaining pointers to another
  friend, who asked why a struct was
  passed with a pointer. The first
  friend talked about how it needed to
  be referenced and modified, but it was
  just a short comment from the other
  friend where it hit me: "It's also
  more efficient." Passing 4 bytes
  instead of 16 bytes was the final
  conceptual shift I needed.

答:
I made my life easier when I just removed all the fluff and started treating pointer as any other variable rather than some magical entity (long long ago in grade 11).. just know 3 things:

Pointer is a variable that store the address of another variable (or just any address).

* is used to get the value at the memory location that is stored in the pointer variable.

& operator gives the address of a memory location.

The rest is syntactic sugar and common sense.. Just write some simple C programs (like implementing a linked list library) using pointers to get a hang of it.

Title: What's a nice explanation for pointers?


答: Have the person scanning the codes visit some other page, with some other long url. On that page place a specific cookie. Then, accept confirmation coming only from users with that cookie.</p>


答:
It is not uncommon for a Developer to be expected to have some system administration skills. As a senior developer, I estimate that about 5% of my time is spent on such tasks.

However, if you are not doing any coding, then you probably should talk to your manager about getting coding tasks. After all, you want to build up coding experience. You are also more valuable as a programmer than as a system administrator.

Title: What defines "software developer" role


问:
Requirement specifications with annotations?
I'm curious if there are any templates using annotations such as ambiguous, needs update and so on. Industrial or Academic does not matter.

If there are, are there any way tools available that use these annotations to show that "22% of the requirements are tagged ambiguous" and so on?

Bonus points for Academic papers on this topic (or a nearly related topic)

答:
Although not a document template, requirements management tools such as IBM Rational DOORS are full-fledged requirements databases. For each requirement, one can add additional attributes to it for various purposes, ranging from commentary to tracking. As a project progresses, these attributes are updated to reflect the current state of the requirement along with the feature(s) that it represents. You can then query over these attributes (find attributes with a certain value or set of values, free-form text fields that are not empty, and so on) and produce counts and metrics over these. In addition, you can export requirements to Word or Excel formats, optionally including these other attributes.

I'm not familiar with any other requirements management systems. Systems I've worked on tended to be small enough where an Excel spreadsheet was sufficient to provide the tracking and traceability of requirements, or DOORS was the system of choice by my employer. I suspect that a requirements database or a spreadsheet (with the ability to count, filter, and sort) would be far better the capturing these numbers and performing analysis.

So, yes. Tools like this exist. However, probably not in document/textual form - you really need some kind of table or data management system to do the kind of automated analysis you're talking about.


问:
RESTful Design: Multiple Relationships Between the Same 2 Entities
I am in the process of designing RESTful web services and got stuck at one point. The design is very simple with 3 entities:

```<code>- Project
- Status
- Employee
</code>```

The part I am having trouble with is capturing the relationships:

```<code>- A project has a current status (1 to 1 between Project and Status).
- A project has multiple 'possible subsequent status' (1 to many between Project and Status).
</code>```

The Visual Studio designer does not allow these two different relationships to be defined between these two entities. I am aware that it is just a modelling tool but at the same time, I am willing to know if this is the right approach.

Also, with this design, I am not sure how to access the Status entities using these two relationships.

```<code>http://serviceRootURL/Project(2)?$expand=Status // For current status
http://serviceRootURL/Project(2)?$expand=SubsequentStatus // For subsequent status
</code>```

Is it possible to use arbitrary relationship names with the expand keyword?

(The question probably touches OData a little bit as well since I am trying to make my library OData-compliant.)

答:
As in Domain Driven Design, it is possible to qualify the relationship wrt time? Then for a particular time period, you will have one-to-one relationship between Project and Status.
Hence, you can define only one relationship?

Sorry, no clue about REST at all


答:
Code is not terribly useful if it doesn't get built into an application properly, or access the correct data, so the activities you list seem very much in line with what a developer does.  I should add that software developers also get very mixed up in documentation and testing as well.  These are activities necessary in the production of software.

It's great if your company has specialists that can do this stuff for you, but if not, software developers are responsible for everything up to (and possibly including) deploying an application into production and supporting it there.

Title: What defines "software developer" role


答:
It is fairly common for a developer in a small to medium sized company to take on some server administrator/DBA/general configuration tasks.

However, if these tasks start to become the bulk of your responsibilities, it may be something to be concerned about depending on your career goals. Though you can probably thrive within certain companies as a general technologist, when you need to move to a new company it can cause many issues in your transition. If you are not doing any traditional development, you need to be sure to make that clear on your resume. If you want to get a job in straight development after a stint in a job as you described, you may have to accept something you are "overqualified" for based on years in the industry.

On the other hand, there may be companies looking for developers with diverse skills. But with the current trend of writing code in interviews, you will need to have top notch coding skills as well, even if the job requires little code once you get in.

If you don't want to get stuck in your current position, I would definitely try to remedy the situation soon.

Title: What defines "software developer" role