答:
There are many more aspects one should consider when settling for assignment/declaration syntax, than simple = vs. := bikeshedding.

Type inference or not, you will want a syntax for explicit type annotations. In some type systems, inference may not be possible without occasional explicit annotations. There two possible classes of syntax for this:

A type-variable statement without further operators implies a declaration, e.g. int i in C. Some languages use postfix types like i int, (Golang to a certain degree).

There is a typing operator, often : or ::. Sometimes, this declares the type of a name: let i : int = 42 (e.g. Ocaml). In an interesting spin of this, Julia allows a programmer to use type assertions for arbitrary expressions, along the lines of sum = (a + b):int.

You may also want to consider an explicit declaration keyword, like var, val or let. The advantage is not primarily that they make parsing and understanding of the code much easier, but that they unambiguously introduce a variable. Why is this important?

If you have closures, you need to precisely declare which scope a variable belongs to. Imagine a language without a declaration keyword, and implicit declaration through assignment (e.g. PHP or Python). Both of these are syntactically challenged with respect to closures, because they either ascribe a variable to the outermost or innermost possible scope. Consider this Python:

def make_closures():
  x = 42;
  def incr():
    x = x + 1
  def value():
    print(x)
  return incr, value

i, v = make_closures();
v();  # expected: 42, behaviour: error because x is uninitialized in value()
```

<p>Compare with a language that allows explicit declaration:</p>

<pre class="lang-javascript prettyprint-override"><code>var make_closures = function() {
  var x     = 42,
      incr  = function() { x++ },
      value = function() { console.log(x) };
  return { incr: incr, value: value };
};

var closures = make_closures();
closures.value();  // everything works
</code>```

Explicit declarations allow variable shadowing. While generally a bad practice, it sometimes makes code much easier to follow – no reason to disallow it.

Explicit declarations offer a form of typo detection, because unbound variables are not implicitly declared. Consider:

var1 = 42
if 0 < 1:
   varl = 12

print(var1)  # 42
```

<p>versus:</p>

<pre class="lang-perl prettyprint-override"><code>use strict;
my $var1 = 42;
$varl = 12 if 0 < 1;  # Doesn't compile: Global symbol "$varl" requires explicit package name
say $var1;
</code>```

You should also consider whether you would like to (optionally) enforce single-assignment form, e.g through keywords like val (Scala), let, or const or by default. In my experience, such code is easier to reason about.

How would a short declaration e.g. via := fare in these points?

Assuming you have typing via a : operator and assigment via =, then i : int = 42 could declare a variable, the syntax i : = 42 would invoke inference of the variable, and i := 42 would be a nice contraction, but not an operator in itself. This avoids problems later on.

Another rationale is the mathematical syntax for the declaration of new names x := expression or expression =: x. However, this has no significant difference to the = relation, except that the colon draws attention to one name. Simply using the := for similarity to maths is silly (considering the = abuse), as is using it for similarity to Pascal.

We can declare some more or less sane characteristics for :=, like:

It declares a new variable in the current scope

which is re-assignable,

and performs type inference.

Re-declaring a variable in the same scope is a compilation error.

Shadowing is permitted.

But in practice, things get murky. What happens when you have multiple assignments (which you should seriously consider), like

```<code>x := 1
x, y := 2, 3
</code>```

Should this throw an error because x is already declared in this scope? Or should it just assign x and declare y? Go takes the second route, with the result that typo detection is weakened:

```<code>var1 := 1
varl, var2 := 2, 3  // oops, var1 is still 1, and now varl was declared
</code>```

Note that the “RHS of typing-operator is optional” idea from above would disambiguate this, as every new variable would have to be followed by a colon:

```<code>x: = 1
x:, y: = 2, 3  # error because x is already declared
x,  y: = 2, 3  # OTOH this would have been fine
</code>```

Should = be declaration but := be assignment? Hell no. First, no language I know of does this. Second, when you don't use single-assignment form, then assignment is more common than declaration. Huffman-coding of operator requires that the shorter operator is used for the more common operation. But if you don't generally allow reassignment, the = is somewhat free to use (depending on whether you use = or == as comparison operator, and whether you could disambiguate a = from context).

Summary

If assignment and declaration use the same operator, bad things happen: Closures, variable shadowing, and typo detection all get ugly with implicit declarations.

But if you don't have re-assignments, things clear up again.

Don't forget that explicit types and variable declarations are somewhat related. Combining their syntax has served many languages well.

Are you sure you want such little visual distinction between assignment and declaration?

Personal opinion

I am fond of declaration keywords like val or my. They stand out, making code easier to grok. Explicit declarations are always a good idea for a serious language.

Title: Variable declaration versus assignment syntax

Body:
Working on a statically typed language with type inference and streamlined syntax, and need to make final decision about syntax for variable declaration versus assignment. Specifically I'm trying to choose between:

```<code>// Option 1. Create new local variable with :=, assign with =
foo := 1
foo = 2

// Option 2. Create new local variable with =, assign with :=
foo = 1
foo := 2
</code>```

Creating functions will use = regardless:

```<code>// Indentation delimits blocks
square x =
    x * x
</code>```

And assignment to compound objects will do likewise:

```<code>sky.color = blue
a[i] = 0
</code>```

Which of options 1 or 2 would people find most convenient/least surprising/otherwise best?

Body:
There are many more aspects one should consider when settling for assignment/declaration syntax, than simple = vs. := bikeshedding.

Type inference or not, you will want a syntax for explicit type annotations. In some type systems, inference may not be possible without occasional explicit annotations. There two possible classes of syntax for this:

A type-variable statement without further operators implies a declaration, e.g. int i in C. Some languages use postfix types like i int, (Golang to a certain degree).

There is a typing operator, often : or ::. Sometimes, this declares the type of a name: let i : int = 42 (e.g. Ocaml). In an interesting spin of this, Julia allows a programmer to use type assertions for arbitrary expressions, along the lines of sum = (a + b):int.

You may also want to consider an explicit declaration keyword, like var, val or let. The advantage is not primarily that they make parsing and understanding of the code much easier, but that they unambiguously introduce a variable. Why is this important?

If you have closures, you need to precisely declare which scope a variable belongs to. Imagine a language without a declaration keyword, and implicit declaration through assignment (e.g. PHP or Python). Both of these are syntactically challenged with respect to closures, because they either ascribe a variable to the outermost or innermost possible scope. Consider this Python:

def make_closures():
  x = 42;
  def incr():
    x = x + 1
  def value():
    print(x)
  return incr, value

i, v = make_closures();
v();  # expected: 42, behaviour: error because x is uninitialized in value()

Compare with a language that allows explicit declaration:

var make_closures = function() {
  var x     = 42,
      incr  = function() { x++ },
      value = function() { console.log(x) };
  return { incr: incr, value: value };
};

var closures = make_closures();
closures.value();  // everything works

Explicit declarations allow variable shadowing. While generally a bad practice, it sometimes makes code much easier to follow – no reason to disallow it.

Explicit declarations offer a form of typo detection, because unbound variables are not implicitly declared. Consider:

var1 = 42
if 0 < 1:
   varl = 12

print(var1)  # 42

versus:

use strict;
my $var1 = 42;
$varl = 12 if 0 < 1;  # Doesn't compile: Global symbol "$varl" requires explicit package name
say $var1;

You should also consider whether you would like to (optionally) enforce single-assignment form, e.g through keywords like val (Scala), let, or const or by default. In my experience, such code is easier to reason about.

How would a short declaration e.g. via := fare in these points?

Assuming you have typing via a : operator and assigment via =, then i : int = 42 could declare a variable, the syntax i : = 42 would invoke inference of the variable, and i := 42 would be a nice contraction, but not an operator in itself. This avoids problems later on.

Another rationale is the mathematical syntax for the declaration of new names x := expression or expression =: x. However, this has no significant difference to the = relation, except that the colon draws attention to one name. Simply using the := for similarity to maths is silly (considering the = abuse), as is using it for similarity to Pascal.

We can declare some more or less sane characteristics for :=, like:

It declares a new variable in the current scope

which is re-assignable,

and performs type inference.

Re-declaring a variable in the same scope is a compilation error.

Shadowing is permitted.

But in practice, things get murky. What happens when you have multiple assignments (which you should seriously consider), like

x := 1
x, y := 2, 3

Should this throw an error because x is already declared in this scope? Or should it just assign x and declare y? Go takes the second route, with the result that typo detection is weakened:

var1 := 1
varl, var2 := 2, 3  // oops, var1 is still 1, and now varl was declared

Note that the “RHS of typing-operator is optional” idea from above would disambiguate this, as every new variable would have to be followed by a colon:

x: = 1
x:, y: = 2, 3  # error because x is already declared
x,  y: = 2, 3  # OTOH this would have been fine

Should = be declaration but := be assignment? Hell no. First, no language I know of does this. Second, when you don't use single-assignment form, then assignment is more common than declaration. Huffman-coding of operator requires that the shorter operator is used for the more common operation. But if you don't generally allow reassignment, the = is somewhat free to use (depending on whether you use = or == as comparison operator, and whether you could disambiguate a = from context).

Summary

If assignment and declaration use the same operator, bad things happen: Closures, variable shadowing, and typo detection all get ugly with implicit declarations.

But if you don't have re-assignments, things clear up again.

Don't forget that explicit types and variable declarations are somewhat related. Combining their syntax has served many languages well.

Are you sure you want such little visual distinction between assignment and declaration?

Personal opinion

I am fond of declaration keywords like val or my. They stand out, making code easier to grok. Explicit declarations are always a good idea for a serious language.


问:
Is the Joel Test really a good gauging tool?
I just learned about the Joel Test. I have been computer programmer for 22 years, but somehow I never heard about it before. I consider my best job so far to be this small investment managing company with 30 employees and only three people in the IT department.

I am no longer with them, but I had being working there for five years – my longest streak with any given company. To my surprise they scored extremely poor on the Joel Test. The only two questions I would answer “yes” are #4: Do you have a bug database? And #9: Do you use the best tools money can buy? Everything else is either “sometimes” or straight “no”.

Here is what I liked about the company however:

Good pay. They bragged about it to my face, and I bragged about it to their face, so it was almost like a family environment.

I always knew the big picture. When writing code to solve a particular problem there were no ambiguity about the business nature of that problem. Even though we did not always had written specifications we could ask business users a question anytime, often yelling it across the floor. I could even talk to executives any time I felt like doing it: no appointment necessary.

Immediate feedback. Once we implement a solution and make business users happy they immediately let us know that, we (programmers) become heroes of the moment.

No red tape. I could always buy any tools I deemed necessary, and design solutions the way my professional judgment dictates.

Flexibility. If I had mid-day dental appointment that is near my house rather than near the office, I would send email to the company: "FYI: I work from home today". As long as one of three IT guys was on the floor (to help traders in case their monitors go dark) they did not care where two others were.

So the question thus becomes: How valuable is the Joel Test? Why bother with it?

答:
Keep in mind that Joel's perspective is from within a software company (Microsoft, Stackoverflow).  The idea behind the test is that a company should be, or strive to be, competent when working within their primary field.

From your description, it sounds like software was not the primary business of your company.  If you described the company as an "Enterprise investment  software provider" with 30 developers instead of 3, the test might be a better indicator of competency.

Additionally, if you applied the concepts behind the test to their primary business, they would probably have a decent score:  Do they have a way to track the history of investments made? Can they make a transaction in as few steps as possible? do they have a spec/algorithm/process for investments? etc...

ContentLicense: CC BY-SA 3.0


问:
Testing on different operating systems
I am a developer who has windows 7 installed as the host operating system with vmware. I have linux installed using vmware. Therefore I am able to test java and c++ apps on windows 7 and Linux.

I also want to test them on windows 8 and I want to familiarise myself with windows 8.

I am debating whether to upgrade my host operating system to windows 8 or install it on vmware?

答:
Use whatever working environment you feel is most productive for you and test in VM on all target platforms including the operating system you're using.

This approach gives you:-

a consistent starting point

a reproducible system (where others can repeat your tests given your VM)

freedom from dependencies

separation of dev / test environments

As for if you should use windows 8 or not, that's up to you...  My experience has been that after installation you struggle with the new UI for a few days and then wonder what everyone made all the fuss was about (it's basically just that people fear change when you get to the bottom of it.)  Your mileage may vary.

Title: Testing on different operating systems


答:
I would recommend testing all of your target operating systems within VMware, both Windows 8 and Windows 7, using a VM for Win7 instead of your development environment.

Your development environment likely has a great deal of differences between a typical deployment machine, that can easily mask many kinds of bugs and configuration issues.

Testing on 'fresh' virtual machines, you can test and verify that you aren't forgetting any dependencies, configurations, etc that you need to run your software.

Title: Testing on different operating systems

Body:
I am a developer who has windows 7 installed as the host operating system with vmware. I have linux installed using vmware. Therefore I am able to test java and c++ apps on windows 7 and Linux.

I also want to test them on windows 8 and I want to familiarise myself with windows 8.

I am debating whether to upgrade my host operating system to windows 8 or install it on vmware?


问:
Is COM truly dead?
I have previously worked on COM, however I have observed for quite sometime that hardly any company asks for COM exp.

Is COM dead or reports of its demise are highly exaggerated?

答:
I wish...

That said, the only context I still have to deal with it in is essentially legacy. So I would say it's "dead" in about the same sense as classic VB is dead: few or no new projects are going to be done with it now and into the future. But legacy support and integration will still be around for quite some time.

ContentLicense: CC BY-SA 2.5

Title: Is COM truly dead?


问:
Type checking and recursive types (Writing the Y combinator in Haskell/Ocaml)
When explaining the Y combinator in the context of Haskell, it's usually noted that the straight-forward implementation won't type-check in Haskell because of its recursive type.

For example, from Rosettacode:

The obvious definition of the Y combinator in Haskell canot be used
because it contains an infinite recursive type (a = a -> b). Defining a data type (Mu) allows this recursion to be broken.

```<code>newtype Mu a = Roll { unroll :: Mu a -> a }

fix :: (a -> a) -> a
fix = \f -> (\x -> f (unroll x x)) $ Roll (\x -> f (unroll x x))
</code>```

And indeed, the “obvious” definition does not type check:

```<code>λ> let fix f g = (\x -> \a -> f (x x) a) (\x -> \a -> f (x x) a) g

<interactive>:10:33:
    Occurs check: cannot construct the infinite type:
      t2 = t2 -> t0 -> t1
    Expected type: t2 -> t0 -> t1
      Actual type: (t2 -> t0 -> t1) -> t0 -> t1
    In the first argument of `x', namely `x'
    In the first argument of `f', namely `(x x)'
    In the expression: f (x x) a

<interactive>:10:57:
    Occurs check: cannot construct the infinite type:
      t2 = t2 -> t0 -> t1
    In the first argument of `x', namely `x'
    In the first argument of `f', namely `(x x)'
    In the expression: f (x x) a
(0.01 secs, 1033328 bytes)
</code>```

The same limitation exists in Ocaml:

```<code>utop # let fix f g = (fun x a -> f (x x) a) (fun x a -> f (x x) a) g;;
Error: This expression has type 'a -> 'b but an expression was expected of type 'a
       The type variable 'a occurs inside 'a -> 'b
</code>```

However, in Ocaml, one can allow recursive types by passing in the -rectypes switch:

```<code>   -rectypes
          Allow  arbitrary  recursive  types  during type-checking.  By default, only recursive
          types where the recursion goes through an object type are supported.
</code>```

By using -rectypes, everything works:

```<code>utop # let fix f g = (fun x a -> f (x x) a) (fun x a -> f (x x) a) g;;
val fix : (('a -> 'b) -> 'a -> 'b) -> 'a -> 'b = <fun>
utop # let fact_improver partial n = if n = 0 then 1 else n*partial (n-1);;
val fact_improver : (int -> int) -> int -> int = <fun>
utop # (fix fact_improver) 5;;
- : int = 120
</code>```

Being curious about type systems and type inference, this raises some questions I'm still not able to answer.

First, how does the type checker come up with the type t2 = t2 -> t0 -> t1? Having come up with that type, I guess the problem is
that the type (t2) refers to itself on the right side?

Second, and
perhaps most interesting, what is the reason for the Haskell/Ocaml
type systems to disallow this? I guess there is a good reason
since Ocaml also will not allow it by default even if it can deal
with recursive types if given the -rectypes switch.

If these are really big topics, I'd appreciate pointers to relevant literature.

答:
First, the GHC error,

GHC is attempting to unify a few constraints with x, first, we use it as a function so

```<code>x :: a -> b
</code>```

Next we use it as a value to that function

```<code>x :: a
</code>```

And finally we unify it with the original argument expression so

```<code>x :: (a -> b) -> c -> d
</code>```

Now x x becomes an attempt to unify t2 -> t1 -> t0, however, We can't unify this since it would require unifying t2, the first argument of x, with x. Hence our error message.

Next, why not general recursive types. Well the first point worth noting is the difference between equi and iso recursive types,

equi-recursive are what you'd expect mu X . Type is exactly equivalent to expanding or folding it arbitrarily.

iso-recursive types provide a pair of operators, fold and unfold which fold and unfold the recursive definitions of types.

Now equi-recursive types sound ideal, but are absurdly hard to get right in complex types systems. It can actually make type checking undecidable. I'm not familiar with every detail of OCaml's type system but fully equirecursive types in Haskell can cause the typechecker to loop arbitrarily trying to unify types, by default, Haskell makes sure that type checking terminates. Further more, in Haskell, type synonyms are dumb, the most useful recursive types would be defined like type T = T -> (), however are inlined almost immediately in Haskell, but you can't inline a recursive type, it's infinite! Therefore, recursive types in Haskell would demand a huge overhaul to how synonyms are handled, probably not worth the effort to put even as a language extension.

Iso-recursive types are a bit of a pain to use, you more or less have to explicitly tell the type checker how to fold and unfold your types, making your programs more complex to read and write.

However, this is very similar to what your doing with your Mu type. Roll is fold, and unroll is unfold. So actually, we do have iso-recursive types baked in. However, equi-recursive types are just too complex so systems like OCaml and Haskell force you to pass recurrences through type level fixpoints.

Now if this interests you, I'd recommend Types and Programming Languages. My copy is sitting open in my lap as I'm writing this to make sure I've got the right terminology :)

ContentLicense: CC BY-SA 4.0

Body:
First, the GHC error,

GHC is attempting to unify a few constraints with x, first, we use it as a function so

x :: a -> b

Next we use it as a value to that function

x :: a

And finally we unify it with the original argument expression so

x :: (a -> b) -> c -> d

Now x x becomes an attempt to unify t2 -> t1 -> t0, however, We can't unify this since it would require unifying t2, the first argument of x, with x. Hence our error message.

Next, why not general recursive types. Well the first point worth noting is the difference between equi and iso recursive types,

equi-recursive are what you'd expect mu X . Type is exactly equivalent to expanding or folding it arbitrarily.

iso-recursive types provide a pair of operators, fold and unfold which fold and unfold the recursive definitions of types.

Now equi-recursive types sound ideal, but are absurdly hard to get right in complex types systems. It can actually make type checking undecidable. I'm not familiar with every detail of OCaml's type system but fully equirecursive types in Haskell can cause the typechecker to loop arbitrarily trying to unify types, by default, Haskell makes sure that type checking terminates. Further more, in Haskell, type synonyms are dumb, the most useful recursive types would be defined like type T = T -> (), however are inlined almost immediately in Haskell, but you can't inline a recursive type, it's infinite! Therefore, recursive types in Haskell would demand a huge overhaul to how synonyms are handled, probably not worth the effort to put even as a language extension.

Iso-recursive types are a bit of a pain to use, you more or less have to explicitly tell the type checker how to fold and unfold your types, making your programs more complex to read and write.

However, this is very similar to what your doing with your Mu type. Roll is fold, and unroll is unfold. So actually, we do have iso-recursive types baked in. However, equi-recursive types are just too complex so systems like OCaml and Haskell force you to pass recurrences through type level fixpoints.

Now if this interests you, I'd recommend Types and Programming Languages. My copy is sitting open in my lap as I'm writing this to make sure I've got the right terminology :)


问:
Double equals (Not equality) during assigning Java
When I tried searching this I would just get things on equality.

When I was reading through some documentation for navigation in Android I had come across something I had never seen before. I came across this:

```<code>mTitle = mDrawerTitle = getTitle();
</code>```

It almost looks like something you can do in JavaScript where you can take the first not-null variable and assign it to a variable.

In JavaScript I would do this:

```<code>mTitle = mDrawerTitle || getTitle();
</code>```

And it would return the first not null, in Java, is this double equals usage the equivalent in Java?

What is this type of expression called?

答:
Looking more into it, it is actually nothing like what I thought it was, it is simply the assignment operator.

As I found here: http://www.rapidprogramming.com/tutorial/JAVA-Operators-Logical-Conditional-Assignment--28

You can assign a value to more then one variable at once using it.

For example:

```<code>int num = 20000;

int p, q, r, s;

p = q = r = s = num;
</code>```

(Taken from the site)

Body:
Looking more into it, it is actually nothing like what I thought it was, it is simply the assignment operator.

As I found here: http://www.rapidprogramming.com/tutorial/JAVA-Operators-Logical-Conditional-Assignment--28

You can assign a value to more then one variable at once using it.

For example:

int num = 20000;

int p, q, r, s;

p = q = r = s = num;

(Taken from the site)


问:
Managing Production Issues during a Scrum Sprint
The question of managing bugs in production has been a large feature in my mind of late. Sprint's are not meant to have any items added into them, but for critical bugs, this is simply unavoidable.

How does one go about managing this break in the sprint? Do you simply give a sprint a percentage "allowance" of time, thus only filling say 80% of the schedule with sprint items "just in case"?

答:
If you use velocity as an 'allowance' indicator based on yesterday's weather, it will automatically adjust for some average amount of extra work cutting into sprints.

If the production issue is caused by bugs created in earlier sprints it's OK to have the fixing work cut into the velocity of the current sprint. This way the team's velocity is 'compensated' for the points they shouldn't have earned previously.

Sometimes you don't make all your sprint goals, get over it ;-) Velocity will average out to a lower number if it happens a lot.

Any other non-critical stuff can just be included on the backlog for normal inclusion in a sprint. I prefer giving top priority to bugs and to not have them count towards velocity.

All the time needed for fixing and troubleshooting production issues is automatically factored into the team's velocity. Only takes time to average out, doesn't really need a separate allowance.


问:
best way to send messages to all subscribers with multiple subscriptions and multiple providers
I'm writing an application in which -

Many users can subsribe to posts made by another users.

So for a single publisher there can be many subscribers.

When a message is posted by an user X, all users who have subscribed to messages of User X will be sent an email.

How to achieve this ? I'm thinking of using publish-subscribe pattern.

And then I came through JMS. Which is the best JMS implementation to use according to your experience ?

Or else what else solution do you propose to the given problem ?

Shall I go for a straight-forward solution ?:
User x posts a message, I find all users (from database) who subscribe to user x
and then for every user, I call the sendEmail() method.

[EDIT]
My intention here is not to send-emails. I'm really sorry if it wasn't clear.
I also have to send kind of system-notifications apart from Email to all subscribers.

Right now, I've implemented the email-sending as a threadPool

答:
I agree with Sarien in that XMPP can be used for the purpose. XEP-0060 - Publish / Subscribe does exactly what you are trying to do... It can send notifications to the subscribers, as well as the payload (on request, or as soon as it is generated). You will have to look deeper though to see if this fits your needs...

Hope it helps.


问:
Is there a name for the Builder Pattern where the Builder is implemented via interfaces so certain parameters are required?
So we implemented the builder pattern for most of our domain to help in understandability of what actually being passed to a constructor, and for the normal advantages that a builder gives. The one twist was that we exposed the builder through interfaces so we could chain required functions and unrequired functions to make sure that the correct parameters were passed. I was curious if there was an existing pattern like this.

Example below:

```<code>public class Foo
{
   private int someThing;
   private int someThing2;
   private DateTime someThing3;

   private Foo(Builder builder)
   {
       this.someThing = builder.someThing;
       this.someThing2 = builder.someThing2;
       this.someThing3 = builder.someThing3;
   }

   public static RequiredSomething getBuilder()
   {
       return new Builder();
   }

   public interface RequiredSomething { public RequiredDateTime withSomething (int value); }
   public interface RequiredDateTime { public OptionalParamters withDateTime (DateTime value); }
   public interface OptionalParamters {
      public OptionalParamters withSeomthing2 (int value);
      public Foo Build ();}

   public static class Builder implements RequiredSomething, RequiredDateTime, OptionalParamters
   {
      private int someThing;
      private int someThing2;
      private DateTime someThing3;

      public RequiredDateTime withSomething (int value) {someThing = value; return this;}
      public OptionalParamters withDateTime (int value) {someThing = value; return this;}
      public OptionalParamters withSeomthing2 (int value) {someThing = value; return this;}
      public Foo build(){return new Foo(this);}
   }
}
</code>```

Example of how it's called:

```<code>   Foo foo = Foo.getBuilder().withSomething(1).withDateTime(DateTime.now()).build();
   Foo foo2 = Foo.getBuilder().withSomething(1).withDateTime(DateTime.now()).withSomething2(3).build();
</code>```

答:
What you are doing is essentially limiting the available methods via the type system. Java's type system is unfortunately a bit on the weak side, so that you are rather limited in those respects.

When you look at stronger type systems in languages like Haskell, or Scala, you will come across the term type-level programming. In its full form, type-level programming can actually involve computations being made at compile-time. However, a less strict form of it is leveraging the type system in order to make implicit designs explicit, which is more ofter referred to as working with phantom types.

For example, you often have designs that require a user to first call method a, before calling method b of an object. In weaker type systems, you have to tell your users via comments, or design documents. But technically, they could still call b first, so you might have to add a check of some sort, then throw an exception or something. Lots of work, and lots of error potentials - which you obviously recognized already.

Phantom types on the other hand are used to turn these implicit dependencies between method calls into an explicit compiler-checkable dependency by moving the different methods into different types.

Here is a nice example of phantom types in Java, and here's a simple example comparing them in Haskell and Scala. Essentially, what these examples achieve is encoding a state into the type system. The second article, f.ex., constructs rocket objects, which can only be launch()ed, if they have been filled with fuel and O2, i.e. you can call that method only if you have called other methods before it. In contrast to a solution, which simply implements all of these methods in one class, leveraging phantom types allows the compiler to automatically check this.

In turn, this also means, that in an IDE your auto-complete variations will be limited to the ones that make sense. If you have a rocket object which hasn't been fueled yet, your auto-complete will simply not show you a launch() method.

To come back to your example, you can replace the launch() method with the build() method and think about the different possible variants for which a build process is feasible. Then you define your phantom types based on the elements that need to be told to the builder, and find out if there is an order to them, or if there are multiple independent aspects. In the two posts I linked to, you can see an example with just one aspect (plane being in flight, or landed), and with two independent aspects (rocket being filled up with fuel and O2).

This approach is generally feasible for any number of aspects, but as you encode these into the type system, I would not recommended going too far with it. In terms of code quality/readability it relates to methods with a lot of parameters. We found these to be sub-optimal and causing more problems than what they're worth. Similarly, phantom types being encoded in type parameters means that you end up with lots and lots of type parameters at the cost of readability. Notice that this only applies to independent aspects being encoded as phantom types. Once you have dependent ones, they are encoded via the same type parameter.


问:
Are VB.NET to C# converters actually compilers?
Whenever I see programs or scripts that convert between high-level programming languages they are always labelled as converters.

"VB.NET to C# converter" on Google results in expected, useful hits.

However "VB.NET to C# compiler" on Google results in things like comparisons between the C# and VB.NET compilers and other hits that are not quite what you'd be looking for.

Webopedia defines Compiler as

A program that translates source code into object code

Eric Lipper in an answer to: "How do I create my own programming language and a compiler for it" suggests:

One of the best ways to get started writing a compiler is by writing a high-level-language-to-high-level-language compiler.

Is a VB.NET to C# converter really just a compiler? If not, What separates the converter from also being a compiler?

答:
According to Wikipedia,

A compiler is a computer program (or set of programs) that transforms source code written in a programming language (the source language) into another computer language

It doesn't say that a high-level language should be transformed into a low-level language. So yes, a converter which transforms code written in VB.NET to C# would be a compiler, as well as a converter from C# to Java or from Python to Ruby or Haskell to Lisp (if such converters exist).

What differentiates the term compiler from the term converter ? Nothing technical, I think. Since in current language, compiler often wrongly refers to a program which transforms source code into machine code, converter  may refer to a compiler which:

produces source code and not machine code,

source code written in higher-level languages compared to Assembler or even C,

source code written in an equally high-level language compared to the original language (Java vs. C#, for example).

Side note: a commonly made mistake is to call LESS to CSS or Sass to CSS compilers. They are preprocessors, not compilers, since they don't take source code written in a programming language as an input.


答: It's better to install Windows 8 in VMWare so that you can test it for the time being, and testing will not create any problems for your system.</p>

Title: Testing on different operating systems


答:
There's plenty of existing COM code out there that needs to be integrated with. Often it can be handled with COM wrappers, but the young upstarts have no awareness of the COM's constraints.

Its very rare to want to, or need to write a new COM object.  Last time I did this was 2 years ago.

Title: Is COM truly dead?

Body:
I have previously worked on COM, however I have observed for quite sometime that hardly any company asks for COM exp.

Is COM dead or reports of its demise are highly exaggerated?


问:
What does the English word "for" exactly mean in "for" loops?
English is not my first language, but since the keywords in programming languages are English words, I usually find it easy to read source code as English sentences:

if (x > 10) f(); => "If variable x is greater than 10, then call function f."

while (i < 10) ++i; => "While variable i is less than 10, increase i by 1."

But how a for loop is supposed to be read?

for (i = 0; i < 10; ++i) f(i); => ???

I mean, I know what a for loop is and how it works. My problem is only that I don't know what the English word "for" exactly means in for loops.

答:
For this particular case, it would be something like:

"For every i starting from 0 up to (but not including) 10, do f(i)"

It would have to be worded a bit differently if the numbers were doubles or the looping conditions were more complicated, but you shouldn't really worry if you can't find a really natural sounding translation to English because programming languages are only based on natural languages, or mathematical notation: for i = 1,... 10 is something you write in math, which is much older than programming.


答:
Meriam Webster definition

For - "used to indicate ... something is going to or toward "

so your statement is i (starting at 0) going to 9.

Title: What does the English word "for" exactly mean in "for" loops?

Body:
English is not my first language, but since the keywords in programming languages are English words, I usually find it easy to read source code as English sentences:

if (x > 10) f(); => "If variable x is greater than 10, then call function f."

while (i < 10) ++i; => "While variable i is less than 10, increase i by 1."

But how a for loop is supposed to be read?

for (i = 0; i < 10; ++i) f(i); => ???

I mean, I know what a for loop is and how it works. My problem is only that I don't know what the English word "for" exactly means in for loops.


问:
Collaborative work (small team) - Best practices
I'm currently working in a very small team of programmers (2-3) and I'm looking for advices/best practices on how to organise our work. We're all working on the same application using PHP. Today we're kind of all working on our way.

Today situation:

List item that have to be worked on by each dev 1/week. What has to
be done is defined at a high functional level (ex: Build the search
engine for this product..)

Commit / merge our individual branches (git) every week before the
next meeting

No real dev rules, no code review

No test written (aouutch)

Problems faced:

Code quality issue: discovering someone else code is sometime tough
(inline, variable+function+class names, spaces, comments..)

Changes in already existing classes (impact on someone else work)

Responsibility of each dev unclear: after getting someone else code

and discover something messy, should I make the change? Should he

make the change? How to plan those things,...

What I'm looking for:

Basically I'm looking into structuring the way we develop things in order to avoid frustration and improve overall quality.

How to define coding standards (naming convention, code rules...)? Do
you you any validation script to make sure code is valid before
committing?

Do you think that defining an architect role in the team is needed?
Someone that would actually define what has to be developed during
the next phase. By defining interfaces or class descriptions that
have to be written. (Does it make sense in such a small team?)

Today we're losing time into understanding what others did or tried to do, we're also losing time in discussion like "you should have done it that way! Why is this class doing that and not that..? Shouldn't we have a embedded class rather that this set of data...".

I'm looking into a work process, maybe with more defined responsibilities and process in order to improve our performance. If you have experience, advices, best practices or anything to share that we could benefit from it will be much appreciated!

Thanks a lot for your time!

答:
For a small team you probably don't need to focus too closely on the type of rigid process that larger teams go through, however there are some low hanging fruit here that can really help.

Daily Stand-Up

A simple stand-up at the start of each day, where everyone just briefly explains what they did yesterday, what they are going to do today and raises anything that is blocking them from making progress.

Coding Standards

Most languages have a standard or a few standards available. The important thing is not which one you choose but that you choose one. Then everyone gets to stick with it, no exceptions.

Document

Before you begin on a "build the search engine for this product" type project, you need to put together a functional specification for that search engine. This will describe in clear terms how the system will work without going into too much implementational detail. The document must be completed and the team must have reviewed it before coding begins. That would probably be enough architectural oversight assuming everyone in the team is at a reasonable level as a developer. These specifications can also then be used as the basis for future documentation to pass on to users or as reference material when revisiting older work.

Code Review

Nobody's code gets merged into the master branch for any project until it has been reviewed by at least one other team member. Code that does not meet the coding standard doesn't go in, code that is undocumented doesn't go in. This will save a lot of problems later on and, combined with the coding standards above, you should end up with much more readable code.

You could also take it in turn to pick examples of code from time to time to share on CodeReview.se - that would give everyone in the team a chance to learn from the wider experience of other developers and help to encourage good coding from everyone.

Testing

Nobody performs functional test on their own features. You have to get someone else to test for you.

Also, no code is complete until it has unit tests and those unit tests pass. Unit tests are part of your build process and if they fail, the build fails.

Merge early, merge often

If you are doing weekly merges and having collisions between developers then you might need to look at your branching strategy- if something is going to have a knock-on effect for other developers then it needs to be merged in as soon as possible so that everyone can use the new version. This is a matter of prioritisation and will make everyone's lives easier.

One of the biggest advantages of a small team is that you are a small team. Everyone can easily tell everyone else what they are up to and ask everyone else's advice. Many of the suggestions I'm making here are really just ways of facilitating communication and that should be way easier in a small team than in a big one.


答: Use VMs. Snapshotting is extremely useful for testing. Snapshot it, do your test, and blow it away again, always mean you have a clean test environment. Also, you can clone a template, install version A in one, version B in another, and perform your tests against each. Very good to identify/spot regressions. Also, it is easier to adjust the system specification, you can ramp down the memory allocation to simulate a resource constrained environment, for example.</p>

Title: Testing on different operating systems


答:
In English we use for in contexts like "This is for children under 6 year of age".  The for statement was adapted in structured programming in this context.

Read for (i = 0; i < 10; ++i) f(i); as for (; i < 10;) f(i); and it might be clearer.  The for statement has three parameters:  initialization, condition, update. In some languages, the parameters can be lists.

For make the looping conditions clearer than the equivalent while loop.  If the body is long the increment may not be obvious.

```<code> i = 0;
 while ( i < 10 ) {
     f(i);
     i++;
 }
</code>```

In the following version the increment is misplaced.  The for construct doesn't allow the increment (update) to be misplaced in this manner.

```<code> i = 0;
 while ( i < 10 ) {
     i++;
     f(i);
 }
</code>```

Some languages provide a for each statement which is used to iterate over sets.

Body:
In English we use for in contexts like "This is for children under 6 year of age".  The for statement was adapted in structured programming in this context.

Read for (i = 0; i < 10; ++i) f(i); as for (; i < 10;) f(i); and it might be clearer.  The for statement has three parameters:  initialization, condition, update. In some languages, the parameters can be lists.

For make the looping conditions clearer than the equivalent while loop.  If the body is long the increment may not be obvious.

 i = 0;
 while ( i < 10 ) {
     f(i);
     i++;
 }

In the following version the increment is misplaced.  The for construct doesn't allow the increment (update) to be misplaced in this manner.

 i = 0;
 while ( i < 10 ) {
     i++;
     f(i);
 }

Some languages provide a for each statement which is used to iterate over sets.


答:
It's a lot more confusing because you've written out a C-style FOR loop, which isn't really a FOR loop; it's a WHILE loop with weird syntax.  The FOR loop was defined by ALGOL. Pascal and BASIC picked up the concept; C, unfortunately, borrowed the name but not the semantics.  (The best indication of this is to look at the for (;;) construct; it's not possible to define a true FOR loop that has no range to iterate over.)

The idea is that you define a range of elements, and an operation to perform for each element.  For example, in Pascal you would write your example loop as:

```<code>for i := 0 to 9 do
   f(i);
</code>```

In BASIC it's similar:

```<code>for i = 0 to 9
   f(i)
next i
</code>```

This is a lot more readable: for each element i from 0 to 9, do something with the value.  Note that there is no loop-ending condition involving i being < 10; instead, the last value of the range (9) is specified.

Body:
It's a lot more confusing because you've written out a C-style FOR loop, which isn't really a FOR loop; it's a WHILE loop with weird syntax.  The FOR loop was defined by ALGOL. Pascal and BASIC picked up the concept; C, unfortunately, borrowed the name but not the semantics.  (The best indication of this is to look at the for (;;) construct; it's not possible to define a true FOR loop that has no range to iterate over.)

The idea is that you define a range of elements, and an operation to perform for each element.  For example, in Pascal you would write your example loop as:

for i := 0 to 9 do
   f(i);

In BASIC it's similar:

for i = 0 to 9
   f(i)
next i

This is a lot more readable: for each element i from 0 to 9, do something with the value.  Note that there is no loop-ending condition involving i being < 10; instead, the last value of the range (9) is specified.


问:
How bad is it to have two methods with the same name but different signatures in two classes?
I have a design problem related to a public interface, the names of methods, and the understanding of my API and code.

I have two classes like this:

```<code>class A:
    ...
    function collision(self):
        ....

...

class B:
    ....
    function _collision(self, another_object, l, r, t, b):
        ....
</code>```

The first class has one public method named collision, and the second has one private method called _collision. The two methods differs in argument type and number.

As an example let's say that _collision checks if the object is colliding with another object with certain conditions l, r, t, b (collide on the left side, right side, etc) and returns true or false. The public collision method, on the other hand, resolves all the collisions of the object with other objects.

The two methods have the same name because I think it's better to avoid overloading the design with different names for methods that do almost the same thing, but in distinct contexts and classes.

Is this clear enough to the reader or I should change the method's name?

答:
I'd say that there is nothing wrong with this.  Method overloading is a pretty standard practice, for multiple reasons.  If you have the same exact functionality, just for two different series of parameters, then using the same exact name makes perfect sense, and it also helps to clarify that the parameter list should be roughly the only real difference between the two functions.  It really does make it easier to code in languages that support it.

As for having those two functions do two slightly different things (A.collision() being more general than B._collision()), in this case, it is fine for two reasons:

They're not really overloaded.  "collision" <> "_collision" (unless Python's doing something here I'm unaware of).

They're not really overloaded.  class A <> class B.  Even if they did have the same basic name, other programmers should be able to distinguish between functions in two different classes fairly easily (unless one is subclassing other).  Different classes obviously tend to do things differently.


问:
How to sell Agile development to (waterfall) clients
Our development shop would really like to do more agile projects but we have a problem getting clients on board. Many clients want a budget and a deadline. It's hard to sell a client on an agile project when our competitors do come up with waterfall-based fixed deadlines and fixed prices. We know their fixed numbers are bad, but the client doesn't know that. So, we end up looking bad to the client because we can't fix the price or a deadline but our competitors can.

So, how can you get your sales force to successfully sell a project that uses agile development methods, or a product that is developed using such methods? All the information I found seems to focus on project management and developers.

答:
I think the answer is that for most cases you probably wont.  I would try and see this initially as a small part of your business - perhaps 20%, with the rest under a traditional model.  Over time I would try to focus more on the Agile products and clients and try to make that part grow more.

Another part of tackling this is perhaps to try and use both approaches.  Use the waterfall approach with the senior management and contract negotiation folks.  For example 'a system to allow clients to maintain portfolios and make investment decisions using both browser based and mobile phone devices (Apple and Android).'  or something like that.  Then use Agile for the development team's development on the more detailed features, e.g., Create Home Page, Create Login Page, Create Portolio Management History, Create Mobile Login, etc.

Another idea is so make Agile your differentiator.  I know that many if not most large organizations are not doing Agile.  However most (the vast majority in my experience) of small companies are.  I think that Agile is growing rapidly and this will continue.  The advantage of this route is that you are pitching what you most want to do to the customers who already recognize it.  This approach will require some work over time with no guarantee of success.

You might also find some traction if your clients like testing.  Having well-tested products can be an easier sell to some clients.  A book that I am finding helpful in this area is 'Agile Testing' by Adison Wesley Press.

You can also use current events to support your case.  For instance the current (writing this in Oct 2012) health care site is a making a great case for how NOT to handle changes that were needed 2 weeks before go-live.  Also the apparent over-engineering would likely have been better addressed more more agile methods.


答:
So, how can you get your sales force to successfully sell a project that uses agile development methods, or a product that is developed using such methods?

By having your sales force bring the customer in to the office. The entire point of agile is to get immediate feedback from the client so that you can produce what they want (and no more). Bring them in, ask what they want. Two weeks later, bring them in and show them a demo/prototype. Sell them on that interaction. Show them progress and explain that this sort of iteration is what you'd like to do so that they get exactly what they want.

Give estimates for the amount of work necessary (that's what a budget is after all), but let them have the power (read: responsibility) to include what they want to fit into their budget.

Title: How to sell Agile development to (waterfall) clients

Body:
Our development shop would really like to do more agile projects but we have a problem getting clients on board. Many clients want a budget and a deadline. It's hard to sell a client on an agile project when our competitors do come up with waterfall-based fixed deadlines and fixed prices. We know their fixed numbers are bad, but the client doesn't know that. So, we end up looking bad to the client because we can't fix the price or a deadline but our competitors can.

So, how can you get your sales force to successfully sell a project that uses agile development methods, or a product that is developed using such methods? All the information I found seems to focus on project management and developers.


答:
Contact previous clients that are happy with your work. Especially if they are Waterfall to Agile converts. At the very least, converts that weren't your clients.

Their testimonials (as a customer) will outweigh anything and everything you could say. They can address the concerns and fears of your new customer more than you ever could.

From a management perspective, a budget and a deadline is a business need for the project. You need to make sure you're addressing those needs, and if you look a business' testimonials about switching, you'll notice that comes up directly. If you look at developer's testimonials about switching, you'll notice that often times it does not.


问:
Session in RESTful web services, how it works?
In a web services, how does the server know which request belongs to which session?

I know that for a web application, the web server inspects the cookie (or the sessonId query parameter in case cookies are disabled) so it knows which session the request is associated with. But for a request that comes from a rest client, how do the server know?

答:
If you really must have session handling in your API then the client would be responsible to handle the session_id and add it to the URL if required. How exactly to handle this would depend on your technology stack. For example Rails defaults to cookies but (if enabled) would also accept a _session_id parameter as part of the URL.

The relevant information normally stored in the cookie together with the session id then must be handled by the server. In Rails you would have to switch session storage from cookie storage to one of the server options like storing it in the database or memcached with the session_id as key.

But you should really think twice if you want to add this feature to your API. Being stateless will keep your API simpler and easier to maintain. If any possible it is preferable to let the client worry about state and send all necessary information with each request. (like using HTTP basic authentication instead of storing a current user in a session).


问:
How to retain familiarity with previously worked on technology/language/feature
One problem that I have faced over the years is that when I stop using a technology (COM,QT)/language (VBScript)/feature (Templates) for development over the time I lose skill in that.

What in your opinion is the "easiest" way to retain familiarity so that when I come back to any of them, effort for relearning is minimal.

答:
Keep hold of your own reference books. That way, you can go back and refresh your memory.  Personally, if you are not regularly using some memory allowing it to fade and to use that capacity for current stuff seems to be a more efficient use of the grey matter.  Rereading the same books that you originally used allows old memories to be refreshed surprisingly quickly.

I am looking forward to 10 years time when COM programmers make £2000 a day.   :)


答:
The key to doing this well is by use of a support contract.

Basically, when you first sell the client, you sell them based of your expertise, and you do it waterfall.
That means a contract that sets the scope and a firm dead line. This is what the client wants. The client more or less knows the scope. Waterfall works very well, in a fixed & defined scope environment, I would say it works better than agile in such environments. And in this case it gives the client a level of comfort when the tendency is to be nervous because he has never worked with you before. That’s Ok, Agile is not always better then waterfall.

So you have a fixed price contract for X scope. Then you tell the client “Look, you are going to want to make changes, and you are going to need us to support you post production, let’s set aside 20% of your budget for these things to be used on an as need basis by means of a support contract.”

Should a change come up during the project, simply defer it to be handled under the support contact. (Assuming this change would cause a serious disruption to the project)

The terms of the support contact are as follows “Work to be done on a per hour basis, as requested by the client, can be used for change requests or general system support and maintenance.” BAM! You are in Agile.

You can then continue to extend the support contact, and simply use the support contact as the means to run new projects. Additionally if these hours are purchased and paid for upfront, we usually give the client a 15% discount. It's Win-Win.


答:
I completely agree with the other answer on the importance of code reviews and daily-standups.

Architect Role

This is a tough one.  I guess it would depend on the experience of the developers on your team.  In a team your size the more experienced the developer the less you need an architect.  I would suggest more pair programming and mentoring of less experienced developers before adding an architect.

Business Analyst

If you are going to add a person to the team I would highly recommend adding a competent business analyst who can write agile style requirements/stories very well.  I have found that in the long run having someone who can properly define the business needs and write requirements/stories that can be easily tested against can be more valuable to the end product.

Coding Standards

Using a tool that warns you when your not following the accepted standards is a good starting point.  Everyone has to use the accepted format.

Regular Code Review Lunches

One team I was on was in a similar situation.  We instituted weekly lunches where everyone brought their own lunch in and met in a conference room and one person on the team presented a piece of code or functionality that they wanted to discuss.  They would do a quick presentation of the code and then we would talk about different aspects of it.

Baby steps

Go slow with any changes you make.  Doing it all at once will only upset the balance that your team already has.  Create a long term plan for where you want to take the team and share it with them.  Choose one step at a time and focus on it until the team has accepted and integrated it into their workflow.  Then move on to the next one.

Don't step on toes

If you are not the teams manager than sit down with him/her and present your goals for the team and suggest how things could be changed.  If you are the manager make sure that you respect the position each team member holds.  Any changes made will upset the balance that already exists and you don't want people leaving because someone was excluded from the process when they really should have been included.

Title: Collaborative work (small team) - Best practices

Body:
I'm currently working in a very small team of programmers (2-3) and I'm looking for advices/best practices on how to organise our work. We're all working on the same application using PHP. Today we're kind of all working on our way.

Today situation:

List item that have to be worked on by each dev 1/week. What has to
be done is defined at a high functional level (ex: Build the search
engine for this product..)

Commit / merge our individual branches (git) every week before the
next meeting

No real dev rules, no code review

No test written (aouutch)

Problems faced:

Code quality issue: discovering someone else code is sometime tough
(inline, variable+function+class names, spaces, comments..)

Changes in already existing classes (impact on someone else work)

Responsibility of each dev unclear: after getting someone else code

and discover something messy, should I make the change? Should he

make the change? How to plan those things,...

What I'm looking for:

Basically I'm looking into structuring the way we develop things in order to avoid frustration and improve overall quality.

How to define coding standards (naming convention, code rules...)? Do
you you any validation script to make sure code is valid before
committing?

Do you think that defining an architect role in the team is needed?
Someone that would actually define what has to be developed during
the next phase. By defining interfaces or class descriptions that
have to be written. (Does it make sense in such a small team?)

Today we're losing time into understanding what others did or tried to do, we're also losing time in discussion like "you should have done it that way! Why is this class doing that and not that..? Shouldn't we have a embedded class rather that this set of data...".

I'm looking into a work process, maybe with more defined responsibilities and process in order to improve our performance. If you have experience, advices, best practices or anything to share that we could benefit from it will be much appreciated!

Thanks a lot for your time!


问:
Advice on designing web application with a 40+ year lifetime
Scenario

Currently, I am apart of a health care project whose main requirement is to capture data with unknown attributes using user generated forms by health care providers. The second requirement is that data integrity is key and that the application will be used for 40+ years. We are currently migrating the client's data from the past 40 years from various sources (Paper, Excel, Access, etc...) to the database. Future requirements are:

Workflow management of forms

Schedule management of forms

Security/Role based management

Reporting engine

Mobile/Tablet support

Situation

Only 6 months in, the current (contracted) architect/senior programmer has taken the "fast" approach and has designed a poor system. The database is not normalized, the code is coupled, the tiers have no dedicated purpose and data is starting to go missing since he has designed some beans to perform  "deletes" on the database. The code base is extremely bloated and there are jobs just to synchronize data since the database is not normalized. His approach has been to rely on backup jobs to restore missing data and doesn't seem to believe in re-factoring.

Having presented my findings to the PM, the architect will be removed when his contract ends. I have been given the task to re-architect this application. My team consists of me and one junior programmer. We have no other resources. We have been granted a 6-month requirement freeze in which we can focus on re-building this system.

I suggested using a CMS system like Drupal, but for policy reasons at the client's organization, the system must be built from scratch.

This is the first time that I will be designing a system with a 40+ lifespan. I have only worked on projects with 3-5 year lifespans, so this situation is very new, yet exciting.

Questions

What design considerations will make the system more "future proof"?

What questions should be asked to the client/PM to make the system more "future proof"?

答:
Rather than trying to figure out how this application is going to still be in operation 20 years from now, I think you should spend your six months fixing the problems you found that the original architect caused, put in place a sensible, robust architecture, and move forward from there.

Partial de-normalization of a database is not necessarily entirely unexpected in a medical setting.  Some parts of medical databases have characteristics which make them a good fit for the EAV (Entity/Attribute/Value) model.


问:
Must OpenCL code be compiled for a specific GPU?
Most OpenCL Tutorials give a nice introduction to OpenCL, yet I have not found information on the question of interoperability of the compilation targets. It seems that I have to compile OpenCL code for the target GPU. Now when making a binary distribution of an application using OpenCL, does one have to make several builds for the vendor-platforms?</p>

答:
OpenCL works similarly to other GPU libraries like OpenGL.  What you ship is an intermediate representation.  The GPU's driver does final compilation for execution on the specific device at run time. Here is an intro to OpenCL slide presentation from Khronos.

Edit:  With OpenCL 2 the compilation model changed some to be much more flexible.  Now there is an LLVM backend that targets the new SPIR-V intermediate representation, so any language compiler that targets LLVM should be capable of being used to target OpenCL.  Other than that the model is pretty much the same but gains a step, source compiles to LLVM IR, LLVM IR compiles to SPIR-V, driver handles final compilation and execution.


答:
Data is King

I think its a bit unreasonable to expect a web application circa 2013 to be still up and runnable in 2053.  Technologies are going to change.  Platforms are going to come and go.  HTML may be a quaint memory by then.  But your data will still be around.

So data is your primary focus.  As long as your data is still there, people will be able to adapt to whatever new technologies come about.  Make sure your data schemes are well thought out, and well suitable for expansion.  Take your time spec'ing them out.

Regarding the actual applications, your company is probably correct here in having a 'build from scratch' directive.  I maintain a couple 10+ year old web apps, and I'm very glad they are not locked into the prevailing CMS systems of 2003.  They use home grown, very simple frameworks.  I think for something like this you are better off with a very basic framework that you create specficially for the needs of the project.

But the reality is, over 40 years, the company will (hopefully) be making quite a few front-end and back end services to adapt to evolving platforms.  So given that, I'd target a 5-10 year lifetime for individual user-facing applications.

Title: Advice on designing web application with a 40+ year lifetime

Body:
Scenario

Currently, I am apart of a health care project whose main requirement is to capture data with unknown attributes using user generated forms by health care providers. The second requirement is that data integrity is key and that the application will be used for 40+ years. We are currently migrating the client's data from the past 40 years from various sources (Paper, Excel, Access, etc...) to the database. Future requirements are:

Workflow management of forms

Schedule management of forms

Security/Role based management

Reporting engine

Mobile/Tablet support

Situation

Only 6 months in, the current (contracted) architect/senior programmer has taken the "fast" approach and has designed a poor system. The database is not normalized, the code is coupled, the tiers have no dedicated purpose and data is starting to go missing since he has designed some beans to perform  "deletes" on the database. The code base is extremely bloated and there are jobs just to synchronize data since the database is not normalized. His approach has been to rely on backup jobs to restore missing data and doesn't seem to believe in re-factoring.

Having presented my findings to the PM, the architect will be removed when his contract ends. I have been given the task to re-architect this application. My team consists of me and one junior programmer. We have no other resources. We have been granted a 6-month requirement freeze in which we can focus on re-building this system.

I suggested using a CMS system like Drupal, but for policy reasons at the client's organization, the system must be built from scratch.

This is the first time that I will be designing a system with a 40+ lifespan. I have only worked on projects with 3-5 year lifespans, so this situation is very new, yet exciting.

Questions

What design considerations will make the system more "future proof"?

What questions should be asked to the client/PM to make the system more "future proof"?


问:
Main activity design too busy
I have a main activity that contains many buttons.  I don't want to have a list of buttons like this. I know this looks bad, only cause I threw this together to show you what I have. As you can see, I really don't even have enough room. I don't want a scrollView in my main Activity. Does anyone have suggestions on building my activity to look sleek and simple?

答:
One approach would be to put the buttons in a NavigationDrawer and display only the most important info in the content of the Activity or one of the other screens as the starting point and the user can navigate from here through the NavigationDrawer

If you don't like this approach you could also try putting the buttons in an ActionBar Spinner as a list. This way you'll have one of the "Fight Cards", "Buy Tickets", etc screen as the starting point and the user can navigate from here through the Spinner

I don't know exactly what you're displaying in the application so I cannot decide what is the best solution for your problem, you'll have to figure that out yourself.

Title: Main activity design too busy


答:
In layman's words:

Method names should be verbs, so both names are inadequate.

When you give them appropiate names ( with a verb ), it's unlikely the two method's names will coincide.

Even if the two methods had the same name, they are in different classes, and there's no way of confusing them because of their having different namespaces.

There's no style (or otherwise) rules stating that two distinct classes or interfaces cannot have methods with the same name, even if they have the same signature (parameter list).

For example

```<code>// there's absolutely no problem with this totally unrelated (or related) classes:
databaseClient.connect();
odbcSource.connect();
navii.connect();
fireHose.connect();
</code>```

Short answer: there's nothing wrong with it.

Title: How bad is it to have two methods with the same name but different signatures in two classes?

Body:
I have a design problem related to a public interface, the names of methods, and the understanding of my API and code.

I have two classes like this:

```<code>class A:
    ...
    function collision(self):
        ....

...

class B:
    ....
    function _collision(self, another_object, l, r, t, b):
        ....
</code>```

The first class has one public method named collision, and the second has one private method called _collision. The two methods differs in argument type and number.

As an example let's say that _collision checks if the object is colliding with another object with certain conditions l, r, t, b (collide on the left side, right side, etc) and returns true or false. The public collision method, on the other hand, resolves all the collisions of the object with other objects.

The two methods have the same name because I think it's better to avoid overloading the design with different names for methods that do almost the same thing, but in distinct contexts and classes.

Is this clear enough to the reader or I should change the method's name?

Body:
In layman's words:

Method names should be verbs, so both names are inadequate.

When you give them appropiate names ( with a verb ), it's unlikely the two method's names will coincide.

Even if the two methods had the same name, they are in different classes, and there's no way of confusing them because of their having different namespaces.

There's no style (or otherwise) rules stating that two distinct classes or interfaces cannot have methods with the same name, even if they have the same signature (parameter list).

For example

// there's absolutely no problem with this totally unrelated (or related) classes:
databaseClient.connect();
odbcSource.connect();
navii.connect();
fireHose.connect();

Short answer: there's nothing wrong with it.


问:
How are generics implemented?
This is the question from compiler internals perspective.

I am interested in generics, not templates (C++), so I marked the question with C#. Not Java, because AFAIK the generics in both languages differ in implementations.

When I look at languages w/o generics it is pretty straightforward, you can validate the class definition, add it to hierarchy and that's it.

But what to do with generic class, and more importantly how handle references to it? How to make sure that static fields are singular per instantiations (i.e. each time generic parameters are resolved).

Let's say I see a call:

```<code>var x = new Foo<Bar>();
</code>```

Do I add new Foo_Bar class to hierarchy?

Update: So far I found only 2 relevant posts, however even they don't go into much details in sense "how to do it by yourself":

http://www.jprl.com/Blog/archive/development/2007/Aug-31.html

http://www.artima.com/intv/generics2.html

答:
I see two actual concrete questions in there.  You're probably want to ask additional related questions (as separate question with a link back to this one) to get a full understanding.

How are static fields given separate instances per generic instance?

Well, for static members which are not related to the generic type parameters, this is pretty easy (use a dictionary mapped from the generic parameters to the value).

Members (static or not) which are related to the type parameters can be handled via type erasure.  Just use whatever the strongest constraint is (often System.Object).  Because the type information is erased after compiler type checks, it means that runtime type checks won't be needed (although interface casts may still exist at runtime).

Does each generic instance appear separately in the type hierarchy?

Not in .NET generics.  The decision was made to exclude inheritance from type parameters, so it turns out that all instances of a generic occupy the same spot in the type hierarchy.

This was probably a good decision, because failure to look up names from a base class would be incredibly surprising.

Title: How are generics implemented?


问:
I want a trivial example of where MongoDB can scale but a relational database will have trouble
I'm just learning to use MongoDB, and when discussing with other programmers would like a quick example of why NoSQL can be a good choice compared to a traditional RDBMS - however the scenarios I come up with and can find online seem pretty contrived.

E.g. a blog with lots of traffic could be represented relationally, but will require some performance tuning and joins across tables (assuming full denormalization is being used). Whereas MongoDB would allow direct retrieval from one collection to the same effect.

But the response I'm getting from other programmers is "why not just keep it relational and then add some trivial caching later?"

Does anybody have a less contrived example where MongoDB will really shine and a relational db will fall over much quicker? The smaller the project/system the better, because it leaves less room for disagreement.

Something along the lines of the complexity of the blog example would be really useful.

Thanks.

答:
The smaller the project/system the better, because it leaves less room for disagreement.

This is hard because NoSQL is only better in large environments. I take it that you mean a Simple Example, and I have a perfect one for you.

Suppose you are making a Travel website and you need to have you users travel from and of the 5,170 US airports destined for any of the other of the (same) 5,170 US airports...

But here is the Kicker, not all flights are direct, you need to tell the user all the stopover options as well, sometimes 2 or 3 stop overs. You also need to tell the user all the options over a 5 hour window! And you need to compute this in under 10 seconds while the user is waiting.

This is the Relational DB Nightmare... In comes NoSql, flight routes are usually set in stone a few weeks in advance, so you can calculate all the Gazillions of possible routs in advance store than in a simple NoSql DB cluster...

NoSql is the clear winner is such a scenario.


答:
How to make sure that static fields are singular per instantiations (i.e. each time generic parameters are resolved).

Each generic instantiation has its own copy of the (confusingly named) MethodTable, which is where static fields are stored.

Let's say I see a call:

```<code>var x = new Foo<Bar>();
</code>```

Do I add new Foo_Bar class to hierarchy?

I'm not sure it's useful to think of the class hierarchy as some structure that actually exists at runtime, it's more of a logical construct.

But if you consider MethodTables, each with an indirect pointer to its base class, to form this hierarchy, then yeah, this adds new class to the hierarchy.

Title: How are generics implemented?

Body:
This is the question from compiler internals perspective.

I am interested in generics, not templates (C++), so I marked the question with C#. Not Java, because AFAIK the generics in both languages differ in implementations.

When I look at languages w/o generics it is pretty straightforward, you can validate the class definition, add it to hierarchy and that's it.

But what to do with generic class, and more importantly how handle references to it? How to make sure that static fields are singular per instantiations (i.e. each time generic parameters are resolved).

Let's say I see a call:

```<code>var x = new Foo<Bar>();
</code>```

Do I add new Foo_Bar class to hierarchy?

Update: So far I found only 2 relevant posts, however even they don't go into much details in sense "how to do it by yourself":

http://www.jprl.com/Blog/archive/development/2007/Aug-31.html

http://www.artima.com/intv/generics2.html

Body:
How to make sure that static fields are singular per instantiations (i.e. each time generic parameters are resolved).

Each generic instantiation has its own copy of the (confusingly named) MethodTable, which is where static fields are stored.

Let's say I see a call:

var x = new Foo<Bar>();

Do I add new Foo_Bar class to hierarchy?

I'm not sure it's useful to think of the class hierarchy as some structure that actually exists at runtime, it's more of a logical construct.

But if you consider MethodTables, each with an indirect pointer to its base class, to form this hierarchy, then yeah, this adds new class to the hierarchy.


答:
First, it scales well.

When a MongoDB database is too frequented or too big for a single server, you can easily add more servers by creating a cluster or replica-set of multiple shards. It scales almost linearly. This doesn't work nearly as well with most relational databases. Take a look at MySQL's list of limitations when working as a cluster, for example. Most of the entries in the list are no problem for MongoDB (or don't apply).

Second, it allows heterogeneous data.

Imagine, for example, the product database of a computer hardware store. What properties do products have? All products have a price and a vendor. But CPUs have a clock rate, hard drives and RAM chips have a capacity (and these capacities aren't comparable), monitors have a resolution and so on. How would you design this in a relational database? You would either create a very long productID-property-value table or you would create a very wide and sparse product table with every property you can imagine, but most of them being NULL for most products. Both solutions aren't really elegant. But MongoDB can solve this much better because it allows each document in a collection to have a different set of properties.

Title: I want a trivial example of where MongoDB can scale but a relational database will have trouble

Body:
I'm just learning to use MongoDB, and when discussing with other programmers would like a quick example of why NoSQL can be a good choice compared to a traditional RDBMS - however the scenarios I come up with and can find online seem pretty contrived.

E.g. a blog with lots of traffic could be represented relationally, but will require some performance tuning and joins across tables (assuming full denormalization is being used). Whereas MongoDB would allow direct retrieval from one collection to the same effect.

But the response I'm getting from other programmers is "why not just keep it relational and then add some trivial caching later?"

Does anybody have a less contrived example where MongoDB will really shine and a relational db will fall over much quicker? The smaller the project/system the better, because it leaves less room for disagreement.

Something along the lines of the complexity of the blog example would be really useful.

Thanks.


问:
Is COM truly dead?
I have previously worked on COM, however I have observed for quite sometime that hardly any company asks for COM exp.

Is COM dead or reports of its demise are highly exaggerated?

答: COM is still widely used within Windows. Many of the new features within Windows are built upon a COM base as it is the main native code component model and Windows is primarily native code. But most non-system application development on Windows is now done in managed code so COM is less relevant (although accessible) as there are .NET framework wrappers. So it is definitely not dead but not that relevant for most people day to day.</p>

Title: Is COM truly dead?


问:
How Python random shuffle works?
How shuffle from random works in Python?

I ask because it works very fast. When I try to write shuffle it works 1 minute for 10^6 element, but Python shuffle does that in 8 sec?

答:
Python's random.shuffle uses the Fisher-Yates shuffle, which runs in O(n) time and is proven to be a perfect shuffle (assuming a good random number generator).

It iterates the array from the last to the first entry, switching each entry with an entry at a random index below it.

The basic process of Fisher–Yates shuffling is similar to randomly picking numbered tickets out of a hat, or cards from a deck, one after another until there are no more left. What the specific algorithm provides is a way of doing this numerically in an efficient and rigorous manner that, properly done, guarantees an unbiased result...

The modern... solution is to move the "struck" numbers to the end of the list by swapping them with the last unstruck number at each iteration. This reduces the algorithm's time complexity to O(n), compared to O(n2) for the naive implementation. This change gives the following algorithm (for a zero-based array).

```<code>To shuffle an array a of n elements (indices 0..n-1):
  for i from n − 1 downto 1 do
       j ← random integer with 0 ≤ j ≤ i
       exchange a[j] and a[i]
</code>```

Title: How Python random shuffle works?

Body:
Python's random.shuffle uses the Fisher-Yates shuffle, which runs in O(n) time and is proven to be a perfect shuffle (assuming a good random number generator).

It iterates the array from the last to the first entry, switching each entry with an entry at a random index below it.

The basic process of Fisher–Yates shuffling is similar to randomly picking numbered tickets out of a hat, or cards from a deck, one after another until there are no more left. What the specific algorithm provides is a way of doing this numerically in an efficient and rigorous manner that, properly done, guarantees an unbiased result...

The modern... solution is to move the "struck" numbers to the end of the list by swapping them with the last unstruck number at each iteration. This reduces the algorithm's time complexity to O(n), compared to O(n2) for the naive implementation. This change gives the following algorithm (for a zero-based array).

To shuffle an array a of n elements (indices 0..n-1):
  for i from n − 1 downto 1 do
       j ← random integer with 0 ≤ j ≤ i
       exchange a[j] and a[i]


答:
Some real world example of a problem I would have no idea how to solve in a reasonable way with SQL and an relational database alone (my fault maybe).

So we have a (common relational) database with about 30,000 products. Nothing big so far. Each of these products has many attributes. There are the common ones like group (cables, antennas, iphone cases... about 80), assortment (somehow similar to groups: car, hifi, mp3, only 15), brand (30).

Then comes the technical data. Each item has many of those like color, cable length, weight, volume. about 200 such value types and thousands of values.

And the most complicated: Many of those products belong either to some car type (or several of them) or some kind of mobile device. Those come in hierarchies in the form like: brand (apple) model (ipad) type (1,2,3,4) and in some cases generation. (for cars it's similar, though instead of generation we have build years)

Problem step One:

We want the amount of products for each of those attributes. How many are red? How many are in the cable group? And so on.

This could partially be solved with SQL. It would be a lot of queries and rather ugly but I think possible. Maybe slow but we could do it even more ugly and keep counters in each table and update at every change. Especially difficult with those attributes where a product can have multiple (like works with iPhone and 12 other mobile phones)

But here comes problem step Two:

When a customer selects one attribute (say he want only see products that are red) we want to update all those counters in real time. This means we would have either extremely complicated queries (not likely fast enough anyway) or keep counters for possible combinations of attributes (billions).

When I started on this project they had given the counter option a try and done this for a very small subset of attributes (group, assortment, brand). The code was ugly, buggy and slow. In addition they now had a table with counters that was far larger then the table of products.

Using Apache Solr's facets was actually the solution. Flatten the tables into a list of Documents (one per product) allowed to get all this data in real time with far simpler queries.


问:
Theory Of A Weird Thought - Forms Submission
In theory, if you were to open two computers that were perfectly synced together on a website that has a form. This form has fields where say for example the username has to be unique. Assuming both computers have the same information on the form, and in theory let's say that the submit button was pressed at the same time, and that these two computers have the exact same build and internet speed and the same response time from the server, whose information would be submitted to the database and whose information would be denied knowing the username field is unique.  </p>

答:
The winner would essentially be random. Whichever request is received first will win.

The definition of "received" could mean a lot of things. If we assume that your server processes all requests in the order that the network packets were received, and there are no software bugs, then once a packet enters the server's receive queue it is considered "received".

In the way you phrased your question, the packets will take different routes to the server and one will inevitably end up first. However even if they both arrive at the same time, one will "win" and be processed first.

Read up on the OSI model for an understanding on how networks function. Once you get down to the physical layer, the winner is whichever electron get access to the network interface first.


答:
Given that both transactions reach the DBMS simultaneously, the database concurrency control mechanism would guarantee isolation of the transactions, in effect choosing one transaction to precede the other. Given the unique constraint of the username, the second would be rejected.

UPDATE:

In effect, avoiding / dealing with concurrency is done at the very lowest level, not even at the DBMS level, but at the CPU level. The instruction pointer is exactly that: it points at a single instruction. Even though instruction blocks (and thus, effectively, 'concurrent' database transactions) are interleaved at execution time, one will always precede the other or be committed first, causing the other to be forcefully rolled back. For completeness:

Concurrent Transaction Processing

When two transactions are being
  processed against a database at the same time, they are termed
  concurrent transactions. Although it may appear to the users that
  concurrent transactions are being processed simultaneously, this
  cannot be true because the CPU of the machine processing the database
  can execute only one instruction at a time. Usually, transactions are
  interleaved, which means that the operating system switches CPU
  services among tasks so that some portion of each transaction is
  carried out in a given interval. This switching among tasks is done so
  quickly that two people seated at browsers side by side, processing
  the same database, may believe that their two transactions are
  completed simultaneously; in reality, however, the two transactions
  are interleaved.

Kroenke & Auer, Database Processing Fundamentals: Design, Implementation (12th Ed.), Part 4 Multiuser Database Processing, p.342

Title: Theory Of A Weird Thought - Forms Submission

Body: In theory, if you were to open two computers that were perfectly synced together on a website that has a form. This form has fields where say for example the username has to be unique. Assuming both computers have the same information on the form, and in theory let's say that the submit button was pressed at the same time, and that these two computers have the exact same build and internet speed and the same response time from the server, whose information would be submitted to the database and whose information would be denied knowing the username field is unique.  </p>


答:
For loops in C/C++ are very flexible, and as such, they don't translate directly to English very well.  The idea behind the for loop is iteration, and thus you would start out describing a simple initializer/condition/increment expression list with for each value of i.

This is my flexible, very verbose English representation of your for loop expressions:

for (i = 0; i < 10; ++i)

For each value of i (initially 0), and while i is less than 10, iterate by incrementing i.

This representation allows you to adapt to more complicated expressions, such as:

```<code>int count = 10;
for (i = 0, j = count - 1; i < count; i++, j--) { //... }
</code>```

For each value of i (initially 0) and j (initially count - 1), and while i is less than count, iterate by incrementing i and decrementing j.

Or even:

```<code>vector<T> v;
for(vector<T>::iterator it = v.begin(); it != v.end(); ++it) { //... }
</code>```

For each value of it (initially the first element of v), and while it is not the last element of v, iterate by incrementing it to the next element of v.

Body:
For loops in C/C++ are very flexible, and as such, they don't translate directly to English very well.  The idea behind the for loop is iteration, and thus you would start out describing a simple initializer/condition/increment expression list with for each value of i.

This is my flexible, very verbose English representation of your for loop expressions:

for (i = 0; i < 10; ++i)

For each value of i (initially 0), and while i is less than 10, iterate by incrementing i.

This representation allows you to adapt to more complicated expressions, such as:

int count = 10;
for (i = 0, j = count - 1; i < count; i++, j--) { //... }

For each value of i (initially 0) and j (initially count - 1), and while i is less than count, iterate by incrementing i and decrementing j.

Or even:

vector<T> v;
for(vector<T>::iterator it = v.begin(); it != v.end(); ++it) { //... }

For each value of it (initially the first element of v), and while it is not the last element of v, iterate by incrementing it to the next element of v.


问:
What is the most inspiring speech from a developer you ever watched?
Please put a direct link to it.

Required:

Still available online (please put a direct link to it)

Must be a speech from a current or former developer

Speaker's popularity doesn't matter

Target audience should be other developers

It is not required that the topic is programming (the task). I'm more looking for subject generally developing here within P.SE rather than SO.

Explain why it was inspiring

(please, native english speaker, edit my question)

答: “Humanity: Epic FAIL” – Jon Skeet at Stack Overflow Dev Days London was a speech I found pretty inspiring.  As the speech shows how computers can have problems with speech, numbers and time, it gave me hope for the future that we may yet beat some of these challenges.  There is a fair bit of humor in the speech which may or may not help those watching it.</p>


答: You can think of anytime you think a EAV table is the best way to do things (notoriously slow in realtional datbases and hard to query), you might need a nosql database. This is especially true when you have no way of knowing in advance what the fields would be. An example would be storing the details of medical tests. Each new test might have entirely different data that you would need to store. And while you could (in theory) model existing tests (with a lot of time and effort as there are thousnads of them), how would you know what new tests you might get results from for tests (and maybe medical equipment) we haven't even invented yet. </p>


答:
We produce software that has been in use by paying customers for over 20 years. The codebase has outlasted several generations of source control tools. Our software hits all your bullet points except for the tablet thing.

Some of the concerns include ESIGN and UETA. Our lawyers believe that we need to keep electronic records readable for a minimum of 10 years. For documents that are retained whole, you should look into PDF/A.

For your database, don't worry too much about normalization. Instead you should be concerned about logging everything and having audit tables that track changes/deletes in data. When upgrading versions, plan on testing new versions in parallel for enough time to ensure that you've got your data migrated. This testing of new versions also includes new operating systems - we've had some very unpleasant surprises over the years. Preserve installation media and license keys in the event that a rollback needs doing. Test backups. If you are going to serialize objects to store in the database, do so as XML instead of the serialization supplied by your development framework.

For your staffing, long term code bases need long term memory. Ideally you'd want people around who have been around a long time. If that is institutionally impossible, then you need to document everything in something like a wiki. And my advice is a wiki that can tie in with your bug tracking system.

For your codebase, make sure you have comments in your code. Migrating from one version control system to another will almost always lose your check-in comments. I'm a fan of naming unit tests after spec and bug numbers. That way if the unit test Test_Bug_1235  breaks, then you know what and where to track down what it is supposed to be testing. It isn't as "sexy" as naming your tests Check_File_Save_Networked_Drives but that sort of test is hard to backtrack to specifications, requirements or bugs unlike Test_requirement_54321_case_2.