问:
How to manage UDP client-server state
I am trying to write a Java application that works similar to MapReduce. There is a server and several workers. Workers may come and go as they please and the membership to the group has a soft-state. To become a part of the group, the worker must send a UDP datagram to the server, but to continue to be part of the group, the worker must send the UDP datagram to the server every 5 minutes. In order to accommodate temporary errors, a worker is allowed to miss as many as two consecutive periodic UDP datagrams. So, the server must keep track of the current set of workers as well as the last time each worker had sent a UDP datagram.

I've implemented a class called WorkerListener that implements Runnable and listens to UDP datagrams on a particular UDP port. Now, to keep track of active workers, this class may maintain a HashSet (or HashMap). When a datagram is received, the server may query the HashSet to check if it is a new member. If so, it can add the new worker to the group by adding an entry into the HashSet. If not, it must reset a "timer" for the worker, noting that it has just heard from the corresponding worker. I'm using the word timer in a generic sense. It doesn't have to be a clock of sorts. Perhaps this could also be implemented using int or long variables.

Also, the server must run a thread that continuously monitors the timers for the workers to see that a client that times out on two consecutive datagram intervals, it is removed from the HashSet. I don't want to do this in the WorkerListener thread because it would be blocking on the UDP datagram receive() function. If I create a separate thread to monitor the worker HashSet, it would need to be a different class, perhaps WorkerRegistrar. I must share the HashSet with that thread. Mutual exclusion must also be implemented, then.

My question is, what is the best way to do this? Pointers to some sample implementation would be great. I want to use the barebones JDK implementation, and not some fancy state maintenance API that takes care of everything, because I want this to be a useful demonstration for a class that I am teaching.
Thanks

答:
My question is, what is the best way to do this? Pointers to some sample implementation would be great

The best sample implementation that I can think of is ZooKeeper.

I want this to be a useful demonstration for a class that I am teaching

There's a lot of architecture documentation on the ZooKeeper site that will guide you through the problems that you'll hit if you try to implement similar functionality. But I have to ask: are you really helping your students if you don't fully understand what you're teaching them?

Title: How to manage UDP client-server state


问:
Is Java (still) the cross platform language of choice?
When I started using Java in the nineties, it was all "Write once, run anywhere!" from day one. That was probably all true then and I was a part of the choir as well.

I am not sure what to think about that anymore, considering all the other languages using multi platform runtimes (python, flash, perl, html, php...). But I am still seeing lots of arguments that says you should use Java because it is supposedly better for cross platform development.

So, Is that still true today? Is Java still the language of choice for multi platform development?

Please be specific with focus on cross platform aspects.

I am not asking for general language feature comparisons.

Update: Great responses so far! Most answers seems to be favoring Java or web. Any input from the script crowd?

答:
While Java may not be the or the only viable cross-platform tool, it has some strengths:

It's extremely fast.

It's extremely robust.

It's extremely portable (e.g. bytecode compiled 10 years ago in Windows 95 runs fine in OS X today).

and some weaknesses:

Core GUI libraries (Swing...) are showing their age (3rd party additions help here).

The language itself could be less verbose (e.g. checked exceptions...).

Startup time could be snappier (although it's improving all the time).

When talking specifically about Java the platform, there's one point more:

There are quite a few languages that run on the JVM and interoperate with Java.

ContentLicense: CC BY-SA 2.5


问:
Scrum: Short VS long sprint
We were trying to figure out the optimal sprint length for our project. After working on a 3-weeks basis we thought that cutting the sprint to 2-weeks would provide better velocity.

The advantages were clear - shorter feedback loop, small stories (with user value) and so on.
On the other hand, there are a lot of disadvantages such as ceremonies (planning, retrospective) and so on in which we don't produce and now happen more often.

I was wondering how, for a new team, can we decide on optimal sprint length?

答:
On the other hand, there are a lot of disadvantages
  such as ceremonies (planning, retrospective) and so on

This a major red flag. If you see it as ceremony rather than essential vehicle that serves the working process and its improvement, probably working on that has more gain than fiddling with sprint length.

The process is in your (meaning the team) hands. You're supposed to chase the best-looking ideas, if need experiment and adjust. We were doing 2-weeks then eventually switched to 3 weeks and it worked better. But sometimes just set the length based on the estimate for the scope.  Yeah, I'm aware of the "equal length" idea, but it's not a dogma, and may not really fit with some real-life project. And having a clear and evident sprint goal may serve better.

The proper length is really not something that can be deduced from outside. You are there to know the relevant factors.  At the planning you can start with "ok, what can we do in next X weeks". Or instead "what would be the next sensible increment". In any case planning up the latter is good, then look what time it would take. And portion that in one or more sprints.

ContentLicense: CC BY-SA 3.0

Title: Scrum: Short VS long sprint


问:
Can we pull future user stories in current sprint?
Suppose we have estimated 5 user stories to complete in a sprint and completed all of them with testing, buffer time and for expected bugs.

Still we have 2-3 days left for one of the developer. Can we pull a future user story in current sprint knowing that only development or part of development can be completed in current sprint?

答:
Of course you can, as long as the team agrees.

Actually if you ran out of work you're supposed to either pull in something or close the sprint.

We never had that situation as right on planning we included some "tentative" items that are not formally part of commitment but are first candidates if scope is rearranged or risks work out our way.

OTOH if the project has technological debt, you can use the time to work some of that down finally.


问:
Daily Scrum when the team is just fixing bugs
I understand all the advantages of Daily Scrum and my team does it when we are working on stories.

But sometimes we just have bugs to fix for days, while we're waiting for new stories, and when this happen we put daily scrum aside. Some of developers says that "There's no need to do a Daily Scrum when we have nothing to discuss".

I don't know if a Daily Scrum when we don't have any new story to develop is necessary. Is there anything interesting we can do on a daily scrum when we just have bugs to fix?

答:
The daily scrum's official purpose is as follow:

Communicating to the rest of the team what you did yesterday

Communicating to the rest of the team what you are going to do today

Communicating to the scrum master any impediments or blocked items

Applying this to your case:

Discussion is not a part of the daily scrum, so whether there's anything to discuss is irrelevant

"I have done bug 23/24/25 yesterday and I am going to concentrate on CSS bug files today" is a valid and useful scrum status. It tells everyone that one is progressing and what to keep their hands off for today. It also tells people that one hasn't been stuck on the same bug for three days.

We need to have a check that there is no trouble brewing, problems happening, impediments etc.

The daily scrum's behind the scenes purpose is:

Embodying the agile principle of transparency

Minimizing the impact of problems by making sure they are reported as fast as possible

Have a very quick feedback cycle of one day for many whole-team issues, which is preferable to having only an iteration-long feedback cycle

To give your developers a place to speak or ask questions to everybody else instead of having to go desk-by-desk

To have an ahead of time understanding if the team is going to make a sprint or not

To let the team re-organize if the current workload distribution is not efficient

...

You can find a very good article by Jeff Sutherland on MSDN:

Individuals and interactions are essential to high-performing teams. Studies of "communication saturation" during one project showed that, when no communication problems exist, teams can perform 50 times better than the industry average. To facilitate communication, agile methodologies rely on frequent inspect-and-adapt cycles. These cycles can range from every few minutes with pair programming, to every few hours with continuous integration, to every day with a daily standup meeting, to every iteration with a review and retrospective.


问:
How to generate random numbers with a (negative) sloping distribution?
Given a maximum integer value M, I want to generate N integer values that are distributed with a lower frequency when approaching M (preferably M should still have a non-zero probability).
I don't really care much about the probability function, let's assume (half of) a normal distribution.

How would I do that if I don't want to keep a history?

for i := 1 to N do GetNextTestValue(M)

What could GetNextTestValue look like?

FWIW I'm doing this in Delphi

答:
I found a solution.

The Controul blog by Hristo Dachev describes several methods, of which I have implemented the Marsaglia polar method.

Delphi code for a quick-and-dirty implementation with a standard normal distribution (multiplied to count integer values) is below.

The blog references the Wikipedia article which has pseudo code for any mean and standard deviation.

Sample distribution generated by the program (10000 points):

Delphi XE2 .pas file:

```<code>unit uMarsaglia;
// Based on     http://blog.controul.com/2009/04/standard-normal-distribution-in-as3/
// Refers to    http://en.wikipedia.org/wiki/Marsaglia_polar_method

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, System.Math,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, VCLTee.TeEngine, Vcl.ExtCtrls,
  VCLTee.TeeProcs, VCLTee.Chart, Vcl.StdCtrls, VCLTee.Series;

type
  TFrmMarsaglia = class(TForm)
    Chart1: TChart;
    Series1: TBarSeries;
    procedure FormShow(Sender: TObject);
  private
    FReady : Boolean;
    FCache : Real;
    function StandardNormal: Real;
  public
  end;

var
  FrmMarsaglia: TFrmMarsaglia;

implementation

{$R *.dfm}

function Ln(R: Real): Real;
begin
   Result := Log10(R) / Log10(2.7182818);
end;

procedure TFrmMarsaglia.FormShow(Sender: TObject);
const
   cTestMax = 1000000;
   cScale = 1000;
   cMaxScale = 5*cScale; // We don't count generated numbers higher than that
var
   A : Array[1..cMaxScale] of Integer;
   i: integer;
   lMax,
   Nr: Integer;
   rScale: Real;
begin
   for Nr := 1 to cMaxScale do A[Nr] := 0;
   rScale := cScale;
   for Nr := 1 to cTestMax do
   begin
      i := Trunc(rScale * StandardNormal);
      if i <= cMaxScale then Inc(A[i]);
   end;
   lMax := 0;
   for Nr := 1 to cMaxScale do if A[Nr] > lMax then lMax := A[Nr];
   Series1.Clear;
   for Nr := 1 to cMaxScale do Series1.Add(A[Nr]);
end;

function TFrmMarsaglia.StandardNormal: Real;
//  Returns real numbers between N(0,1) that when repeated have a normal distribution
var x,y,w,l: Real;
begin
   if FReady then
   begin                // Return a cached result from a previous call if available.
      FReady := false;
      Result := FCache;
      Exit;
   end;

   // Repeat extracting uniform values in the range (-1,1) until 0 < w = x*x + y*y < 1
   repeat
      x := Random;
      y := Random;
      w := x * x + y * y;
   until (w > 0) and (w < 1);

   l := Ln(w);
   w := sqrt (-2 * l / w);

   FReady := true;
   FCache := x * w;         //  Cache one of the outputs
   Result := y * w;         //  and return the other.
end;

end.
</code>```

Delphi .frm file using a TChart (TeeChart) showing the results:

```<code>object FrmMarsaglia: TFrmMarsaglia
  Left = 0
  Top = 0
  Caption = 'Marsaglia polar method'
  ClientHeight = 626
  ClientWidth = 964
  Color = clBtnFace
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clWindowText
  Font.Height = -11
  Font.Name = 'Tahoma'
  Font.Style = []
  OldCreateOrder = False
  OnShow = FormShow
  PixelsPerInch = 96
  TextHeight = 13
  object Chart1: TChart
    Left = 0
    Top = 0
    Width = 964
    Height = 626
    BackWall.Visible = False
    BottomWall.Visible = False
    Foot.Visible = False
    LeftWall.Visible = False
    Legend.Visible = False
    Title.Text.Strings = (
      'TChart')
    Title.Visible = False
    View3D = False
    Align = alClient
    BevelOuter = bvNone
    TabOrder = 0
    ExplicitLeft = 272
    ExplicitWidth = 692
    ColorPaletteIndex = 13
    object Series1: TBarSeries
      Marks.Arrow.Visible = True
      Marks.Callout.Brush.Color = clBlack
      Marks.Callout.Arrow.Visible = True
      Marks.Visible = False
      XValues.Name = 'X'
      XValues.Order = loAscending
      YValues.Name = 'Bar'
      YValues.Order = loNone
    end
  end
end
</code>```

Note that 'not keeping a history' is not satisfied: there's one boolean and one real number to remember state. That's good enough for me; I was afraid of having to maintain arrays of already generated numbers.

Body:
I found a solution.

The Controul blog by Hristo Dachev describes several methods, of which I have implemented the Marsaglia polar method.

Delphi code for a quick-and-dirty implementation with a standard normal distribution (multiplied to count integer values) is below.

The blog references the Wikipedia article which has pseudo code for any mean and standard deviation.

Sample distribution generated by the program (10000 points):

Delphi XE2 .pas file:

unit uMarsaglia;
// Based on     http://blog.controul.com/2009/04/standard-normal-distribution-in-as3/
// Refers to    http://en.wikipedia.org/wiki/Marsaglia_polar_method

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, System.Math,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, VCLTee.TeEngine, Vcl.ExtCtrls,
  VCLTee.TeeProcs, VCLTee.Chart, Vcl.StdCtrls, VCLTee.Series;

type
  TFrmMarsaglia = class(TForm)
    Chart1: TChart;
    Series1: TBarSeries;
    procedure FormShow(Sender: TObject);
  private
    FReady : Boolean;
    FCache : Real;
    function StandardNormal: Real;
  public
  end;

var
  FrmMarsaglia: TFrmMarsaglia;

implementation

{$R *.dfm}

function Ln(R: Real): Real;
begin
   Result := Log10(R) / Log10(2.7182818);
end;

procedure TFrmMarsaglia.FormShow(Sender: TObject);
const
   cTestMax = 1000000;
   cScale = 1000;
   cMaxScale = 5*cScale; // We don't count generated numbers higher than that
var
   A : Array[1..cMaxScale] of Integer;
   i: integer;
   lMax,
   Nr: Integer;
   rScale: Real;
begin
   for Nr := 1 to cMaxScale do A[Nr] := 0;
   rScale := cScale;
   for Nr := 1 to cTestMax do
   begin
      i := Trunc(rScale * StandardNormal);
      if i <= cMaxScale then Inc(A[i]);
   end;
   lMax := 0;
   for Nr := 1 to cMaxScale do if A[Nr] > lMax then lMax := A[Nr];
   Series1.Clear;
   for Nr := 1 to cMaxScale do Series1.Add(A[Nr]);
end;

function TFrmMarsaglia.StandardNormal: Real;
//  Returns real numbers between N(0,1) that when repeated have a normal distribution
var x,y,w,l: Real;
begin
   if FReady then
   begin                // Return a cached result from a previous call if available.
      FReady := false;
      Result := FCache;
      Exit;
   end;

   // Repeat extracting uniform values in the range (-1,1) until 0 < w = x*x + y*y < 1
   repeat
      x := Random;
      y := Random;
      w := x * x + y * y;
   until (w > 0) and (w < 1);

   l := Ln(w);
   w := sqrt (-2 * l / w);

   FReady := true;
   FCache := x * w;         //  Cache one of the outputs
   Result := y * w;         //  and return the other.
end;

end.

Delphi .frm file using a TChart (TeeChart) showing the results:

object FrmMarsaglia: TFrmMarsaglia
  Left = 0
  Top = 0
  Caption = 'Marsaglia polar method'
  ClientHeight = 626
  ClientWidth = 964
  Color = clBtnFace
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clWindowText
  Font.Height = -11
  Font.Name = 'Tahoma'
  Font.Style = []
  OldCreateOrder = False
  OnShow = FormShow
  PixelsPerInch = 96
  TextHeight = 13
  object Chart1: TChart
    Left = 0
    Top = 0
    Width = 964
    Height = 626
    BackWall.Visible = False
    BottomWall.Visible = False
    Foot.Visible = False
    LeftWall.Visible = False
    Legend.Visible = False
    Title.Text.Strings = (
      'TChart')
    Title.Visible = False
    View3D = False
    Align = alClient
    BevelOuter = bvNone
    TabOrder = 0
    ExplicitLeft = 272
    ExplicitWidth = 692
    ColorPaletteIndex = 13
    object Series1: TBarSeries
      Marks.Arrow.Visible = True
      Marks.Callout.Brush.Color = clBlack
      Marks.Callout.Arrow.Visible = True
      Marks.Visible = False
      XValues.Name = 'X'
      XValues.Order = loAscending
      YValues.Name = 'Bar'
      YValues.Order = loNone
    end
  end
end

Note that 'not keeping a history' is not satisfied: there's one boolean and one real number to remember state. That's good enough for me; I was afraid of having to maintain arrays of already generated numbers.


问:
How to make a license to prohibit redistribution?
I have a script I want to sell. It's written in PHP, but that's not relevant here I guess. I want to secure my script with a license, so the buyer is forbidden from redistributing it.

This is the first time I am selling my own script, so I have no idea how to start with this. Please let me know how I can protect my script with a license and what kind of license.

答:
Don't ask mostly anonymous people on the Internet for legal advice.

Look around at the commercial software you already have and read their licenses.

Look at your competition's licenses (they're often available on the web site, no purchase required.

If you find one you like, consider having your own lawyer (familiar with the laws in your country) take a look at it.


问:
Should a primary key be immutable?
A recent question on stackoverflow provoked a discussion about the immutability of primary keys. I had thought that it was a kind of rule that primary keys should be immutable. If there is a chance that some day a primary key would be updated, I thought you should use a surrogate key. However it is not in the SQL standard and some RDBMS' "cascade update" feature allows a primary key to change.

So my question is: is it still a bad practice to have a primary key that may change ? What are the cons, if any, of having a mutable primary key ?

答:
As some comments already said it, one solution is to use a new primary key

For example (following the example of @onedaywhen), let's say that exists the table Books that store a list of books and we "used" to determine the ISBN as the primary key. However, some authors committed the mistake of typed a wrong ISBN so, they asked for change the ISBN, it involved the next tasks:

create a new registry in the table Books

point all references from the old ISBN to the new ISBN. (*)

And finally, delete the old registry from the table Books.

(*) this could be trivial to find all the references for a database model that uses Foreign Keys but some models lacks of it.

```<code>Table Books
ISBN  is the primary key
NAME is a simple field.
etc.
</code>```

We change it as

```<code>Table Books
InternalBookId as the primary key
ISBN as a simple field or an indexed field.
NAME is a simple field.
etc.
</code>```

Where the new InternalBookId could even been a autonumeric value.

The cons about it:

it adds a new field that uses more space / resource.

it could requires to rewrite the entire model.

the new model could be less self explained.

The pro

Allows to mutate the "primary key".

Allows to even drop or refactoring the "primary key", for example, to change Books to ISBN-13 is so simple as to drop the older column and to create a new one

New table:

```<code>Table Books
InternalBookId as the primary key
ISBN13 is a new field.
NAME is a simple field.
etc.
</code>```

Title: Should a primary key be immutable?

Body:
As some comments already said it, one solution is to use a new primary key

For example (following the example of @onedaywhen), let's say that exists the table Books that store a list of books and we "used" to determine the ISBN as the primary key. However, some authors committed the mistake of typed a wrong ISBN so, they asked for change the ISBN, it involved the next tasks:

create a new registry in the table Books

point all references from the old ISBN to the new ISBN. (*)

And finally, delete the old registry from the table Books.

(*) this could be trivial to find all the references for a database model that uses Foreign Keys but some models lacks of it.

Table Books
ISBN  is the primary key
NAME is a simple field.
etc.

We change it as

Table Books
InternalBookId as the primary key
ISBN as a simple field or an indexed field.
NAME is a simple field.
etc.

Where the new InternalBookId could even been a autonumeric value.

The cons about it:

it adds a new field that uses more space / resource.

it could requires to rewrite the entire model.

the new model could be less self explained.

The pro

Allows to mutate the "primary key".

Allows to even drop or refactoring the "primary key", for example, to change Books to ISBN-13 is so simple as to drop the older column and to create a new one

New table:

Table Books
InternalBookId as the primary key
ISBN13 is a new field.
NAME is a simple field.
etc.


问:
btnBack vs backButtonField
For blackberry GUI developement.  I am using the name convention like backButtonField and some of my colleagues are using btnBack.

But sometimes I stuck with the names like loginVerticalFieldManager its a very long name.  At that time vfmLogin looks better

So for GUI components names what convention should I follow?

答:
I would say use btnBack instead of backButtonField. Even I at the other side of the world recognize that type of notation.

Update:
However there is no right or wrong as long as all members in the team agree to write the same notation.

Title: btnBack vs backButtonField


问:
Does dedicated maintenance work hamper a programmer's career?
The majority of my work over the last three years has largely been around maintaining legacy systems that needed patching up or the occasional revamp before being sold again.

I understand the critical role dedicated maintenance programmers have to play in companies with a large number of projects and limited developers on hand.

But as I judge my current career progress and look at my peers; contractors and corporate developers alike; I do feel as if I am lagging far behind since I've gained a great deal of breadth in terms of the areas I've touched but not much depth.
I've begun to address this by starting a blog, working on my own little git-hub projects and rescheduling my life to have time to do personal coding after work on a regular basis.

I feel that were I to interview at other companies to escape maintenance work I would have to represent myself as being quite junior in skill level since I would not have the depth of level of knowledge required of a person with three years experience focused on a particular path in feature development would. So half my current work experience would count for naught in the long run.

But this leads me to my main questions, apologies if this feels too centered around my personal dilemma,:

Do dedicated maintenance programming roles end up being detrimental to an early career?
Are other programmers right to avoid roles like these?
Does doing this line of work lock you into doing similar tasks unless you're prepared to start over as a junior?

答:
Do dedicated maintenance programming roles end up being detrimental to an early career?

More often than not - YES, assuming:

that career here means expertise in many different technical skills.

that you spend more than X years there, where X is enough to "set" your ways of thinking.

that you don't do anything aside.

that "dedicated maintainer" (see EDIT, below) means you don't code to maintain as well as code new things, but that you almost always code to maintain or even work on a project in maintenance mode - no new features, required least changes in code to fix the bug.

This doesn't mean that is always the case.

People maintaining software rarely are encouraged (see EDIT, below) to do research, rarely can plug in new library or DB and spend few days finding out how it works. It's (usually) a steady job that requires minimal changes to existing code base and thus "shapes" the way you approach problems later on. I can name quite a few companies that have a policy for maintaining software that explicitly states "less changes in the code = better", despite bad things this can bring.

Are other programmers right to avoid roles like these?

I know very good maintainers who like their jobs and wouldn't want to apply for something else precisely because it's comfortable where they are. Not everybody likes to learn new things every now and then. So - avoid or look for it depending on your preferences.

Does doing this line of work lock you into doing similar tasks unless you're prepared to start over as a junior?

More often than not - YES. Because you already have experience doing that, because you already "know the ropes" etc. But shift is definitely possible and can happen without applying for a junior position. You already started doing things aside, keep at it! That's actually very worthwhile and can shrink the 'skill gap' you noticed.

EDIT: Dan has pointed out (very rightly), that maintenance tasks can often be done WITH research. That is true. I've changed the answer above in two places to better address this.

Such tasks surely COULD be done this way and if they are - great! However AFAIK most DEDICATED maintainers of LEGACY systems have policies or management expectations and deadlines that - again, more often than not - coerce them into solving the problem with least changes possible.
Often the pressure is high enough that even if you can do it this way, you may not want to. Especially if it's not YOUR code: without theory (as per Ryle and Naur) behind it you risk damaging more than you fix.

Nevertheless it should be noted: I don't have hard global data, I speak from my own experience - I worked in a situation as OP, I recruited people with 4 - 10 years of experience as maintainers, I talked to many maintainers and I know people working as dedicated maintainers. Not just people who code new things but also code to maintains a project - dedicated maintainers, who's only job is to do bugs and patches and not even one new feature, because it's old project and it's now only in "maintenance mode".


问:
Should I include terms of agreement and privacy policy in my iOS application?
I am developing mobile based social network with backend and I cache some data from facebook. I asssume I should include a kind of Terms of use and privacy policy statement in the application? is it really neccessary? where can I find proper templates for this?</p>

答:
Yes

It helps you protect against legal consequences. It helps you to limit your damages. It's a legal contract that your users agrees before using the platform.


问:
What are the 'must know' Emacs commands?
I'm a fairly new convert to Emacs and I really love it as an editor, primarily because I keep finding new and super-useful commands. Are there any other programmer 'must known' commands missing from my list?</p>

```<code>M-x replace-string     - Find and replace a given string.
M-x goto-line          - Goto a specific line
M-x column-number-mode - Show the current column number in text bar
</code>```

答: M-x help-with-tutorial</p>

Body: M-x help-with-tutorial


问:
What is a Package Diagram? and What is a Sequence Diagram?
In many interviews I've been asked this question. What is a Package Diagram? and What is a Sequence Diagram? and difference between Package Diagram and Sequence Diagram.

Thanks in Advance.

Edit

Sorry, google give me lot of answer, but i want to practical answer with example.

答:
A package diagram is a UML diagram that describes the hierarchical relationships (groupings) between packages and other packages or objects.  A package represents a namespace.

Package Diagram Example

A sequence diagram is a UML diagram that describes how objects collaborate together in a specific scenario.

Sequence Diagram Example


问:
Solo developer vs. team developer : should I move on?
I work as a solo developer in a small company. There's more than enough work, but the same does not apply for money. Thus, I won't be seeing any new colleagues in the near future.

I am responsible for absolutely everything that has do to with IT operations. This involves development and maintenance of software used in-house, development and maintenance of various websites which our clients use, website infrastructure, local network infrastructure including maintenance of several servers and in-house support to mention the most immediate things.

I really enjoy 95% of what I do, and I've got a high degree of flexibility in my work. I get to decide what do when, and no one really tells me what do to except that I now and then sit down with my colleagues to create a roadmap for what I need to get done. I do consider myself to have a high work ethic and being above average focused on what I do, so things get done.

However, I've come to the point where I really miss having other people around me who work with the same. Even though I need to get familiar with a wide range of technologies as I am a solo developer, I have the feeling that I am missing out one the "knowledge sharing" which other "like minded" people who work in bigger companies are taking part in. I don't really have anyone to discuss programming obstacles and design decisions with - and I am starting to miss that. Also, I'm worried about what future employers might think of this "hermit" who has been working on his own for too long to ever be able to take part in a team.

However, on the other side, I'm thinking that I won't get my current degree of flexibility in a larger company. I'll be seeing a lot more strict deadlines, late hours and specialized areas of work. Also; I'm not sure if this idea of "knowledge sharing" will ever take take place?

Has anyone else been in this situation? Is it a good idea seen from a career perspective and a personal development perspective? Should I consider moving on to a bigger place to (maybe) become a part of a larger group of developers and "like minded" people? In other words, will the grass be greener on the other side?

答:
There are no guarantees in life, so you could move to a larger company and trade a set of problems for a different and possibly larger set. Many have recommended joining local tech groups to take care of interacting with like minded people, but they're not going to be able to get into a lot of the little decisions you're making on your own.

My suggestion would be to keep your current job, but get involved and network inside the local tech community. Be on the lookout for individuals and possibly companies you would like to work with. Every large company does not offer what you are looking for. If a better opportunity comes up (and you should have first-hand knowledge that it is better), look into it.

Most of us have not found the perfect job that is offers the type of work we ultimately want. You're not getting experience working with a team, but that is not by choice. You took a job that has other things you prefer. I don't think it would be too difficult to get this point across in a personal interview.


问:
SSO between multiple Flex applications
We have three applications developed in Flex and all these use BlazeDS. These applications have their own authentication implementations (Database). Also they will be deployed in tomcat. Deploying all these applications in the same tomcat instance is acceptable for us.

We want to bring the authentication credentials of all these applications into a single place and also provide SSO feature between these applications. We also want the authentication module to be configurable. Something like the system administrator can decide if the authentication should be done against a database or LDAP.

Say, if the user successfully logs into app1, and when he access app2 in the same browser he should be automatically logged in. Same goes for logout as well.

We have been exploring OpenAM, jGuard and JOSSO. I'm not sure if these require lot of customization to work with Flex. I would like to know how people are implementing SSO for Flex applications.

Is there a common and simple SSO solution available for Flex based applications ?

答:
We had a Flex app with a tcServer(tomcat)/Spring app using BlazeDS.  We were using SiteMinder as our SSO, and Spring Security to handle the security.  Everything was done on the server-side using Spring Security annotations.  The basics of SSO with Spring Security is to use a preauth filter, which uses the SiteMinder headers to lookup the user, and then let Spring Security wire together the roles and handle authorization.  Once everything was setup, it was extremely easy to use.  SiteMinder handled the login process, and secured the URL.  The UI code didn't have to change at all, save for removing the login screens since SiteMinder handled that for us.

Not sure if OpenAM, jGuard, or JOSSO work in a similar fashion, but if you are using Spring in your backend, or are thinking about it, I would recommend using Spring Security and letting it handle everything.

Title: SSO between multiple Flex applications


问:
Unit tests and language-native function calls
Is there a best practice for calling language-native functions when writing testable code?

I have experimented a little with php code and have come up with two methodologies:

create a wrapper class for all native functions and mocking this wrapper when writing tests

using "namespace magic": calling all native functions without  specifying the global namespace (aFunction in stead of \aFunction) and then writing a method stub in the given namespace during testing, which will result in the code to be tested using the stub instead of the native function

Is there a more commonly used approach? What are the benefits and shortcomings of the most commonly used methodologies to test language-native function calls?

答:
Generally you don't want to mock the native functions.  You should rely on them to do their thing.  Though there are the exceptions like (in php: ftp_connect, time, etc)

You have a couple of options.

1) You create a wrapper class that wraps the native function calls so that you are able to control it.  The downside to this is that you are still needing to possibly call an actual resource if you wanted to test your wrapper.  Or you end up with a location of untested code.

2) As you state with doing the namespace magic (specific to PHP).  I like this method as it allows you to control the native function even with having a wrapper class.

If the functionality has a native class interface, use that instead as you would be able to create a mock.
In other languages, you are also able to overload native functions which would allow to create a mock of the function in question.


问:
Why the current enthusiasm for Functional Programming?
I've been hearing a lot of enthusiasm about functional programming languages lately, with regards to Scala, Clojure, and F#.  I've recently started studying Haskell, to learn the FP paradigm.

I love it, it's really fun, and fits my math background.

But will it ever really matter?  Obviously, it's hardly a new idea.

Here's my questions:

What has contributed to the recent FP enthusiasm?  Is is merely boredom with OO, or has something changed to make FP more needed than before?

Is this indicative of a FP future?  Or is this a fad, like object orient databases?

In other words, can anyone help me understand where this comes from and where it might be going?

答:
In this talk Anders Hejlsberg explains his view on the topic.

[EDIT]

Sorry, the link was wrong. Now it points to the right place.

Extremely short summary of some points of the one-hour-talk:

Functional languages allow for a more declarative style of programming than procedural languages, so programs written in FLs usually concentrate more on the what instead of the how. Because of their elegant mathematical structure FLs are also easier to optimize and transform by compilers, which also enables easy meta-programming and the construction of embedded DSLs. All this together makes funtional programs more succinct and self-documenting than procedural programs.

Also, in the face of the manycore era of the near future, programming languages need to be able to utilize multi threading/processing in different ways. Multi threading on single core machines was in effect a time sharing mechanism, and the architecture of systems reflected this. Multi threading on manycore machines will be very different. Funcional languages are especially suitable for parallelization, since they mostly avoid state, so one needn't worry as much about the integrity of shared mutable data (because there tend to be no shared mutable data).


问:
I don't understand how TDD helps me get a good design if I need a design to start testing it
I'm trying to wrap my head around TDD, specifically the development part. I've looked at some books, but the ones I found mainly tackle the testing part - the History of NUnit, why testing is good, Red/Green/Refactor and how to create a String Calculator.

Good stuff, but that's "just" Unit Testing, not TDD. Specifically, I don't understand how TDD helps me get a good design if I need a Design to start testing it.

To illustrate, imagine these 3 requirements:

A catalog needs to have a list of products

The catalog should remember which products a user viewed

Users should be able to search for a product

At this points, many books pull a magic rabbit out of a hat and just dive into "Testing the ProductService", but they don't explain how they came to the conclusion that there is a ProductService in the first place. That is the "Development" part in TDD that I'm trying to understand.

There needs to be an existing design, but stuff outside of entity-services (that is: There is a Product, so there should be a ProductService) is nowhere to be found (e.g., the second requirement requires me to have some concept of a User, but where would I put the functionality to remind? And is Search a feature of the ProductService or a separate SearchService? How would I know which I should choose?)

According to SOLID, I would need a UserService, but if I design a system without TDD, I might end up with a whole bunch of Single-Method Services. Isn't TDD intended to make me discover my design in the first place?

I'm a .net developer, but Java resources would also work. I feel that there doesn't seem to be a real sample application or book that deals with a real line of business application.  Can someone provide a clear example that illustrates the process of creating a design using TDD?

答:
TDD helps a lot, however there is important part in software development. Developer should listen to the code that is being written. Refactoring is 3rd part in TDD cycle. This is the main step where developer should focus and think before go to next red test. Is there any duplication? Are SOLID principles applied? What about high cohesion and low coupling? What about names? Take a closer look at code that is emerging from the tests and see if there is something that needs to be changed, redesigned. Question the code and code will tell you, how it want's to be designed.
I usually write sets of multiple tests, examine that list and create first simple design, it doesn't need to be "final", usually it's not, because it's changed when adding new tests. That's where the design comes.


问:
Code Alteration During Runtime
Since Javascript is an interpreted language, entire functions can be changed during runtime. I have recently been contemplating a framework that would allow for dynamic code changes (such as UI plugins) to take effect without having to reload the page, while still providing enough information to undo the change if desired.

I have begun to test this concept with small examples with success, but have not had the chance to test the idea for anything useful.

Is there any common adverse side effects to changing code during runtime or is it considered bad practice?

答:
Self-modifying code has been almost universally viewed as an invention of the devil almost since the beginning of computing time.

The fundamental issue is this: When the code can modify itself at runtime, you no longer have any idea what code is really running.  Is it the code in the listing, or is it something that was beamed down from an extraterrestrial hacker on the smaller moon of Rigel 7?

Plugins are useful, but you want to be very careful what you do and what you allow plugins to do.

Title: Code Alteration During Runtime


答:
What you're probably referring to is more dynamic language features. As such, that's how you'll find more information about benefits and drawbacks.

In general, this has been well-explored. The primary adverse side effect you'll probably have when changing code at runtime is that it explodes the complexity of debugging by a nontrivial factor, because in order to solve problems, you generally have to figure out where they're coming from. This can be anywhere from relatively "easy" (jQuery is a decent example) to really really hard.

Title: Code Alteration During Runtime

Body:
Since Javascript is an interpreted language, entire functions can be changed during runtime. I have recently been contemplating a framework that would allow for dynamic code changes (such as UI plugins) to take effect without having to reload the page, while still providing enough information to undo the change if desired.

I have begun to test this concept with small examples with success, but have not had the chance to test the idea for anything useful.

Is there any common adverse side effects to changing code during runtime or is it considered bad practice?


问:
How does the concept of a class change when passing data to the constructor instead of method parameters?
Let's say we're making a parser. One implementation could be:

```<code>public sealed class Parser1
{
    public string Parse(string text)
    {
       ...
    }
}
</code>```

Or we could pass the text to the constructor instead:

```<code>public sealed class Parser2
{
    public Parser2(string text)
    {
       this.text = text;
    }

    public string Parse()
    {
       ...
    }
}
</code>```

Usage is simple in both cases, but what does it mean to enable parameter input to Parser1, compared to the other? What message have I sent to a fellow programmer, when they look at the API? Also, are there any technical advantages/disadvantages in certain cases?

Another question comes up when I realize that an interface would be quite meaningless in the second implementation:

```<code>public interface IParser
{
    string Parse();
}
</code>```

...where an interface on the first one could serve at least some purpose. Does that signify anything in particular, that a class is "interfaceable" or not?

答:
The second version of the class can be made immutable.

The interface can still be used to provide the ability to swap out the underlying implementation.


答:
Parser1

Building with a default constructor and passing input text into a method implies that Parser1 is re-usable.

Parser2

Passing the input text into the constructor implies that a new Parser2 must be created for each input string.

Title: How does the concept of a class change when passing data to the constructor instead of method parameters?

Body:
Let's say we're making a parser. One implementation could be:

```<code>public sealed class Parser1
{
    public string Parse(string text)
    {
       ...
    }
}
</code>```

Or we could pass the text to the constructor instead:

```<code>public sealed class Parser2
{
    public Parser2(string text)
    {
       this.text = text;
    }

    public string Parse()
    {
       ...
    }
}
</code>```

Usage is simple in both cases, but what does it mean to enable parameter input to Parser1, compared to the other? What message have I sent to a fellow programmer, when they look at the API? Also, are there any technical advantages/disadvantages in certain cases?

Another question comes up when I realize that an interface would be quite meaningless in the second implementation:

```<code>public interface IParser
{
    string Parse();
}
</code>```

...where an interface on the first one could serve at least some purpose. Does that signify anything in particular, that a class is "interfaceable" or not?


答:
Well, let's recall what it means to pass a variable as constructor parameter: You initialize an object in order to use its instance variables in methods of the object. The point is that you probably want to use it in more than one method since you want to have a high cohesion in your class.

Passing a parameter directly to a method means in a way sending a message to an object and probably receive an answer. By that, the client wants the object to deliver a service for him.

So in conclusion, those are two very different means of passing parameters and you should choose whether your object should either deliver a service or provide some functionality inherently while managing some information internally.


问:
Automatically observing changes in database tables
currently I'm working on a project with the following setting:

There is a proprietary application which performs transactions on a Microsoft Access database (which is actually stored as an .mdb file)

The API of the application doesn't have enough functionality for the requirements we're facing

Our application has direct access to the database

We're designing a C# application which has to react to events which are not triggered through the API, so the only way I can think of is to somehow observe the database directly and react accordingly to custom events.

One approach would probably be to query the DB time triggered and react, but this possibly leads to performance issues when the DB is large. I would rather appreciate an approach, where the DB itself notifies our application if specified events occur.

EDIT: The proprietary application is Enterprise Architect modeling tool, so the expected number of concurrent users will definitely not exceed 10 users and the database size will not be larger than 50 MB. Would it probably be an acceptable solution to outsource the polling activity in a separate thread and notify the rest of the application by events?

Concerning the number of users and database size, which load can the MS Access database approximately handle?

Is there any well-known pattern/approach for this kind of problem available and if you don't know any, how would you face this problem?

答: Acess will let you use linked tables to tables in another db especially SQL server. Is it possible to migrate your data to such? Then you can use triggers or jobs to do the montioring you need. </p>


答:
In the late 80ies/early 90ies computers became powerful enough for Smalltalk-style OOP. Nowadays computers are powerful enough for FP.
FP is programming at a higher-level und thus often - while more pleasant to program in - not the most efficient way do solve a certain problem. But computers are so fast that you don't care.

Multi-core prorgamming can be easier with purely functional programming languages since you are forced to isolate state-changing code.

Also programming language borders are blurred today. You don't have to give up one paradigm if you want to use another. You can do FP in most popular languages so the entry barrier is low.

Title: Why the current enthusiasm for Functional Programming?

Body:
I've been hearing a lot of enthusiasm about functional programming languages lately, with regards to Scala, Clojure, and F#.  I've recently started studying Haskell, to learn the FP paradigm.

I love it, it's really fun, and fits my math background.

But will it ever really matter?  Obviously, it's hardly a new idea.

Here's my questions:

What has contributed to the recent FP enthusiasm?  Is is merely boredom with OO, or has something changed to make FP more needed than before?

Is this indicative of a FP future?  Or is this a fad, like object orient databases?

In other words, can anyone help me understand where this comes from and where it might be going?


问:
Which closely represents Aggregation?
I know Aggregation is a has-a relationship, but I encountered a question in a test which did not make sense (and had grammatical mistakes as well)

Which of the following statements correctly describe the concept of aggregation in OOP?

A Splitting a class into a several sub classes

B Creating one piece of code that works with all similar objects

C Accessing data only through methods

D Combining several classes to create a new class

E Creating a new class from an existing class

I think;

A Could be true.

B Sounds like inheritance.

C Seems like property.

D Could be true.

E Could be true.

I'm uncertain how the has-a relationship translates into actual code in these statements. Any ideas?

答:
Hmm, Based on this wiki, I would go with D.
It seems that the intent was to 'Combining several classes to create a new class', means, to include several classes.

Clarification:
I am not sure though. Its confusing because the Answer could be read as the opposite of sub-classing. Where one takes a bunch of sub classes and creates one monster object with all its properties. In which case all the properties are lost on the objects destruction.

My quick read:

A: Sounds like Sub-classing

B: Sounds like Polymorphism or something similar

C: Sounds like property

D:

E: Sounds like inheritance

OwnerDisplayName: Qash

Title: Which closely represents Aggregation?

OwnerDisplayName: SH-


答:
I think the answer they want is "D - Combining several classes to create a new class."

Aggregate means group together;

A1

A2

B1

Aggregated;

A

1

2

B

1

Title: Which closely represents Aggregation?

Body:
I know Aggregation is a has-a relationship, but I encountered a question in a test which did not make sense (and had grammatical mistakes as well)

Which of the following statements correctly describe the concept of aggregation in OOP?

A Splitting a class into a several sub classes

B Creating one piece of code that works with all similar objects

C Accessing data only through methods

D Combining several classes to create a new class

E Creating a new class from an existing class

I think;

A Could be true.

B Sounds like inheritance.

C Seems like property.

D Could be true.

E Could be true.

I'm uncertain how the has-a relationship translates into actual code in these statements. Any ideas?

OwnerDisplayName: Nigel Alderton


问:
Does learning to play an instrument improve programming ability?
I've seen plenty of questions asking if listening to music boosts productivity, etc. but I haven't been able to find one about performing music. Learning to play the piano has been on my to-do list for a while, partly because I have a sneaky suspicion that learning to deal with the relationships, recursions, etc. inherent in music will make me a better programmer (plus it looks fun).

Does anyone know of any research on, or have first-hand experience with, learning a musical instrument having any sort of noticeable effect on one's programming or mathematical ability? Most of what I've been able to find seems to be interested in the effects of learning music at a very young age on boosting overall mental ability. I would also be interested in the other direction, aka learning to program improving one's ability with an instrument.

答:
Personally, at a certain level of abstraction, I see little difference between Symphony No.9 and say, for example, Boost.

Fundamentally, music and code are both entirely based on patterns. This is why music translates so effectively into digital performance - the patterns can be turned into numbers.

Ergo, learning to play music effectively isn't so much about the tool you do it with; the instrument. It's more about the ability to discover and exploit patterns. That's what makes a sound good or bad. There are instruments that have naturally better and worse sounds (obviously), but this shouldn't be confused with the essence of music.

Similarly, programming isn't so much about the language you do it with, it's more about the ability to discover and exploit meaningful and effective abstractions.. or patterns. That's what makes code good or bad.

So I don't really see much of a distinction between the two and feel like anything you can do to improve your ability to spot, interpret, and synthesize patterns is going to improve your code.

The only experience I have with instruments was far before I started programming, so it would be difficult for me to convey firsthand experience. There are, however, resources about this kind of thing. I'm also aware of at least one author that was a musician before getting into programming and he discusses this a little in his book.


答:
The most common solution for this kind of problem is: try to design your C# application in a way it does not have to react to changes within your database. Even when using a "real" client/ server database where you have things like triggers available, most client/server applications avoid the need for a "push model" where the server has to send a "trigger event" to the client. Indeed, there are only few databases which provide such a mechanism. At least client applications typically don't rely on getting all events, since the network between client and server may fail sometimes.

Of course, I don't know your requirements, and how much scope is left for dicussing them, and some requirements can be really hard to be implemented without an appropriate event mechanics.

If you really need this, I guess polling is the only option you have.

Would it probably be an acceptable solution to outsource the polling activity in a separate thread and notify the rest of the application by events?

Technically: probably yes, but you have to measure the performance for your specific case. Crucial factors are how much data has to be scanned in each cycle, and which latency is acceptable (seconds? ok. miliseconds or fewer? may become hard).

Title: Automatically observing changes in database tables

Body:
currently I'm working on a project with the following setting:

There is a proprietary application which performs transactions on a Microsoft Access database (which is actually stored as an .mdb file)

The API of the application doesn't have enough functionality for the requirements we're facing

Our application has direct access to the database

We're designing a C# application which has to react to events which are not triggered through the API, so the only way I can think of is to somehow observe the database directly and react accordingly to custom events.

One approach would probably be to query the DB time triggered and react, but this possibly leads to performance issues when the DB is large. I would rather appreciate an approach, where the DB itself notifies our application if specified events occur.

EDIT: The proprietary application is Enterprise Architect modeling tool, so the expected number of concurrent users will definitely not exceed 10 users and the database size will not be larger than 50 MB. Would it probably be an acceptable solution to outsource the polling activity in a separate thread and notify the rest of the application by events?

Concerning the number of users and database size, which load can the MS Access database approximately handle?

Is there any well-known pattern/approach for this kind of problem available and if you don't know any, how would you face this problem?


答:
Aggregation is a Whole-Part relationship. And so it is also a has-a relationship.

By definition the part objects can have life cycles of their own, independent of the "whole" object.

Composition is aggregation with a twist. It adds the idea that the constituent parts do not/cannot/should not exist without the whole. The parts have no real meaning or functionality outside the whole. And conversely the whole is incomplete or cannot function properly without its parts.

A is wrong because this is either inheritance or composition. Depends on how technically we read "sub class." Either way, its not aggregation.

B is wrong, that is polymorphism, implying the idea of coding to interfaces

C is wrong, that is encapsulation; in its pure form I'd say. Using a class via what it does - methods - vice accessing its state properties.

D is the best answer.

E is wrong, it simply does not meet the definition of aggregation.

Title: Which closely represents Aggregation?


问:
Deploy PHP project without giving away the source code?
I am working on developing range of web based software solutions. But the problem is that for some clients we need to deploy the applications in their local intranet. In such a situation I have to stick with Java as development language as I cannot give away the source code of the project.

Now in order to tap on more consumers we put these solutions online. Now considering the fact that Java hosting is more expensive than PHP we are left with no choice but to again re develop the entire solution in PHP. Thus we end up having two version of same solution for maintenance and upgrading in different platforms.

So can any point us to some good solution in which we can have the online solution and also have a deployable version of the application in which we can ship the application without its source code and at the same time we also need the application to be cost effective from hosting point of view?

答:
There are many ways to protect your code, although none of them can virtually make you a bullet proof but they do a pretty good job.

In my experience, we develop and distribute several Web Applications written in PHP to end clients, we use the following two products to protect our work:

We encrypt our code using the IonCube PHP Encoder - http://www.ioncube.com

We use WHMCS's Licensing Addon - http://www.whmcs.com/addons/licensing-addon

Using the above two products you can do the following

Protect and license your code before distribution.

Time restrict your web application to protect evaluation copies

Protect your scripts against unauthorized use by locking to specific machines

Restrict access to certain IP, Domain and Directory.

I hope that helps.


答:
I have never met Rich Hickey, but I have three things in common with him: we both like to program, we play guitar, and we have Music Composition Bachelors degrees from Berklee College of Music.  Here's what Mr. Hickey has to say on the subject:

Software design and composition have a lot of similarities. Both
  involve manipulating and coordinating abstractions, and envisioning
  their realization, in the case of programs that are processes, in and
  over time. I’ve certainly found software design satisfies the creative
  urge I intended to pursue in composition, and has completely displaced
  it.

Source: http://codequarterly.com/2011/rich-hickey/

A retired MIT graduate and programmer friend of mine remembers the days when there weren't enough math majors to draft into programming and companies actively recruited music majors (probably composition, but I can't remember) as a second choice.

Berklee is accredited and the music courses count for the math credits toward that accreditation.

Learning a musical instrument and learning to read music is a great way to keep your mind agile in general.  Most programmers don't need to know base-2 fractions, but IEEE floating point is base 2 fractions.  Most written music uses base 2 fractions to notate rhythm: a half-note, quarter-note, sixteenth-note, etc., though triplets are common too.  So that one little small cross-over point is there.  I suppose that finger dexterity can help you type, but typing helps that more, so I don't think that counts.  Basically, I agree with @JimmyHoffa that instrumental ability is just not particularly related to programming.

On the other hand, I feel that my study of music composition has improved my ability to construct programs.  Both involve creative manipulation of abstract concepts with regard to certain mathematical rules.  Whether I'm writing music or designing a system, days/weeks/months of mental energy is spent conceptualizing things that don't exist, that I can neither touch, nor adequately draw a picture of, or build a physical model of.  Each design needs to be tested inside my head and compared to other design alternatives.  When difficulties arise, I need to creatively imagine new solutions or modify parts of the existing solution until things work out.  This has proved to be a valuable skill for me in my career.

Also, a sensitivity to how your work will be received is a factor.  Even if you are just writing code to be read, or creating an API for other programmers to use, a sense of craft and style can go a long way toward making it usable.  Do you just name your methods willy-nilly, or do you try to find the most sensible and appropriate names?  Obviously this is especially important in UI design.  So that's another partial cross-over.

Composing music, especially serial or 12-tone music uses modulo arithmetic (modulo 12 for 12-tone equal temperament) which sometimes comes up in programming.  But now I'm grasping at straws again.

Music improvisation is interesting because it combines instrumental ability with spontaneous composition.  Many improvisers have a few "licks" that they vary the way a painter might mix a little yellow with his favorite red.  The ability to truly compose on-the-spot is a rare gift and even for those who have it.  But it's the composition aspect, not the instrumental aspect that's really related to program design.

The collaboration aspect of performing music (whether as an instrumentalist, conductor, or composer) translates directly to software or corporate projects.  Amateur music relies heavily on volunteer support and most performers are passionate about what they are doing.  If you don't keep people motivated, they just quit.  Often they tell you frankly and directly what they are feeling in a way that never happens when their performance review or pension is at stake.  Experiencing the NSFW version of these conflicts often provides insights into the cloak-and-dagger version that happens in boardrooms and design meetings.  Good money gives activities a priority that participant's families can support, but at the end of the day, most people are motivated primarily by doing something they can be proud of.  Harnessing creative energy for productive purposes is pretty much front and center in a band or with a development team.

So I would have to conclude that learning an instrument (or several) hasn't helped me much at all with programming.  Learning to compose classical orchestral compositions and fugues has helped me a great deal.  Certainly a CS degree from almost any university is a better way to learn to design computer programs, a math degree is probably a good second choice, but a music composition degree is more related than it might at first seem.

Ultimately, the best way to learn something is to do it - all the time!  Check out How to Really Master a Programming Language

Still diversity is valuable.  I suppose my composition degree gives me an edge in certain program-design circumstances, but people with a CS degree definitely have an edge in others, just as math or physics majors might have an edge in other circumstances.  At this point, I'd say that all the experience I've had and all the CS studying that I've done outside of school have done my programming more good than my Composition degree, but it does still help with abstract design.

P.S.  I don't write music any more.  I pluck out a few songs for fun sometimes, but that's about it.  Like Mr. Hickey, programming satisfies my creative urges in a way that music never did.

Title: Does learning to play an instrument improve programming ability?

Body:
I've seen plenty of questions asking if listening to music boosts productivity, etc. but I haven't been able to find one about performing music. Learning to play the piano has been on my to-do list for a while, partly because I have a sneaky suspicion that learning to deal with the relationships, recursions, etc. inherent in music will make me a better programmer (plus it looks fun).

Does anyone know of any research on, or have first-hand experience with, learning a musical instrument having any sort of noticeable effect on one's programming or mathematical ability? Most of what I've been able to find seems to be interested in the effects of learning music at a very young age on boosting overall mental ability. I would also be interested in the other direction, aka learning to program improving one's ability with an instrument.


问:
Should you reward based on overall project completeness or velocity?
The development team I'm in has been working on a VERY large project for months now and we recently started to implement a kanban board with agile practices into our process. We have seen MASSIVE improvement in our throughput! Its so exciting! But we have one struggle right now. We have a total ticket count for the project and our supervisor has given us incentive(candy and popcorn boxes) for when we get down to 100 and 50 tickets. It at first felt like a great idea but it feels like new tickets are created just as fast as we can resolve them, and its making the team feel worse about our progress. So heres my question:

Should you reward based on overall project completeness or velocity? And if completeness how do you make that feel more reachable?

答:
Are you incrementally delivering the system to production?  If not, I would begin, deploying even small parts of the system can help morale, and build a good relationship with the customer.  Doing these incremental deliveries will give the team a shorter horizon to focus on, helping the goal to feel more reachable.

As far as rewards go, I would not reward based on velocity, it brings to mind an old Dilbert cartoon where the boss states he will give bonuses for each bug fixed, after a bit of celebration, Wally proudly declares, "I am going to go code myself a mini-van".  Rewarding based on velocity I feels sends the wrong message to the team, we value metrics over working software.

Cheers!


答:
Usage is simple in both cases, but what does it mean to enable parameter input to Parser1, compared to the other?

Its a fundamental design shift. And design should convey intent and meaning. Do you need to have separate objects for every string you want to parse? In other words, why do we need an instance of parser with stringX and another instance with stringY? What is it about parse(ing) and the given string that the two must live and die together? Assuming that the "underlying [parsing] implementation" (as Robert Harvey says) does not change, there seems to be no point. And even then its questionable IMHO.

How does the concept of a class change when passing data to the constructor instead of method parameters?

Constructor parameters tell me these things are required for an object. Proper state is not guaranteed without them. Also, I know how/why one parser is fundamentally different from another.

Constructor parameters keep me from having to know too much about how to use the class. If instead I'm supposed to set certain properties - how do I know that? A whole can of worms opens up. What properties? In what order? Before I use what methods? and so on.

Another question comes up when I realize that an interface would be quite meaningless in the second implementation:

An interface, as in A.P.I., is the methods and properties exposed to client code. Do not get wrapped up in public interface { ... } exclusively. So the meaning of the interface is in the either-or constructor vs method parameter dilemma, NOT public interface Iparser vs public sealed class Parser

The sealed class is odd. If I'm thinking about different parser implementations - you did mention "Iparser" - then inheritance is my first thought. It's just a natural conceptual extension in my thinking. I.E. all ParserXs are fundamentally Parsers. How else to say it?... A German Shepard is a dog (inheritance), but I can train my parrot to bark (act like a dog - "interface"); but Polly is not a dog, merely pretending, having learned a subset of dogness. Classes, abstract or otherwise, serve perfectly well as interfaces.


答:
Semantically speaking, in OOP you should only pass the constructor a set of parameters which are needed to build the class - similarly when you call a method, you should only pass it the parameters it needs to execute its business logic.

The parameters that you need to pass in the constructor are parameters which have no sensible default value and if your class is immutable (or indeed a struct) then all-non default properties must be passed.

Regarding your two example:

if you pass text to the constructor, it hints that the Parser2 class will be specifically built to parse that instance of text at a later time. It will be a specific parser. This is typically the case when building the class is very expensive or subtle, a RegEx might be compiled in the constructor, so once you hold an instance you can re-use it without having to pay the cost of compiling; another example is initializing the PRNG - it's better if it is done rarely.

if you pass text to the method, it signals that Parser1 can be reused to parse different texts by calls.


问:
What Specifications should a Programmer Seek in a Computer Purchase ? Or, What Computer should I buy?
I wish to acquire a new computer that is specially designed for programming.

I would like to build it myself for the learning experience, but am willing to purchase it made as well.

Basically I have downloaded so many files dedicated to programming that are so large that a) my computer is near capacity and b) my 4 year old computer is extremely slow.

Specifically, I am into databases (Oracle/PostGreSQL, Mongo, Hadoop) and java, but love learning all possible languages.

答:
I would say build a computer that has decent amount of power. The reason for this is that some languages have useful IDEs (ex: Visual Studios for .NET), and some of those IDEs require a powerful machine (ex: Eclipse for Java).

Also, we computer people should have powerful and interesting computers. :)

CPU, RAM, and storage (HDD or SSD) are probably most important for a programmer. Some specs that would be ideal for such a computer (in my view) are:

```<code>Intel i5 CPU (3.0+ GHz)
8+ GB RAM
~500GB Harddrive
(Optional) An SSD for OS and big programs such as Eclipse
</code>```

These specs will suffice for a programmers use, but you may go for better specs if you so desire. The rest of the parts won't really matter much and are based more on preference than specs.

Body:
I would say build a computer that has decent amount of power. The reason for this is that some languages have useful IDEs (ex: Visual Studios for .NET), and some of those IDEs require a powerful machine (ex: Eclipse for Java).

Also, we computer people should have powerful and interesting computers. :)

CPU, RAM, and storage (HDD or SSD) are probably most important for a programmer. Some specs that would be ideal for such a computer (in my view) are:

Intel i5 CPU (3.0+ GHz)
8+ GB RAM
~500GB Harddrive
(Optional) An SSD for OS and big programs such as Eclipse

These specs will suffice for a programmers use, but you may go for better specs if you so desire. The rest of the parts won't really matter much and are based more on preference than specs.


答:
Subjective Question but here's my answer:

Whatever you do, include a SSD, at least big enough to install the OS (64-128GB). sacrifice some CPU power to get it if you have to. Also the more RAM the better.

My current 'Basic' Davelopment system (I have built 2 this year and they are good for my programming needs):

```<code>Pentium G630. (entry level, socket compatible with i3 i5 i7 etc)
4GB RAM DDR3
500GB 7200RPM hard drive
128GB SSD (I used Kingston SSDNow which is cheaper but there are better ones)
350w Power supply
Cheapest Gigabyte motherboard
24-inch 1920x1080 monitor. (This is just big enough to display two documents side by side - of course dual screen would be nicer!)
</code>```

Title: What Specifications should a Programmer Seek in a Computer Purchase ? Or, What Computer should I buy?

Body:
I wish to acquire a new computer that is specially designed for programming.

I would like to build it myself for the learning experience, but am willing to purchase it made as well.

Basically I have downloaded so many files dedicated to programming that are so large that a) my computer is near capacity and b) my 4 year old computer is extremely slow.

Specifically, I am into databases (Oracle/PostGreSQL, Mongo, Hadoop) and java, but love learning all possible languages.

Body:
Subjective Question but here's my answer:

Whatever you do, include a SSD, at least big enough to install the OS (64-128GB). sacrifice some CPU power to get it if you have to. Also the more RAM the better.

My current 'Basic' Davelopment system (I have built 2 this year and they are good for my programming needs):

Pentium G630. (entry level, socket compatible with i3 i5 i7 etc)
4GB RAM DDR3
500GB 7200RPM hard drive
128GB SSD (I used Kingston SSDNow which is cheaper but there are better ones)
350w Power supply
Cheapest Gigabyte motherboard
24-inch 1920x1080 monitor. (This is just big enough to display two documents side by side - of course dual screen would be nicer!)


问:
Looking for meaningful, strong argument in favor of antivirus software on development machines
When forming opinions, it is a good practice to follow scholastic tradition - think as hard as you can against the opinion you hold and try to find counter-arguments.

However, no matter how hard I try, I just cannot find reasonable arguments in favor of antivirus (and related security measures) on development machines.

Arguments against antivirus(AV) in development are plentiful:

It is not uncommon for 1 minute build to take 10 times longer with AV on

In a conference talk, IntelliJ developers claim AV software is #1 suspect when their IDE is sluggish

Unzipping comes with roughly 100 kb/s speed with AV on

AV renders Cygwin completely unusable (vim takes 1 minute to open a simple file)

AV blocks me from downloading useful files (JARs, DLLs) from colleagues' e-mails

I can't use multiple computers for development, since AV / security measures prevent me from unblocking ports

AV kills performance of programs with high file turnover, such as Maven or Ant

Last, but not least - what does AV actually protect me from? I am not aware of my AV program ever stopping any security thread.

If the reason is fear of disclosing NDA stuff - no AV can possibly prevent me from doing it if I set my mind to it.

If the reason is fear of losing source code and/or documentation - there are distributed revision systems for this (there are at least 20 copies of our repo and we sync on daily basis).

If the reason if fear of disclosing customer data - developers rarely work connected to real production databases, instead they are playing around in toy environments.

Even if there are meaningful arguments in favor of having AV on development machines, they fall apart when faced with the ability to run a Virtual Machine in your paranoidly protected environment.

Since I want to keep an open mind of the issue, could anyone present meaningful, strong argument in favor of Anti-virus software for developers?

答:
I've never experienced slow downs with build times. I'm a Windows developer & Windows 8 has robust AV built in (Win XP-7 you could use the free Microsoft Security Essentials - which is an excellent product that have very little impact on performance).

If your build times are taking 10x longer I would suggest finding better AV software on your platform - and ensure you're using MSE on your Windows machine.


问:
Tex and Absence of bugs
I have been reading a lot lately and I have come across articles in which people make the 'grand' assertions that there are no bugs in the Tex program by donald knuth. Is this in any way possible and if so how is this possible?</p>

答:
(even though it's been marked as duplicate, my answer is not ;)

It is possible but no one can prove it, not for TeX size.
http://ertos.nicta.com.au/research/l4.verified/ is an example of a verified piece of software.

There are two things that anyone can do to say that their software is bug free (not saying that Don said it):

test the hell out of it and fix the bugs until there's no more bug.

come up with a proof by formal method.

Problem with (1) is even if a software passed testing, there's still no proof that there's no bug. It only proves the program has no bug which would be detected by the set of tests. For large program, the cost of testing would be too high. TeX has enjoyed basically free testing from its user base. If Don could prove that TeX is bug free, he could've put a million dollar bounty.

The link I put up there is an example of (2) how a reasonable size program can be proven. By reasonable I mean, it can do something useful, not one line program that has trivial proof. What they've done is they've designed, refined the design and translated the design to C and had those steps checked by theorem prover (Isabelle/HOL). The size of the proven part is 7500 lines of C code.

Probably it would be too hard to have all programs built as trustworthy system, but it is conceivable to have some parts of a program verified and have tests cover the remaining parts of the program.

Title: Tex and Absence of bugs


问:
How should I organize my source tree?
I am an individual developer working, largely, on web-projects (W/LAMP) and, at times, on C/C++ (non-GUI) projects of about average scale.

I often struggle with structuring my source-code tree. In fact, usually, I don't complete a project without dumping the entire tree and rearranging the pieces three-four times which really takes up a lot of effort and moreover the end result does seem like a compromise.

Sometimes, I end up with over classification of source - very long tree of folders and sub-folders. At other times, I simply end up concentrating all files in a particular folder based on the larger purpose they serve and thereby leading to 'chaotic' folders in the source.

I would want to ask:

Are there any principles/logic/best-practices that can help me better at structuring my source tree?

Are there any graphical/diagrammatic techniques (for eg.: DFD in case of dataflow) that can help me visualize my source tree beforehand based on the analysis of the project?

What strategy to adopt to structure multi-media files-tree associated with the project?

About the bounty: I appreciate existing answers with the members sharing their own practices, however, I'd like to encourage more general and instructive answers (or resources) and more responses from the members.

答:
I like the ideas presented in this page www.javapractices.com/topic/TopicAction.do?Id=205. Basically, the recommendation is to organize your project into features(or modules, components). In addition to the reasons presented there:

Less cognitive load when you think about the scope of the code you are working on since you have a guarantee that any code in the feature your are working on is "feature-private".

There is an added sense of security when you are guaranteed that you are only modifying code for given a feature. E.g., you won't break anything other than the feature you are working on. Again this is because of the "feature-private".

Less cognitive load simple because there is less files you can see for a given package. I am sure everyone has seen a package that contain more than 15 files.

Note this is focused on Java packages (aka namespaces). For big projects, I do recommend, for the same reasons, dividing the project into multiple projects (as in multiple maven projects) that represents a business feature. For maven projects, I recommend this reading.

So far, the projects I was/am involved in does not follow these. There are many reasons, but here's a few:

The misunderstanding of Java default access modifier (most misunderstood access modifier as per this book)

"Argumentum ad populum": Prevailing culture of package-by-layer (probably caused by Reason #1)

I think there is a missed opportunity to prevent complexity if project source organization is not taken seriously at the start of the project as the architect Alexander said:

"As any designer will tell you, it is the first steps in a design
  process which count for most. The first few strokes, which create the
  form, carry within them the destiny of the rest." - Christopher
  Alexander

Depending on the size & complexity of a project, the missed opportunity to cut costs or ROI can be really big. (I'm interested to see a study to see the exact numbers for this)

Title: How should I organize my source tree?


问:
Which could be a good design pattern for complex numeric calculations between three or more different data models?
The source code I'm working on at the moment performs numeric calculations between a bunch of different properties belonging to different data models. All the calculations are  coded in a big method with a lot of If statements than make it very complex, difficult to change and it contains some bugs.

I have not found a design pattern that fits into this problem that I think is very common in any financial application. Any help with this?

The source code is c# with .NET fw 4.

答:
Well, something that might be helpful for you is doing Refactor:

Refactoring is a disciplined technique for restructuring an existing
  body of code, altering its internal structure without changing its
  external behavior. Its heart is a series of small behavior preserving
  transformations. Each transformation (called a 'refactoring') does
  little, but a sequence of transformations can produce a significant
  restructuring. Since each refactoring is small, it's less likely to go
  wrong. The system is also kept fully working after each small
  refactoring, reducing the chances that a system can get seriously
  broken during the restructuring.
  http://refactoring.com/

There is a book about it.

Anyway. I was in the same situation and I have to do a lot of refactor, like:

Simplifying blocks of if statements in methods doing "Decompose Conditional"

Decompose Conditional   You have a complicated conditional (if-then-else) statement. Extract methods from the condition, then part, and else parts.

```<code>if (date.before (SUMMER_START) | | date.after( SUMMER_END))
     charge = quantity * _winterRate + _winterServiceCharge;
else
     charge = quantity * _summerRate;
</code>```

Changed to:

```<code>if (notSummer( date))
    charge = winterCharge( quantity);
else
    charge = summerCharge (quantity);
</code>```

Consolidating conditional expressions in a single method. For example, if I have a bunch of ifs in a method before doing the real job, then I group all those ifs in one single method

Once that you have done some refactor of your code, you realize that is easy move the pices together so at that point I would suggest the Strategy pattern.

In computer programming, the strategy pattern (also known as the
  policy pattern) is a software design pattern, whereby an algorithm's
  behaviour can be selected at runtime. http://en.wikipedia.org/wiki/Strategy_pattern

and finally, remove switch statements (if you have them) with some polymorhism.

Body:
Well, something that might be helpful for you is doing Refactor:

Refactoring is a disciplined technique for restructuring an existing
  body of code, altering its internal structure without changing its
  external behavior. Its heart is a series of small behavior preserving
  transformations. Each transformation (called a 'refactoring') does
  little, but a sequence of transformations can produce a significant
  restructuring. Since each refactoring is small, it's less likely to go
  wrong. The system is also kept fully working after each small
  refactoring, reducing the chances that a system can get seriously
  broken during the restructuring.
  http://refactoring.com/

There is a book about it.

Anyway. I was in the same situation and I have to do a lot of refactor, like:

Simplifying blocks of if statements in methods doing "Decompose Conditional"

Decompose Conditional   You have a complicated conditional (if-then-else) statement. Extract methods from the condition, then part, and else parts.

if (date.before (SUMMER_START) | | date.after( SUMMER_END))
     charge = quantity * _winterRate + _winterServiceCharge;
else
     charge = quantity * _summerRate;

Changed to:

if (notSummer( date))
    charge = winterCharge( quantity);
else
    charge = summerCharge (quantity);

Consolidating conditional expressions in a single method. For example, if I have a bunch of ifs in a method before doing the real job, then I group all those ifs in one single method

Once that you have done some refactor of your code, you realize that is easy move the pices together so at that point I would suggest the Strategy pattern.

In computer programming, the strategy pattern (also known as the
  policy pattern) is a software design pattern, whereby an algorithm's
  behaviour can be selected at runtime. http://en.wikipedia.org/wiki/Strategy_pattern

and finally, remove switch statements (if you have them) with some polymorhism.


问:
Using GPLv3 software in a open source project licensed BSD (3-Clause)

Preamble

If I say "BSD" I mean the 3-Clause BSD license

If I say "GPL" I mean the GPLv3 license

I am not the author of the GPL project

I am the author of the BSD project

Simple Task

I want to use a 3rd party software (GPL) in (or better 'with') my open source project (BSD).

Situation

I won't change any of the GPL project code (using it AS IS).

I want to use it as kind of a library (I know about LGPL but it's not available).

I will use the GPL software as bulk, not only parts of the code.

I will indicate the use of the GPL project with the license, homepage and where and why it is used in my BSD project (in README file).

I will not take the credits for the functionality of the GPL project.

I will take the credits for my project and the "Adapter" connecting my BSD project to the GPL project.

I don't want to re-license the GPL project as BSD

I won't charge any fees or something like that.

To gain insight, you can find the BSD project at

GitHub: MOC-Framework (see /Extension/FlowPlayer and /Module/Office/Video)

and the GPL project here:

Flowplayer (free flash-version)

Simple Question

Is this possible?

Closing Words

I found some discussions, stating "it is possible", others say "no". Most of the "no" were for commercial projects. Most of the "yes" are referring to: "include BSD in GPLv3", but that's not what I mean. I want GPLv3 along with BSD.

I simply can't figure it out.

答:
Yes, it is possible with the following implications:

The combined binary is covered by GPL. Only applies if they are statically or dynamically linked together. If your binary just runs the GPL one, it isn't covered. Distribution method does not matter.

You still may distribute your sources under the more permissive BSD license.

A program is not a derived work of a plugin, so if you have a program, that can, optionally, load a plugin and only the plugin uses the GPL code, the main program is not covered by GPL, only the glue that adapts the GPL code to work as plugin is.


答:
Functional programming gives me the same tingling sense of "wow, this is new" as when I first started dabbling with objects years ago.

I realize that FP is not a new concept by far, but neither was OO when it got its real break  in the nineties when "everyone" suddenly jumped ship from procedural programming. This was largely due to the timely success of Java and later C#.

I imagine the same thing will happen with FP eventually once the next batch of languages starts spreading in the same way. Much as they already have, at least in some circles, with languages like Scala and F#.


问:
How to securely implement auto-login
I've read many, many, many posts on how "you're probably storing passwords wrong". They are always referring to storing passwords on a server into which a user is logging; they basically rehash (pun intended) ubiquitous advice like make sure to salt the passwords, etc. etc. However, I've never seen an article on best practises for storing passwords on a client so that the client doesn't have to log in manually every time they want to log in; the "remember me" feature.

Many pieces of software have this feature, from browsers to programs like Dropbox.

I did read an old article recently about how Dropbox was storing an ID on your computer that you could just copy/paste to another computer and start Dropbox and be logged in as the device you got the ID from; no login, no nothing, and full access to the Dropbox account. This seems like a really stupid design, but I can't think of any better way to do it.

I'm not even sure how to avoid storing something like a cookie in plain-text. If you encrypt it, where do you store the key to decrypt it?

The only way I see to not introduce security vulnerabilities is to remove the autologin feature and make the user type their password every time they want to use  a service, but that's a usability struggle and users are spoiled to expect not to have to do that.

What can I read about locally storing credentials safely to implement the automatic login feature? If the principles are too simple for an entire article, what are they? The software in question should not depend on features not present on all platforms (like the "keychain" some linux distributions have).

答:
It's actually not that hard. First store a cookie with this format:

```userID.token```

You can use an sha1 hash for the token. Then in your remember_me_tokens database table store userID, a bcrypt hash of the token and the time the token was generated.

Then when someone visits your site, check to see if the cookie is set. If the cookie is set then see if there's a valid row for it in the database within the last 7 days say. If there's a valid row in the database for the cookie then set the session to indicate that the user is logged in and also delete the matched cookie/database row and generate a fresh cookie/token/database row.

If they log out then delete the cookie.

Run a cron job to prune remember_me_tokens that are older than say 7 days.

Title: How to securely implement auto-login

Body:
It's actually not that hard. First store a cookie with this format:

userID.token

You can use an sha1 hash for the token. Then in your remember_me_tokens database table store userID, a bcrypt hash of the token and the time the token was generated.

Then when someone visits your site, check to see if the cookie is set. If the cookie is set then see if there's a valid row for it in the database within the last 7 days say. If there's a valid row in the database for the cookie then set the session to indicate that the user is logged in and also delete the matched cookie/database row and generate a fresh cookie/token/database row.

If they log out then delete the cookie.

Run a cron job to prune remember_me_tokens that are older than say 7 days.


答:
One way is:

When the user logs in, store a session ID in a cookie on the client's computer (not the username or password).

Tie session to IP address, so an individual session ID only works with the computer it was started on.

Depending on what framework you are using to develop your site, this behavior may be available as a built-in feature.

Note that, because the HTTP protocol is stateless anyway, there is actually no functional difference between keeping someone logged in during a single session of using the website and "auto-login" the next time they use the site; it is solely a matter of how much time you allow before the session expires.

Update: Also, use HTTPS for increased security, obviously.

Update 2: Note that this approach has limitations, in that it doesn't work well for users who change their IP address a lot.  However, it does provide an increased level of security and may be useful in some situations.

Title: How to securely implement auto-login

Body:
I've read many, many, many posts on how "you're probably storing passwords wrong". They are always referring to storing passwords on a server into which a user is logging; they basically rehash (pun intended) ubiquitous advice like make sure to salt the passwords, etc. etc. However, I've never seen an article on best practises for storing passwords on a client so that the client doesn't have to log in manually every time they want to log in; the "remember me" feature.

Many pieces of software have this feature, from browsers to programs like Dropbox.

I did read an old article recently about how Dropbox was storing an ID on your computer that you could just copy/paste to another computer and start Dropbox and be logged in as the device you got the ID from; no login, no nothing, and full access to the Dropbox account. This seems like a really stupid design, but I can't think of any better way to do it.

I'm not even sure how to avoid storing something like a cookie in plain-text. If you encrypt it, where do you store the key to decrypt it?

The only way I see to not introduce security vulnerabilities is to remove the autologin feature and make the user type their password every time they want to use  a service, but that's a usability struggle and users are spoiled to expect not to have to do that.

What can I read about locally storing credentials safely to implement the automatic login feature? If the principles are too simple for an entire article, what are they? The software in question should not depend on features not present on all platforms (like the "keychain" some linux distributions have).


问:
Evaluation order of the expressions
The C Programming Language by K & R states that C, like most languages, does not specify the order in which operands of an operator are evaluated. (The exceptions are &&,||,?: and ','). According to the book, the result of the statement :

```<code>printf("%d %d\n",++x,power(2,x));
</code>```

depends on the compiler. But it itself says in the previous line,that I have quoted that it does not predict the order of evaluation,except ',' and others. So don't you think book is contradicting itself?

答:
The first statement (the exceptions) refers to the comma operator, this is (usually) different to commas in function calls.

The comma operator is used rarely, but can be used to do things like this:

```<code>int i,j; /* not comma operator */
for(i=0,j=0; i<10 && j<10; ++i, ++j) /* comma operators */
{
    doProcWith2Args(i,j); /*not comma operator*/
}
</code>```

evaluation of operands of the comma operator is always left to right (it forms a sequence in standardese). Normal function parameter commas do not promise anything about their order of evaluation (and in general a program that changed depending on order of evaluation will be said to exhibit 'undefined behaviour').

I don't have my copy of K&R here but I suspect if you re-read the part with the knowledge of the comma operator it may make more sense.

Title: Evaluation order of the expressions

Body:
The first statement (the exceptions) refers to the comma operator, this is (usually) different to commas in function calls.

The comma operator is used rarely, but can be used to do things like this:

int i,j; /* not comma operator */
for(i=0,j=0; i<10 && j<10; ++i, ++j) /* comma operators */
{
    doProcWith2Args(i,j); /*not comma operator*/
}

evaluation of operands of the comma operator is always left to right (it forms a sequence in standardese). Normal function parameter commas do not promise anything about their order of evaluation (and in general a program that changed depending on order of evaluation will be said to exhibit 'undefined behaviour').

I don't have my copy of K&R here but I suspect if you re-read the part with the knowledge of the comma operator it may make more sense.


问:
btnBack vs backButtonField
For blackberry GUI developement.  I am using the name convention like backButtonField and some of my colleagues are using btnBack.

But sometimes I stuck with the names like loginVerticalFieldManager its a very long name.  At that time vfmLogin looks better

So for GUI components names what convention should I follow?

答:
Avoid non-standard abbreviations.

Button -> btn is arguably ok (some people will disagree with that).

VerticalFieldManager -> vfm is definitely not (I thought it was was Visual Form or something).

(WTF is a Vertical Field Manager anyway - possibly sounds like a stupid way of saying "Column"?)

Definitely the element type should be a suffix, not a prefix.

So BackButton (or BackBtn) and so on.

Title: btnBack vs backButtonField


答:
You can only if you trust the device where you store it. It is up to the user (if you can't influence the device) how secure it is. It is simply out of your hands.

As stated in the comments:

It is about what you trust. If you don't trust the machine store the ID then that is your issue. If you trust the keychain then that is the maximum security you will get. Off course you could add some custom safety like detecting device hardware or something but it's all fake-able so you cannot know in the end. It is out of your control.

Title: How to securely implement auto-login