问:
Nesting Linq-to-Objects query within Linq-to-Entities query –what is happening under the covers?
```<code>   var numbers = new int[] { 1, 2, 3, 4, 5 };

   var contacts = from c in context.Contacts
                  where c.ContactID == numbers.Max() | c.ContactID == numbers.FirstOrDefault()
                  select c;

    foreach (var item in contacts) Console.WriteLine(item.ContactID);
</code>```

Linq-to-Entities query is first translated into Linq expression tree, which is then converted by Object Services into command tree. And if Linq-to-Entities query nests Linq-to-Objects query, then this nested query also gets translated into an expression tree.

a) I assume none of the operators of the nested Linq-to-Objects query actually get executed, but instead data provider for particular DB (or perhaps Object Services) knows how to transform the logic of Linq-to-Objects operators into appropriate SQL statements?

b) Data provider knows how to create equivalent SQL statements only for some of the Linq-to-Objects operators?

c) Similarly, data provider knows how to create equivalent SQL statements only for some of the non-Linq methods in the Net Framework class library?

EDIT:

I know only some Sql so I can't be completely sure, but reading Sql query generated for the above code  it seems data provider didn't actually execute numbers.Max method, but instead just somehow figured out that numbers.Max should return the maximum value and then proceed to include in generated Sql query a call to TSQL's build-in MAX function. It also put all the values held by numbers array into a Sql query.

```<code> SELECT CASE
         WHEN (([Project1].[C1] = 1)
               AND ([Project1].[C1] IS NOT NULL)) THEN '0X0X'
         ELSE '0X1X'
       END                      AS [C1],
       [Extent1].[ContactID]    AS [ContactID],
       [Extent1].[FirstName]    AS [FirstName],
       [Extent1].[LastName]     AS [LastName],
       [Extent1].[Title]        AS [Title],
       [Extent1].[AddDate]      AS [AddDate],
       [Extent1].[ModifiedDate] AS [ModifiedDate],
       [Extent1].[RowVersion]   AS [RowVersion],
       CASE
         WHEN (([Project1].[C1] = 1)
               AND ([Project1].[C1] IS NOT NULL)) THEN [Project1].[CustomerTypeID]
       END                      AS [C2],
       CASE
         WHEN (([Project1].[C1] = 1)
               AND ([Project1].[C1] IS NOT NULL)) THEN [Project1].[InitialDate]
       END                      AS [C3],
       CASE
         WHEN (([Project1].[C1] = 1)
               AND ([Project1].[C1] IS NOT NULL)) THEN [Project1].[PrimaryDesintation]
       END                      AS [C4],
       CASE
         WHEN (([Project1].[C1] = 1)
               AND ([Project1].[C1] IS NOT NULL)) THEN [Project1].[SecondaryDestination]
       END                      AS [C5],
       CASE
         WHEN (([Project1].[C1] = 1)
               AND ([Project1].[C1] IS NOT NULL)) THEN [Project1].[PrimaryActivity]
       END                      AS [C6],
       CASE
         WHEN (([Project1].[C1] = 1)
               AND ([Project1].[C1] IS NOT NULL)) THEN [Project1].[SecondaryActivity]
       END                      AS [C7],
       CASE
         WHEN (([Project1].[C1] = 1)
               AND ([Project1].[C1] IS NOT NULL)) THEN [Project1].[Notes]
       END                      AS [C8],
       CASE
         WHEN (([Project1].[C1] = 1)
               AND ([Project1].[C1] IS NOT NULL)) THEN [Project1].[RowVersion]
       END                      AS [C9],
       CASE
         WHEN (([Project1].[C1] = 1)
               AND ([Project1].[C1] IS NOT NULL)) THEN [Project1].[BirthDate]
       END                      AS [C10],
       CASE
         WHEN (([Project1].[C1] = 1)
               AND ([Project1].[C1] IS NOT NULL)) THEN [Project1].[HeightInches]
       END                      AS [C11],
       CASE
         WHEN (([Project1].[C1] = 1)
               AND ([Project1].[C1] IS NOT NULL)) THEN [Project1].[WeightPounds]
       END                      AS [C12],
       CASE
         WHEN (([Project1].[C1] = 1)
               AND ([Project1].[C1] IS NOT NULL)) THEN [Project1].[DietaryRestrictions]
       END                      AS [C13]
FROM   [dbo].[Contact] AS [Extent1]
       LEFT OUTER JOIN (SELECT [Extent2].[ContactID]            AS [ContactID],
                               [Extent2].[BirthDate]            AS [BirthDate],
                               [Extent2].[HeightInches]         AS [HeightInches],
                               [Extent2].[WeightPounds]         AS [WeightPounds],
                               [Extent2].[DietaryRestrictions]  AS [DietaryRestrictions],
                               [Extent3].[CustomerTypeID]       AS [CustomerTypeID],
                               [Extent3].[InitialDate]          AS [InitialDate],
                               [Extent3].[PrimaryDesintation]   AS [PrimaryDesintation],
                               [Extent3].[SecondaryDestination] AS [SecondaryDestination],
                               [Extent3].[PrimaryActivity]      AS [PrimaryActivity],
                               [Extent3].[SecondaryActivity]    AS [SecondaryActivity],
                               [Extent3].[Notes]                AS [Notes],
                               [Extent3].[RowVersion]           AS [RowVersion],
                               cast(1 as bit)                   AS [C1]
                        FROM   [dbo].[ContactPersonalInfo] AS [Extent2]
                               INNER JOIN [dbo].[Customers] AS [Extent3]
                                 ON [Extent2].[ContactID] = [Extent3].[ContactID]) AS [Project1]
         ON [Extent1].[ContactID] = [Project1].[ContactID]
       LEFT OUTER JOIN (SELECT TOP (1) [c].[C1] AS [C1]
                        FROM   (SELECT [UnionAll3].[C1] AS [C1]
                                FROM   (SELECT [UnionAll2].[C1] AS [C1]
                                        FROM   (SELECT [UnionAll1].[C1] AS [C1]
                                                FROM   (SELECT 1 AS [C1]
                                                        FROM   (SELECT 1 AS X) AS [SingleRowTable1]
                                                        UNION ALL

                                                        SELECT 2 AS [C1]
                                                        FROM   (SELECT 1 AS X) AS [SingleRowTable2]) AS [UnionAll1]
                                                UNION ALL

                                                SELECT 3 AS [C1]
                                                FROM   (SELECT 1 AS X) AS [SingleRowTable3]) AS [UnionAll2]
                                        UNION ALL

                                        SELECT 4 AS [C1]
                                        FROM   (SELECT 1 AS X) AS [SingleRowTable4]) AS [UnionAll3]
                                UNION ALL

                                SELECT 5 AS [C1]
                                FROM   (SELECT 1 AS X) AS [SingleRowTable5]) AS [c]) AS [Limit1]
         ON 1 = 1
       LEFT OUTER JOIN (SELECT TOP (1) [c].[C1] AS [C1]
                        FROM   (SELECT [UnionAll7].[C1] AS [C1]
                                FROM   (SELECT [UnionAll6].[C1] AS [C1]
                                        FROM   (SELECT [UnionAll5].[C1] AS [C1]
                                                FROM   (SELECT 1 AS [C1]
                                                        FROM   (SELECT 1 AS X) AS [SingleRowTable6]
                                                        UNION ALL

                                                        SELECT 2 AS [C1]
                                                        FROM   (SELECT 1 AS X) AS [SingleRowTable7]) AS [UnionAll5]
                                                UNION ALL

                                                SELECT 3 AS [C1]
                                                FROM   (SELECT 1 AS X) AS [SingleRowTable8]) AS [UnionAll6]
                                        UNION ALL

                                        SELECT 4 AS [C1]
                                        FROM   (SELECT 1 AS X) AS [SingleRowTable9]) AS [UnionAll7]
                                UNION ALL

                                SELECT 5 AS [C1]
                                FROM   (SELECT 1 AS X) AS [SingleRowTable10]) AS [c]) AS [Limit2]
         ON 1 = 1
       CROSS JOIN (SELECT MAX([UnionAll12].[C1]) AS [A1]
                   FROM   (SELECT [UnionAll11].[C1] AS [C1]
                           FROM   (SELECT [UnionAll10].[C1] AS [C1]
                                   FROM   (SELECT [UnionAll9].[C1] AS [C1]
                                           FROM   (SELECT 1 AS [C1]
                                                   FROM   (SELECT 1 AS X) AS [SingleRowTable11]
                                                   UNION ALL

                                                   SELECT 2 AS [C1]
                                                   FROM   (SELECT 1 AS X) AS [SingleRowTable12]) AS [UnionAll9]
                                           UNION ALL

                                           SELECT 3 AS [C1]
                                           FROM   (SELECT 1 AS X) AS [SingleRowTable13]) AS [UnionAll10]
                                   UNION ALL

                                   SELECT 4 AS [C1]
                                   FROM   (SELECT 1 AS X) AS [SingleRowTable14]) AS [UnionAll11]
                           UNION ALL

                           SELECT 5 AS [C1]
                           FROM   (SELECT 1 AS X) AS [SingleRowTable15]) AS [UnionAll12]) AS [GroupBy1]
WHERE  [Extent1].[ContactID] IN ([GroupBy1].[A1], (CASE
                                                     WHEN ([Limit1].[C1] IS NULL) THEN 0
                                                     ELSE [Limit2].[C1]
                                                   END))
</code>```

Based on this, is it possible that Linq2Entities provider indeed doesn't execute non-Linq and Linq-to-Object methods, but instead creates equivalent SQL statements for some of them ( and for others it throws an exception )?

Thank you in advance

答:
Presumably the data provider looks at each sub-expression and if it can be computed it just does a compile and execute while it's constructing the query.  This would be no different than saying:

```<code>where c.ContactID == (4 + 5)
</code>```

That's because numbers in your example is an int[] type.

Interestingly this is only evaluated once before the query is generated, so it's only calculated once.  If you did something like this:

```<code>where c.ContactID == myObject.NextID()
</code>```

...then it evaluates myObject.NextID() during the construction of the query, so it only calls it once.  I have witnessed, in Linq2NHibernate, that not only does it only call it once during the creating of the query, but the data provider has built-in query caching, and it won't re-evaluate it the next time you execute the same query.  YMMV.

Also remember it's lazy evaluated, so if you never execute the query, the subexpression is never compiled and executed.  Also, if you modify numbers after your statement but before executing the foreach then the query will be built using your modified value.

Edit:

Here's an article called Walkthrough: Creating an IQueryable LINQ Provider.  Check the section on "Adding the Expression Evaluator".  Specifically the Nominator class:

```<code>/// <summary>
/// Performs bottom-up analysis to determine which nodes can possibly
/// be part of an evaluated sub-tree.
/// </summary>
</code>```

Basically it's searching the expression tree for anything that can be evaluated, and compiling and executing it, then replacing that sub-expression with a constant expression.

Here's the function that determines if an expression can be evaluated:

```<code>private static bool CanBeEvaluatedLocally(Expression expression)
{
    return expression.NodeType != ExpressionType.Parameter;
}
</code>```

So as long as no sub-expression contains a parameter of the expression, then it can be evaluated.

Edit 2:

Based on your edit, it does look like it's putting the values from the array into a table in SQL and selecting MAX from that.  I honestly have no idea why it would bother doing that when none of the elements of the sub-expression numbers.Max() are parameters.  I certainly know that you can write an expression like numbers.Contains(c.ID) and that will actually create an IN clause such as c.ID IN (@p0, @p1, @p2, @p3, @p4) where @p0 = 1, @p1 = 2, etc.

So, to answer your question: "is it possible that Linq2Entities provider indeed doesn't execute non-Linq and Linq-to-Object methods, but instead creates equivalent SQL statements for some of them"

Yes, it's possible.

Body:
Presumably the data provider looks at each sub-expression and if it can be computed it just does a compile and execute while it's constructing the query.  This would be no different than saying:

where c.ContactID == (4 + 5)

That's because numbers in your example is an int[] type.

Interestingly this is only evaluated once before the query is generated, so it's only calculated once.  If you did something like this:

where c.ContactID == myObject.NextID()

...then it evaluates myObject.NextID() during the construction of the query, so it only calls it once.  I have witnessed, in Linq2NHibernate, that not only does it only call it once during the creating of the query, but the data provider has built-in query caching, and it won't re-evaluate it the next time you execute the same query.  YMMV.

Also remember it's lazy evaluated, so if you never execute the query, the subexpression is never compiled and executed.  Also, if you modify numbers after your statement but before executing the foreach then the query will be built using your modified value.

Edit:

Here's an article called Walkthrough: Creating an IQueryable LINQ Provider.  Check the section on "Adding the Expression Evaluator".  Specifically the Nominator class:

/// <summary>
/// Performs bottom-up analysis to determine which nodes can possibly
/// be part of an evaluated sub-tree.
/// </summary>

Basically it's searching the expression tree for anything that can be evaluated, and compiling and executing it, then replacing that sub-expression with a constant expression.

Here's the function that determines if an expression can be evaluated:

private static bool CanBeEvaluatedLocally(Expression expression)
{
    return expression.NodeType != ExpressionType.Parameter;
}

So as long as no sub-expression contains a parameter of the expression, then it can be evaluated.

Edit 2:

Based on your edit, it does look like it's putting the values from the array into a table in SQL and selecting MAX from that.  I honestly have no idea why it would bother doing that when none of the elements of the sub-expression numbers.Max() are parameters.  I certainly know that you can write an expression like numbers.Contains(c.ID) and that will actually create an IN clause such as c.ID IN (@p0, @p1, @p2, @p3, @p4) where @p0 = 1, @p1 = 2, etc.

So, to answer your question: "is it possible that Linq2Entities provider indeed doesn't execute non-Linq and Linq-to-Object methods, but instead creates equivalent SQL statements for some of them"

Yes, it's possible.


问:
Static DataTable or DataSet in a class - bad idea?
I have several instances of a class. Each instance stores data in a common database. So, I thought "I'll make the DataTable table field static, that way every instance can just add/modify rows to its own table field, but all the data will actually be in one place!"

However, apparently it's a bad idea to do use static fields, especially if it's databases: Don't Use "Static" in C#?

Is this a bad idea? Will I run into problems later on if I use it?

This is a small project so I can accept no testing as a compromise if that is the only drawback. The benefit of using a static database is that there can be many objects of type MyClass, but only one table they all talk to, so a static field seems to be an implementation of exactly this, while keeping syntax concise.

I don't see why I shouldn't use a static field (although I wouldn't really know) but if I had to, the best alternative I can think of is creating one DataTable, and passing a reference to it when creating each instance of MyClass, perhaps as a constructor parameter.

But is this really an improvement? It seems less intuitive than a static field.

答:
Reading DataTable across multiple threads should be OK . Writing is not, you should synchronize  write access. See "Thread Safety" in Data Table doc.

Might need to create a separate object that deals with data access and synchronization.

At the most basic though, you could just call lock(table) {//Write here} before you write the data in every thread.

Now, you shouldn't need to have a static variable to have it shared between instances, you could just set every thread to reference the same instance. This will give you more flexibility going forward (For example: to improve write performance you can have multiple connections and you can assign them from the pool every time a new thread is created)

ContentLicense: CC BY-SA 3.0


问:
Why do browsers leak memory?
A colleague and I were speaking about browsers (using a browser control object in a project), and it appears as plain as day that all browsers (Firefox, Chrome, IE, Opera) display the same characteristic or side-effect from their usage and that being 'Leaking Memory'.

Can someone explain why that is the case? Surely as with any form of code, there should be proper garbage collection?

PS. I've read about some defensive patterns on why this can happen from a developer's perspective. I am aware of an article Crockford wrote on IE; but why is the problem symptomatic of every browser?
Thanks

答: I wouldn't be surprised if what you are categorizing as "leaks" is instead some aggressive cacheing.  Even today, network round-trip time is "expensive" (time-wise) compared to fetching something from an in-memory cache.  I'd recommend grabbing the source for Firefox or Chromium and taking a look at how they manage their caches.  I know that Firefox at least supports re-opening recently-closed windows/tabs, so even completely closing a site doesn't necessarily mean that the cached images and scripts are evicted.</p>

Title: Why do browsers leak memory?


问:
What are some famous one-liner or two-liner programs and equations?
I'm experimenting with a new platform and I'm trying to write a program that deals with strings that are no longer than 60 characters and I'd like to populate the data store with some famous or well-known small chunks of code and equations, since programming and math goes along with the theme of my software. The code can be in any language and the equations from any discipline of mathematics, just so long as they're less than a total of 60 characters in length. I suspect people are gonna break out some brainfuck for this one.

For example,

```<code>#include<stdio.h>
int main(){printf ("Hi World\n");return 0;}
</code>```

60 characters exactly!

Thanks so much for your wisdom!

答:
My favorite lambda calculus example is the Y combinator:</p>

```<code>Y = λf.(λx.f (x x)) (λx.f (x x))
</code>```

ContentLicense: CC BY-SA 2.5

Body:
My favorite lambda calculus example is the Y combinator:

Y = λf.(λx.f (x x)) (λx.f (x x))


问:
Can I trust the Basic Schedule Equation?
I've been reading Steve McConnell's Software Estimation: Demystifying the Black Art book, and he gives an equation for estimating nominal schedule based on Person-months of effort:

```ScheduleInMonths = 3.0 x EffortInMonths<sup>1/3</sup>```

Per the book, this is very accurate (within 25%), although the 3.0 factor above varies depending on your organization (typically between 2 and 4).  It is supposedly easy to use historical projects in your organization to derive an appropriate factor for your use.

I am trying to reconcile the equation against Agile methods, using 2-6 week cycles which are often mini-projects that have a working deliverable at the end.  If I have a team of 5 developers over 4 weeks (1 month), then EffortInMonths = 5 Person Months.  The algorithm then outputs a schedule of 3.0 x 51/3 = 5 months.

5 months is much more than 25% different than 1 month.  If I lower the 3.0 factor to 0.6, then the algorthim works (outputs a schedule of approx 1 month).  The lowest possible factor mentioned in the book through is 2.0.

Whats going on here?  I want to trust this equation for estimating a "traditional" non-agile project, but I cannot trust it when it does not reconcile with my (agile) experience.  Can someone help me understand?

答:
Consider two projects A and B.  Project A has a certain amount of effort, and is estimated to take 1 month.  Project B is estimated to have 27 times as much effort as project A.  The equation appears to tell us that project B will only take 3 months.

I find this HIGHLY counterintuitive.


问:
What is the difference between "data hiding" and "encapsulation"?
I'm reading "Java concurrency in practice" and there is said: "Fortunately, the same object-oriented techniques that help you write well-organized, maintainable classes - such as encapsulation and data hiding -can also help you create thread-safe classes."

The problem #1 - I never heard about data hiding and don't know what it is.

The problem #2 - I always thought that encapsulation is using private vs public, and is actually the data hiding.

Can you please explain what data hiding is and how it differs from encapsulation?

答:
They are often used interchangablely in discussion, and often I think they work together to achieve the same purpose, and while the following may not be completely accurate, it may provide some meaningful distinction, if a distinction needs to be made:

When talking about encapsulation, often it is implemented as a procedural/functional mechanism. There is some type of guard for the underlying state, and access through the guard requires certain protocols be followed to be given access (read or change the desired state).  Encapsulation also offers the opportunity for side-effects to occur due to access (like cascading state change, or notification/raising an event/issuing a signal when the thing of interest is read or changed) so follow-up actions can be initiated.  Again, I often think of encapsulation as a concept that is something that is implemented as a procedure.

I see the concept of data hiding is similar in purpose to encapsulation; however, the mechanism is structural and operates at a different level.  In practice, instead of providing a guard and side-effect mechanism through procedure, state is protected and affected through structural mechanisms of the language and runtime.  These types of guards would be visibility clauses, type definitions, inheritence, and the like.  Side-effects that you can leverage from the structurally guarded objects are again something that depend on language and runtime: perhaps object activation, reference count, or something along those lines.


问:
how to model this relationship ? in ERD
I have three entities :

```<code>Technician
Vehicle
Repair
</code>```

The question is how to model this in ERD? Knowing that a technician can repair multiple cars, and the same car can be repaired by one and only one technician? How should the repair entity tied to all this?

答:
You need to specify more description of your tables and of your requirements. Anyway, here is one way to model the tables. However, in a real application there would be other things to consider. Only PKs and FKs are shown. Other columns depend on your case.

Note:
In the original version of the answer, I missed the requirement that "the same car can be repaired by one and only one technician". To implement this, in the Repair_Job table, the TechID column + VIN column should be constrained to be unique.

Title: how to model this relationship ? in ERD

ContentLicense: CC BY-SA 4.0


问:
What is a closure?
Every now and then I see "closures" being mentioned, and I tried looking it up but Wiki doesn't give an explanation that I understand. Could someone help me out here?</p>

答:
It is hard to define what closure is without defining the concept of 'state'.

Basically, in a language with full lexical scoping that treats functions as first class values, something special happens. If I were to do something like:

```<code>function foo(x)
return x
end

x = foo
</code>```

The variable x not only references function foo() but it also references the state foo was left in last time it returned. The real magic happens when foo has other functions further defined within its scope; it's like its own mini-environment (just as 'normally' we define functions in a global environment).

Functionally it can solve many of the same problems as the C++(C?)'s 'static' keyword, which retains a local variable's state throughout multiple function calls; however it's more like applying that same principle (static variable) to a function, as functions are first class values; closure adds support for the entire function's state to be saved (nothing to do with C++'s static functions).

Treating functions as first class values and adding support for closures also means that you can have more than one instance of the same function in memory (similar to classes). What this means is you can re-use the same code without having to reset the function's state, as is required when dealing with C++ static variables inside a function(may be wrong about this?).

Here is some testing of Lua's closure support.

```<code>--Closure testing
--By Trae Barlow
--

function myclosure()
    print(pvalue)--nil
    local pvalue = pvalue or 10
    return function()
        pvalue = pvalue + 10 --20, 31, 42, 53(53 never printed)
        print(pvalue)
        pvalue = pvalue + 1 --21, 32, 43(pvalue state saved through multiple calls)
        return pvalue
    end
end

x = myclosure() --x now references anonymous function inside myclosure()

x()--nil, 20
x() --21, 31
x() --32, 42
    --43, 53 -- if we iterated x() again
</code>```

results:

```<code>nil
20
31
42
</code>```

It can get tricky, and it probably varies from language to language, but it seems in Lua that whenever a function is executed, its state is reset. I say this because the results from the code above would be different if we were accessing the myclosure function / state directly (instead of through the anonymous function it returns), as pvalue would be reset back to 10; but if we access myclosure's state through x (the anonymous function) you can see that pvalue is alive and well somewhere in memory. I suspect there is a bit more to it, perhaps someone can better explain the nature of the implementation.

PS: I don't know a lick of C++11 (other than what's in previous versions) so do note that this isn't a comparison between closures in C++11 and Lua. Also, all the 'lines drawn' from Lua to C++ are similarities as static variables and closures are not 100% the same; even if they are sometimes used to solve similar problems.

The thing I'm not sure of is, in the code example above, whether the anonymous function or the higher order function is considered the closure?

Title: What is a closure?

Body:
It is hard to define what closure is without defining the concept of 'state'.

Basically, in a language with full lexical scoping that treats functions as first class values, something special happens. If I were to do something like:

function foo(x)
return x
end

x = foo

The variable x not only references function foo() but it also references the state foo was left in last time it returned. The real magic happens when foo has other functions further defined within its scope; it's like its own mini-environment (just as 'normally' we define functions in a global environment).

Functionally it can solve many of the same problems as the C++(C?)'s 'static' keyword, which retains a local variable's state throughout multiple function calls; however it's more like applying that same principle (static variable) to a function, as functions are first class values; closure adds support for the entire function's state to be saved (nothing to do with C++'s static functions).

Treating functions as first class values and adding support for closures also means that you can have more than one instance of the same function in memory (similar to classes). What this means is you can re-use the same code without having to reset the function's state, as is required when dealing with C++ static variables inside a function(may be wrong about this?).

Here is some testing of Lua's closure support.

--Closure testing
--By Trae Barlow
--

function myclosure()
    print(pvalue)--nil
    local pvalue = pvalue or 10
    return function()
        pvalue = pvalue + 10 --20, 31, 42, 53(53 never printed)
        print(pvalue)
        pvalue = pvalue + 1 --21, 32, 43(pvalue state saved through multiple calls)
        return pvalue
    end
end

x = myclosure() --x now references anonymous function inside myclosure()

x()--nil, 20
x() --21, 31
x() --32, 42
    --43, 53 -- if we iterated x() again

results:

nil
20
31
42

It can get tricky, and it probably varies from language to language, but it seems in Lua that whenever a function is executed, its state is reset. I say this because the results from the code above would be different if we were accessing the myclosure function / state directly (instead of through the anonymous function it returns), as pvalue would be reset back to 10; but if we access myclosure's state through x (the anonymous function) you can see that pvalue is alive and well somewhere in memory. I suspect there is a bit more to it, perhaps someone can better explain the nature of the implementation.

PS: I don't know a lick of C++11 (other than what's in previous versions) so do note that this isn't a comparison between closures in C++11 and Lua. Also, all the 'lines drawn' from Lua to C++ are similarities as static variables and closures are not 100% the same; even if they are sometimes used to solve similar problems.

The thing I'm not sure of is, in the code example above, whether the anonymous function or the higher order function is considered the closure?


问:
Compiler Warnings
Many compilers have warning messages to warn the programmers about potential runtime, logic and performance errors, most times, you quickly fix them, but what about unfixable warnings?

How do you deal with unfixable warnings? Do you re-write a portion of the code, or rewrite it in the "long, hackless way" or disable warnings all together? What should be the best practice?

What if you are editing someone else's code and his code has warnings?

Here is a good example:
jQuery has a lots of JavaScript warnings as a Mozilla-class browser detected, why the jQ developers don't fix them? If you contribute to jQuery, are you going to fix them?

答:
In my case warnings come from the PyLint tool and I can disable a warning on a particular line by adding special text in the comments.

In most cases, I don't do that. In most cases I change the code to follow what PyLint suggests because PyLint is usually correct. However, in dislikes constructs which are generally a bad idea, but which make sense in a particular context. For example, it complains if I catch all possible exceptions. Usually, its correct, that would be a bad idea. However, in some cases I do want to catch all exceptions such as to send myself an error report with the details.

So: In almost all cases, get rid of the hacks. When the hack is really justified, add a comment telling PyLint its okay.

Title: Compiler Warnings


问:
Thin client Web browser?
Many times i have heard people saying that a particular hardware to be running a thin client web browser. But from the definition of "thin-client", doesnt all browser qualify as a thin-client? as all they do is rendering the information sent from a remote server minimizing the work at the browser end?</p>

答:
The definition of a "thin client" (from wikipedia):

A thin client (sometimes also called a lean or slim client) is a computer or a computer program which depends heavily on some other computer (its server) to fulfill its traditional computational roles

Browsers started as rendering engines for HTML. Servers provided the raw HTML text and the clients (the browser) rendered the text into something nicer - so browsers are actually fat clients!.

Now if you have an application that is web-based (that is, runs on a browser), you can develop it as a thin- or a fat-client independent of the fact that it runs on a browser. You can develop full applications that will run on the browser without needing to fetch any data from the server and doing all the computation by itself, or you can develop an app that has no state, no calculations, only visual logic, and everything else is done on the server.

Title: Thin client Web browser?


问:
Independent contractors posting projects to their portfolio
I'm about to hire freelance contractors to do small pieces of my web projects.

Is it standard to allow them to put the project on their portfolio? Say a simple debugging task getting a specific mobile problem fixed in <5 hours.

I'm just concerned as it could potentially dilute my company's portfolio by having it listed by each contractor when in fact the majority of work is done by me. I'm trying to build a portfolio here as an agency.

I think it's a risk for my company since I'm working hard to get clients and the whole point is putting projects on my portfolio.

Am I wrong here?

Is there an standard policy for this? Perhaps a limited policy whereby attribution is required to the agency? Did exactly X for agency Y (link).

答:
There is no rule I know about, but if I were to contribute to a project I would agree to take attribution only for what I did. I would even agree to sign a paper or include this clause in the contract.

But as you said, not all may think as I do and they would want to just have it on their resume. Here comes another question, would you actually want to work with people like that?


答:
Write up a small legal agreement for any contractors you hire that they must sign, in addition to your NDA (if you don't have one, make or get one) that limits how they can list your project in their resume or portfolio. If they don't agree to it, don't hire them. Plain and simple.

But just remember that if they worked on it, they have the right to list it as work experience, which is much different than claiming it as their own project in a portfolio. In the end, you don't have control over what they do with their portfolio's or resume's. Don't let that prevent you from getting work done, just always deal with it calmly and responsibly.

Title: Independent contractors posting projects to their portfolio

Body:
I'm about to hire freelance contractors to do small pieces of my web projects.

Is it standard to allow them to put the project on their portfolio? Say a simple debugging task getting a specific mobile problem fixed in <5 hours.

I'm just concerned as it could potentially dilute my company's portfolio by having it listed by each contractor when in fact the majority of work is done by me. I'm trying to build a portfolio here as an agency.

I think it's a risk for my company since I'm working hard to get clients and the whole point is putting projects on my portfolio.

Am I wrong here?

Is there an standard policy for this? Perhaps a limited policy whereby attribution is required to the agency? Did exactly X for agency Y (link).


问:
What is a proper way of building Winform apps with multiple "screens"
What's a proper way of building a Winform app that has multiple 'screens'?  For example, I'm trying to write a small backup program (mainly for giggles), and I've been dumping controls and containers onto the form.

I'm using panels and group boxes to separate out the different screens (eg:  I'm using a panel to hold all of the controls for the "Settings" window, and another panel to show all the current backups that have been set up).  Well, my form.cs file ballooned into a massive amount of code, and I feel like I'm doing something wrong.  I can hardly find anything in the file, and I'm ready to start over.  This project was just for me to expand my knowledge of C# and .NET, so starting a new project is not a huge deal.

答:
There's a number of ways to control UI complexity.

If you have lots of forms, you can choose a design pattern that manages transitions: Application Controller for example, or closer to the metal: State.

You can compose groups of controls into single controls. In winforms, you use User Controls.

If the complexity is coming from the quantity of code in your form, as opposed to the quantity of controls on the form, you could simply better encapsulate code into objects using standard object oriented programming techniques. Understanding the SOLID principles is a good place to start.

Otherwise, there are patterns for working with user interfaces. Among other things (separation of concerns being prominent), they facilitate organization of code. Some common ones are MVC, MVP, MVVM

From your description, I'd use custom user controls to replace what you're using panels for now. Then just place those user controls onto your form(s) where your panels were.


答:
The Ackerman function. The implementation of the Ackermann-Péter version should fit into 60 chars :)

This lovely hexadecimal constant: 0x5f3759df. It is the heart of the most WTFing code I've ever seen: the fast inverse square root.

The famous XOR swap.

question = /(bb|[^b]{2})/

Title: What are some famous one-liner or two-liner programs and equations?

Body:
I'm experimenting with a new platform and I'm trying to write a program that deals with strings that are no longer than 60 characters and I'd like to populate the data store with some famous or well-known small chunks of code and equations, since programming and math goes along with the theme of my software. The code can be in any language and the equations from any discipline of mathematics, just so long as they're less than a total of 60 characters in length. I suspect people are gonna break out some brainfuck for this one.

For example,

```<code>#include<stdio.h>
int main(){printf ("Hi World\n");return 0;}
</code>```

60 characters exactly!

Thanks so much for your wisdom!


答:
CONCEPTUAL

Note that in the ERD ( conceptual data model ) you don't specify the foreign keys, they are implicit in the relationship ( lines ).

Your data modeling tool will generate the foreing keys for you when you generate the physical data model (RDBMS dependant):

PHYSICAL

Title: how to model this relationship ? in ERD

Body:
I have three entities :

```<code>Technician
Vehicle
Repair
</code>```

The question is how to model this in ERD? Knowing that a technician can repair multiple cars, and the same car can be repaired by one and only one technician? How should the repair entity tied to all this?


答:
A modified version of a famous Perl one-liner:

```<code>/^.?$|^(..+?)\1+$/
</code>```

This regular expression matches strings whose length is prime.

The original version is:

```<code>/^1?$|^(11+?)\1+$/
</code>```

which matches strings consisting of a prime number of 1s.

Body:
A modified version of a famous Perl one-liner:

/^.?$|^(..+?)\1+$/

This regular expression matches strings whose length is prime.

The original version is:

/^1?$|^(11+?)\1+$/

which matches strings consisting of a prime number of 1s.


答:
From an exercise in K&R, here is a function that will return how many bits are set in the number given. At 58 characters:

```<code>int bits(int n){int b=0;while(n){n=n&(n-1);b++;}return b;}
</code>```

It takes time proportional to the number of bits set. The "ah ha" part here is that

```<code>n = n & (n - 1)
</code>```

Removes the rightmost set bit from n.

Body:
From an exercise in K&R, here is a function that will return how many bits are set in the number given. At 58 characters:

int bits(int n){int b=0;while(n){n=n&(n-1);b++;}return b;}

It takes time proportional to the number of bits set. The "ah ha" part here is that

n = n & (n - 1)

Removes the rightmost set bit from n.


答:
Quicksort:

```<code>qsort []     = []
qsort (x:xs) = qsort (filter (< x) xs) ++ [x] ++ qsort (filter (>= x) xs)
</code>```

If the list is empty, the sorted result is the empty list.

If the list starts with the element x, and the rest of the list is xs, then the sorted result is list consisting of the sorted list consisting of all elements in xs less than x concatenated with the element x concatenated with the sorted list of all elements in xs larger than x.

(or in other words - divide in two piles, all less than x and all larger than x, sort them both and create a list with the less-than pile, the element x, and the larger-than pile).

Beats the understandability of the C version quite easily.

Body:
Quicksort:

qsort []     = []
qsort (x:xs) = qsort (filter (< x) xs) ++ [x] ++ qsort (filter (>= x) xs)

If the list is empty, the sorted result is the empty list.

If the list starts with the element x, and the rest of the list is xs, then the sorted result is list consisting of the sorted list consisting of all elements in xs less than x concatenated with the element x concatenated with the sorted list of all elements in xs larger than x.

(or in other words - divide in two piles, all less than x and all larger than x, sort them both and create a list with the less-than pile, the element x, and the larger-than pile).

Beats the understandability of the C version quite easily.


问:
What are the solutions to the Distributed Queue problem?
I am trying to learn more about the various ways that the problem of a Distributed Queue may be solved. So I would like know what products, services, implementations and research papers that are already out there.

An implementation will face many challenges and will be forced to make tradeoffs:

Does it have strong or loose ordering?

Does it have idempotent put?

Can we have more queues than what can fit on a single machine?

Can we have more data in a queue than what can fit on a single machine?

How many machines can crash before we potentially lose data?

Can it tolerate net-splits?

Can it automatically reconcile data when a net-split is fixed?

Can it guarantee delivery when clients can crash?

Can it guarantee that the same message is not delivered more than once?

Can a node crash at any given point, come back up, and not send out junk?

Can you add nodes to, or remove nodes from, a running cluster without down time?

Can you upgrade nodes in a running cluster without down time?

Can it run without problems on heterogeneous servers?

Can you “stick” queues to a group of servers? (example: “these queues are only allowed in the european datacenter”)

Can it make sure to put data replicas in at least two datacenters, if so available?

I have no illusion that any implementation will be able to say “yes” to all of that. I am merely interested in hearing about the various implementations; how they work, what tradeoffs they have made and perhaps why they decided on their particular set of tradeoffs.

Also if there are any challenges that I may have missed in the above list.

答:
Writing a basic queuing system is fairly simple, but as you noted above with all of the challenges, doing it right is another matter.  I've used home grown systems for which I wrote the source code, 3rd party systems, and various JMS providers.  JMS (Java Messaging Service) by far is the most complete solution I've encountered thus far.  Much of what you ask is available in JMS.  My favorite JMS provider is ActiveMQ.  Free, performant, easy to install, and more importantly easy to embed in my app with Spring.  JMS providers don't provide everything you asked for out of the box, but they provide a set of tools to handle much of what you asked about should your application need it.  I haven't found lots of applications need everything you listed.  Ordering might not be important (it's best if it isn't), durable topics might not be important, guaranteed delivery, etc.  You just have to stick to the problem and use what it demands.

http://activemq.apache.org/what-open-source-integration-solution-works-best-with-activemq-.html

Does it have strong or lose ordering? Yes.  It has both depending on your programs needs.  Here are the details: http://activemq.apache.org/total-ordering.html.

Does it have idempotent put? No, but this is trivial to implement in your application layer should you need that.

Can we have more queues than what can fit on a single machine? Yes.  You can have clustered servers, and if you wanted to setup multiple machines with different queues you could, and pull from either.

Can we have more data in a queue than what can fit on a single machine? Yes most JMS providers have to use some sort of DB/persistent storage to ensure messages aren't dropped or lost if the JMS provider goes down.

How many machines can crash before we potentially lose data?  This is a little harder to answer because it's timing related.  However, you can crash a JMS provider and provided the disk isn't corrupt it will come back up and start where it received the last commit.  This means messages could be delivered twice, but if you code your app to handle this it's not a problem.  As long as you have at least one of each type (producers, consumers, or JMS servers) it will complete. You can also have load/balance/failover for redundancy should a disk go out on you.

Can it tollerate net-splits? I think I understand what you mean by "net-split", but I'm not entirely sure.  I guess you mean if the JMS servers are clustered, and we loose connection with one of the servers will it jump to another server and pickup where it left off.  Yes, but again these types of situations can lead to duplicate messages depending on at what point the client lost connection.

Can it automatically reconcile data when a net-split is fixed? If you are using transacted sessions it will only redeliver any message that has had a commit called on it to existing clients that are up.

Can it guarantee delivery when clients can crash? Yes this is one of the main goals of JMS.  Guaranteed delivery means that if a message is queued it's guaranteed to be handled by a client.

Can it guarantee that the same message is not delivered more than once? Yes if the transacted sessions are being used.  That means a client has accepted the message and called commit/rollback.  Once the commit is called it won't redeliver the message.

Can a node crash at any given point, come back up, and not send out junk? In the case where you have durable clustered queues.  Yes it won't spew "junk" if the other node in the cluster has delivered the message.  It can still redeliver anything that hasn't been acknowledged.

Can you add nodes to, or remove nodes from, a running cluster without down time?  Yes.

Can you upgrade nodes in a running cluster without down time? This is a little trickier for me to answer, but I believe that yes you can do this.

Can it run without problems on heterogeneous servers? What does this mean exactly?  I've found most JMS providers are very easy to run in environments using different hardware, OS, etc.  Although, if you mean performance, that's a whole another thing.  Any distributed processing system can be negatively impacted by a slow node.  I had 2 8 Core Intel servers running the queue and the consumers.  That's 16 cores together, and I got better performance from using only those two boxes, than when I added a single core machine as a consumer.  That single core machine was so much slower it slowed down the entire grid by a factor of 2x.  This had nothing to do with JMS per se.

Can you “stick” queues to a group of servers? Short answer yes.  I can think of a way where you can run a cluster that's only in the european data center, and configure the queue there.  Then in your spring config setup your consumers to consume that queue as well as other queues on other clusters.  You might want to consult the docs:

http://activemq.apache.org/clustering.html

Can it make sure to put data replicas in at least two datacenters, if so available? Again I believe so, but it's best to consult the clustering docs.

Again JMS has lots of options you can tweak as your need dictates.  Using transacted sessions and durable queues comes with a performance cost.  I've seen turning on all the bells and whistles impact performance as much as 10x.  When I used JBossMQ if we turned off some of these features we could get around 10,000 messages/s, but turning them on brought us down to 1000 messages/s.  Big drop.


问:
How do you use blank lines in your code?
There has been a few remarks about white space already in discussion about curly braces placements.

I myself tend to sprinkle my code with blank lines in an attempt to segregate things that go together in "logical" groups and hopefully make it easier for the next person to come by to read the code I just produced.

In fact, I would say I structure my code like I write: I make paragraphs, no longer than a few lines (definitely shorter than 10), and try to make each paragraph self-contained.

For example:

in a class, I will group methods that go together, while separating them by a blank line from the next group.

if I need to write a comment I'll usually put a blank line before the comment

in a method, I make one paragraph per step of the process

All in all, I rarely have more than 4/5 lines clustered together, meaning a very sparse code.

I don't consider all this white space a waste because I actually use it to structure the code (as I use the indentation in fact), and therefore I feel it worth the screen estate it takes.

For example:

```<code>for (int i = 0; i < 10; ++i)
{
    if (i % 3 == 0) continue;

    array[i] += 2;
}
</code>```

I consider than the two statements have clear distinct purposes and thus deserve to be separated to make it obvious.

So, how do you actually use (or not) blank lines in code ?

答: I agree, I use whitespace the same way. However, if I find myself using whitespace to break a method into too many parts, it's a sign I might need to refactor that code into multiple methods. Too many logical sections in a method might signal that the method will be harder to test.</p>


问:
As a software engineer, who should I be following on Twitter?
Who in the software engineering and software development fields uses Twitter to tweet about relevant happenings in the field?</p>

答: UncleBob (Robert C. Martin)</p>

Body: UncleBob (Robert C. Martin)


答: I use them to seperate code into logical units. I've seen very few code samples that did not use blank lines, of course obfuscation is excepted.</p>

Title: How do you use blank lines in your code?

Body:
There has been a few remarks about white space already in discussion about curly braces placements.

I myself tend to sprinkle my code with blank lines in an attempt to segregate things that go together in "logical" groups and hopefully make it easier for the next person to come by to read the code I just produced.

In fact, I would say I structure my code like I write: I make paragraphs, no longer than a few lines (definitely shorter than 10), and try to make each paragraph self-contained.

For example:

in a class, I will group methods that go together, while separating them by a blank line from the next group.

if I need to write a comment I'll usually put a blank line before the comment

in a method, I make one paragraph per step of the process

All in all, I rarely have more than 4/5 lines clustered together, meaning a very sparse code.

I don't consider all this white space a waste because I actually use it to structure the code (as I use the indentation in fact), and therefore I feel it worth the screen estate it takes.

For example:

```<code>for (int i = 0; i < 10; ++i)
{
    if (i % 3 == 0) continue;

    array[i] += 2;
}
</code>```

I consider than the two statements have clear distinct purposes and thus deserve to be separated to make it obvious.

So, how do you actually use (or not) blank lines in code ?


问:
What is the difference between "good" designers and "great" designers?
While reading this wikipedia article, Brookes has told that there is a difference between "good" designers and "great" designers.  What is the difference between them? How can I decide if a designer is good or great?</p>

答:
A good designer writes code that works.

A great designer writes code that good designers borrow.


答:
The Psychopath answer is the best, but I would replace that with assuming that the next person is an idiot, and that they will assume that you are, and you will want to prove them wrong.

Just as important to readability is the use of comments. I open each function or subroutine with a comment block, explaining in clear text, what it is, what it does, what the arguments are, and what the expected outcomes are (including a list of error conditions). Then there is no question of what it is intended and/or designed to do. What it achieves may vary, but that is further down the track.

I think way too many coders either assume that it will be they, themselves that will be doing "repairs" on code, or simply don't care.

OwnerDisplayName: Peter


答:
Blank lines are important. However, wasting a whole blank line on the opening brace reduces the amount of code you can see in a screenful. Should be:

```<code>for (int i; i < 10; ++i)
{  if (i % 3 == 0) continue;

   array[i] += 2;
}
</code>```

(Don't get me started on putting the brace '{' on the same line as the 'for'... that's meshuggah).

Body:
Blank lines are important. However, wasting a whole blank line on the opening brace reduces the amount of code you can see in a screenful. Should be:

for (int i; i < 10; ++i)
{  if (i % 3 == 0) continue;

   array[i] += 2;
}

(Don't get me started on putting the brace '{' on the same line as the 'for'... that's meshuggah).


问:
Most logically consistent way to create methods of the form a affects b?
I have a common scenario where I have an object (a) that logically affects another object (b), like a makes a note on b, or a marks b as disabled (usually a is a user object of the system and b is some kind of business object like a customer or an appointment).

In the past, the method was on the affected object like:

```<code>customer.Disable(user); // user is marking the customer as disabled
</code>```

... but it doesn't read well (it appears backwards). The opposite:

```<code>user.Disable(customer);
</code>```

... reads better, but there's something about it that I can't put my finger on that just doesn't seem right. The only other option is to have a static intermediary:

```<code>ThirdPartyClass.DisableCustomer(customer, user);
</code>```

... but the domain objects end up becoming more like DTOs and I prefer the domain model approach because it makes more sense.

So the question is: which makes the most sense? Is there an option I haven't considered? Who actually owns an operation like this?

Edit

With the second option, the actionable objects in the system (users usually) end up becoming huge because the users of the system are the ones that pretty much do and affect everything.

答:
As you point out having lots of methods on the User class is introducing the God Object anti-pattern. It seems that the problem is one of encapsulation, so the data flow

User performs an action on an entity

can be re-interpreted as

System perform command on entity with
  reference to User

This would mean a design that favoured using a Command pattern with a typical command being like this:

```<code>public class DisableCustomerCommand implements EntityCommand<Customer,User> {

  // This is the single EntityCommand templated method
  public Customer execute(Customer customer, User user) {
    customer.setEnabled(false);

    // TODO Add in audit code for User object

    return customer;
  }
}
</code>```

This follows the general OOD principle of creating find grained simple objects that do very little, but do it well.

Edit

I should point out that this is an over-simplification. Typically, the disabling of a Customer would require several other fields to be modified. Also this does lead to anaemic entities (Customer would be just a bunch of getters/setters), but sometimes that can be a simpler overall design.

Body:
As you point out having lots of methods on the User class is introducing the God Object anti-pattern. It seems that the problem is one of encapsulation, so the data flow

User performs an action on an entity

can be re-interpreted as

System perform command on entity with
  reference to User

This would mean a design that favoured using a Command pattern with a typical command being like this:

public class DisableCustomerCommand implements EntityCommand<Customer,User> {

  // This is the single EntityCommand templated method
  public Customer execute(Customer customer, User user) {
    customer.setEnabled(false);

    // TODO Add in audit code for User object

    return customer;
  }
}

This follows the general OOD principle of creating find grained simple objects that do very little, but do it well.

Edit

I should point out that this is an over-simplification. Typically, the disabling of a Customer would require several other fields to be modified. Also this does lead to anaemic entities (Customer would be just a bunch of getters/setters), but sometimes that can be a simpler overall design.


问:
What causes overtime and how can it be avoided?
Today, my manager told me that I must work over time to make up for a lack of planning and project management. Instead of incentivizing this unpaid mandatory overtime, my manager has made it clear I have no choice in the matter.

This isn't a single project. We currently have a dozen projects all on the go at one time, and I simply can't get them all done. Therefore, I must work overtime so we don't have to push deadlines.

Is this a sign of an ignorant or disrespectful manager, or simply an inexperienced one?

I'm in this position because of a lack of planning and project management (I think). How might I avoid this in the future? I'm no Project Manager, it isn't my strength.

What are good ways to get an employee to work overtime if you can't directly pay them? Good incentives, etc.

From what I hear, gaining your employee's respect is the single best way to get your employees to work over time, although you should never make a habit of it.

答:
Wow! Does That Sound Familiar

This happens because the manager bid the job for less money than he should have. At my last job I was on billable hours. We billed customers at the rate of $100 per hour. So, each job that came in was broken down into hours based on $100. Therefore, a $5,000 project worked out to be 50 hours. Tasks were assigned and set number of hours were allotted for each task.

So, if I had 15 hours to complete my tasks but it took me 20 hours to actually complete them I owed the company 5 hours of overtime.

That's how it works. 95% of the time the reason I would go over on my time was because the job was under bid. If you here the salesman say "Yeah, we can do that. Oh yeah, we can do that." Count the number of We Can Do That's. The more We Can Do That's the more overtime.


问:
What's the worst question you were ever asked at interview?
It doesn't have to be programming or software development related, but just asked during an interview for an IT related job.

I know some "left field" questions are meant to see how the candidate copes with unexpected and novel situations, but here I'm looking for a question that appeared to be completely unrelated to the job they were interviewing you for, or something that made you think "what useful information could they possibly get from my answer to that question?".

答:
How come you haven't learned OOP? Don't you believe in upgrading your skill set?

I was so pissed off. I have forgotten more about writing code than that snot nose will ever learn.


问:
Hard-copy approaches to time tracking
I have a problem: I suck at tracking time-on-task for specific feature/defects/etc while coding them.  I tend to jump between tasks a fair bit (partly due to the inherit juggling required by professional software development, partly due to my personal tendancy to focus on the code itself and not the business process around code).

My personal preference is for a hard-copy system.  Even with gabillions of pixels of real-estate on-screen I find it terribly distracting to keep a tracking window convienient; either I forget about it or it gets in my ways.

So, looking for suggestions on time-tracking.  My only requirement is a simple system to track start/stop times per task.  I've considered going as far as buying a time-clock and giving each ticket a dedicated time-card.  When I start working on it, punch-in; when done working, punch-out.

答:
At my last job I had to keep track of task down to 15 minute increments. I bought a classic size franklin planner from franklin covey. Daily Planner.

This was an absolute lifesaver. If I was heads down on a project and the manager wanted to talk with me about something. I'd start a new line item on my daily sheet. If I didn't have that planner I would have gone crazy trying to account for my time.

At the end of the day I could just refer to my planner to update my tasks in the job control system that we had.

Title: Hard-copy approaches to time tracking


问:
What corners have have you cut at work?
Have you ever let your coding standards slip to meet deadlines or save time?

I'll start with a trivial example:

We came up with a coding standard at work around which brackets/formatting to use and so on. I ignore it and use the auto-format tool in netbeans.

答:
None... I bit the bullet

I got so upset one day I intentionally spent six hours writing a code generator in SQL. It was the best six hours of programming time I ever spent. That one code generator saved me at least 3 hours on every project from that day on.

Title: What corners have have you cut at work?


问:
CMP Entity Beans as a "naive" ORM solution
I was browsing through this talk about "Historically Bad Ideas" over the history of Computer Science, and found an interesting presentation about the rise & fall of the Java Enterprise initiatives. Slide #16 grabbed my attention by suggesting that Container Managed Persistence is a "naïve ORM solution". Of course, I assume  the presenter made a live in-depth analysis of the problem, which is missing in the slide. So I was left intrigued by that statement. Is CMP Entity Beans just a heavy piece of naive engineering?

Aside any bias from the author(s) of the presentation, what would constitute a more adequate ORM solution in the domain of languages like Java or C#? I'm not asking for specific tools or frameworks, but better approaches.

答:
In general a good ORM solution should be easy to use and understand. It should promote the use of good design patterns (DAOs, DTOs, lazy loading, services, transaction boundaries, ease of configuration etc). It should be non-invasive - that is, it should not force you to extend special classes or implement special interfaces.

The EJB specifications fell over a lot in the early days leading to the mass migration away to the likes of Spring and Hibernate. EJB1 failed to adequately define CMP fields on the bean, EJB2 sort of implied that they should be abstract accessors rather than actual fields, which was just odd, and it wasn't until EJB3 that something close to what everyone actually wanted was created. By then it was too late, everyone believed EJB sucked and it took the JPA and JTA JCRs to put things right again.

EJB1 and 2 generally forced the developer to put all their persistence configuration in a bunch of XML files well away from the actual code that was using it. This lead to lots of confusion and buggy code. Other ORM frameworks learned from this and decided to use annotations instead. Big win for them.

EJB1 and 2 had very limited support for different kinds of relationships and how they could be implemented in the underlying relational database. All kinds of special interfaces had to be adhered to and the resulting code was hard to fathom.

Anyway, all that is in the past and we can look forward to a bright future with the likes of Hibernate implementing JPA and JTA. All very harmonious.


问:
Language agnostic programming books
Are there any great programming or software development books that are language agnostic?  Why should I read it?</p>

答:
Design Patterns.  The patterns largely OOP-bent, but within OOP, they're pretty applicable to any language.

You should read it because it'll make you a better designer.  It teaches you good ways to solve subsystem design problems that you might not have figured out until you'd been designing systems for 40 years.  They're reusable solutions to semi-common problems.  That said, there's a pattern that sophomores go through when they learn design patterns in school:

Design patterns are kinda neat.  I wonder how I can use them in this project I'm working on?

Design patterns are 10x better than sliced bread!  I'm gonna use'em everywhere!

Ok, there is a time and a place for using specific patterns.  Moderation is good.

We should solve this problem with solution X.  Oh right, that happens to be pattern Y.  How 'bout that.

Title: Language agnostic programming books


问:
Do people in non-English-speaking countries code in English?
I've heard it said (by coworkers) that everyone "codes in English" regardless of where they're from. I find that difficult to believe, however I wouldn't be surprised if, for most programming languages, the supported character set is relatively narrow.

Have you ever worked in a country where English is not the primary language?

If so, what did their code look like?

答:
I'm surely the weird one: I use a language that is tokenized, and so even the language itself can be displayed in your own native language (French, English, German, Spanish and Japanese). It's an RBDMS language born in the 1980s, called 4th Dimension. Have a look at the Language Command translation by clicking on the flags icons.

Hereunder you can see the same code seen with French and English settings.


答:
Not only do i use whitespace, i use braces for clarity.

Braces i use to say these can potentially be functions.

```<code>code
{
    code
    code
    code
    code
}
{
    code
    code=code
    code
    code

    code()
    code()
}
</code>```

Body:
Not only do i use whitespace, i use braces for clarity.

Braces i use to say these can potentially be functions.

code
{
    code
    code
    code
    code
}
{
    code
    code=code
    code
    code

    code()
    code()
}


问:
Which library/framework did you ditch as being too complex for the problem it is solving?
... and coded the functionality "manually"?

As a rather metaphorical example, you'd hardly need a library for solving quadratic equations, although such libraries do exist and someone takes them seriously.

As a more questionable case, depending on the circumstances I may ditch jQuery (for example when I don't need to support some stone age browsers): it does simplify some things but it adds another layer of complexity and unreliability to DOM. And overusing jQuery leads to absurd problems, such as one seen recently on SO: how do I assign an empty href to an a tag with jQuery? Turned out it was a HTML question, not even JavaScript.

Another absurd case and yet non-obvious for many is using some templating engine/language built on top of another templating system: PHP. Third level of templating anyone?

And another one: sometimes just spitting out XML with (figurally) printf is far easier than doing it with some monstrous XML engine.

Any other cases from your experience?

答:
In almost every case I've done this, I've ended up regretting it:

Using the PHP oci_* functions instead of a wrapper library turned out to be a bad move because of code maintainability. Porting all the code to Zend_Db made developing maintaining the database code much easier.

Rolling my own ajax grid component, which took up too much time to develop further, given how fast some of the other grid components evolve. I'm currently porting it all to Ext JS grids because with those there's a huge mass of third-party functionality available.

Avoiding libraries like prototype and jquery led to repeated occurrences of cross-browser issues, often hard to track down. The Ext JS port has solved my cross-browser woes. It is magic, even if it is a vast framework that took me weeks to understand.

I've come to the conclusion that it's much better to pick a few reliable third party frameworks, and use them as the foundation for everything you do. Those frameworks are developed and debugged by someone else, which is an incredible time-saver once you've standardized on them and understand them well.


答:
"How many years of DLL do you have?

It happened during a phone interview with a recruiter.  I kind of saw this question coming because the previous five or so questions were all in the form of "how many years of X do you have", for each X from the list of buzzwords exactly in the order they occurred in the job ad.

This question will not only make you think "what useful information could they possibly get from my answer to that question?", but also "what useful information could they possibly get from any of my answers?"

The job would have required an 80km (50-mile) one-way commute, so I knew at that moment I wasn't going to pursue it.

Title: What's the worst question you were ever asked at interview?

Body:
It doesn't have to be programming or software development related, but just asked during an interview for an IT related job.

I know some "left field" questions are meant to see how the candidate copes with unexpected and novel situations, but here I'm looking for a question that appeared to be completely unrelated to the job they were interviewing you for, or something that made you think "what useful information could they possibly get from my answer to that question?".


答:
One of the problems I've experienced with people "rolling their own" is that -- while their approach is often faster and simpler -- it is also more likely to be brittle, have bugs, be incomplete, and/or contain security flaws.

Simple example: it might be 10 times easier to use printf to emit XML than to use a library:

```<code>printf("<xml>%s</xml>", str);
</code>```

but did you remember to escape special characters in str? For example '<' and '&'?  Some people might say "no I didn't" and proceed to write this:

```<code>printf("<xml><![CDATA[%s]]></xml>", str);
</code>```

But it'll still emit broken XML if str contains the substring "]]>" anywhere in it.  Edge case -- sure.  But still a valid scenario which could lead to unexpected problems with serious consequences.

There are many times and places where "rolling your own" may be appropriate, but it sometimes takes a lot of experience and knowledge to identify when it is appropriate.  That is why I often encourage programmers to prefer using established libraries (where available) instead of self-implemented routines.

Title: Which library/framework did you ditch as being too complex for the problem it is solving?

Body:
... and coded the functionality "manually"?

As a rather metaphorical example, you'd hardly need a library for solving quadratic equations, although such libraries do exist and someone takes them seriously.

As a more questionable case, depending on the circumstances I may ditch jQuery (for example when I don't need to support some stone age browsers): it does simplify some things but it adds another layer of complexity and unreliability to DOM. And overusing jQuery leads to absurd problems, such as one seen recently on SO: how do I assign an empty href to an a tag with jQuery? Turned out it was a HTML question, not even JavaScript.

Another absurd case and yet non-obvious for many is using some templating engine/language built on top of another templating system: PHP. Third level of templating anyone?

And another one: sometimes just spitting out XML with (figurally) printf is far easier than doing it with some monstrous XML engine.

Any other cases from your experience?

Body:
One of the problems I've experienced with people "rolling their own" is that -- while their approach is often faster and simpler -- it is also more likely to be brittle, have bugs, be incomplete, and/or contain security flaws.

Simple example: it might be 10 times easier to use printf to emit XML than to use a library:

printf("<xml>%s</xml>", str);

but did you remember to escape special characters in str? For example '<' and '&'?  Some people might say "no I didn't" and proceed to write this:

printf("<xml><![CDATA[%s]]></xml>", str);

But it'll still emit broken XML if str contains the substring "]]>" anywhere in it.  Edge case -- sure.  But still a valid scenario which could lead to unexpected problems with serious consequences.

There are many times and places where "rolling your own" may be appropriate, but it sometimes takes a lot of experience and knowledge to identify when it is appropriate.  That is why I often encourage programmers to prefer using established libraries (where available) instead of self-implemented routines.


问:
The 10 minutes technical interview
I must do a quick assessment of dozens of fresh students very quickly. I have 30 minutes meeting with each of them (in two or three days). I want to use most of the time to discuss non technical aspects. So I plan to use 10 minutes for technical questions. The same questions for all of them.

They are all hired already (they are students), what I need to know is the average level in order to prepare a training.

Ideally, the difficulty must be progressive in order to set a level for each. Level I will average, and I'll do an average on each question too.

If you had only 10 minutes and 10 questions to ask to a candidate, what would be your top 10 ?

答:
Create 5 simple flowchart constructs and a separate list of answers. Ask them to match the picture with the phrase.

Draw the following:

If Construct

If Else Construct

Do While Loop

Do Until loop

Case Statement Construct

Ask them to explain the difference between 1 and 2.

Ask them to explain the difference between 3 and 4.

Ask them for an example of when a Case Statement Construct would be applicable.

Title: The 10 minutes technical interview


答:
I'm all for making code as clear as possible, and whitespace is often a useful tool in that endeavor. But let's not forget refactoring:

in a class, I will group methods that go together, while separating them by a blank line from the next group.

Since you have several related members, they are a candidate for a new class.

if I need to write a comment I'll usually put a blank line before the comment

Whenever code is unclear enough to want a comment, I ask if I can refactor to make the code clear enough to not need the comment.

in a method, I make one paragraph per step of the process

Why not make one method for each "paragraph"?

If you end up with a bunch of methods in your class, see my note above about extracting a new class.


问:
About the book "Peopleware - Productive Projects and Teams"
I've read Peopleware in 2009. It was one of the best book I ever read.

But this book is a little old. I'd like to know, in your opinion, what is and what is not relevant in this book?

答:
It's been a while since I read it, but I don't remember anything in the book that wasn't relevant to someone.

What stood out the most was the discussion of process improvement using CMM and CMMI, and no mention of agile processes (although the second edition was printed in 1999, which is a few years before the Manifesto for Agile Software Development and agile development went mainstream). But the book is about people, and people haven't changed that much since the first printing of the book in 1987.


问:
Compiler Warnings
Many compilers have warning messages to warn the programmers about potential runtime, logic and performance errors, most times, you quickly fix them, but what about unfixable warnings?

How do you deal with unfixable warnings? Do you re-write a portion of the code, or rewrite it in the "long, hackless way" or disable warnings all together? What should be the best practice?

What if you are editing someone else's code and his code has warnings?

Here is a good example:
jQuery has a lots of JavaScript warnings as a Mozilla-class browser detected, why the jQ developers don't fix them? If you contribute to jQuery, are you going to fix them?

答:
Every time you see a compiler warning, you have to stop and think about whether it is really a problem waiting to blow up in your face at the customer's site, or something you can ignore.  Worse, the things you can ignore TODAY may be things that will blow up at the customer's site in a few years, after a seemingly-unrelated code change Somewhere Else.

Fix the warnings.  Period.  It is that or document every single one of them, with as many pages of explanation as is necessary to prove it isn't a risk, accompanied by a signed sales order on your favorite girlfriend (or porn stash) if it turns out that it WAS a risk.

Title: Compiler Warnings


问:
What was your most difficult bug hunt and how did you find it and kill it?
This is a "Share the Knowledge" question. I am interested in learning from your successes and/or failures.

Information that might be helpful...

Background:

Context: Language, Application,
Environment, etc.

How was the bug identified ?

Who or what identified the bug ?

How complex was reproducing the bug ?

The Hunting.

What was your plan  ?

What difficulties did you encounter ?

How was the offending code finally found ?

The Killing.

How complex was the fix ?

How did you determine the scope of the fix ?

How much code was involved in the fix ?

Postmortem.

What was the root cause technically ? buffer overrun, etc.

What was the root cause from 30,000 ft ?

How long did the process ultimately take ?

Were there any features adversely effected by the fix ?

What methods, tools, motivations did you find particularly helpful ? ...horribly useless ?

If you could do it all again
?............

These examples are general, not applicable in every situation and possibly useless. Please season as needed.

答:
Main-Frame Program Stopped Working For No Reason

I just posted this to another question.See Post Here

It happened because they installed a newer version of the compiler on the Main-Frame.

Update 06/11/13: (Original answer was deleted by OP)

I inherrited this main-frame application. One day, out of the clear blue it stopped working. That's it... poof it just stopped.

My job was to get it working as fast as possible. The source code had not been modified for two years, but all of the sudden it just stopped. I tried to compile the code and it broke on line XX. I looked at line XX and I could not tell what would make line XX break. I asked for the detailed specs for this application and there were none. Line XX was not the culprit.

I printed out the code and started reviewing it from the top down. I started to create a flowchart of what was going on. The code was so convoluted I could hardly even make sense of it. I gave up trying to flowchart it. I was afraid to make changes without knowing how that change would effect the rest of the process, especially since I had no details of what the application did.

So, I decided to start at the top of the source code and add whitespce and line brakes to make the code more readable. I noticed, in some cases, there were if conditions that combined ANDs and ORs and it wasn't clearly distinguishable between what data was being ANDed and what data was being ORed. So i started putting parenthesis around the AND and OR conditions to make them more readable.

As I slowly moved down cleaning it up, I would periodically save my work. At one point I tried compiling the code and a strange thing happend. The error had jumped passed the original line of code and was now further down. So I continued, speparating the AND and OR conditions with parens. When I got done cleaning it up it worked. Go Figure.

I then decided to visit the operations shop and ask them if they had recently installed any new components on the main-frame. They said yes, we recently upgraded the compiler. Hmmmm.

It turns out that the old compiler evaluated expression from left to right regardless. The new version of the compiler also evaluated expressions from left to right but ambiguous code meaning unclear combination of ANDs and ORs could not be resolved.

Lesson I learned from this... ALWAYS, ALWAYS, ALWAYS use parens to separated AND conditions and OR conditions when they are used in conjuction with each other.


问:
Should my multi-server RDBMS or my Application handle database Referential Integrity?
Should items like Foreign Keys, Constraints, Default Values, and so on be handled by the database management system (in this case, MS SQL 2005) or the application? I have heard opinions from both sides and I'm honestly not sure which way to go.

There is a chance we will be spanning multiple servers/databases and I don't think Foreign Keys can be used across linked servers. In addition to that, there are some circular references in the database design which prevents me from using ON UPDATE CASCADE on everything.

The database is MS SQL 2005 (possibly 2008) and all interactions with it should go through the application.

答: I would say put in the database.  If you're using a persistent framework, It would pick up the keys automatically.</p>


答:
Some warning are usually safe to ignore but if you do so then over time they'll multiply until that day comes when there are so many that you miss the one warning that really matters because it's hidden in the noise.

Fix warnings immediately (which may include disabling individual rules if you feel that it's never relevant for your context).

Title: Compiler Warnings

Body:
Many compilers have warning messages to warn the programmers about potential runtime, logic and performance errors, most times, you quickly fix them, but what about unfixable warnings?

How do you deal with unfixable warnings? Do you re-write a portion of the code, or rewrite it in the "long, hackless way" or disable warnings all together? What should be the best practice?

What if you are editing someone else's code and his code has warnings?

Here is a good example:
jQuery has a lots of JavaScript warnings as a Mozilla-class browser detected, why the jQ developers don't fix them? If you contribute to jQuery, are you going to fix them?


问:
What are some famous one-liner or two-liner programs and equations?
I'm experimenting with a new platform and I'm trying to write a program that deals with strings that are no longer than 60 characters and I'd like to populate the data store with some famous or well-known small chunks of code and equations, since programming and math goes along with the theme of my software. The code can be in any language and the equations from any discipline of mathematics, just so long as they're less than a total of 60 characters in length. I suspect people are gonna break out some brainfuck for this one.

For example,

```<code>#include<stdio.h>
int main(){printf ("Hi World\n");return 0;}
</code>```

60 characters exactly!

Thanks so much for your wisdom!

答:
How to detect even numbers:</p>

```<code>x % 2 == 0
</code>```

Body:
How to detect even numbers:

x % 2 == 0


答:
not one line, but I present The World's Last C Bug:</p>

```<code>    status = GetRadarInfo();
    if (status = 1)
      LaunchNukes();
</code>```

Body:
not one line, but I present The World's Last C Bug:

    status = GetRadarInfo();
    if (status = 1)
      LaunchNukes();


答: Do whatever your obligated to do as defined in your contract. I don't know how things are as a contractor, but in the corporate environment you're expected to do whatever it takes to get the project completed on time. Pick your battles and the time you want to fight them. Just be prepared to leave, because in my experience, management backs management.</p>

Title: What causes overtime and how can it be avoided?

Body:
Today, my manager told me that I must work over time to make up for a lack of planning and project management. Instead of incentivizing this unpaid mandatory overtime, my manager has made it clear I have no choice in the matter.

This isn't a single project. We currently have a dozen projects all on the go at one time, and I simply can't get them all done. Therefore, I must work overtime so we don't have to push deadlines.

Is this a sign of an ignorant or disrespectful manager, or simply an inexperienced one?

I'm in this position because of a lack of planning and project management (I think). How might I avoid this in the future? I'm no Project Manager, it isn't my strength.

What are good ways to get an employee to work overtime if you can't directly pay them? Good incentives, etc.

From what I hear, gaining your employee's respect is the single best way to get your employees to work over time, although you should never make a habit of it.


问:
How do you use blank lines in your code?
There has been a few remarks about white space already in discussion about curly braces placements.

I myself tend to sprinkle my code with blank lines in an attempt to segregate things that go together in "logical" groups and hopefully make it easier for the next person to come by to read the code I just produced.

In fact, I would say I structure my code like I write: I make paragraphs, no longer than a few lines (definitely shorter than 10), and try to make each paragraph self-contained.

For example:

in a class, I will group methods that go together, while separating them by a blank line from the next group.

if I need to write a comment I'll usually put a blank line before the comment

in a method, I make one paragraph per step of the process

All in all, I rarely have more than 4/5 lines clustered together, meaning a very sparse code.

I don't consider all this white space a waste because I actually use it to structure the code (as I use the indentation in fact), and therefore I feel it worth the screen estate it takes.

For example:

```<code>for (int i = 0; i < 10; ++i)
{
    if (i % 3 == 0) continue;

    array[i] += 2;
}
</code>```

I consider than the two statements have clear distinct purposes and thus deserve to be separated to make it obvious.

So, how do you actually use (or not) blank lines in code ?

答:
Yes. It makes it easier to visually scan a file. Among other things, it makes it clearer which line a comment goes with.</p>

```<code>Some code here
// Which line does this comment go with?
More code here

// It's pretty clear which line this comment goes with
More code here

Still more code here
</code>```

Body:
Yes. It makes it easier to visually scan a file. Among other things, it makes it clearer which line a comment goes with.

Some code here
// Which line does this comment go with?
More code here

// It's pretty clear which line this comment goes with
More code here

Still more code here


答:
Generally, you want your build to be warning free.  Warnings are there for a reason, and often they do point to very real problems.  If you get into a habit of ignoring compiler warnings, then eventually your build will have a ton of them, and you will miss the one warning that is caused by a catastrophic problem that will cost your company dearly.  On the other hand, if your program normally compiles without warnings, then every new warning is immediately noticed, and can be quickly addressed.

Having said that, sometimes compilers can have warnings that make little sense and which cannot be easily fixed.  I face this situation every day at work with TI CodeComposer, which is a development environment for TI DSPs.  I have C++ code that compiles with no warnings under Visual Studio, but which results in strange warnings in CodeComposer, simply because TI's support for standard C++ could be better.  Luckily, CodeComposer lets you disable specific warnings individually, which is what we have to do when there is no way to fix the code that produces the warning.

Title: Compiler Warnings


答:
I usually do everything in English when programming C#, but sometimes we throw in some Spanish or Italian in comments. Some business objects are in Spanish (but always mixed with English for actions and such).

Now, when I’m in Objective-C, I always stick to English. It makes so much sense (in the way the language is structured) that it’s easier to read.

Title: Do people in non-English-speaking countries code in English?

Body:
I've heard it said (by coworkers) that everyone "codes in English" regardless of where they're from. I find that difficult to believe, however I wouldn't be surprised if, for most programming languages, the supported character set is relatively narrow.

Have you ever worked in a country where English is not the primary language?

If so, what did their code look like?


答:
At one time, I'd sprinkle blank lines liberally throughout my code.  Nowadays, I tend to be more sparing.  I think that this is part of what Steve Yegge was talking about here:

Hopefully the scene I've painted so
far helps you understand why sometimes
you look at code and you just hate it
immediately. If you're a n00b, you'll
look at experienced code and say it's
impenetrable, undisciplined crap
written by someone who never learned
the essentials of modern software
engineering. If you're a veteran,
you'll look at n00b code and say it's
over-commented, ornamental fluff that
an intern could have written in a
single night of heavy drinking.

The sticking point is
compression-tolerance. As you write
code through your career, especially
if it's code spanning very different
languages and problem domains, your
tolerance for code compression
increases. It's no different from the
progression from reading children's
books with giant text to increasingly
complex novels with smaller text and
bigger words.

...

A programmer with a high tolerance
for compression is actually hindered
by a screenful of storytelling. Why?
Because in order to understand a code
base you need to be able to pack as
much of it as possible into your head.
If it's a complicated algorithm, a
veteran programmer wants to see the
whole thing on the screen, which means
reducing the number of blank lines and
inline comments – especially comments
that simply reiterate what the code is
doing. This is exactly the opposite of
what a n00b programmer wants. n00bs
want to focus on one statement or
expression at a time, moving all the
code around it out of view so they can
concentrate, fer cryin' out loud.

I fundamentally agree with him.  It's much better to compress the code so you can get as much of it as possible on one screen than to space it out too much.  That's not to say that you should never use blank lines.  It's just that I think unless the grouping you're trying to create doesn't increase readability immensely, it does more harm than good.


答: I would fix any warning.  If you ignore them and let them accumulate, you might actually missed something important. </p>

Title: Compiler Warnings


问:
How can I find a good open source project to join?
I just started working a year ago, and I want to join an open source project for the same reasons as anyone else: help create something useful and develop my skills further.

My problem is, I don't know how to find a project where I'll fit in.

How can I find a beginner-friendly project?  What attributes should I be searching for?  What are warning signs that a project might not be the right fit?  Are there any tools out there to help match people with open source projects?

There's a similar question here, but that question has to do with employment and is limited to PHP/Drupal.

答:
Here what I suggest to do in order to find your perfect match:

If you have an open-source project that you already use, know and care about, it should be your first candidate to try. Otherwise think about what you would like to do in general and search for a project in this area.

When you have found a potential project, do not rush into it. Try to use it yourself. Is it as good in action as it seemed from description and reviews? If not it isn't a complete show-stopper; maybe it is an opportunity for you to jump in and really make a difference. After all nobody needs another developer for a perfect product. But it will give you a important insight whether you want to be part of this project, while you gain first hand experience with new technology in an area you are interested in.

Also before starting to invest too much time in the project and learning its ins and outs, consider hanging around in the project mailing lists, forums, even bug tracking system for a couple of weeks. If you will start contributing to the project on the regular basis you will spend a lot of time there.

Figure out: do you enjoy hanging around there, or is it a drag for you? Does it feels like this project has a good and energetic community or is it slowly dying? Do core people there seem to encourage and mentor newcomers or you will be on your own?

Do these steps for several projects, potentially in different areas and you are less likely to experience disappointment that comes when you join a wrong team. Such an experience can potentially discourage you from doing it again in the future.

A few more thoughts:

If the project you are really interested in is a high profile one with a lot of developers and activity around it, you probably will have a hard time establishing a sufficient reputation there to get, say, commit rights or an interesting role in the community. In this case consider joining a related spin-off project with lower visibility. For example instead of trying to start contributing to jQuery, try to find jQuery plugin that will be a good fit to you. Later you can consider "moving up".

If you like a project but feel intimidated by its size, complexity, or code quality requirements, consider starting from supporting roles, like testing, documentation maintenance, or bug report verification. If you ask in the project mailing list what kind of help they need most at the moment they will be more than happy to guide you there. :)

This way you will learn the project and build your reputation there while contributing way more to it than if you started to submit sub-standard patches that would be rejected multiple times until they were ready.

The last and the most important: if you get burned in one place, move on; don't give up.

Hope that helps.


答:
I like to think of whitespaces the same way as paragraphing. You group together lines that contribute to one idea.

If you're starting a new idea or a new facet of the same idea, you start a new paragraph -- like this.

In imperative code, I group together tasks that perform one cohesive task; in declarative code, I group together code that describes one cohesive statement of an idea.

You clearly have no trouble doing that in English (some people are horrible with paragraphing), so with a little practice, applying the same skill to code should be no stretch at all.


问:
async & await - poll for alternatives
Now that we know what is in store for c#5, there is apparently still an opening for us to influence the choice of the two new keywords for 'Asynchrony' that were announced by Anders Heijsberg yesterday at PDC10.

```<code>async void ArchiveDocuments(List<Url> urls) {
    Task archive = null;
    for(int i = 0; i < urls.Count; ++i) {
        var document = await FetchAsync(urls[i]);
        if (archive != null)
            await archive;
        archive = ArchiveAsync(document);
    }
}
</code>```

Eric Lippert has an explanation of the choice of the current two keywords, and the way in which they have been misunderstood in usability studies. The comments have several other propositions.

Please - one suggestion per answer, duplicates will be nuked.

答:
async = task -- It's modifying a function to return a task, so why not use the keyword "task"?

await = finish -- We don't necessarily need to wait, but the task has to "finish" before using the result.

Title: async & await - poll for alternatives


问:
What keymap do you prefer in ReSharper?
I am using ReSharper since version 3 and I always used InteliJ Idea/Resharper 2.x keymap schema. Recently I have learned Ilya's Visual Studio keymap. They each have advantages.

What keymap do you use/prefer with ReSharper?

答:
Typically I use the IntelliJ mapping, simply because that's what was introduced to me when I started at my company, plus a few additions:

Alt+; to run the unit tests in context

Alt+C to close all windows.

Title: What keymap do you prefer in ReSharper?


答:
Write that which is most legible and least surprising.

```<code>function validEmail($addr) {
    $regex = "/.../";
    return preg_match($regex, $addr);
}
</code>```

This function doesn't need 12 lines of doc comments.

In fact, it doesn't need any comments.

Or blank lines.

They would detract from its essence.

Body:
Write that which is most legible and least surprising.

function validEmail($addr) {
    $regex = "/.../";
    return preg_match($regex, $addr);
}

This function doesn't need 12 lines of doc comments.

In fact, it doesn't need any comments.

Or blank lines.

They would detract from its essence.


答:
Yes. For readability.
Sometimes I even put blank lines in code that I did not write.
I find it easier to understand code when they have logical grouping via blank lines - like u can "speed-read" through it.</p>