问:
Every SQL statement has to be reviewed by a DBA -- common?
I mean everything, not just schema changes. Even a simple SELECT on a primary key can't go into production, even though it has been code-reviewed by other developers (in context), without a DBA review of every statement, extracted from the code and submitted with EXPLAIN output, details of how often it will be called, etc, etc.

If you've been in such an environment, did you find it to be a net gain, or a drag on development? As someone who has been working with relational databases for years, I find the "developers can't be trusted to use databases" attitude unwarranted, and I'm curious as to how common this situation is. For what it's worth, this is just for web development, not something critical.

答:
I've never worked in an environment like that, I'm sure I would hate it. A thought comes to mind to start keeping track of some metrics around this...

How much time does a dev spend pulling sql out of code and preparing
it to be submitted to a DBA

How long does the DBA take to review the sql?

How often are changes requested by the DBA? Broken down by query

type?

Keeping track of this for just a little while would likely show how much of a drag it is versus how effective it is.


答:
At one of my previous jobs I (along with three other programmers) were responsible for reviewing every stored procedure created or updated before it went into production for about 40+ programmers.  As a reviewer it was a real drag on my time but overall it was still needed because with that many developers will make a mistake once in a while.  It came about because we had off-shore programmers who wrote really bad (efficient wise) SQL statements and they flat-out refused to learn (that team was eventually shut down).

Overall we looked for:

Index usage - was the query doing a full table scan?

Maintainability - was the query going to need to be changed in a couple of weeks because something was hard-coded into it?  And is the query readable?

Overall efficiency - could a inner join be replaced with an exists?  Would adding a With block help?

Locking issues - would the query lock the database and prevent updates from happening?  This happened more than I care to think about.

More often than not most queries had no issues and we pushed it on.  But each review took between 10 minutes and two hours depending on the query.  Part of me liked the idea of doing reviews because it prevented the dreaded 2 AM phone call because some report was causing an issue with another application.  But at the same time I thought it was a bit overkill because we are all grown-ups and the person writing the query should do all that stuff themselves.

I think complex queries should be part of the standard code review, but doesn't need to go through a DBA.  Nor is reviewing simple insert/update/delete statements is not needed.  In addition, as a writer of a query you should know when it has gotten too complex and know when to ask for a review from a DBA.

Update
In my very first job all queries were written by DBAs and that was a major time killer on development.  I had to submit all the columns I wanted, tables where the columns were located and finally my search criteria.  Even basic insert/update/delete statements needed to go through a DBA.  Eventually I got to the point where I could write the SQL I wanted, have them take a look at it and make any necessary changes, and then wrap a stored procedure around it, but that was only have a couple of years there.  That particular company hired a lot of recent college grads and this was the way they ensured the new guys didn't write queries that killed the performance.

ContentLicense: CC BY-SA 3.0

Title: Every SQL statement has to be reviewed by a DBA -- common?

Body:
I mean everything, not just schema changes. Even a simple SELECT on a primary key can't go into production, even though it has been code-reviewed by other developers (in context), without a DBA review of every statement, extracted from the code and submitted with EXPLAIN output, details of how often it will be called, etc, etc.

If you've been in such an environment, did you find it to be a net gain, or a drag on development? As someone who has been working with relational databases for years, I find the "developers can't be trusted to use databases" attitude unwarranted, and I'm curious as to how common this situation is. For what it's worth, this is just for web development, not something critical.


答: Depends on how big the database is, and if it's shared among multiple applications.  Often the DBA team likes to know what queries will be run so they can ensure that the proper indexes are in place, or so they know who to notify if they have to partition a table.  And they do tend to be a bit better than the average developer at reading query execution plans and spotting places where hints could be specified to improve performance.  It's also a chance for them to get a heads-up that some high-impact queries are going to be coming down in the next release, so they can collect different statistics for the optimizer.</p>


问:
Why is there no generic implementation of OrderedDictionary in .net?
Why did Microsoft not provide generic implementation of OrderedDictionary?

There are a few custom implementations I've seen, including: http://www.codeproject.com/KB/recipes/GenericOrderedDictionary.aspx

But why did Microsoft not include it in the base .net library? Surely they had a reason for not building a generic.... but what is it?

Prior to posting this message, I did see:
https://stackoverflow.com/questions/2629027/no-generic-implementation-of-ordereddictionary

But that just confirms that it does not exist. Not why it does not exist.

Thanks

答:
In C# 4.0 In A Nutshell I read this:

An OrderedDictionary is a combination of a HashTable and ArrayList

There is no generic ArrayList

"The nongeneric ArrayList class is used mainly for backward compatibility with Framework 1.x..."

"An ArrayList is functionally similiar to List<object>"

"Reflection is easier with a nongeneric ArrayList than a List<object>"

Conclusion?

No generic OrderedDictionary because it's underlying construct is a (unofficially) depreciated class that has no generic version itself.

ContentLicense: CC BY-SA 2.5


问:
What parts of your coding standard contribute to quality code?
In response to This Question, I ask:   What are the best parts of your coding standard?

What are the best practices that help with code quality, reliability, maintainability, readability, etc.

Please include the language, the item from the standard, and the reason it improves your code.

答:
C# and Java:

Making sure logging of critical   sections is properly defined (log4*).

Keep methods and classes small (Single Responsibility).

TDD or
writing unit tests for important
sections of business logic (jUnit or
nUnit).


问:
Which http response do you return to a hit from a blacklisted ip?
I have been using the http:BL to block bad IP's from accessing my site.

If a malicious IP (comment spammer) trys to hit the site I just exit the web script which implicitly returns a 200 OK response.

Other responses I could return:

404 - Not found?

If I return a 404 maybe the robots will think "this is a waste of time, lets move on to attack another site" which would reduce the load on the site (I currently get about 2 spam-hits per second).

However

I'm reluctant to return 404's on urls that, under normal circumstances, can be found.

I'm not sure if spam robots can 'waste time'. i.e Why would a bot writer be bothered to code for 404's when they just blitz the web anyway?

401 Unauthorized?

Blocking a bad IP is not quite the same as "resource requires user authentication 1) which has not yet been provided or 2) which has been provided but failed authorization tests"

In general I feel that 'responding to the bad-bots according to proper http protocol' gives the bad guys the upper hand. In the sense that I play by the rules while they do not. On some days I feel like I should do something clever to divert these bot's away. On other days I just think that I should not take it personally and just ignore them. Accepting it as par for the course of running a web site.

I dunno - what are your thoughts? How do you respond when you know its a bad IP?

答: I don't know whether it's a bad practice, but I'd configure server not to send any response at all.</p>

ContentLicense: CC BY-SA 4.0


答:
It totally depends on the environment, the industry and the company.

Some examples:

At NASA, multiple levels of checking and reviewing are the standard. The most well-known "should have doubled-checked" was when a probe was sent to Mars and the US did calculations in feet, but the Europeans in meters. The probe was lost.

At a startup with no DBA (common these days) there will be no DBA review and possibly even no programmer review (for example, if there are no other programmers in the company).

At a company whose product is a data warehouse of hundreds of millions of rows, making sure that queries are efficient and correct may be key issues at the core of the business that should be checked.

A company whose main product is a mainly static web site with a small number of database interactions, may consider the database and its efficiency to be less relevant. It may be that the company chooses to spend it's review "budget" on the static pages that are considered most critical.


答:
Because maintaining order prevents the O(1) lookup that IDictionary implies unless you wrap two collections (one for order, one for lookup), which makes add/remove less performant and increases memory usage. Or you could have slower lookup in exchance for less memory usage.

My guess is that there was no 'clearly better' choice here, so it didn't go into the standard library. Especially around 2.0, C# was still learning from Java's mistakes. I wouldn't be surprised if Java's 'everything and the kitchen sink' approach to collections in their standard library was viewed as something to avoid as well.

Title: Why is there no generic implementation of OrderedDictionary in .net?

Body:
Why did Microsoft not provide generic implementation of OrderedDictionary?

There are a few custom implementations I've seen, including: http://www.codeproject.com/KB/recipes/GenericOrderedDictionary.aspx

But why did Microsoft not include it in the base .net library? Surely they had a reason for not building a generic.... but what is it?

Prior to posting this message, I did see:
https://stackoverflow.com/questions/2629027/no-generic-implementation-of-ordereddictionary

But that just confirms that it does not exist. Not why it does not exist.

Thanks


答:
I would even go further. I'd check the surrounding code and see how are variables passed to the query. It's often to see how developers expose their application to sql injection attacks due to their lack of basic knowledge ("this can't be hacked" false assumptions).

Also unexperienced developers may drag the database down to its knees with a misuse of ORM or a query that is far from optimal.

In the most recent project I work at, none front-end developer is allowed to access database directly. They raise a demand for a function returning a given set of data and the back-end developers prepare it for them. It's working quite well, front-end devs write UI and process data supplied by functions written by back-end devs.


问:
Programming Language Parser (in Java) - What would be a better design alternative for a special case?

Background

I'm currently designing my own programming language as a research project.
I have most of the grammar done and written down as context-free grammar, and it should be working as is. - Now I'm working on the actual compiler that should translate the language into x86 binary assembly code, more specifically, I am working on the parser (the front end).

The language's syntax is, for the most part, very similar to Java/C/C++.
The parser, which constructs an intermediate representation out of source code, works as follows:

The grammar is built as a big tree in which the actual source code only determines the leaves; Each syntactic variable (or nonterminal) has it's own class, and each of these classes has a static get(byte[] source, int offset) method which returns a new leaf (node), or null if the source code syntax does not fit this nonterminal structure.

I am using a variation of predictive parsing, by the way.

For the nonterminal DataType, I have chosen the following grammatical structure:

```<code>DataType:
    PrimitiveDataType
 |  ArrayDataType
 |  ComplexDataType

ArrayDataType:
    DataType []
</code>```

Did I mention this language is object-oriented?

So the problem here is that when DataType's get method is called, it first checks whether the following is a primitive data type, PrimitiveDataType's get method is called. Assuming we have an array, this would return null, so it continues on to check whether it's an ArrayDataType, by calling it's get method.

Problem

Arrays may be created of any data type, including arrays themselves (which would look like Type[][]). So what ArrayDataType's get method would do is again call DataType's get method to figure out what type the array is of.
Unfortunately, this is where my parser implementation would fail because this behavior results in a loop!

Question

Would there be any good/better design alternatives to this?

答:
This problem you are facing looks with something I've already faced. In that case, it should be implemented in the Syntatic Analyzer class, and yes, it will generate a tree, it would be indeed recursive.

E.g.: in my case, I had to implement a way that the function would receive a list of arguments, so my grammar rule for arguments list would be something like this:

```<code><ArgLi> ::= <Arg> <ArgLi> |
</code>```

where:

<Arg> ::= '(' <Type> Identifier ')'

<ArgLi> is called recursivelly

<Type> ::= 'int' | 'real' | 'str'

Identifier    = {ID Head}{ID Tail}*

So, to implement that feature, the command has delimiters, so even if it enters a loop, it will check the rule, and determine the action based on the current token I'm looking.

For example, let's say I want to write this:

```<code>( def main [ ( int a1 ) ( str a2 )  ]

...

)
</code>```

The code my language follows to understand this is:

```<code>/**
 * <Def> ::= '(' 'def' Identifier '[' <ArgLi> ']' <CommandLi> ')'
 */
public Node Def() {

    Node node = new Node(NodeIdentifier.DEF);
    if (token.getImage().equals("(")) {
        node.addSon(new Node(NodeIdentifier.TOKEN, token));
        token = readToken();
        if (token.getImage().equals("def")) {
            node.addSon(new Node(NodeIdentifier.TOKEN, token));
            token = readToken();
            if (token._getClass().equals("ID")
                    || token.getImage().equals("main")) {
                node.addSon(new Node(NodeIdentifier.TOKEN, token));
                token = readToken();
                if (token.getImage().equals("[")) {
                    node.addSon(new Node(NodeIdentifier.TOKEN, token));
                    token = readToken();
                    node.addSon(argLi());
                    if (token.getImage().equals("]")) {
                        node.addSon(new Node(NodeIdentifier.TOKEN, token));
                        token = readToken();
                        node.addSon(commandLi());
                        if (token.getImage().equals(")")) {
                            node.addSon(new Node(NodeIdentifier.TOKEN,
                                    token));
                            token = readToken();
                        } else {
                            errors.add("Error: token ')' not recognized. line: "
                                    + token.getLine());
                        }
                    } else {
                        errors.add("Error: token ']' not recognized. line: "
                                + token.getLine());
                    }
                } else {
                    errors.add("Error: token '[' not recognized. line: "
                            + token.getLine());
                }
            } else {
                errors.add("Error: token 'ID' not recognized. line: "
                        + token.getLine());
            }
        } else {
            errors.add("Error: token 'def' not recognized. line: "
                    + token.getLine());
        }
    } else {
        errors.add("Error: token '(' not recognized. line: "
                + token.getLine());
    }
    return node;
}

/**
 * <ArgLi> ::= <Arg> <ArgLi> |
 */
public Node argLi() {

    Node node = new Node(NodeIdentifier.ARGLI);
    if (token.getImage().equals("(")) {
        node.addSon(arg());
        node.addSon(argLi());
    }
    return node;
}

/**
 * <Arg> ::= '(' <Type> Identifier ')'
 */
public Node arg() {
    Node node = new Node(NodeIdentifier.ARG);
    if (token.getImage().equals("(")) {
        node.addSon(new Node(NodeIdentifier.TOKEN, token));
        token = readToken();
        node.addSon(type());
        if (token._getClass().equals("ID")) {
            node.addSon(new Node(NodeIdentifier.TOKEN, token));
            token = readToken();
            if (token.getImage().equals(")")) {
                node.addSon(new Node(NodeIdentifier.TOKEN, token));
                token = readToken();
            } else {
                errors.add("Error: token ')' not recognized. line: "
                        + token.getLine());
            }
        } else {
            errors.add("Error: token 'ID' not recognized. line: "
                    + token.getLine());
        }
    } else {
        errors.add("Error: token '(' not recognized. line: "
                + token.getLine());
    }

    return node;
}
</code>```

As you can see the methods arg() and argLi() are called recursivelly, and that's how I've implemented it to avoid infinit loops in an efficient way.

I'm pretty sure this technique can help you with your problem.

OwnerDisplayName: Kierrow

Body:
This problem you are facing looks with something I've already faced. In that case, it should be implemented in the Syntatic Analyzer class, and yes, it will generate a tree, it would be indeed recursive.

E.g.: in my case, I had to implement a way that the function would receive a list of arguments, so my grammar rule for arguments list would be something like this:

<ArgLi> ::= <Arg> <ArgLi> |

where:

<Arg> ::= '(' <Type> Identifier ')'

<ArgLi> is called recursivelly

<Type> ::= 'int' | 'real' | 'str'

Identifier    = {ID Head}{ID Tail}*

So, to implement that feature, the command has delimiters, so even if it enters a loop, it will check the rule, and determine the action based on the current token I'm looking.

For example, let's say I want to write this:

( def main [ ( int a1 ) ( str a2 )  ]

...

)

The code my language follows to understand this is:

/**
 * <Def> ::= '(' 'def' Identifier '[' <ArgLi> ']' <CommandLi> ')'
 */
public Node Def() {

    Node node = new Node(NodeIdentifier.DEF);
    if (token.getImage().equals("(")) {
        node.addSon(new Node(NodeIdentifier.TOKEN, token));
        token = readToken();
        if (token.getImage().equals("def")) {
            node.addSon(new Node(NodeIdentifier.TOKEN, token));
            token = readToken();
            if (token._getClass().equals("ID")
                    || token.getImage().equals("main")) {
                node.addSon(new Node(NodeIdentifier.TOKEN, token));
                token = readToken();
                if (token.getImage().equals("[")) {
                    node.addSon(new Node(NodeIdentifier.TOKEN, token));
                    token = readToken();
                    node.addSon(argLi());
                    if (token.getImage().equals("]")) {
                        node.addSon(new Node(NodeIdentifier.TOKEN, token));
                        token = readToken();
                        node.addSon(commandLi());
                        if (token.getImage().equals(")")) {
                            node.addSon(new Node(NodeIdentifier.TOKEN,
                                    token));
                            token = readToken();
                        } else {
                            errors.add("Error: token ')' not recognized. line: "
                                    + token.getLine());
                        }
                    } else {
                        errors.add("Error: token ']' not recognized. line: "
                                + token.getLine());
                    }
                } else {
                    errors.add("Error: token '[' not recognized. line: "
                            + token.getLine());
                }
            } else {
                errors.add("Error: token 'ID' not recognized. line: "
                        + token.getLine());
            }
        } else {
            errors.add("Error: token 'def' not recognized. line: "
                    + token.getLine());
        }
    } else {
        errors.add("Error: token '(' not recognized. line: "
                + token.getLine());
    }
    return node;
}

/**
 * <ArgLi> ::= <Arg> <ArgLi> |
 */
public Node argLi() {

    Node node = new Node(NodeIdentifier.ARGLI);
    if (token.getImage().equals("(")) {
        node.addSon(arg());
        node.addSon(argLi());
    }
    return node;
}

/**
 * <Arg> ::= '(' <Type> Identifier ')'
 */
public Node arg() {
    Node node = new Node(NodeIdentifier.ARG);
    if (token.getImage().equals("(")) {
        node.addSon(new Node(NodeIdentifier.TOKEN, token));
        token = readToken();
        node.addSon(type());
        if (token._getClass().equals("ID")) {
            node.addSon(new Node(NodeIdentifier.TOKEN, token));
            token = readToken();
            if (token.getImage().equals(")")) {
                node.addSon(new Node(NodeIdentifier.TOKEN, token));
                token = readToken();
            } else {
                errors.add("Error: token ')' not recognized. line: "
                        + token.getLine());
            }
        } else {
            errors.add("Error: token 'ID' not recognized. line: "
                    + token.getLine());
        }
    } else {
        errors.add("Error: token '(' not recognized. line: "
                + token.getLine());
    }

    return node;
}

As you can see the methods arg() and argLi() are called recursivelly, and that's how I've implemented it to avoid infinit loops in an efficient way.

I'm pretty sure this technique can help you with your problem.

OwnerDisplayName: rogcg


问:
What's the most important, useful or enlightening thing you learnt in the last 12 months?
A lot of people in the coding community talk about continuous improvement, deliberate practice and so-on - but when they talk about their current practices it's almost like they 'sprang fully formed from the loins of Zeus' because you don't hear about how their opinions changed over time or what they learnt recently.

Every now and then though I go to a talk, or read a book, or talk to someone and they open up a bit more and I find that I learn a lot from these insights.

So, if you had to pick one thing from the last 12 months that you learnt what would it be?

答: I had to start maintaining a Python web application -- so I decided it was a good time to learn Vim as well.  Now I'm using IdeaVim plugin for Intellij for my Java and Flex development and I definately believe it's made my typing faster and more efficient.


问:
Is ATL a deprecated language?
I currently developing some M2M-transformations with the Atlas Transformation Language (ATL).

During studying the language constructs and properties I have often read, that ATL is a prototype for QVT, but was not used for QVT. This leads me to the question, if ATL is a deprecated language.

Personally, I claim that ATL is not deprecated because there are some indications for this:

If I look at the website of ATL the last Update was August, 26th 2011. The first specification of QVT was 2008. So I think the development of ATL seems to proceed.

There are also some papers since 2011 on google scholar:
http://scholar.google.de/scholar?q=atl+m2m&btnG=&hl=de&as_sdt=0&as_ylo=2011

It is still part of the M2M-frameworks of Eclipse

What would you say? Would it be better to user another M2M language or is ATL future proof? If not, do you know possibilities to transform ATL into other M2M-languages?

答:
In order to be deprecated, someone (that is, whoever maintains it) has to deprecate it. That doesn't seem to be the case here, as OBEO (listed on Wikipedia as a maintainer) still lists it in the Elicpse market as a current offering. It looks like it was updated last month.

So, no, it's not deprecated. Whether it's a good choice for whatever you want to do and how far into the future it might be maintained are separate questions and probably not on topic here.

Title: Is ATL a deprecated language?


问:
Scoring/analysis of Subjective testing for skills assessment
I am lucky in the sense that I have been given the opportunity to be a 'Technical Troubleshooter' for our offshore development team. While I am confident and capable of dealing with most issues, I have come across something that I am not. Based on initial discussions with various team members both on and offshore, a requirement for a 'repeatable, consistent' skills assessment has been identified.

In my opinion, the best way to achieve this would be a combination of objective and subjective tests. The former normally being an initial online skills assessment on various subjects, for example General C#, WCF and MVC. The latter being a technical test where the candidate would need to solve various problems and (hopefully) explain the thought processes involved with the  solution whilst doing so.

Obviously, the first method is consistent, repeatable and extremely accurate. The second is always going to be subjective and based on the approach, the solution (or possibly not) and other factors. The 'scoring' of this is also going to be down to the experience and skills of the assessor and this is where my problem lies;

The person that is expected to be the assessor initially (me) has no
experience.

The people that will ultimately continue this process for other
people will never remain the same due to project constraints and
internal reasons, this changes the baseline for comparison.

I am not aware of any suitable system that can be classed as
consistent and repeatable for subjective tests with the 2 factors
above, let alone if those did not exist.

So anyway, I have to present a plan that will ultimately generate a skills/gap analysis and it is unlikely that I will be able to use an objective method (budget constraints most likely reason). The only option left is the subjective methods and the issues above.

Does anyone have any suggestions for an approach that may tick all the boxes?

答:
For the second type of test (subjective), you may be able to follow a process such as this. Try and break up each of the topics for which skills are important to you, into groups. So C# can have groups such as:

String handling

OO programming

IO

Threads

You could do this for other topics as well.

Then for each of these groups try and write some simple statements. For String handling you could write statements like:

A developer should know how to concatanate strings

A developer should be able to determine if a String contains a specified substring

A developer should be able to split a String based on a regex

A developer should be able to determine if a String matches a regex

Then for each of these you can create some test cases which run against empty functions. Once completed these functions will get the test cases to pass.

This could be your subjective tests which can be run automatically.

Though keep in mind that creating your initial collection of tests will probably take a good deal of time.


答:
The problem is that using a LL(1) parser can lead to left-recursion.  You can avoid this by switching to a LR parser or using this grammar to avoid recursion:

```<code>DataType:
    PrimitiveDataType ArrayDataType
 |  ComplexDataType ArrayDataType

ArrayDataType:
    [] ArrayDataType
 |  (empty)
</code>```

If parsing is not part of your project, just search for a parsing library/generator, there are probably many out there.

Title: Programming Language Parser (in Java) - What would be a better design alternative for a special case?

Body:
Background

I'm currently designing my own programming language as a research project.
I have most of the grammar done and written down as context-free grammar, and it should be working as is. - Now I'm working on the actual compiler that should translate the language into x86 binary assembly code, more specifically, I am working on the parser (the front end).

The language's syntax is, for the most part, very similar to Java/C/C++.
The parser, which constructs an intermediate representation out of source code, works as follows:

The grammar is built as a big tree in which the actual source code only determines the leaves; Each syntactic variable (or nonterminal) has it's own class, and each of these classes has a static get(byte[] source, int offset) method which returns a new leaf (node), or null if the source code syntax does not fit this nonterminal structure.

I am using a variation of predictive parsing, by the way.

For the nonterminal DataType, I have chosen the following grammatical structure:

```<code>DataType:
    PrimitiveDataType
 |  ArrayDataType
 |  ComplexDataType

ArrayDataType:
    DataType []
</code>```

Did I mention this language is object-oriented?

So the problem here is that when DataType's get method is called, it first checks whether the following is a primitive data type, PrimitiveDataType's get method is called. Assuming we have an array, this would return null, so it continues on to check whether it's an ArrayDataType, by calling it's get method.

Problem

Arrays may be created of any data type, including arrays themselves (which would look like Type[][]). So what ArrayDataType's get method would do is again call DataType's get method to figure out what type the array is of.
Unfortunately, this is where my parser implementation would fail because this behavior results in a loop!

Question

Would there be any good/better design alternatives to this?

Body:
The problem is that using a LL(1) parser can lead to left-recursion.  You can avoid this by switching to a LR parser or using this grammar to avoid recursion:

DataType:
    PrimitiveDataType ArrayDataType
 |  ComplexDataType ArrayDataType

ArrayDataType:
    [] ArrayDataType
 |  (empty)

If parsing is not part of your project, just search for a parsing library/generator, there are probably many out there.


问:
What is the name to differentiate between parts of an app that have different types of users in each part?
On a project I'm working on, I'm trying to find a noun to describe the different parts of the application dependent on user interface. There are three parts: super admin, admin and regular users. Each of these parts consist of modules, interfaces with users, interfaces with the other parts.

I've tried "sub-system", "module", "environment", "platform" but none of these really described what each of these parts of the system is. I need a noun that captures everything included within each part e.g. the super admin(?) enables the owner to manually add and edit content. Normally I would just use "module" but there are many modules within each part.

答:
I typically refer to the back-end of my web apps as the "administrative interface".  Users understand that an interface is a specific view different from others, but can work with the same information.  The front-end is the "public interface".  There's never been a misunderstanding.

I should point out many of my clients often say "admin site" and "public site", which is technically incorrect, but seems to make the most sense to them conceptually.

I think "domain" or "tier" are also good suggestions (@LMC) since they imply security levels.  I reserve the word "role" for security and not UI.


问:
Documentation degrading - how to deal with it?
Important: we have no issues whatsoever with source code documentation. This belongs to regular code audit and is kept up to date. Our problem is with developers documentation (or, "external" if you like), little blog-like tips from programmers to programmers which tend to be once written, often left behind.

We use wiki-like system to produce programmers documentation - articles wrote by programmers for programmers describing in a bit more details how particular piece of code works. Those wiki-pages usually include:

motivations behind design decisions for parts of API (for example; we did this ugly thing because this particular 3rd party library wants stuff to be done this way, because this other library ..., because ...)

explanation of how we deal with particular common tasks (for example; displaying trivial popup, which needs to reference appropriate application styles, register itself in registry component, and implement some interface in order to be automatically "scanned" by other component)

good practices (subjective as it is, we do actually write this stuff down)

environment configuration, required tools and its setup

In general, primarily stuff related to writing code that doesn't fit regular code-documentation due to its size and blog post/article-like nature.

The Problem

As far as introducing this system seemed like a good idea few months ago, nowadays I feel like it's causing more problems than it solves. For example:

people do write articles... but once code changed, wiki update rarely follows

lot of scratch articles, wrote by somebody in hurry and left like that

even though article-request usually comes from project lead, it's hardly ever verified for correctness/composition - which sometimes results in poor quality

The usual degradation. Code changed, wiki stays the same. Next time somebody looks for information, what he usually finds is bunch of outdated, low quality stuff - and is wondering what's going on, whether stuff that he found is accurate or (even worse) which parts of it are. And what was supposed to help, ends up doing the opposite.

At the moment it seems people are aware of the problem, project lead included, but apparently nobody seems to be bothered to do anything with it (or has more interesting stuff to do).

My initial thought was to throw it all into the oblivion (after I got bitten by outdated "tips" few times in a row), but I suppose that might be too extreme. Some information is worth noting and good read sometimes, but the problem is still the same: how you deal with its "up-to-dateness"? Have it linked to source code somehow (so when updated version of file is checked into, author of article gets notified that he might need to revise code/article)? Have designated person "watching over" it on daily basics? Do regular cleanups?

答:
Radical but effective. If somebody wrote a new module but did not document it - reopen the task in issue tracker and if it is necessary prevent from shipping all not documented source code. If you allow developers to treat source code documentation as necessary evil you'll end up with fragmentary and outdated scraps of documentation.

In my recent project we tend to at least track all the necessary third party libraries. If somebody introduces new library, but it is not documented - we roll back the solution until the documentation is introduced. Without such a radical approach there would be chaos. For example an unexperienced developer could use a library whose license is in conflict with our software's license.


答:
Documentation should be treated as a deliverable and thus subject to the rules of traceability and acceptance, as well as given the appropriate amount of time to be developed.

It is not uncommon to see people "expecting" software documentation to be a given, when it isn't.

Title: Documentation degrading - how to deal with it?

Body:
Important: we have no issues whatsoever with source code documentation. This belongs to regular code audit and is kept up to date. Our problem is with developers documentation (or, "external" if you like), little blog-like tips from programmers to programmers which tend to be once written, often left behind.

We use wiki-like system to produce programmers documentation - articles wrote by programmers for programmers describing in a bit more details how particular piece of code works. Those wiki-pages usually include:

motivations behind design decisions for parts of API (for example; we did this ugly thing because this particular 3rd party library wants stuff to be done this way, because this other library ..., because ...)

explanation of how we deal with particular common tasks (for example; displaying trivial popup, which needs to reference appropriate application styles, register itself in registry component, and implement some interface in order to be automatically "scanned" by other component)

good practices (subjective as it is, we do actually write this stuff down)

environment configuration, required tools and its setup

In general, primarily stuff related to writing code that doesn't fit regular code-documentation due to its size and blog post/article-like nature.

The Problem

As far as introducing this system seemed like a good idea few months ago, nowadays I feel like it's causing more problems than it solves. For example:

people do write articles... but once code changed, wiki update rarely follows

lot of scratch articles, wrote by somebody in hurry and left like that

even though article-request usually comes from project lead, it's hardly ever verified for correctness/composition - which sometimes results in poor quality

The usual degradation. Code changed, wiki stays the same. Next time somebody looks for information, what he usually finds is bunch of outdated, low quality stuff - and is wondering what's going on, whether stuff that he found is accurate or (even worse) which parts of it are. And what was supposed to help, ends up doing the opposite.

At the moment it seems people are aware of the problem, project lead included, but apparently nobody seems to be bothered to do anything with it (or has more interesting stuff to do).

My initial thought was to throw it all into the oblivion (after I got bitten by outdated "tips" few times in a row), but I suppose that might be too extreme. Some information is worth noting and good read sometimes, but the problem is still the same: how you deal with its "up-to-dateness"? Have it linked to source code somehow (so when updated version of file is checked into, author of article gets notified that he might need to revise code/article)? Have designated person "watching over" it on daily basics? Do regular cleanups?


答: The key here is simply to use an LR parser rather than LL. There's a reason why virtually no implementations actually use LL as it's stated, and it's because it really can't recognize many particularly useful grammars.</p>


问:
Hardware programming for kids. What is the good way to start?
I am thinking about introducing my 12 year old son to hardware programming.  I built a robot with the .NET Micro Framework and while he was fascinated with controlling the robot, his eyes glazed over when I attempted to explain how the code worked.  And to be fair, it's quite complex for a beginner, requiring knowledge of OOP, interrupts, etc...

So I was thinking what is the best way for a kid to get into hardware programming?  I've heard of Basic Stamp, Arduino and Lego Mindstorms.

It seems like Arduino can do pretty much everything, but it's C and it sounds like the learning curve is really high.

Basic Stamp seems interesting and it is using BASIC from what I can see, but I can't tell whether it can do anything more complex than messing with the breadboard.  For instance, could I build a web server on it?

And finally, Lego Mindstorms looks impressive, but I don't understand how it's programmed, if you want to do anything out of the box.

Ideas?

答:
Lego Mindstorms is purpose-built for your task, i.e. teaching a kid about building programmable machines. I don't think you'll go wrong starting there. In addition to being easier to program than the other options, you also have the advantage that the hardware components integrate nicely with Lego bricks, so machines are easy to build and easy to modify.

Once the kid in question is comfortable with what you can do with Mindstorms, you can start looking at ways to make it do other things, or start looking at other systems. An Arduino board can be had for $25 or so, and Basic STAMP is pretty cheap too. Having some experience building with Mindstorms will let you (and the kid) focus on what's different.


答:
Predictive parser you selected (LL(k)) means you will have to solve left-recursion problems. Algorithm for solving direct and indirect recursions is clearly described on wikipedia:

http://en.wikipedia.org/wiki/Left_recursion

Some info can be found in posts here on StackOverflow:

https://stackoverflow.com/questions/2652060/removing-left-recursion
https://stackoverflow.com/questions/2999755/removing-left-recursion-in-antlr
https://stackoverflow.com/questions/4994036/left-recursion-elimination

In human language (non-scientific :) "left-recursion problem" means you can't endlessly go into recursion with non-terminal (A -> Ab) again and again. At some time you HAVE TO feed parser algorithm with a terminal to breake a loop.

In BNF this could look like:

Recursion Problem:

```<code>NT: NT T
NT: T
</code>```

One solution:

```<code>NT: T NT2
NT2: T NT2
NT2:
</code>```

For your grammar this could look like:

```<code>DataType:
    PrimitiveDataType ArrayDimensions
 |  ComplexDataType ArrayDimensions

ArrayDimensions:
    [] ArrayDimensions
 |
</code>```

If your parser generator doesn't allow empty productions and/or if you want to process array types separately, try something like this:

```<code>DataType:
    DataTypeName
 |  ArrayDataType

ArrayDataType:
    DataTypeName ArrayDimensions

DataTypeName:
    PrimitiveDataType
 |  ComplexDataType

ArrayDimensions:
    []
 |  [] ArrayDimensions
</code>```

Body:
Predictive parser you selected (LL(k)) means you will have to solve left-recursion problems. Algorithm for solving direct and indirect recursions is clearly described on wikipedia:

http://en.wikipedia.org/wiki/Left_recursion

Some info can be found in posts here on StackOverflow:

https://stackoverflow.com/questions/2652060/removing-left-recursion
https://stackoverflow.com/questions/2999755/removing-left-recursion-in-antlr
https://stackoverflow.com/questions/4994036/left-recursion-elimination

In human language (non-scientific :) "left-recursion problem" means you can't endlessly go into recursion with non-terminal (A -> Ab) again and again. At some time you HAVE TO feed parser algorithm with a terminal to breake a loop.

In BNF this could look like:

Recursion Problem:

NT: NT T
NT: T

One solution:

NT: T NT2
NT2: T NT2
NT2:

For your grammar this could look like:

DataType:
    PrimitiveDataType ArrayDimensions
 |  ComplexDataType ArrayDimensions

ArrayDimensions:
    [] ArrayDimensions
 |

If your parser generator doesn't allow empty productions and/or if you want to process array types separately, try something like this:

DataType:
    DataTypeName
 |  ArrayDataType

ArrayDataType:
    DataTypeName ArrayDimensions

DataTypeName:
    PrimitiveDataType
 |  ComplexDataType

ArrayDimensions:
    []
 |  [] ArrayDimensions


问:
How far should I expose this status enum?
I wrote a little app to manage an arbitrary series of tasks (e.g., call a SQL sproc and capture out-vars, run another app, run an SSIS package) with dependencies between tasks.  Each task has a status (waiting to start, failed and waiting to retry, failed and abandoned, succeeded, etc.).  Internally, each Task object has a field of the TaskStatus enum type.  There's a TaskManager object which starts tasks and monitors their successes and failures, and a Dashboard WinForm which displays progress.

Should I expose each Task's status as an enum throughout the app, or only to TaskManager, or always expose only the string value?  My approach has been to expose the status as an enum, but this means that not only TaskManager but also Dashboard has a dependency on the possible values for TaskStatus.

I almost posted this question on code review, but on balance I think it fits better here, sense it's mostly a matter of principle.

Dashboard only interacts with Task.Status in a two places.  First, its value is displayed in a DataGridView which summarizes all tasks, and this really should use a text value instead, if only to allow for prettier values.  Second, status values are compared when the Status column is sorted, and obviously this will work either way.

TaskManager is the iffy part.  For example, a TaskManager has props NumTasksRunning, NumTasksComplete, and NumTasksWaiting.  Originally, with Tasks exposing their statuses directly, I put this logic in TaskManager:

```<code>public int  NumTasksRunning   { get { return _tasks.Count(t => t.IsEnabled && (t.Status == TaskStatus.Running || t.Status == TaskStatus.Aborting || t.Status == TaskStatus.FailedAwaitingRetry)); } }
public int  NumTasksComplete  { get { return _tasks.Count(t => t.IsEnabled && (t.Status == TaskStatus.Succeeded || t.Status == TaskStatus.FailedAbandoned)); } }
public int  NumTasksWaiting   { get { return _tasks.Count(t => t.IsEnabled && (t.Status == TaskStatus.Waiting)); } }
</code>```

I could move this logic to properties in Task, protecting TaskManager from needing to know about the enum:

```<code>public bool  IsRunning   { get { return _status == TaskStatus.Running || _status == TaskStatus.Aborting || _status == TaskStatus.FailedAwaitingRetry; } }
public bool  IsComplete  { get { return _status == TaskStatus.Succeeded || _status == TaskStatus.FailedAbandoned; } }
public bool  IsWaiting   { get { return _status == TaskStatus.Waiting; } }
</code>```

However, there are other places where the code is much simpler if TaskManager can see tasks' statuses directly:

```<code>public void  Abort(Exception ex)
    {
    State = TaskManagerState.Aborting;

    foreach (Task task in _tasks)
        if (task.Status == TaskStatus.Running && task.CanAbort)
            task.Abort(ex);
    }
</code>```

Of course I could add a new property to Task, maybe called CanAbortNow (CanAbort means the task can be aborted in principle, separate), but this is just one of several touch points.  If I end up with an "IsX" property for every possible value of TaskStatus, have I really made the code any easier to maintain?

This app is for my personal use, so the choice really only matters in that I'd like to know the "right" way - if there is any consensus.

答:
I'm not sure you'll find a consensus, but:

In my opinion, it's pretty okay to reuse the enum; better than supplying arbitrary strings anyways... If the dependency is harder than you'd like then have an intermediary adapter layer. Let the UI have its own status enum, and the glue layer adapts one enum to the other to help decouple the change impact between the UI and the task layer.

I'd tend to favor having the adapter layer, but for small or infrequently changing apps it is perhaps an unnecessary complexity.


问:
How do I locate Uncalled Functions?
I am looking at some C/C++ code that appears to have functions that are defined, but never used. This is a pretty tedious process to trace through the code and verify. I've done some surveys and there are a number of tools that can do this type of analysis.

Can anyone share any experiences or tips on which tools and techniques are best or alternative methods of verifying this code is in fact not used?

答:
IDEs usually have this feature well implemented and it works by default (it can usually be disabled).

Whatever method you pick from the other answers to find dead code, always be aware of reflection issues. Some methods/fields may be accessed through reflection alone. Removing those methods will not trigger any alarm, except on runtime.

If you have (good) tests written for your projects, they will be of great value in this situation.

Title: How do I locate Uncalled Functions?


问:
How granular should TDD tests be?
During TDD training based on medical software case we are implementing the following story: "When user presses Save button, system should add patient, add device and add device data records".

The final implementation will look something like this:

```<code>if (_importDialog.Show() == ImportDialogResult.SaveButtonIsPressed)
{
   AddPatient();
   AddDevice();
   AddDeviceDataRecords();
}
</code>```

We have two ways to implement it:

Three tests where each verifies one method (AddPatient, AddDevice,     AddDeviceDataRecords) was called

One test which verifies all three methods were called

In the first case if something wrong is happend to if clause condition, all three tests will fail. But in the second case if test fails, we are not sure what is exactly wrong. What way would you prefer.

答: One simple rule of thumb that I've been following is to name the test so that it describes precisely what the test does. If the name of the test gets too complex it is a sign that the test is perhaps doing too much. So for example naming a test to do what you propose in option 2 may look like PatientIsAddedDeviceIsAddedAndDeviceDataRecordsWhenSaved which is much more complex than three separate tests PatientIsAddedWhenSaved, DeviceIsAddedWhenSaved, DataRecordsWhenSaved. I also think the lessons that can be learned from BDD are pretty interesting where each test is really representative of a single requirement that could be described in a natural language. In this vein I like the idea of handing a list of the test names to a non-developer for verification that we have covered all necessary requirements so anytime a single test becomes too intimidating in terms verbosity I think it's a great reason to consider breaking up the tests.</p>

Title: How granular should TDD tests be?


答: There's always Scratch for Arduino.  Haven't played with it personally (one of the reasons I enjoy programming my Arduinos is I get to use C), but it looks like a pretty good project.</p>

Title: Hardware programming for kids. What is the good way to start?

Body:
I am thinking about introducing my 12 year old son to hardware programming.  I built a robot with the .NET Micro Framework and while he was fascinated with controlling the robot, his eyes glazed over when I attempted to explain how the code worked.  And to be fair, it's quite complex for a beginner, requiring knowledge of OOP, interrupts, etc...

So I was thinking what is the best way for a kid to get into hardware programming?  I've heard of Basic Stamp, Arduino and Lego Mindstorms.

It seems like Arduino can do pretty much everything, but it's C and it sounds like the learning curve is really high.

Basic Stamp seems interesting and it is using BASIC from what I can see, but I can't tell whether it can do anything more complex than messing with the breadboard.  For instance, could I build a web server on it?

And finally, Lego Mindstorms looks impressive, but I don't understand how it's programmed, if you want to do anything out of the box.

Ideas?


答:
Get the kid a power supply, a breadboard, a set of components, a mountain of LEDs, and some 555 timers. If he wants to play with hardware, give him hardware. </p>

<p>(and maybe a scope, if he's been a good boy.)</p>

Body:
Get the kid a power supply, a breadboard, a set of components, a mountain of LEDs, and some 555 timers. If he wants to play with hardware, give him hardware.

(and maybe a scope, if he's been a good boy.)


答:
I have not worked in such an environment, nor would I.

There is a difference between teamwork and hostile bureaucracy. As a developer, I'd love to have DBA input on difficult queries. But I know when to ask for help.

If I'm not competent enough for simple SELECT queries, I should be fired.


答:
If something's changing rapidly, it shouldn't be maintained outside of the code.

motivations behind design decisions for parts of API

This is especially important to keep close to the code. As in, in the same source file. That way, it will be a little harder to ignore whenever someone touches the file, and prompt fewer submissions to TheDailyWTF by people who don't know that the external documentation exists.

The usual degradation. Code changed, wiki stays the same.

This is where "executable documentation" -- unit tests -- becomes very useful. If the code changes and the tests don't change along with it, then the build breaks. Of course, writing tests as documentation takes some skill. But so does writing (good) external documentation.


问:
Capturing correct level of detail in a user story
I have written various user stories that describe functionality at a pretty high-level. For example:

```<code>As an analyst, I want to view the current share price, so that I have quick access to an up-to-date valuation of stock across the Euronext, London and New York stock exchanges.
</code>```

This requirement is based on existing functionality that is being re-developed in a new version of some software. I can see from the existing implementation that the actual information displayed includes a lot of extra data such as different classes or shares, different timescales of graphs etc.

I think it is impractical to capture all the functionality in the current implementation. So I have two questions:

How do I decide an appropriate level of detail for the requirement that is basically 'do what the current piece of functionality does'.

Is there some structured approach of accompanying the user story with more information? At the moment, I feel this would be the job of wireframes.

答:
How do I decide an appropriate level of detail for the requirement that is basically 'do what the current piece of functionality does'.

You should be wary of doing this. This requirement implies that the functionality needs to be maintained, rather than the business need be satisfied. Often times this can lead to bad decisions being carried forward, or limit the innovation that your team might be able to provide the business.

I would be inclined to go with this high level story, and then provide more stories around the other use cases that the business has. Granularity has its advantages.

OwnerDisplayName: Jack


答:
As an analyst, I want to view the current share price, so that I have quick access to an up-to-date valuation of stock across the Euronext, London and New York stock exchanges

As written, this has no business value: you don't say what the analyst does with the data, just that s/he can access it. Here's how I'd rewrite the story to add value (which may not be the value that your analyst actually wants):

As an analyst, I want to view the current share price across the Euronext, London and New York stock exchanges, so that I can make trades to arbitrage differences in the price.

The first part of the story says what the analyst wants, the second gives the business value. In your original formulation, both parts said what the analyst wanted, but not why.

And the relevance to your question: the level of detail should give both what and why, but not how (the how might be covered by wireframes).

Title: Capturing correct level of detail in a user story

Body:
I have written various user stories that describe functionality at a pretty high-level. For example:

```<code>As an analyst, I want to view the current share price, so that I have quick access to an up-to-date valuation of stock across the Euronext, London and New York stock exchanges.
</code>```

This requirement is based on existing functionality that is being re-developed in a new version of some software. I can see from the existing implementation that the actual information displayed includes a lot of extra data such as different classes or shares, different timescales of graphs etc.

I think it is impractical to capture all the functionality in the current implementation. So I have two questions:

How do I decide an appropriate level of detail for the requirement that is basically 'do what the current piece of functionality does'.

Is there some structured approach of accompanying the user story with more information? At the moment, I feel this would be the job of wireframes.


答:
I've seen this done at a couple of different places.  It's great in theory, but I have rarely seen it be effective.  Here's why.  Firstly, if you have a team of DBAs (or other people), I've generally found that the least competent or least liked person of the group gets the brunt of the review work.  Why, you say?  It's because, no one else wants to do it, and everyone else is busy doing other things that are probably more urgent.  Ever seen a DBA sit around and say, "Man everything is running perfect; I can just sit back and surf the net.  I wish I had something to do."  Me either, at least not the good ones.  They are as busy or busier than everyone else.  This means that the person who is least capable is most likely doing the reviewing, and this is exactly the person you don't want doing it.  The code you want reviewed is the really really hard code that people look at and pass it off as some sort of black magic.  Junior DBAs or just plain bad ones, won't ever be able to catch the subtleties of how a really hard query works.  Rarely, like never, does someone ever say, "Man I didn't think of selecting a single row out of a table using the primary key!  Thanks DBA you're a lifesaver."  So in this scenario, really all you are doing is creating a lot of work for little value.

Secondly, it's just plain more work for the DB group.  What is probably going to happen even if they do look at other things is they are going to take a quick look at it and something is going to get missed.  They are busy people, and reviewing code is really time consuming.  In truth it's not fair that they get tasked with this, because it's an excuse for everyone else to be lazy and use them as an out, which is ultimately what happens.  Something breaks in production, and the developer quickly points out, "Well the DBA reviewed it."  Now is this true all the time, no, but it is true part of the time and often from the people who need to have their code really reviewed.  So you have buried the DBA with extra work and forced that person to be responsible for someone else's mistakes, when that person probably doesn't have enough time to fix all the mistakes currently in production.

The only way to really solve the problem is to have people who know how to write SQL code write it. Should they get input from the DBAs from time to time?  Of course they should, but I have always found, if you don't have time to do it right the first time, when are you going to find time to fix it.


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

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

答:
A computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are, in short, a perfect match.

    — Bill Bryson

LastEditorDisplayName: Roger Pate


答:
I've worked in that sort of environment. All system changes were peer reviewed by appropriate peers. For me it just meant I had to plan ahead and submit my changes a few days in advance. SQL went to the DBAs who would ultimately release the SQL into production.

My SQL is usually fine, they caught a couple of silly errors. It feels overly bureaucratic at first, but I work in finance. You saw what happens (If you're in the UK) a few months ago when a major bank here messed up a routine upgrade and messed up all all the transactions leading to millions (At the least hundreds of thousands) of people unable to get at their money.


答:
It sounds like you are documenting too much trivia in the wiki.

Document blocks of code and methods in the code.  Try to make your code self-documenting so you don't have to make a lot of comments.  Writing unit tests can help too.

Document design decisions and architecture at higher granularity in the wiki so the wiki doesn't need to change often or take a lot of work to change.  If a lot of people on your team already know the architecture and the team is not growing rapidly then there may not be a strong case for documenting them at all, face-to-face is often the best knowledge transfer.

Rewrite or delete out-of-date information immediately, like dead-code the longer it remains the harder it becomes to spot and the more of it accumulates.  If you don't have time just delete it and mark the article as needing rework, it slows you down and is stored in version control anyway.

Document procedures by automating them in a script or installation file.  Otherwise keep them in the wiki, but every time someone uses a procedure from the wiki, tell them to try to improve the article or automate parts of the process.

Blog articles belong in blogs.  If people want to share their personal opinions and advice create a company blog for that.  They probably don't want their articles to be modified and no one will modify them anyway, so don't let them clutter up the wiki.


问:
How should I test my TEST code?

One of the few things that most software developers agree on is that
  you shouldn't rely on code to work correctly unless you test it. If
  you don't test it, it may have hidden bugs that are only going to
  cause you more work down the road.

I understand how to test my normal code, but how should I test my test code to make sure it can effectively find and report errors when they are present? I personally have been stupid enough to write erroneous test cases that would pass when they should not have, thus defeating the purpose of my writing tests in the first place. Fortunately, I found and fixed the errors in time, but according to testing mantra it seems like no test suite would be complete without having its own set of tests to make sure it worked.

It seems to me that the best way to do this would be to make sure the test fails for buggy code.* If I spend 2 minutes alternately adding bugs to the code and making sure it fails, I should have an acceptable degree of confidence that the tests 'work'. This brings me to my second question: What are good ways to introduce bugs to make sure that they are caught by the test cases? Should I just randomly comment out statements, make sure the wrong branch of an if-else gets run by negating its condition, and change the execution order of code with side-effects, etc., until I'm satisfied my tests will catch most common bugs? How do professional developers validate that their tests actually do what they're supposed to do? Do they just assume the tests work, or do they take the time to test them as well? If so how do they test the tests?

I'm not suggesting the people should spend so much time testing their tests and then testing the tests for their tests that they never actually write the real code, but I've done stupid enough things that I feel like I could benefit from a bit of 'meta-testing', and was curious about the best way to go about it. :D

* I could check to see if the test passes when testing 'bug-free' code, but using the code as a spec for the test seem quite backwards...

答:
One approach is Mutation Testing, using a tool like Jester:

Jester makes some change to your code, runs your tests, and if the tests pass Jester displays a message saying what it changed

Title: How should I test my TEST code?


答:
Tests for tests? Don't go that road. Then you'll probably need tests for tests for tests, and then tests for tests for tests for tests... where do you stop?

Usual testing flow goes like this, and as a developer, you'll spend majority of your time on points 1-3:

Code

Unit tests

Integration tests

System/other automated

QA/human testers

If I spend 2 minutes alternately adding bugs to the code (...)

Your code will eventually "grow" its own bugs, don't waste time introducing them by hand. Not to mention, is a thing you knew about upfront really a bug? Bugs will come, I wouldn't worry about that.

Should I just randomly comment out statements, make sure the wrong branch of an if-else gets run by negating its condition (...)

This is actually a viable approach to verify whether you actually test what you think you do. I don't think it is always that good as it suffers from the same problem as "test for test for test ..." thing: when do you stop altering code knowing code you're testing 100% works?

It's also good to remember about all time classic pragmatic programmer advice - you ain't gonna need it. Be agile, write tests and code for actual bugs, instead for those hypothetical that might or might not appear.

Title: How should I test my TEST code?

Body:
One of the few things that most software developers agree on is that
  you shouldn't rely on code to work correctly unless you test it. If
  you don't test it, it may have hidden bugs that are only going to
  cause you more work down the road.

I understand how to test my normal code, but how should I test my test code to make sure it can effectively find and report errors when they are present? I personally have been stupid enough to write erroneous test cases that would pass when they should not have, thus defeating the purpose of my writing tests in the first place. Fortunately, I found and fixed the errors in time, but according to testing mantra it seems like no test suite would be complete without having its own set of tests to make sure it worked.

It seems to me that the best way to do this would be to make sure the test fails for buggy code.* If I spend 2 minutes alternately adding bugs to the code and making sure it fails, I should have an acceptable degree of confidence that the tests 'work'. This brings me to my second question: What are good ways to introduce bugs to make sure that they are caught by the test cases? Should I just randomly comment out statements, make sure the wrong branch of an if-else gets run by negating its condition, and change the execution order of code with side-effects, etc., until I'm satisfied my tests will catch most common bugs? How do professional developers validate that their tests actually do what they're supposed to do? Do they just assume the tests work, or do they take the time to test them as well? If so how do they test the tests?

I'm not suggesting the people should spend so much time testing their tests and then testing the tests for their tests that they never actually write the real code, but I've done stupid enough things that I feel like I could benefit from a bit of 'meta-testing', and was curious about the best way to go about it. :D

* I could check to see if the test passes when testing 'bug-free' code, but using the code as a spec for the test seem quite backwards...


问:
How can I write a set of functions that can be invoked from (almost) any programming language?
I'd like to find a way to write an API that can be accessed from any other programming language via language bindings (or some other framework). Is it possible to do this? If so, which programming language would be the most suitable for writing a "cross-language" API? My goal is to create a single set of functions that I can access from any programming language that I'm working with, so that I won't need to manually re-write the entire API in each language.</p>

答:
OpenGL is a good example of what you describe - it's an API written in C, designed in a way that is easy to write bindings for in other languages

C libraries can be called from most programming languages (usually as compiled extensions, or things like PyPy's ctypes library etc)

All functions take simple data-types as arguments (boolean, integer, floating point, constants, arrays), as functions taking pointers can be awkward to translate into some languages

Having it's own numeric data-types, which specify precision and signed'ness (whereas int float etc can differ)

The resulting API isn't necessarily the nicest-to-use C API you could write if targeting only C users. However it means the functions can be almost directly exposed to another language (e.g the PyOpenGL docs list the differences, most of which are pretty minimal)

On top of this verbose API, you can write more "developer friendly" wrappers around this (game frameworks and such)


答:
A good way to deal with the problem, is to make it part of the process.  If you have code trace up to/reference the relevant pages on the wiki, a developer can easily find out what might need to be updated.  In addition, make the reviewers responsible in a code review for ensuring that the wiki is up-to-date (with regards to the update).

Another way to add it as part of the process -- since you're using an agile model, part of the planning process for iterations, could be to update planned changes in the wiki.  The wiki then serves as a 'this is how things should work' resource.


问:
Every SQL statement has to be reviewed by a DBA -- common?
I mean everything, not just schema changes. Even a simple SELECT on a primary key can't go into production, even though it has been code-reviewed by other developers (in context), without a DBA review of every statement, extracted from the code and submitted with EXPLAIN output, details of how often it will be called, etc, etc.

If you've been in such an environment, did you find it to be a net gain, or a drag on development? As someone who has been working with relational databases for years, I find the "developers can't be trusted to use databases" attitude unwarranted, and I'm curious as to how common this situation is. For what it's worth, this is just for web development, not something critical.

答: In our development team there is a sub-team of 4 Database Developers experienced in the DBMS platform we use. They write all SQL or at least reviews and make changes to meet their coding standards any SQL written by .Net developers. They are part of project team. The production DBAs belong to a completely different department and their job is operational. They do not review our SQL code or schema and even deployment is scripted,all they do is run the script. The most they help is in performance tuning.</p>


问:
Why are the arguments for substring functions mismatched?
In many languages, the substring function works like this:

substring(startIndex, endIndex)

returns the substring from startIndex until endIndex-1 (if you view startIndex and endIndex as 0-based) / from startIndex+1 to endIndex (1-based)

This is confusing. I understand that the two parameters can be interpreted as "startIndex" and "length of the substring", but in my opinion that is still confusing and even in this case, startIndex is 0-based while length is 1-based.

Why not stick to one convention for both the function arguments? and why do  newer languages like ruby and python continue to stick to this standard?

答:
There are reasons why Python and Ruby use the convention you describe.  These reasons may not be immediately evident -- but experience, and reasoned explanations (transcribed) by well-respected language designers, give good reason to think that zero-based, half-open array ranges are the least error-prone of many possible options.

@KilianFoth's answer gives a common and useful mnemonic for visualizing and using this convention.  But the reason newer languages use the convention is because it works.


答:
For situations where [3,6] would mean the third, fourth, and fifth characters, but not the sixth, I would suggest that it may be helpful to imagine the characters as occupying space on a number line, with indices representing points between the characters.  The first character would sit in the space between 0 and 1, the next between 1 and 2, then 2..3, etc.  The range [3,6] would include the spaces from 3..4, 4..5, and 5..6.  By convention, using just a single subscript n will refer to the range (n)..(n+1).

Viewed in this fashion, it becomes clear that [3,6] and [6,8] refer to two touching but not overlapping ranges of characters, since they occupy touching but non-overlapping space on the number line.

Title: Why are the arguments for substring functions mismatched?

Body:
In many languages, the substring function works like this:

substring(startIndex, endIndex)

returns the substring from startIndex until endIndex-1 (if you view startIndex and endIndex as 0-based) / from startIndex+1 to endIndex (1-based)

This is confusing. I understand that the two parameters can be interpreted as "startIndex" and "length of the substring", but in my opinion that is still confusing and even in this case, startIndex is 0-based while length is 1-based.

Why not stick to one convention for both the function arguments? and why do  newer languages like ruby and python continue to stick to this standard?


答:
Most developers are flat out ignorant when it comes to databases. They are not even aware of their ignorance. I used to be an ignorant developer myself.

Developers live in an optimization-is-evil world. That mindset doesn't work when you are performing operations against a disk. That mind set doesn't work when you choose a datatype that's 8 times bigger than it has to be which causes the index to be 8 times bigger than it has to be so it can no longer fit into memory. That mindset doesn't work when you program against a generic API that redundantly updates all columns in a table (no thanks Java beans).

They don't know what a full table scan is. They don't know how to process data in a single set operation instead of opening a cursor. Worse than a cursor they will query data, then row-by-row process it going back and forth to the database when a single simple plain-jane update would suffice. Resulting in HORRIBLE performance.

They don't know the serious impacts of reporting against large tables. Maybe the need for reports will require creating a star schema and a data feed into it. Your average developer will just query the exisitng tables and wonder why it takes 3 hours for the query to run (this is a real figure).

The knowledge your average developer has will suffice for "average" CRUD apps where a user simply edits a record. It will not suffice once they break out of the Ruby-on-Crack bubble and into the real world.


问:
BitBucket working with multiple developers on same project
I am new to BitBucket. I have my repository. And 2 people working on it me, Admin and another developer with Read only access.

So in order for him to do changes he forked repository and made changes, uploaded to his repository and created pull request.

Now I merged this pull request with my repository. And made few small changes afterwards and also committed them and uploaded to my repository.

What would be the next step for him to continue working? Does he have to fork it each time I make changes to my repo?

Is there some way for him to sync his with my repository without creating new fork each time?

答:
He should be able to pull changes from your repository just like you are pulling when he requests. In fact, it is considered good form to pull in upstream changes -- that would be changes from your repository in this case -- before submitting pull requests.

If I were working with the guy pretty heavily, I would probably just let him into the repository directly. Less hoo-ha in the workflow, easier for continuous integration.


问:
One or many RESTful APIs for large company?
I work for a large company which has several non-RESTful APIs. I am tasked with building a web application to interact with these APIs. Each API handles and provides very different business processes and data.

I'd like to build RESTful (a) interface(s) fronting the APIs so as to make them reusable by other future web applications. Then, I'd like JavaScript to interact with the RESTful interface(s).

Should I build one RESTful API (one subdomain) for my entire company

```<code>http://api.mycompany.com
    /business_process_1/resource/
    /business_process_2/resource
    /business_process_3/resource
</code>```

and make it front the very different business processes and data? Or, should I build multiple APIs (multiple subdomains)?

```<code>http://business-process-1.mycompany.com
http://business-process-2.mycompany.com
http://business-process-3.mycompany.com
</code>```

答:
I would probably run with a single URL fronting the web services for matter of simplicity on some levels. With modern proxies and load balancing tricks a single URL will not tie your hands insofar as infrastructure options go.

The most crucial piece of your URL strategy is missing -- version your API. That is the one thing that will get you into trouble insofar as your URLs are concerned. Everything else is fixable with a new endpoint.

Implementation-wise, you are most likely going to want to go for individual endpoints rather than something monolithic -- you will thank yourself in the long term. It will let you get out of the door quicker in almost all cases to boot.


问:
Clojure state and persistence
I'm learning Clojure to see if it's something I can leverage at my current job, and more importantly, how I can convince my bosses that Clojure has a 'killer feature' over java that makes it worth the investment1.

The feature that I'm guessing most clojure evangelists would tout is state management and concurrency.

The example that I see often in blogs and books is an account balance that’s being updated by multiple threads.  Clojure’s state management can always cleanly ensure that the balance will be accurate regardless of the number of threads reading and writing that value.

In practice, though, an application would never allow an account balance to live only in memory, it would have to be persisted outside of the JVM (probably in a database) for two hopefully obvious reasons:

If the app goes down the database will need to accurately reflect
the latest state for recovery.  For this reason the database cannot be asynchronously updated, and all reads would have to block until the database update is complete.

If other applications are reading or
manipulating the account balance (maybe because we’ve scaled our app
out to several servers), that balance would need to be kept in sync
between all instances.

Can Clojure’s state management handle situations like this elegantly?  For instance, given scenario 2 above, all reads of the account balance would first need to check the database to get the value, and if the database is locked, it would have to block until the correct value is available, no?

It’s great that Clojure handles my in-memory concurrency very elegantly but if that elegance can’t be extended to external state then do I really gain anything?

1(note that things like expressiveness, elegance, etc. are rarely considered killer features by mgmt.)

答:
As for the classic bank transfer example, you can perfectly get durability: just send-off an agent inside the STM transaction. As transactions can get retried, the agent only runs on the last, successful try. The agent would persist the transaction info to a DB.

I reckon that at times, RDBMSs' better-understood approach of mixing transactions and persistence can be the best bet. So I'd like to introduce a common use case:

Web server apps often feature a global cache (implemented as some data
  stucture) in order to avoid DB abuse. Each HTTP request (hence a
  thread) could read/write to it, so access needs to be
  concurrency-managed somehow. A locking approach can make this 'cache'
  actually a bottleneck!

It's in this and other similar scenarios where STM really shines.

Title: Clojure state and persistence


问:
Should laying out a GUI graphically be considered "cheating?"
I have a friend who has a slightly greater amount of programming experience as me. We were talking about all the different programming technologies we use and Interface Builder came up in conversation.

Being of no programming background except for what I've taught myself, I personally believe that IB and all it's features (IBOutlets, IBActions) help coders of my skill level (and all skill levels, for that matter) complete projects of theirs in less time.

His view of IB is a little enthusiastic. He believes that coders that utilize Interface Builder are "cheating" in the fact that they don't have to lay out interfaces by hand.

Question:

Should using a GUI builder to lay out interface elements be considered "cheating" (since most programming originally required laying interfaces out by hand in code)? Why?

答:
It's only cheating if you're sacrificing something to get there. Most GUI layouts just generate code that you'd make anyways (and often have to edit by hand since the layout isn't sufficient).

So basically, no.

All else being equal, any tool that lets you get the same thing done faster is good.


答:
It's not cheating. Programs like IB are tools. Use the right one for the job. There is no need to get dogmatic about it.

If you are more effective using such a tool, use it. The only caveat is that you should learn the trade-offs when making your decisions. Doing layouts by hand give you precise control at the expense of drag-and-drop ease. Drag-and-drop tools let you do many things quick and easy, but may make your code harder to maintain over time.

Personally, I've never had success or derived much pleasure from using a drag and drop UI design tool, but that's just me. I find laying GUIs out by hand is the most effective for me, and yields a code base that is easier to maintain over time. Others have the opposite experience.

Title: Should laying out a GUI graphically be considered "cheating?"

Body:
I have a friend who has a slightly greater amount of programming experience as me. We were talking about all the different programming technologies we use and Interface Builder came up in conversation.

Being of no programming background except for what I've taught myself, I personally believe that IB and all it's features (IBOutlets, IBActions) help coders of my skill level (and all skill levels, for that matter) complete projects of theirs in less time.

His view of IB is a little enthusiastic. He believes that coders that utilize Interface Builder are "cheating" in the fact that they don't have to lay out interfaces by hand.

Question:

Should using a GUI builder to lay out interface elements be considered "cheating" (since most programming originally required laying interfaces out by hand in code)? Why?


答:
The key question here is whether your company is liable to sell/divest any of its divisions or products?

If the answer is yes then you probably want to have a url per brand or per product. If your company is a "single product" company then a single URL is the way to go.

Title: One or many RESTful APIs for large company?

Body:
I work for a large company which has several non-RESTful APIs. I am tasked with building a web application to interact with these APIs. Each API handles and provides very different business processes and data.

I'd like to build RESTful (a) interface(s) fronting the APIs so as to make them reusable by other future web applications. Then, I'd like JavaScript to interact with the RESTful interface(s).

Should I build one RESTful API (one subdomain) for my entire company

```<code>http://api.mycompany.com
    /business_process_1/resource/
    /business_process_2/resource
    /business_process_3/resource
</code>```

and make it front the very different business processes and data? Or, should I build multiple APIs (multiple subdomains)?

```<code>http://business-process-1.mycompany.com
http://business-process-2.mycompany.com
http://business-process-3.mycompany.com
</code>```


答:
Hell no.  Doing it entirely by hand, however, is a clear case of making unnecessary work for yourself.

(Generally I'd lay it out using a builder and if any fine-tuning was needed it tends to - but not always - get done by hand).


问:
Examples of concurrent iterating scenarios needed
I'm trying to wrap my head around different concurrency solutions to several threads iterating over the same collection but I'm having difficulty coming up with good realistic (but preferably easy to model) scenarios to  code against. I'm looking for realistic scenarios for:

A scenario where several threads can iterate over a collection simultaneously and lock      each item as it comes to it and do some modification, item's can't be visible in a partially updated state

A scenario where different threads try to iterate over a collection but only one at a time should be allowed to

A scenario where several threads might iterate over a collection for reading, but only one thread might iterate for writing

Any other nice concurrency iterating scenarios you might come up with are welcome as well :) thanks!

答:
(1) would be a naiive object-oriented approach to keeping a collection of moving objects in a simulation of sorts that needs to be made visible to other threads: The "simulator" would need to lock, not only its list (to prevent slicing), but also each "object" it is updating.

Realistically, I would do that for something like a pathfinder: Lock the agent collection to prevent slicing and iterate over all agents, putting them into a "job queue" (the queue pointers would be reserved for this purpose only, so no other thread would see it).

Then, using OpenMP or something similar, I'd have each worker thread quickly lock the queue, pop an agent off of it, then unlock the queue (or use an [almost] lock-free queue). Each worker thread locks its agent before updating it.

My answer for (1) could also apply to (2): The "simulator" and whatever keeps the collection of agents are really the only things that should be allowed to iterate over the whole list (and desirably do so in one thread at a time, or just one thread period).

An examaple for (3) would be a string table: Multiple threads can obtain a shared lock to look up existing strings, and only one thread at a time can add a string to the table.


问:
What are the usual difficulties in concurrent programming and tuning of concurrent programs (shared-memory model)?
I can list part of the problems that will show up when writing a moderately-sized concurrent application with shared memory:

Locking granularity

Choice of synchronization primitive

Number of threads

Method for decomposing into threads (data parallelism; task parallelism; how threads are organized, etc)

What are other similar problems?

答:
All of the above, in addition to the fact that one has to assume an arbitrary amount of time may pass for other threads (remote or otherwise) during and in-between the execution of a single instruction in a given thread.

Unless you can work with assembly, higher level languages (especially things like Java and C#) make this problem difficult to work around without inline assembler, "intrinsics", or a modicum of "atomized" operations exposed as functions.

Even so, there exist "atomic" instructions that fail spuriously on some platforms, and so have to be used in a loop anyway (which is the C++ standard committee's rationale behind compare_exchange_strong and compare_exchange_weak).


问:
How to justify code refactoring time?
Have a very large project more than 70k LOC.

The project definitely needs some code refactoring in Core Framework and in other parts as well. There was NO time set in the beginning of the project for refactoring. However with time and more than 40 developers joint and left the project. From my perspective is indispensable.

What would be your key points in arguing and defending a proper software development principle?

答:
Refactoring, like any other activity, must have a clear goal defined for it. Once that goal is clear, you would consider the current project status and life cycle stage. For a development project that is 80% complete, 30% behind schedule you should justify refactoring effort based on the goal set earlier. In this example, if the code pieces were unit tested and is working fine in a development environment, it is hard to justify refactoring.

The fact that 40 developers left may not be as dramatic as it sounds. I'd expect that those developers have delivered working code that was reviewed and tested. So, unless there are known problems in this code, I'd leave it as is. The idea is that in a large project like yours, I'd expect that there were standards and procedures and that the code is not a complete mess.

Remember that refactoring will cause many if not all tests that has been made to be repeated. Also, since the refactoring of this size can't be done by a one or two senior members, the refactoring may introduce problems that did not exist. This is a risk that should not be neglected.

Having said that, it is not unusual to add tasks to a project when the unforeseen happens. So, if the developers disappeared for some reason, that that would be considered an event of a special nature and whatever actions to remedy the situation must be taken. It would be treated like a fire or an earthquake, etc.

In summary, I would not refactor large working code in a large project for no good solid technical reason, specially that we all know that most project are usually in late status.

Title: How to justify code refactoring time?


答:
In general, refactoring should be done in order to enable another change you need to make to the code or as a natural clean-up step after a change has been made to the code. In that case, there's nothing to justify. Refactoring is simply part of the process of doing work on the project. The time is billed to the task you were working on when you did the refactoring.

If it ain't done in small increments, then it ain't really refactoring, eh?

Title: How to justify code refactoring time?

Body:
Have a very large project more than 70k LOC.

The project definitely needs some code refactoring in Core Framework and in other parts as well. There was NO time set in the beginning of the project for refactoring. However with time and more than 40 developers joint and left the project. From my perspective is indispensable.

What would be your key points in arguing and defending a proper software development principle?


答:
All good answers here - but may I add a business dimension to this. Let me ask you WHY/So-What? (think of your pointy hair boss (PHB) :)

```
PHB: why?
You: It'll make things easier to fix
PHB: So-what?
You: It'll increase throughput - we'll get new builds out the door quicker?
PHB: So-what?
You: Err...Happier customers?
PHB: WTF?
You: I mean increased recommendations, greater satisfaction,
     more profit sooner due to low turnaround
PHB: Oh! Sounds nice. But it only "sounds" nice can I see it?
You: WTF?
PHB: Show me the money! (i.e. numbers please)
You: Oh! Brb...(go and put some numbers in simple spreadsheet to make your case)
```

Basically you must make a business case - run some numbers to clarify your thought process and get the numbers to reflect the 'benefit' objectively. You'll also know how much time it'll take, approximate costs etc. It should make sense. If it's worth it you'll get the green signal and maybe spearhead the initiative too :)

If you think how can I measure everything try this book

Title: How to justify code refactoring time?

Body:
All good answers here - but may I add a business dimension to this. Let me ask you WHY/So-What? (think of your pointy hair boss (PHB) :)

PHB: why?
You: It'll make things easier to fix
PHB: So-what?
You: It'll increase throughput - we'll get new builds out the door quicker?
PHB: So-what?
You: Err...Happier customers?
PHB: WTF?
You: I mean increased recommendations, greater satisfaction,
     more profit sooner due to low turnaround
PHB: Oh! Sounds nice. But it only "sounds" nice can I see it?
You: WTF?
PHB: Show me the money! (i.e. numbers please)
You: Oh! Brb...(go and put some numbers in simple spreadsheet to make your case)

Basically you must make a business case - run some numbers to clarify your thought process and get the numbers to reflect the 'benefit' objectively. You'll also know how much time it'll take, approximate costs etc. It should make sense. If it's worth it you'll get the green signal and maybe spearhead the initiative too :)

If you think how can I measure everything try this book


答:
When working on legacy or brownfield application it is tempting to do a "spring cleaning" hoping to refactor the whole thing back into shape. That is in no way justifiable use of resources. After all, how is halting development on working software (only working code can be refactored) jusitifiable? Can you guarantee the time spent on the Big Refactoring Phase is going to pay off later and not cause degeneration on the project?

How do you eat an elephant? One bite at a time. Whenever you need to implement new feature or fix a bug you see if that part needs reimprovement. Like the boy scout rule says: "Always leave the campground cleaner than you found it." Refactoring shouldn't be a separate phase, it is part of every day development.

When you get this culture of quality introduced to the development team, the quality will improve. After that there is not anything to justify to the management.

Title: How to justify code refactoring time?


问:
Initialize array in amortized constant time -- what is this trick called?
There is this data structure that trades performance of array access against the need to iterate over it when clearing it. You keep a generation counter with each entry, and also a global generation counter. The "clear" operation increases the generation counter. On each access, you compare local vs. global generation counters; if they differ, the value is treated as "clean".

This has come up in this answer on Stack Overflow recently, but I don't remember if this trick has an official name. Does it?

One use case is Dijkstra's algorithm if only a tiny subset of the nodes has to be relaxed, and if this has to be done repeatedly.

答: I believe it is a special case of memoization, except in this case, the "memos" implicitly "age" with each increment of the global counter. I guess a kind of "backwards memoization'.</p>


答:
I'm not familiar with using Git on BitBucket since I'm more of a GitHub user, but since you're using Git, I assume that the solution will be the same.

After your collaborator forks your project into his own BitBucket account, and clones it into his local machine, all he needs to do is add the main repository as an upstream source for his fork:

git remote add upstream https://yourusername@bitbucket.org/yourusername/your_app_name.git

Your collaborator can now fetch the changes in your repository into his own by doing the following:

git fetch upstream

Note that this only fetches the changes and doesn't merge it, so your collaborator has to merge it into the master branch (or any branch) of his fork:

git merge upstream/master

Once that's done, he can now push the changes of the main repo into his own fork:

git push

Title: BitBucket working with multiple developers on same project

Body:
I am new to BitBucket. I have my repository. And 2 people working on it me, Admin and another developer with Read only access.

So in order for him to do changes he forked repository and made changes, uploaded to his repository and created pull request.

Now I merged this pull request with my repository. And made few small changes afterwards and also committed them and uploaded to my repository.

What would be the next step for him to continue working? Does he have to fork it each time I make changes to my repo?

Is there some way for him to sync his with my repository without creating new fork each time?


问:
XAML Controls in WinForms
We're considering converting our WinForms application to a WPF application. Part of the reason is that WPF/XAML seem to be the future. We are also using third party controls that we would like to be able to phase out. Making this conversion seems like a pretty big and time consuming undertaking, though. Would it make sense to develop XAML controls that could be used in our WinForms application as a first step in the process? My thinking is that the same controls would then be used in the WPF application and all of the look, feel, and functionality would be built into the controls in either environment.</p>

答:
Have you considered doing it the other way round? If your end goal is to convert to WPF completely, you could start by setting up WPF application which hosts your WinForms control. Then you could replace WinForms controls one by one over time. WPF can be quite different from WinForms and you might want to tackle some architectural issues first such as navigation.

The preferred pattern for building WPF apps is Model-View-ViewModel. I suggest doing some prototyping to get to know it if you aren't familiar with it.

Title: XAML Controls in WinForms


答:
Programming as a job is not a sport nor a game. So the cheating argument is very thin. If the visual tools increase your productivity you would be stupid to not use them.
My experience is that these get me to spend more time on actual problem solving code without doing the trivial interface stuff over and over again.

Beware though, it's easy for settings or data to creep into the interface. Be radical about keeping presentation and logic seperated.


问:
Are there any design patterns that are unnecessary in dynamic languages like Python?
I've started reading the design pattern book by the GoF. Some patterns seem very similar with only minor conceptual differences.

Do you think out of the many patterns some are unnecessary in a dynamic language like Python (e.g. because they are substituted by a dynamic feature)?

答:
The only one that comes to mind is the Singleton pattern.

Since Python doesn't force you to use classes for everything, you can just use a global data structure instead. That global data structure could be managed by an instance, but you do not have to control the instantiation of that class, you just create the instance on import and leave it at that.

Mostly, Singletons in python are replaced with a module. Modules in python are by their very nature Singletons; the python interpreter creates these once and once only.

All other patterns in Design Patters I've used in Python at one time or another, and you'll find examples of them throughout the Python standard library and in Python itself.