问:
A backlog of "bite-size" tasks in parallel to the "main" feature backlog?
After over two years of working in a highly siloed, "lone-wolf" development department structure, we're adopting Agile SCRUM. Great. I like Agile; as a dev it keeps you focused, busy, and productive without having myriad stakeholders shoving project after project down your throat with the expectation they all be done yesterday.

There is, however, one aspect of moving to SCRUM versus our current "model", that I think people outside Development are not going to like in the slightest. That is their current ability to have us do small changes "while you wait". A large portion of our development is for in-house consumption only, and we're mostly all in the same building. So, it's been common practice for years for a department lead or manager elsewhere to come to the "codebase owner" of a particular application and ask for small stuff (sometimes not so small, but we're pretty good about not taking on three-week projects based on these "drive-bys"). Even our boss sometimes relays things brought up to him in this way. Very often, if we're working in the codebase in question at the time, we can simply pop up the source file, make the change, and run it with them looking over our shoulder to verify the change is what they want, before checking it into Subversion for inclusion in the next build.

With a basic Agile SCRUM methodology, these tweaks would either be logged as defects (we didn't meet a requirement specified in a story previously consumed) or new small stories (we met all stated requirements, but those requirements were incomplete, vague or incorrect, or they changed after delivery once the users saw the new features). Either way, the vast majority would be one-pointers at most if not zeroes, and of relatively low priority (the system is usable in its current state, but it would be so much cooler if...), making them unlikely to be brought into a sprint when working the backlog top-down.

This possibility was raised at a dev meeting as being a source of active opposition to our Agile process by other departments, who would see it as less "agile" than our current ability to make small tweaks on request. It's a valid concern IMO; the stakeholders behind the PO don't always agree on what things are most important, because they don't all have the same point of view, yet it's typically only the managers who make the final decision, and therefore their bias is the one that shows in the product backlog.

A solution was then proposed, which was tentatively called the "candy jar" (another term thrown out was the "gravy boat"). Small tweaks requested by the "little guys" in the various departments, that are not defects in an existing story, that are estimated by consensus or acclamation within the team to take less than one-half of a developer-day, and that would have an immediate, significant, positive impact on the user experience in the opinion of the end user, are put on a list in parallel to the primary backlog. They'd be identified as "stories", but would be kept separate from the primary backlog of "big" stories subject to prioritization. If, at any time during the normal progress of a sprint, we happen to be working in an area of the system in which one of these tweaks can be made, making the tweak trivial, we can bring the tweak into the sprint and code it alongside the larger story. Doing this must not jeopardize the completion of the larger story or any other committed work. The PO would also have access to this list, and if they were working on an upcoming user story touching the basic feature involving the tweak, they could fold it into the story as a requirement and then we'd meet the requirement as we would any other. This, it was thought, would make tweaks more likely to be worked on sooner than later.

This triggered the reaction among those of us with ScrumMaster training of "uh-uh". There is one backlog. Two backlogs introduces the question of which #1 item is really the most important, which list's items determine real velocity, and which of the two backlogs a story actually belongs in (any demarcation of size/complexity is going to have some cases that fall relatively arbitrarily to one side or the other). "Let the process work", we said; if the change really is significant to the end users, they'll make enough noise to get the department heads making time/money decisions on board, and it'll get bumped up into the dev team's consciousness toward the top of the backlog.

I thought I'd pose the question to the floor: In your opinion, would a parallel list of "bite-size" stories have value in getting small, useful but ultimately low-priority changes made faster, or is it overall a better decision to fold them into the main backlog and let the basic process govern their inclusion in a sprint?

答:
Based on your initial question and subsequent clarifications, this is what I have perceived that your pain points are

Constantly changing requirements

Inability for developers to focus on other areas of the application, ie. we're heroes on one part of the application but not
keen to touch any other.

Different approaches to architecture, solutions, frameworks being adopted

Requirements gathering process doesn't seem to work

Scrum, if initially adhered to correctly should fix a lot of these issues, and more importantly, bring other issues to the fore that should be resolved.

- Constantly changing requirements

Having a single backlog that everything is fed into and prioritised correctly should mean that the team should not be bearing the brunt of requirements changing while in the middle of development.
If it is a very dynamic environment, smaller sprints of 1 or 2 weeks should ensure changing priorities can still be facilitated in a relatively short period of time.

- Inability for developers to focus on other areas of the application, ie. we're heroes on one part of the application but not keen to touch any other.

A scrum team working well together and supporting each other, with a specific drive towards sharing knowledge within the team and looking for the challenge of working on other parts of the application will seek to ensure the knowledge of the application gets shared. Some practices like pair programming can help people overcome their fear of working on code they are not familiar with while also learning and sharing that knowledge. This may take a few sprints before the knowledge of the application is distributed between the teams and people are comfortable working on any area of the application. Also, allowing people to pull tasks of a board, i.e. make their own choice on what they would like to work, can encourage this.

- Different approaches to architecture, solutions, frameworks being adopted

Scrum facilitates better communication, it facilitates teamwork and better decision-making as well as providing greater visibility into what is going on. This is turn should facilitate the organisational decisions around the use of frameworks, architectural solutions, etc and the use of a Scrum of Scrums mechanism may help in instilling that throughout the organisation.

- Requirements Gathering Process

Again, if you adhere to rules strictly, if a requirement isn't clearing specified and ready for the team to be able to understand and estimate what is required to fulfill the requirement, it should not be brought into the sprint. Take another requirement that is a high priority and has been well-defined... because then you know you will be able to deliver that! While it may not fix the requirements gathering process immediately, it will force the change required to get that process fixed.

To answer your first question, no, there shouldn't be two separate backlogs. At any given time, it is in everyone's best interest that the developers and the organisation are working on the highest priority items first. Priorities should mainly be based on business value, and it is quite possible many of the small tweaks and requests do add business value. Let the product owner decide that.

I've been a Scrum Master for over 7 years and helped with the introduction of Scrum into many different teams and companies. In my humble opinion and from my observations, I feel that if Scrum is being introduced into your organisation for the very first time, follow it by the book. Don't deviate.
Scrum requires discipline to be able to stick to the practices and processes. It is too easy to make exceptions to fit certain circumstances, and if done too early, will lead
to the erosion of benefits and values it brings with it. Do the basics, do them really well. Become an expert at doing the basics and understanding why they are there, and then change the process to better suit and to drive continuous improvement within your organisation. Deviating from the basic processes and practices early on can be a mechanism to hide some other issues or the underlying problems existing in the organisation [probably the main reason why Scrum is being introduced].

There are very valid cases for saying this is "Agile", so we must be willing to change the process, but there is a significant difference between a self-directed, self-organising team understanding the process and discussing changes that could be made to the process, as opposed to a team who are only beginning to walk down the path of Agile or Scrum. It's like trying to run before you know to crawl...


问:
Other than XML, what are some examples of "coding" a GUI design?
I've been trying to think outside of the box as to how desktop GUIs can be designed in code(not a graphical designer!). I've come across basically three ways this is done:

XML

Raw code (create a window, create a text box, add text box to window, etc)

HTML and friends

I'm sure that someone has done something other than these three though. Are there any existing examples of frameworks or languages which allow you to code a GUI using a format other than these three

答:
Maybe Delphi .dfm files can serve as an example:</p>

```<code>inherited DialoogConfigExchange: TDialoogConfigExchange
  ActiveControl = EditHost
  Caption = 'Exchange (Agenda)'
  ClientHeight = 198
  ClientWidth = 600
  ExplicitWidth = 616
  ExplicitHeight = 236
  PixelsPerInch = 96
  TextHeight = 16
  inherited PanelButtons: TcxGroupBox
    Top = 163
    ExplicitTop = 163
    ExplicitWidth = 600
    Width = 600
    inherited ButtonCancel: TcxButton [0]
      Left = 490
      ExplicitLeft = 490
    end
    inherited ButtonOK: TcxButton [1]
      Left = 380
      Caption = '&Opslaan'
      OnClick = ButtonOKClick
      ExplicitLeft = 380
    end
  end
  object Panel1: TcxGroupBox [1]
    Left = 0
    Top = 0
    Align = alClient
    PanelStyle.Active = True
    PanelStyle.OfficeBackgroundKind = pobkGradient
    Style.BorderStyle = ebsNone
    TabOrder = 1
    Height = 163
    Width = 600
    object LabelHost: TcxLabel
      Left = 10
      Top = 10
      AutoSize = False
      Caption = 'Exchange Web Services URL:'
      Properties.Alignment.Vert = taVCenter
      Transparent = True
      Height = 24
      Width = 200
      AnchorY = 22
    end
    object LabelGebruiker: TcxLabel
      Left = 10
      Top = 38
      AutoSize = False
      Caption = 'Exchange server gebruiker:'
      Properties.Alignment.Vert = taVCenter
      Transparent = True
      Height = 24
      Width = 200
      AnchorY = 50
    end
    object LabelWachtwoord: TcxLabel
      Left = 10
      Top = 66
      AutoSize = False
      Caption = 'Exchange server wachtwoord:'
      Properties.Alignment.Vert = taVCenter
      Transparent = True
      Height = 24
      Width = 200
      AnchorY = 78
    end
    object EditHost: TcxTextEdit
      Left = 217
      Top = 10
      AutoSize = False
      TabOrder = 0
      Height = 24
      Width = 345
    end
    object EditGebruiker: TcxTextEdit
      Left = 217
      Top = 38
      AutoSize = False
      TabOrder = 1
      Height = 24
      Width = 345
    end
    object EditWachtwoord: TcxTextEdit
      Left = 217
      Top = 66
      AutoSize = False
      Properties.EchoMode = eemPassword
      Properties.PasswordChar = '*'
      TabOrder = 2
      OnEnter = EditWachtwoordEnter
      OnExit = EditWachtwoordExit
      Height = 24
      Width = 345
    end
    object CheckEncrypted: TcxCheckBox
      Left = 215
      Top = 92
      Hint = 'Sla het databasewachtwoord encrypted op'
      AutoSize = False
      Caption = 'Encrypted'
      TabOrder = 6
      Height = 24
      Width = 100
    end
    object ButtonTest: TcxButton
      Left = 50
      Top = 132
      Width = 100
      Height = 25
      Caption = '&Test'
      OptionsImage.ImageIndex = 167
      OptionsImage.Images = DataModuleImageLists.cxImageListSmall
      TabOrder = 7
      OnClick = ButtonTestClick
    end
  end
  inherited FormTranslator: TIvTranslator
    Left = 485
    Top = 125
  end
  inherited LookAndFeelControllerTimeTellForm: TcxLookAndFeelController
    Left = 485
    Top = 65
  end
  inherited StyleRepositoryForm: TcxStyleRepository
    Left = 485
    Top = 95
    PixelsPerInch = 96
  end
  inherited EditStyleControllerVerplicht: TcxEditStyleController
    Left = 485
    Top = 5
    PixelsPerInch = 96
  end
  inherited EditStyleControllerReadOnly: TcxEditStyleController
    Left = 485
    Top = 35
    PixelsPerInch = 96
  end
e
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Maybe Delphi .dfm files can serve as an example:

inherited DialoogConfigExchange: TDialoogConfigExchange
  ActiveControl = EditHost
  Caption = 'Exchange (Agenda)'
  ClientHeight = 198
  ClientWidth = 600
  ExplicitWidth = 616
  ExplicitHeight = 236
  PixelsPerInch = 96
  TextHeight = 16
  inherited PanelButtons: TcxGroupBox
    Top = 163
    ExplicitTop = 163
    ExplicitWidth = 600
    Width = 600
    inherited ButtonCancel: TcxButton [0]
      Left = 490
      ExplicitLeft = 490
    end
    inherited ButtonOK: TcxButton [1]
      Left = 380
      Caption = '&Opslaan'
      OnClick = ButtonOKClick
      ExplicitLeft = 380
    end
  end
  object Panel1: TcxGroupBox [1]
    Left = 0
    Top = 0
    Align = alClient
    PanelStyle.Active = True
    PanelStyle.OfficeBackgroundKind = pobkGradient
    Style.BorderStyle = ebsNone
    TabOrder = 1
    Height = 163
    Width = 600
    object LabelHost: TcxLabel
      Left = 10
      Top = 10
      AutoSize = False
      Caption = 'Exchange Web Services URL:'
      Properties.Alignment.Vert = taVCenter
      Transparent = True
      Height = 24
      Width = 200
      AnchorY = 22
    end
    object LabelGebruiker: TcxLabel
      Left = 10
      Top = 38
      AutoSize = False
      Caption = 'Exchange server gebruiker:'
      Properties.Alignment.Vert = taVCenter
      Transparent = True
      Height = 24
      Width = 200
      AnchorY = 50
    end
    object LabelWachtwoord: TcxLabel
      Left = 10
      Top = 66
      AutoSize = False
      Caption = 'Exchange server wachtwoord:'
      Properties.Alignment.Vert = taVCenter
      Transparent = True
      Height = 24
      Width = 200
      AnchorY = 78
    end
    object EditHost: TcxTextEdit
      Left = 217
      Top = 10
      AutoSize = False
      TabOrder = 0
      Height = 24
      Width = 345
    end
    object EditGebruiker: TcxTextEdit
      Left = 217
      Top = 38
      AutoSize = False
      TabOrder = 1
      Height = 24
      Width = 345
    end
    object EditWachtwoord: TcxTextEdit
      Left = 217
      Top = 66
      AutoSize = False
      Properties.EchoMode = eemPassword
      Properties.PasswordChar = '*'
      TabOrder = 2
      OnEnter = EditWachtwoordEnter
      OnExit = EditWachtwoordExit
      Height = 24
      Width = 345
    end
    object CheckEncrypted: TcxCheckBox
      Left = 215
      Top = 92
      Hint = 'Sla het databasewachtwoord encrypted op'
      AutoSize = False
      Caption = 'Encrypted'
      TabOrder = 6
      Height = 24
      Width = 100
    end
    object ButtonTest: TcxButton
      Left = 50
      Top = 132
      Width = 100
      Height = 25
      Caption = '&Test'
      OptionsImage.ImageIndex = 167
      OptionsImage.Images = DataModuleImageLists.cxImageListSmall
      TabOrder = 7
      OnClick = ButtonTestClick
    end
  end
  inherited FormTranslator: TIvTranslator
    Left = 485
    Top = 125
  end
  inherited LookAndFeelControllerTimeTellForm: TcxLookAndFeelController
    Left = 485
    Top = 65
  end
  inherited StyleRepositoryForm: TcxStyleRepository
    Left = 485
    Top = 95
    PixelsPerInch = 96
  end
  inherited EditStyleControllerVerplicht: TcxEditStyleController
    Left = 485
    Top = 5
    PixelsPerInch = 96
  end
  inherited EditStyleControllerReadOnly: TcxEditStyleController
    Left = 485
    Top = 35
    PixelsPerInch = 96
  end
e


问:
Is it a good practice to write a method that gets something and checks the value?
Occassinally I have to write methods like this:

```<code>string GetReportOutputDirectoryAndMakeSureExist()
{
    string path = Path.Combine ( ... ) //whatever logic
    if(!Directory.Exists(path)) Directory.Create(path);
    return path;
}
</code>```

or

```<code>string GetAndVerifyExistenceOfReportConfigurationPath()
{
    string path = Path.Combine ( ... ) //whatever logic to find the configuration
    if(!File.Exists(path)) throw new Exception("Report configuration not found");
    return path;
}
</code>```

or

```<code>Customer GetCustomerAndVerifyActive(int id)
{
    Customer customer = Db.GetCustomerById(id);
    if(!customer.IsActive) throw new Exception("Customer is not active");
    return customer;
}
</code>```

Is it a good practice? I am told that it is normally not a good idea for a method to do more than one things, or for a method to have side-effects (like creating directory). But if I split, for example the last metod to GetCustomer(id) and VerifyActive(customer), I will have to do:

```<code>var customer = GetCustomer(id);
VerifyActive(customer);
</code>```

consecutively at several places, and I think it counts as violation of DRY. Is this a good idea? Any idea how to help with the long method names?

答:
What your methods are doing is not at all unreasonable. Its just unfortunate that their names are a bit of a mouthful.

For example where you have a method GetCustomerAndVerifyActive, surely you could call this GetActiveCustomer instead, and its easier on the eye? The new name doesn't detract from what the method actually does.

In summary I think your method names should reflect what the method does at a high level, not line-by-line. And certainly in .net you have the /// embellishments which allow you to specify what the method does in a more detailed way.

Example

```<code>/// <summary>
/// Returns an Active customer
/// </summary>
/// <param name="id">the customer's id</param>
/// <returns>the active customer</returns>
/// <remarks>Note this will throw an exception if the customer doesn't exist, or is inactive</remarks>
Customer GetActiveCustomer(int id)
{
    Customer customer = Db.GetCustomerById(id);
    if(!customer.IsActive) throw new Exception("Customer is not active");
    return customer;
}
</code>```

Body:
What your methods are doing is not at all unreasonable. Its just unfortunate that their names are a bit of a mouthful.

For example where you have a method GetCustomerAndVerifyActive, surely you could call this GetActiveCustomer instead, and its easier on the eye? The new name doesn't detract from what the method actually does.

In summary I think your method names should reflect what the method does at a high level, not line-by-line. And certainly in .net you have the /// embellishments which allow you to specify what the method does in a more detailed way.

Example

/// <summary>
/// Returns an Active customer
/// </summary>
/// <param name="id">the customer's id</param>
/// <returns>the active customer</returns>
/// <remarks>Note this will throw an exception if the customer doesn't exist, or is inactive</remarks>
Customer GetActiveCustomer(int id)
{
    Customer customer = Db.GetCustomerById(id);
    if(!customer.IsActive) throw new Exception("Customer is not active");
    return customer;
}


答:
The sole point of "one responsibility" is to make programs easier to understand for human readers. Computing a certain path and making sure it exists can be seen as two different responsibilities, but they are certainly very closely related; I don't see a risk of confusing your understanding here, particularly as long as the lookup routine stays as short as it is now.

Certainly it is better than having to remember that the path, which you will probably want to manipulate after you've retrieved it, may not exist - that would require you to write twice as much code in every place where you use the routine, at a clear net loss.

A good litmus test for such questions is: if ensuring existence isn't this routine's job, whose job is it? Any utility you would write for the purpose would first have to call the path computation routine, so that they resemble a pair of conjoined twins - neither really with any purpose except in combination with the other. It can be good practice to refactor such "twin" routines into separate methods anyway for better readability, but not when both are as tiny as these are. (Note: this is an opinion. I am aware that there are people who refactor everything away when it is longer than one line.)

I have assumed here that you do actually need to ensure the existence of this path on every access. If that isn't the case, then you really do have two different tasks:

Hypothetically, if I had a , where would I put it?

Give me a location where I can put this  right now!

Those two would probably merit different methods.

Title: Is it a good practice to write a method that gets something and checks the value?

Body:
Occassinally I have to write methods like this:

```<code>string GetReportOutputDirectoryAndMakeSureExist()
{
    string path = Path.Combine ( ... ) //whatever logic
    if(!Directory.Exists(path)) Directory.Create(path);
    return path;
}
</code>```

or

```<code>string GetAndVerifyExistenceOfReportConfigurationPath()
{
    string path = Path.Combine ( ... ) //whatever logic to find the configuration
    if(!File.Exists(path)) throw new Exception("Report configuration not found");
    return path;
}
</code>```

or

```<code>Customer GetCustomerAndVerifyActive(int id)
{
    Customer customer = Db.GetCustomerById(id);
    if(!customer.IsActive) throw new Exception("Customer is not active");
    return customer;
}
</code>```

Is it a good practice? I am told that it is normally not a good idea for a method to do more than one things, or for a method to have side-effects (like creating directory). But if I split, for example the last metod to GetCustomer(id) and VerifyActive(customer), I will have to do:

```<code>var customer = GetCustomer(id);
VerifyActive(customer);
</code>```

consecutively at several places, and I think it counts as violation of DRY. Is this a good idea? Any idea how to help with the long method names?


答:
There two general principles at stake here:

single responsibility

smart interfaces

It is always a good idea that one entity, method or class, have one responsibility, but the interface to any function or class should be easy to use.

If it should always be verified and especially if it does not make any sense to use the object, which you get without verification, then you should verify it within the get method.

such long names for variables are not readable and not necessary. It is very sensible to just use the getVarName and let it do the check.


答:
The first two examples and the third one are quite different.

In the first two examples you first check a condition (if the path exists), and only then construct an object to return. This is absolutely acceptable.

What you do in the third example is retrieve data and check if the data is valid. I think this is over-complicated. It would be better to first check if the customer is active (maybe by adding a method to the DB layer for that) before retrieving it.

Throwing an exception if an object couldn't be created is IMHO over-complicated too. You could return null instead of throwing and exception, and then simply check for null instead of having try-catch blocks.

What comes for the methods names, you verbally describe all the steps in the methods _ retrieving, validating, checking. They can be easily simplified:

GetReportOutputDirectory instead of  GetReportOutputDirectoryAndMakeSureExist

GetReportConfigurationPath instead of GetAndVerifyExistenceOfReportConfigurationPath

GetActiveCustomer instead of GetCustomerAndVerifyActive

The methods are usually expected to return valid data, which can be guaranteed by pre-checking a condition. So I wouldn't say that the methods do two things: they return a valid object, which is quite reasonable.


答:
I am told that it is normally a good idea for a method to do two things, or for a method to have side-effects (like creating directory).

Well, it's normal that methods do more than one thing, i.e. we got used to it, but it is not advisable (generally speaking).

In your particular examples I see a very thin line between comfort/single responsibility and readability/seperation of concerns. The major problem I see, however, is that you encoded the methods' behavior in their names. E.g. GetReportOutputDirectoryAndMakeSureExist does exactly that in code. When you change the behavior slightly (e.g. add a dummy file in every new directory), you'd have to change the method name, too.

My suggestion (and it seems I'm not the only one) is to start with changing the method-names. For example GetReportOutputDirectoryAndMakeSureExist could be renamed to initReportOutputDirectory. Then you should take a look at the surrounding of the methods - is one method really used that often around in the project? Or just within a single class? I often find another segregation makes more sense, when looking back.


问:
Software Management Tools for Agile Process Development
We would like to implement the Agile/ Scrum process in our daily software management, so as to provide better progress visibility and feature managements, here are some of the activities that we want to do:

Daily stand-up

Release cycles of 6 weeks with 3 2-week iterations.

Having a product back-log of tasks (integrate with bugzilla) and bugs estimated out.

Printing a daily burn down to make velocity visible. When used as motivator, it's great.

Easy feature development tracking and full blown visibility, especially for the sales and stake holders ( this means that it must be a web based tool).

My team is distributed, so physical whiteboards aren't feasible.

Is there such a web based tool that meets our needs? I heard icescrum may be one, but I've never used it so I don't know.

There are a few more suggestions as here, but I've never heard of them, anyone cares to elaborate or suggest new tools?

答:
Years ago, a group of Agile coaches at Proteus Technologies were trying to find a decent Agile tool to help collaborating our Agile projects with their remote customers. Like many Agile teams, we started with physical story wall but having remote customers make this a challenge. In the attempt to keep customer as close to the team as possible, we tried to send pictures of the board and the cards on daily basis but it created too much overhead especially when our handwriting is not that clear! We then looked for electronic tools but none of them seem to fit. Most of the tools out there are bloated with unnecessary features that we will never use. At the end of the day, we ended up creating our own tool, Eidos. It was not perfect but it worked very well in our context.

Eidos is currently in beta but it is certainly good enough to run a project. We use Eidos to build Eidos and attached here is the screenshot of our current iteration.

Here is another screenshot when we bring up the release burndown.

If you are interested to check it out, feel free to sign up at http://theeidos.com/


问:
Training old timey fortran programmers to better code design. hints?
I need to quickly train Fortran 90 developers into object oriented design, good coding, and general coding practices to make code maintenance easier and accessible to everybody. Their current style is the usual:

long routines that do too much

modules are aggregated in "family mode" (routines that have something to do with different kind of objects who share a common use are all in one module, instead of having different modules for different type)

huge globals module with hundreds of variables

general un-greppability of identifiers

This is just out of my head. I did a course to one of them explaining OO and modularization in terms of a Pen (with methods such as uncap(), and members like inkLevel) and I was very successful in diverting his point of view. I also gave him the exercise to code in OO style a very simple textual adventure, where the player can move around rooms. I also introduced the concept of patterns and antipatterns.

I would like to know any hints and suggestions on how to perform this task at best.

Thanks

答:
This is an answer from a Java background, but I'm sure there are equivalent options elsewhere.
I'd get your guys into using JUnit or a similar automated-unit-test piece of kit.

1) I've found a number of 'procedural' people who struggle with the whole transition to OO simply for not understanding where the whole thing 'starts'. A unit test framework can give an easier learning curve rather than having to worry about how Application servers work.

2) Writing good JUnits pushes you towards accidentally writing good OO code... and once you've got the bug you find yourself churning out useful bits of recyclable code left right and center... This sort of thing may well help with the motivation to shift from oldskool to newskool...

In addition, once you've got people into the groove a bit, you can get good automated 'checkstyle' plug-ins for your IDE that will highlight things like excessive file-length, method lengths, global variables etc. etc. so If JUnit or similar can get them over the chasm of wanting to develop in an OO manner, some automated tools can then highlight the areas that want re-working with their new understanding!

ContentLicense: CC BY-SA 2.5


问:
Is physical Agile board "always" better than electronic tool?
Whenever the question comes up on which Agile tool to use use there always some people that answer "don't use an electronic tool because you will lose the big-visible-board advantage which better generate team conversation".

Is this always the case or are there any contexts where an electronic tool is a better choice?  What are some of the pros and cons of each approach?

答:
The short answer is "no".
The long answer starts with the realization that there are no absolutes in software development or most other fields: it all comes down to what you need and who will need it.

A physical whiteboard is an awfully versatile and useful thing.  You can write on it, you can tape things to it, you can put index cards on it with magnets and shuffle them around, you can get up and look at it even when the internet/intranet is down.  A whiteboard can contain very dense information - drawings, text.  It has a bigger effective resolution than a computer screen so you can see more information at once.

Overall, It is a low tech and easy-to-use tool for a lot of typical development communication and tracking.

Of course, a whiteboard is low tech and therefore many things we're used to as developers are not achievable, or difficult.  You cannot put hyperlinks to click on an index card on a whiteboard.  You may miss changes that other members have made to the whiteboard when you weren't looking. If your team is not all in the same room then some team members will not be able to interact with and around the whiteboard.  This is the most common argument against using whiteboards: they do not work very well with geographically distributed teams.

If you have a project manager then that project manager is likely to be interested in all sorts of metrics that could be easily derived from an electronic tool, not so from whiteboards.


问:
Best Practice for Argument Checking
Say I have a web service with a method MyWebServiceMethod(string passedValue).

The web service calls a method MyServiceMethod(string passedValue) where the value from the web service is passed along.

The service calls a repository method MyRepositoryMethod(string passedValue) where again, the value from the service is passed along.

I hope that is clear enough.  I can post code if need be.

My question is around null argument checking.

Should I check passedValue and throw an exception in:

The Web Service

The Service

The Repository

Obviously, if passedValue is null in the web service, the following methods will never get invoked but should I check in case the solution changes in the future?

Edit

I should have said that I don't expect null to ever be a valid value.

Also, My worry in these situations is that someone may change the web service or create another client with no argument checking that will call the service with invalid arguments.  So I tend to think the checking should be in both places.  Then I think of YAGNI and wonder if we should cross that bridge when we come to it.

What is considered best practice in these situations?

答:
As long as a "layer" expose a public interface with a contract, the null value should be checked. So in your case you should have 3 null checks.
This will allow you to be fool proof if MyServiceMethod or MyRepositoryMethod are invoked from somewhere else.</p>

OwnerDisplayName: davy

Title: Best Practice for Argument Checking


问:
Initializing derived classes in the same way
I have a class Base that has several children, say A, B, C. For testing purposes I'd like to mock those derived classes by deriving from them. So MockA derives from A, MockB derives from B and so on.

The problem is, that MockA, MockB, ... all inherit protected members from Base that have to be set in the same way in each mock class. The code looks like this:

```<code>MockA::init()
{
    x = 1;     // inherited from Base
    y = "abc"; // inherited from Base
    z = 0.5;   // inherited from Base
}

MockB::init()
{
    x = 1;     // inherited from Base
    y = "abc"; // inherited from Base
    z = 0.5;   // inherited from Base
}
</code>```

and so on.

So my question is, how can I avoid this cut&paste initialization? Can I achieve it without touching Base, A, B, C, ...?

答:
Well, you could introduce a static method which returns a default set of all protected member values and fetch them in each init method into the fields of the mock objects.

Edit:

```<code>MockA::init()
{
  initMock(MockInitializer.getDefaultValues());
  //go on with your code
}

MockA::initMock(anystruct def_values)
{
  //assign your values
}
</code>```

The problem is that in any place you'll have to do the assignment, why not do it in its own method?

Body:
Well, you could introduce a static method which returns a default set of all protected member values and fetch them in each init method into the fields of the mock objects.

Edit:

MockA::init()
{
  initMock(MockInitializer.getDefaultValues());
  //go on with your code
}

MockA::initMock(anystruct def_values)
{
  //assign your values
}

The problem is that in any place you'll have to do the assignment, why not do it in its own method?


问:
Is XML, HTML/CSS, XSL analogous to Model, View, Controller?
For some time in personal projects I have been using XSL to convert my raw XML data into human-friendly HTML/CSS (in simple projects, I have no JavaScript, so let's leave that out of the equation for simplicity).

Now I'm trying to understand the MVC architectural pattern (not my first experience with it, but it is taking some work to go from understanding it basically to understanding it well), and I'm wondering if there is an analogy between the two.

XML: data model; lacks the complexity/logic of a full-blown model component, but intent seems similar

XSL: converts raw data for viewing—seems like a controller

HTML/CSS (rendered): the viewable output

Is this analogy fitting? What in it matches well and what does not?

(One dissimilarity, I suppose, is that in my example I am not getting any input back from the view—only producing output.)

答:
Your analogy is flawed.

First of all, if you have a completely static website (no dynamic content at all), then I would say that you only have a set of Views. There is no Model and the small Controller part you need is completely taken care of by the webserver.

The task of the Controller is to update the Model based on the actions and input of the user and to decide what page to show next based on the result of that update. In your XML/XSL/HTML there is no component filling that role.
Assuming you XML is dynamically generated, it could be argued that the component generating the XML is (part of) the Controller. and the source for the XML is the Model.

What you have with your XML/XSL is only a View component. In most frameworks, the View consists of a collection of classes and the class' methods are the means to provide the relevant data to the View. In your case, the View consists of a collection of XSL specifications and XML is the means to provide data to the View. In both cases, the HTML is just the (ephemeral) output of the View.

Static content is usually not considered in the MVC triad, but if I must, I would classify it as part of the View.


问:
Why is 0 false?
This question may sound dumb, but why does 0 evaluates to false and any other [integer] value to true is most of programming languages?

String comparison

Since the question seems a little bit too simple, I will explain myself a little bit more: first of all, it may seem evident to any programmer, but why wouldn't there be a programming language - there may actually be, but not any I used - where 0 evaluates to true and all the other [integer] values to false? That one remark may seem random, but I have a few examples where it may have been a good idea. First of all, let's take the example of strings three-way comparison, I will take C's strcmp as example: any programmer trying C as his first language may be tempted to write the following code:

if (strcmp(str1, str2)) { // Do something... }
```

<p>Since <code>strcmp</code> returns <code>0</code> which evaluates to <code>false</code> when the strings are equal, what the beginning programmer tried to do fails miserably and he generally does not understand why at first. Had <code>0</code> evaluated to <code>true</code> instead, this function could have been used in its most simple expression - the one above - when comparing for equality, and the proper checks for <code>-1</code> and <code>1</code> would have been done only when needed. We would have considered the return type as <code>bool</code> (in our minds I mean) most of the time.</p>

<p>Moreover, let's introduce a new type, <code>sign</code>, that just takes values <code>-1</code>, <code>0</code> and <code>1</code>. That can be pretty handy. Imagine there is a spaceship operator in C++ and we want it for <code>std::string</code> (well, there already is the <code>compare</code> function, but spaceship operator is more fun). The declaration would currently be the following one:</p>

<pre class="lang-cpp prettyprint-override"><code>sign operator<=>(const std::string& lhs, const std::string& rhs);
</code>```

Had 0 been evaluated to true, the spaceship operator wouldn't even exist, and we could have declared operator== that way:

sign operator==(const std::string& lhs, const std::string& rhs);
```

<p>This <code>operator==</code> would have handled three-way comparison at once, and could still be used to perform the following check while still being able to check which string is lexicographically superior to the other when needed:</p>

<pre class="lang-cpp prettyprint-override"><code>if (str1 == str2) { // Do something... }
</code>```

Old errors handling

We now have exceptions, so this part only applies to the old languages where no such thing exist (C for example). If we look at C's standard library (and POSIX one too), we can see for sure that maaaaany functions return 0 when successful and any integer otherwise. I have sadly seen some people do this kind of things:

#define TRUE 0
// ...
if (some_function() == TRUE)
{
    // Here, TRUE would mean success...
    // Do something
}
```

<p>If we think about how we think in programming, we often have the following reasoning pattern:</p>

<pre class="lang-none prettyprint-override"><code>Do something
Did it work?
Yes ->
    That's ok, one case to handle
No ->
    Why? Many cases to handle
</code>```

If we think about it again, it would have made sense to put the only neutral value, 0, to yes (and that's how C's functions work), while all the other values can be there to solve the many cases of the no. However, in all the programming languages I know (except maybe some experimental esotheric languages), that yes evaluates to false in an if condition, while all the no cases evaluate to true. There are many situations when "it works" represents one case while "it does not work" represents many probable causes. If we think about it that way, having 0 evaluate to true and the rest to false would have made much more sense.

Conclusion

My conclusion is essentially my original question: why did we design languages where 0 is false and the other values are true, taking in account my few examples above and maybe some more I did not think of?

Follow-up: It's nice to see there are many answers with many ideas and as many possible reasons for it to be like that. I love how passionate you seem to be about it. I originaly asked this question out of boredom, but since you seem so passionate, I decided to go a little further and ask about the rationale behind the Boolean choice for 0 and 1 on Math.SE :)

答:
Zero can be false because most CPU's have a ZERO flag that can be used to branch.
It saves a compare operation.

Lets see why.

Some psuedocode, as the audience probably don't read assembly

c- source
simple loop calls wibble 10 times

for (int foo =10; foo>0; foo-- ) /* down count loop is shorter */
{
   wibble();
}
```

<p>some pretend assembly for that</p>

```0x1000 ld a 0x0a      'foo=10
0x1002 call 0x1234    'call wibble()
0x1005 dec a          'foo--
0x1006 jrnz -0x06      'jump back to 0x1000 if not zero
0x1008
```

<p>c- source
another simple loop calls wibble 10 times</p>

<pre class="lang-c prettyprint-override"><code>for (int foo =0; foo<10; foo-- ) /* up count loop is longer  */
{
   wibble();
}
</code>```

some pretend assembly for this case

```<code>0x1000 ld a 0x00      'foo=0
0x1002 call 0x1234    'call wibble()
0x1005 dec a          'foo--
0x1006 cmp 0x0a       'compare foo to 10 ( like a subtract but we throw the result away)
0x1008 jrns -0x08      'jump back to 0x1000 if compare was negative
0x100a
</code>```

some more c source

int foo=10;
if ( foo ) wibble()
```

<p>and the assembly </p>

```0x1000 ld a 0x10
0x1002 jz 0x3
0x1004 call 0x1234
0x1007
```

<p>see how short that is ?</p>

<p>some more c source</p>

<pre class="lang-c prettyprint-override"><code>int foo=10;
if ( foo==0 ) wibble()
</code>```

and the assembly (lets assume a marginally smart compiler that can replace ==0 with no compare)

```<code>0x1000 ld a 0x10
0x1002 jz 0x3
0x1004 call 0x1234
0x1007
</code>```

Now lets try a convention of true=1

some more c source
    #define TRUE 1
    int foo=TRUE;
    if ( foo==TRUE ) wibble()

and the assembly

```<code>0x1000 ld a 0x1
0x1002 cmp a 0x01
0x1004 jz 0x3
0x1006 call 0x1234
0x1009
</code>```

see how short the case with nonzero true is ?

Really early CPU's had small sets of flags attached to the Accumulator.

To check if a>b or a=b generally takes a compare instruction.

Unless B is either ZERO - in which case the ZERO flag is set
Implemented as a simple logical NOR or all bits in the Accumulator.

Or NEGATIVE in which just use the "sign bit" i.e. the most significant bit of the Accumulator if you are using two's complement arithmetic.  (Mostly we do)

Lets restate this. On some older CPU's you did not have to use a compare instruction for accumulator equal to ZERO, or accumulator less than zero.

Now do you see why zero might be false?

Please note this is psuedo-code and no real instruction set looks quite like this. If you know assembly you know I'm simplifying things a lot here. If you know anything about compiler design, you didn't need to read this answer. Anyone who knows anything about loop unrolling or branch prediction, the advanced class is down the hall in room 203.

Title: Why is 0 false?

Body:
Zero can be false because most CPU's have a ZERO flag that can be used to branch.
It saves a compare operation.

Lets see why.

Some psuedocode, as the audience probably don't read assembly

c- source
simple loop calls wibble 10 times

for (int foo =10; foo>0; foo-- ) /* down count loop is shorter */
{
   wibble();
}

some pretend assembly for that

0x1000 ld a 0x0a      'foo=10
0x1002 call 0x1234    'call wibble()
0x1005 dec a          'foo--
0x1006 jrnz -0x06      'jump back to 0x1000 if not zero
0x1008

c- source
another simple loop calls wibble 10 times

for (int foo =0; foo<10; foo-- ) /* up count loop is longer  */
{
   wibble();
}

some pretend assembly for this case

0x1000 ld a 0x00      'foo=0
0x1002 call 0x1234    'call wibble()
0x1005 dec a          'foo--
0x1006 cmp 0x0a       'compare foo to 10 ( like a subtract but we throw the result away)
0x1008 jrns -0x08      'jump back to 0x1000 if compare was negative
0x100a

some more c source

int foo=10;
if ( foo ) wibble()

and the assembly

0x1000 ld a 0x10
0x1002 jz 0x3
0x1004 call 0x1234
0x1007

see how short that is ?

some more c source

int foo=10;
if ( foo==0 ) wibble()

and the assembly (lets assume a marginally smart compiler that can replace ==0 with no compare)

0x1000 ld a 0x10
0x1002 jz 0x3
0x1004 call 0x1234
0x1007

Now lets try a convention of true=1

some more c source
    #define TRUE 1
    int foo=TRUE;
    if ( foo==TRUE ) wibble()

and the assembly

0x1000 ld a 0x1
0x1002 cmp a 0x01
0x1004 jz 0x3
0x1006 call 0x1234
0x1009

see how short the case with nonzero true is ?

Really early CPU's had small sets of flags attached to the Accumulator.

To check if a>b or a=b generally takes a compare instruction.

Unless B is either ZERO - in which case the ZERO flag is set
Implemented as a simple logical NOR or all bits in the Accumulator.

Or NEGATIVE in which just use the "sign bit" i.e. the most significant bit of the Accumulator if you are using two's complement arithmetic.  (Mostly we do)

Lets restate this. On some older CPU's you did not have to use a compare instruction for accumulator equal to ZERO, or accumulator less than zero.

Now do you see why zero might be false?

Please note this is psuedo-code and no real instruction set looks quite like this. If you know assembly you know I'm simplifying things a lot here. If you know anything about compiler design, you didn't need to read this answer. Anyone who knows anything about loop unrolling or branch prediction, the advanced class is down the hall in room 203.


答:
Here is how i would to that if I understand your problem :

```<code>
class Base
{
protected:
    initMock()
    {
        x = 1;
        y = "abc";
        z = 0.5;
    }
};

class A { /* Whatever you want ... */ };

class B { /* Whatever you want ... */ };

class MockA : public A, public Base
{
public:
    initMock()
    {
         Base::initMock();
    }

};
</code>```

And you can do the same thing with MockB.

Title: Initializing derived classes in the same way

Body:
I have a class Base that has several children, say A, B, C. For testing purposes I'd like to mock those derived classes by deriving from them. So MockA derives from A, MockB derives from B and so on.

The problem is, that MockA, MockB, ... all inherit protected members from Base that have to be set in the same way in each mock class. The code looks like this:

```<code>MockA::init()
{
    x = 1;     // inherited from Base
    y = "abc"; // inherited from Base
    z = 0.5;   // inherited from Base
}

MockB::init()
{
    x = 1;     // inherited from Base
    y = "abc"; // inherited from Base
    z = 0.5;   // inherited from Base
}
</code>```

and so on.

So my question is, how can I avoid this cut&paste initialization? Can I achieve it without touching Base, A, B, C, ...?

Body:
Here is how i would to that if I understand your problem :

class Base
{
protected:
    initMock()
    {
        x = 1;
        y = "abc";
        z = 0.5;
    }
};

class A { /* Whatever you want ... */ };

class B { /* Whatever you want ... */ };

class MockA : public A, public Base
{
public:
    initMock()
    {
         Base::initMock();
    }

};

And you can do the same thing with MockB.


答:
I thought this had to do with the "inheritance" from electronics, and also boolean algebra, where

0 = off, negative, no, false

1 = on, positive, yes, true

strcmp returns 0 when strings are equal has to do with its implementation, since what it actually does is to calculate the "distance" between the two strings. That 0 also happens to be considered false is just a coincidence.

returning 0 on success makes sense because 0 in this case is used to mean no error and any other number would be an error code. Using any other number for success would make less sense since you only have a single success code, while you can have several error codes. You use "Did it work?" as the if statement expression and say 0=yes would make more sense, but the expression is more correctly "Did anything go wrong?" and then you see that 0=no makes a lot of sense. Thinking of false/true doesn't really make sense here, as it's actually no error code/error code.

Title: Why is 0 false?

Body:
This question may sound dumb, but why does 0 evaluates to false and any other [integer] value to true is most of programming languages?

String comparison

Since the question seems a little bit too simple, I will explain myself a little bit more: first of all, it may seem evident to any programmer, but why wouldn't there be a programming language - there may actually be, but not any I used - where 0 evaluates to true and all the other [integer] values to false? That one remark may seem random, but I have a few examples where it may have been a good idea. First of all, let's take the example of strings three-way comparison, I will take C's strcmp as example: any programmer trying C as his first language may be tempted to write the following code:

if (strcmp(str1, str2)) { // Do something... }
```

<p>Since <code>strcmp</code> returns <code>0</code> which evaluates to <code>false</code> when the strings are equal, what the beginning programmer tried to do fails miserably and he generally does not understand why at first. Had <code>0</code> evaluated to <code>true</code> instead, this function could have been used in its most simple expression - the one above - when comparing for equality, and the proper checks for <code>-1</code> and <code>1</code> would have been done only when needed. We would have considered the return type as <code>bool</code> (in our minds I mean) most of the time.</p>

<p>Moreover, let's introduce a new type, <code>sign</code>, that just takes values <code>-1</code>, <code>0</code> and <code>1</code>. That can be pretty handy. Imagine there is a spaceship operator in C++ and we want it for <code>std::string</code> (well, there already is the <code>compare</code> function, but spaceship operator is more fun). The declaration would currently be the following one:</p>

<pre class="lang-cpp prettyprint-override"><code>sign operator<=>(const std::string& lhs, const std::string& rhs);
</code>```

Had 0 been evaluated to true, the spaceship operator wouldn't even exist, and we could have declared operator== that way:

sign operator==(const std::string& lhs, const std::string& rhs);
```

<p>This <code>operator==</code> would have handled three-way comparison at once, and could still be used to perform the following check while still being able to check which string is lexicographically superior to the other when needed:</p>

<pre class="lang-cpp prettyprint-override"><code>if (str1 == str2) { // Do something... }
</code>```

Old errors handling

We now have exceptions, so this part only applies to the old languages where no such thing exist (C for example). If we look at C's standard library (and POSIX one too), we can see for sure that maaaaany functions return 0 when successful and any integer otherwise. I have sadly seen some people do this kind of things:

#define TRUE 0
// ...
if (some_function() == TRUE)
{
    // Here, TRUE would mean success...
    // Do something
}
```

<p>If we think about how we think in programming, we often have the following reasoning pattern:</p>

<pre class="lang-none prettyprint-override"><code>Do something
Did it work?
Yes ->
    That's ok, one case to handle
No ->
    Why? Many cases to handle
</code>```

If we think about it again, it would have made sense to put the only neutral value, 0, to yes (and that's how C's functions work), while all the other values can be there to solve the many cases of the no. However, in all the programming languages I know (except maybe some experimental esotheric languages), that yes evaluates to false in an if condition, while all the no cases evaluate to true. There are many situations when "it works" represents one case while "it does not work" represents many probable causes. If we think about it that way, having 0 evaluate to true and the rest to false would have made much more sense.

Conclusion

My conclusion is essentially my original question: why did we design languages where 0 is false and the other values are true, taking in account my few examples above and maybe some more I did not think of?

Follow-up: It's nice to see there are many answers with many ideas and as many possible reasons for it to be like that. I love how passionate you seem to be about it. I originaly asked this question out of boredom, but since you seem so passionate, I decided to go a little further and ask about the rationale behind the Boolean choice for 0 and 1 on Math.SE :)


答:
Advantages of physical whiteboards:

Usually cheaper. Even free software requires a server to run on, data backed up and so on.

Easier to use than software, particularly for less technical people or those involved temporarily.

Easier to customize. Write on it, add a sticky note, add a heart sticker and so on. Many software packages are less flexible or require customization.

More visible. A whiteboard in a common area is something people see everyday. It reinforces the tasks at hand, communicates process and can be impressive to those outside the team. Acts as a focus point - a team "campfire" where people meet and discuss team issues.

A minor point but some people also like the tactile satisfaction of moving a sticky note from one column to the next or creativity in drawing pictures and symbols to show state or impediments rather than looking at columns of text.

Advantages of electronic tools (usually software):

Easier to backup. "Backing up" a physical whiteboard or even keeping it in sync with software can be time consuming and frustrating.

Keeps history and an audit log whereas a whiteboard only shows current tasks.

Less fragile. Sticky notes on a physical whiteboard can fall off. Writing can be erased or smudged. Important details can get lost.

Scales up beyond the physical surface size to more tasks and people, particularly with a projector.

Automated integration with other tools, such as defect tracking and project management.

Can enforce standardized process, such as phases or steps.

Can produce metrics, graphs and reports automatically, such as burn down charts.

Can be distributed across different teams in the same building, different buildings, different cities or even different countries.

I would recommend prototyping new processes with a whiteboard or similar but, as the team scales up or out, move to an electronic system. Losing your team's status to spilled coffee is hard to explain to management. That said, every team is different and, as others have said, there are few, if any, absolutes in software development.

Title: Is physical Agile board "always" better than electronic tool?

Body:
Whenever the question comes up on which Agile tool to use use there always some people that answer "don't use an electronic tool because you will lose the big-visible-board advantage which better generate team conversation".

Is this always the case or are there any contexts where an electronic tool is a better choice?  What are some of the pros and cons of each approach?


答:
You want a "mixin". In C++ they are usually implemented with templates and specifically using CRTP, the "curiously recurring template pattern". It might be an overkill if it's just a bit of common code, than Pierre's answer seems most appropriate. But as the amount of common code for the mock classes grows, so will value of template.

Basic CRTP would go like this:

```<code>template <typename ConcreteT> class Mock {
    initMock() {
        static_cast<ConcreteT *>(this)->x = 1;
        static_cast<ConcreteT *>(this)->y = "abc";
        static_cast<ConcreteT *>(this)->z = 0.5;
    }
};

class MockA : A, Mock<MockA> { ... };
//                    ^^^^^ specialized on the type that inherits it, that's the point
</code>```

Here it would make things simple to inherit A through the Mock class though, so

```<code>template <typename BaseT> class Mock : public BaseT {
    initMock() {
        x = 1;
        y = "abc";
        z = 0.5;
    }
};

class MockA : Mock<A> { ... };
//                 ^ just the base class
</code>```

That does away with the ugly static_casts, but does not allow you to provide methods in MockA that will be called by Mock. But you can have both...

```<code>template<typename ConcreteT, typename BaseT>
class Mock : public BaseT { ... };

class MockA : Mock<MockA, A> { ... };
</code>```

Now Mock can call methods of MockA on itself via static cast and call methods of A (or rather the ultimate base) directly.

Note: The mixin templates are basically the same thing as mixins in Ruby or interfaces with method implementations introduced in Java 8. Those languages it is a special construct, because they don't have anything of the power of C++ templates, but the implementation is similar—an intermediate class is constructed by compiler and injected in the hierarchy.

Body:
You want a "mixin". In C++ they are usually implemented with templates and specifically using CRTP, the "curiously recurring template pattern". It might be an overkill if it's just a bit of common code, than Pierre's answer seems most appropriate. But as the amount of common code for the mock classes grows, so will value of template.

Basic CRTP would go like this:

template <typename ConcreteT> class Mock {
    initMock() {
        static_cast<ConcreteT *>(this)->x = 1;
        static_cast<ConcreteT *>(this)->y = "abc";
        static_cast<ConcreteT *>(this)->z = 0.5;
    }
};

class MockA : A, Mock<MockA> { ... };
//                    ^^^^^ specialized on the type that inherits it, that's the point

Here it would make things simple to inherit A through the Mock class though, so

template <typename BaseT> class Mock : public BaseT {
    initMock() {
        x = 1;
        y = "abc";
        z = 0.5;
    }
};

class MockA : Mock<A> { ... };
//                 ^ just the base class

That does away with the ugly static_casts, but does not allow you to provide methods in MockA that will be called by Mock. But you can have both...

template<typename ConcreteT, typename BaseT>
class Mock : public BaseT { ... };

class MockA : Mock<MockA, A> { ... };

Now Mock can call methods of MockA on itself via static cast and call methods of A (or rather the ultimate base) directly.

Note: The mixin templates are basically the same thing as mixins in Ruby or interfaces with method implementations introduced in Java 8. Those languages it is a special construct, because they don't have anything of the power of C++ templates, but the implementation is similar—an intermediate class is constructed by compiler and injected in the hierarchy.


问:
Chain class behaviour
I have a Bird class.
A bird can learn and a bird can fly (methods).
A bird can only fly after it learns.

Considering both methods are public. How can you make this clear to another fellow developer. Usually they should take a look at the public method names and understand what they do. But how can he understand without reading comments or understand the encapsulated code that method2 can be called only after method1?

答:
The accepted answer is not up to OO standards as I understand this solution, because it would imply the object changing class. First we dealt with an instance of Bird, then with an instance of EducatedBird.

This is an anti-pattern requiring you to copy state of the old object to the new, and to check that all references to the "old" object now point to the "new" object.

A State pattern implementation is better: a Bird has an association with Education. This is an abstract class. The actual instance a Bird has a relation with is an instance of a concrete subclass. The Bird instance remains the same throughout its life.

When a Bird is born, its Education is actually an instance of a subclass of Education called, say, "None".

Actually you could delegate the responsibility of "learning" to that class, thereby making Bird simpler (everything related to education is delegated out of the class). So that the Bird will soon become "Novice" and then move on from "Grad" to "Master" and finally "Guru", so it will be able to post on Stack Exchange ;-)

Title: Chain class behaviour


答:
If Base is the common base class of A, B, C holding protected members Base::x, Base::y, etc., then I guess there are accessor methods like

```<code>Base::SetX(type_x xval){x=_val;}
</code>```

etc. So write a static function in a helper class MockInit

```<code>void MockInit::initForTests(Base &b)
{
    b.SetX(1);
    b.SetY("abc");
    b.SetZ(0.5);
}
</code>```

and call that function this way:

```<code>MockA::init()
{
     MockInit::initForTests(*this);
}

MockB::init()
{
     MockInit::initForTests(*this);
}
</code>```

That's it - simple and stupid. However, if there are no such accessor methods, and you have you have absolutely no access to x,y,z from outside the inheritance hierarchy, I would consider changing the initial design of Base for better testability. At least, I would consider to make MockInit a friend class of Base.

Body:
If Base is the common base class of A, B, C holding protected members Base::x, Base::y, etc., then I guess there are accessor methods like

Base::SetX(type_x xval){x=_val;}

etc. So write a static function in a helper class MockInit

void MockInit::initForTests(Base &b)
{
    b.SetX(1);
    b.SetY("abc");
    b.SetZ(0.5);
}

and call that function this way:

MockA::init()
{
     MockInit::initForTests(*this);
}

MockB::init()
{
     MockInit::initForTests(*this);
}

That's it - simple and stupid. However, if there are no such accessor methods, and you have you have absolutely no access to x,y,z from outside the inheritance hierarchy, I would consider changing the initial design of Base for better testability. At least, I would consider to make MockInit a friend class of Base.


问:
Find common functionalities or functions between 2 programs
I've been facing a problem recently, in which I want to optimize two programs.

For that, I wanted to create some kind of "Common Interface" which I could reuse between my two programs.

However, the code of these are approximately 1000 lines, and I don't want to spend a big amount of time checking if this or that function is the same as this one and whatsoever.

So I used BOUML to check the similarities between class diagrams. But I wonder if there is a global way to do such a study ?

答:
Well, I assume that you know the functionality of both programs. Extracting the common interface is a regular refactoring job since you probably just want to remove code duplication.

So just load your two programs in any IDE and look at the outline view where the classes/method signatures are shown. Since you know the functionality of both programs it shouldn't be a difficult task to find the duplicate code parts.


答:
What you listed can be grouped by programming language paradigm:

Declarative: X(A)ML, (X)HTML.

Imperative: "raw code".

If you really want to think outside of the box, then you need to check other paradigms.
Seeing how fashionable functional paradigm has become, it might be worth thinking around that area, some inspiration: http://www.chris-granger.com/2013/01/24/the-ide-as-data/

It could also be worth looking through modern JS frameworks. For example D3 has an interesting approach.

Title: Other than XML, what are some examples of "coding" a GUI design?

Body:
I've been trying to think outside of the box as to how desktop GUIs can be designed in code(not a graphical designer!). I've come across basically three ways this is done:

XML

Raw code (create a window, create a text box, add text box to window, etc)

HTML and friends

I'm sure that someone has done something other than these three though. Are there any existing examples of frameworks or languages which allow you to code a GUI using a format other than these three


问:
When to refactor
I've read through most of Fowler's Refactoring book and have refactored many applications in my past big and small.

One of the harder things I find to teach is "when" to refactor.  I tend to do this based on a gut feel which has served me remarkably well in the past.  However, when getting into discussions with people about whether a piece of code should be left alone or refactored right now it is hard to stand by the "gut check".

I feel like there should be more rigorous approaches to this, but am not sure what they are.

I understand "code-smells", red-green-refactor and other thoughts, but often I feel that the best time to refactor is not the first time you write the code, but the second or third time you are using the code and realize that it is actually a problem and is in actual use.

答:
Is the cyclomatic complexity of the function below 5?

Did you completely understand what cyclomatic complexity was without following that link?

Do you have an automated test or documented test case for every path through the function?

Do all of the existing test cases pass?

Can you explain the function and all it's edge cases to me in less than 1 minute?

If not, how about 5 minutes?

10 minutes?

Are there fewer than 100 lines of code in the function (including comments)?

Can you find two other developers who agree this code is error free just by visual inspection?

Is this function used in only one place?

Does the function meet it's performance goals (Time/Memory/CPU)?

Scoring

Add up the "no" answers above:

0-1 - Why would you even think about refactoring this?  You probably just want to rename variables because you don't like the previous developer's naming convention

2-5 - This might need a little tweaking, but I wouldn't hold up a production release for something in this range

6-8 - OK, we probably need to fix this... It's likely we're going to keep revisiting this and/or we don't actually know what it's doing.  Still on the fence, but it's highly suspect

9+ - This is a prime candidate for refactoring.  (Note, writing test cases is a form of refactoring)

http://mikemainguy.blogspot.com/2013/05/when-to-refactor-code.html

Title: When to refactor


答:
Though the internals are XML-based, Apple's Interface Builder offers a graphical interface for coding GUIs.

application for Apple's Mac OS X operating system. It is part of Xcode (formerly Project Builder), the Apple Developer Connection developer's toolset. Interface Builder allows Cocoa and Carbon developers to create interfaces for applications using a graphical user interface. The resulting interface is stored as a .nib file, short for NeXT Interface Builder, or more recently, as a .xib file...


问:
Useful Scripts for CM?
I'll be forming a remote team, and I want to be able to use scripts (or something) to make sure that people's code is checked in every night.  I currently use some BASH scripts that are kindof wonky and aren't customizable easily.

Does anyone have any useful tools, tips, or resources for this?

Are there any pitfalls to doing this that I'm not seeing, or can I do it better another way?

(cross-posted to super-user)

答:
There's no real reason for not using revision control as a form of backup, as long as you have a backup plan for your repository.

If you are willing to educate your developers and administer your revision control system of choice, you can use tags and/or branches to handle the broken code issue.

As a matter of fact, I think that tagging (or branching) your release, beta and alpha code is the best way to go.  This way it requires an active decision to screw up your released product instead of an 'oh shit' moment by a developer.

Title: Useful Scripts for CM?


问:
Standard Java Error Reporting
I am currently working on creating a toolkit for work and I've gotten to the point where I'm wondering about error reporting.

Basically all of my tools, which consist of a grouping of classes, will eventually be ran from a main method.  Many of these tools will be doing operations on file like reading them in and converting them into some sort of array of objects or writing an object array to a file in a certain format. Whenever you are dealing with data that your program didn't create there is always room for error and those errors need to be known.

With that said what would be a good method to document all of the errors that occur during the processing and allow them to be retrieved later?  Considering that I may want to send these error information out later I don't think that Log4J would be a good fit.  I was considering using a string builder in each of my processing classes and append all error to that builder and retrieve it later at my leisure.  I was also thinking of using some sort of arrayList or something that would hold the different types of errors but I'm a bit at a loss.

Does anyone have any good methods of doing this?

答:
It sounds like you are trying to enable remote logging.  Log4J is a fine fit for this.  What you can do in the most basic way possible is open up a socket that sends data to a message queue.  This message queue will have a listener attached to it that can handle the different log messages it receives.  This data can later be persisted into a database which you can than query against to generate reports.

Using StringBuilder makes very little to no sense, because it sounds like you are trying to just consume a bunch of space on the host system.

FROM THE COMMENTS

Correct, once these errors are fixed I no longer need them. Is it
  standard practice to funnel all errors from applications into a single
  database? I don't mind keeping the data if this is the correct method
  of doing so however only the newest information will be looked at

It is more a standard practice to keep a dedicated audit log, depending on your policy / legal requirements this can be anywhere from 90 days to 2 years.  This enables you to go back and prove that steps were taken to mitigate compliance issues, track down malicious activity, etc.  While it is true that logs are only good for a limited period of time, it is greatly beneficial to see audit logs when you are trying to track down a recurring issue in the system.

OwnerDisplayName: David Wallace

Title: Standard Java Error Reporting


问:
Apache license in non-Apache licensed software; how to distinguish?
The Apache License states:

"You must give any other recipients of the Work or Derivative Works a copy of this License;"

So if you've copied a bunch of functions from some Apache-licensed code (so it's not just linking, you've borrowed code) into a product that is not itself Apache-licensed, what's a good way to indicate that the license you included only applies to some bits of code in your product, not to the product as a whole?  (To avoid the suggestion that the product as a whole is freely copyable.)

Should a list of projects you've borrowed from and their various licenses be included in the "About" screen for the product, insisting that the licenses only apply to those bits?  I'm asking because that seems to make sense, but I don't recall seeing that anywhere.

答:
From a coding perspective, try your best to segregate and encapsulate the Apache parts.

From a license perspective, I would just note in the About screen "Some aspects of the $myproduct codebase covered under the Apache license" or something like that. You don't need to specify which pieces, unless there's a specific, named algorithm that you're borrowing,


答:
Enyo is essentially a GUI layer designed to be implemented in pure javaScript, as opposed to HTML.  For that matter, you can think of jQuery UI in a similar fashion.

Even if you use a WYSIWYG designer, the GUI will be spelled out in some code format.  Depending on what toolkit you use, it may be easy to write that format by hand, or it may be annoyingly difficult.


问:
Why is it impossible for Google to port V8 along with Chrome's codebase in C/Obj-C on iOS?
Google has given a reason that All apps on iOS have to run in the sandbox environment except for special apps by apple that get to tap into some private APIs.

So Chrome on iOS uses whatever the UIWebView provides  plus it might be doing its UI stuff and some external caching to add something extra to it.

But Why does Google need access to Nitro engine that Safari on iOS has access to.

Can't Chrome port the whole webkit engine and V8 for iOS ?

Xamarin 2.0 manages to port mono (.net runtime) on iOS along with every app.

答:
There are two reasons.

Apple wants to review all code that runs on an iOS device in order to ensure the quality of the overall platform. Obviously, in order to review the code, they need to have it. So, Apple requires that all code that is run by your app, needs to be either part of the app or part of the public iOS APIs. You can embed an execution engine in your app, but you cannot execute code downloaded from the web. However, the whole point of an ECMAScript engine in a web browser is to execute arbitrary code from the web.

[Note: I'm not 100% sure about this.] The iOS security model does not allow an app to execute native code from writeable memory. Memory is either writeable or executable (but read-only). However, V8 is a pure compiler, it doesn't have an interpreter. It compiles ECMAScript to native code in memory, then executes it. But the security model prevents this. So, Google would have to first develop an interpreter for V8. But that would be potentially devastating for performance, and would be a substantial development effort.

Xamarin 2.0 manages to port mono (.net runtime) on iOS along with every app.

The code that is executed by the Mono runtime in this case is all part of the app. No code is downloaded from anywhere.

Mono contains an interpreter.


问:
Is it possible to import vb.net form to blend?
I have created a windows form using visual studio design, that is simply drag n drop component into the form from Toolbox.
Is it possible to import it into Blend and change its appearence using Blend?

I opened the project from Blend but ony the code appears not the form itself.

Thanks in advance!

答:
No - winforms applications are not WPF applications.

Blends knows XAML, the markup language of WPF applications - it has no understanding of winforms.

If you want to work with both Blend and Visual Studio in one project, use WPF.


答:
If both programs are from the same author, and you have the suspicion that the author might have copy-pasted some functions from one program to the other, using a tool like "diff" (or WinDiff or WinMerge) may help you to find some of that code blocks. Of course, this works only if you do not have too many source code files (which I guess is unlikely, since 1000 lines of code is not really huge).

However, if you want to find functions or code blocks which do essentially the same, but the functions in stake have a completely different implementation, there is IMHO no short-cut to learn and understand what the code does (at least the parts you want to merge). Before refactoring common functionality, you have to be sure that the code you want to refactor really does the same. You may not have to understand the full code, but even for identifying candidates, a rough understanding of the functions is IMHO necessary.

Title: Find common functionalities or functions between 2 programs

Body:
I've been facing a problem recently, in which I want to optimize two programs.

For that, I wanted to create some kind of "Common Interface" which I could reuse between my two programs.

However, the code of these are approximately 1000 lines, and I don't want to spend a big amount of time checking if this or that function is the same as this one and whatsoever.

So I used BOUML to check the similarities between class diagrams. But I wonder if there is a global way to do such a study ?


问:
How can I bootstrap a software development community at my school?
I'm a student at the University of South Florida who's frustrated with the educational environment in the Computer Science program. Right now, I'm taking "Program Design." I should be learning how to organize my source code into functions and modules in order to make my programs readable and maintainable; instead, I'm learning about arrays and recursion in C. Next semester, I have to take "Object-Oriented Design," which is taught through C++ (shudder.)

Two years ago, I fell in love with programming, and I've been learning as much as I could since then. The prospect of taking another C++ class bores me almost to tears. For that reason, I thought I would start a programming club in order to meet similarly ambitious students, learn new languages, discuss software development topics, and work with other students developers.

However, I'm beginning to realize that there may not be any other students who share my software development experience. It's not because of a lack of motivation but a lack of opportunity: I know of only one other programming class ("Programming Languages") and no classes on real-world software development. Everybody else only has experience writing trivial scripts in C and C++.

I've realized that if I want to work with other student software developers, I'm going to have to train them myself. Now, I'm planning to make the club a software development bootcamp, teaching members how to develop software with modern tools and languages. Obviously, starting an unofficial software development course is a monumental task with many possible approaches. My question to you, dear reader, is

What's my plan of attack?

Should I

lecture the club myself, trying to balance club work with homework?

ask the CS faculty to teach on topics within their expertise which may be less than relevant to members?

try to find a sympathetic, experienced developer inside or outside the school who can share my workload?

show video lectures (from MIT OpenCourseWare, Google Tech Talks, etc)?

hold hands-on programming workshops?

assign homework?

do something else?

答:
How about finding an open-source project (or more than one) that your group is interested in contributing to?

I think the biggest challenge you're likely to face is that while writing code is fun, it's all the surrounding admin etc. that can rapidly turn it into a painful experience. If you can find an existing open-source project you should at least have some of the support framework in place.

Open source will get you into some good habits, and although you'll be a bit wet behind the ears compared to some of the contributors you will have one major advantage over other people- you'll all be in the same location and able to hold conversations with your team members which is normally one of the biggest pains with open source community work...


问:
Would Task-based programming in C++ require new language standard features?
So I saw this video on Youtube with all these C++ masters on GoingNative 2012 : Interactive panel where everybody could ask the questions.

This is the video I was talking about: GoingNative 2012 - Day 1 - Interactive Panel: The importance of being native

And at time 0:24:00 someone put a very interesting question:

We've been doing concurrent programming for some time using pthreads,
  using windows threads, and so on and I'm so happy that C++ and C
  caught up with concurrent programming, but it seems to me like it's
  already behind by five years or ten years because right now we have we
  have all these powerful multicores and the programming of these
  multicores really should not be based on threads, it should be
  task-based [...] and Microsoft has  the PPL library and so on and
  this is totally not reflecting in the C++ standard. [...] The only
  thing I'm afraid of is that the standard could be locked into threads
  and sort of make it very difficult to move to Task-Based
  Programming...

Now I'm quite new to these concepts and I'm a little confused. What is actually Task-Based Programming. Does this term refer to the same thing that Lock-Free Programming refers to? Are these two equivalent terms or are there any links between them?

答:
Microsoft has the "Task Parallel Library," or TPL.

It's a higher-level abstraction over threads, and it's library-based, so I see no reason why something similar could not be built in C++, since the TPL is already thread-based, and it doesn't depend on special features in the language standard for its implementation (although the keywords async and await were added to the C# compiler to make such programming easier).

A Task in the Microsoft ecostructure is more or less equivalent to a Future or a Promise.  Basically, it's a non-blocking (asynchronous) function; you call it, it returns control back to you while it executes on a new thread, and then you retrieve the return value at some later time when it becomes available.

The TPL has other facilities like Parallel.For, which allows you to process a loop concurrently, using multiple threads.  All of these things could be implemented in C++ as library functions.  In fact, such a library has already been written.

As far as I know, the PPL (Parallel Patterns Library for Microsoft C++) doesn't depend on any special language features.


问:
Returning a boolean when success or failure is the sole concern
I often find myself returning a boolean from a method, that's used in multiple locations, in order to contain all the logic around that method in a single place. All the (internal) calling method needs to know is whether the operation was successful, or not.

I'm using Python but the question isn't necessarily specific to that language. There are only two options I can think of

Raise an exception, though the circumstances are not exceptional, and remember to catch that exception in every place the function is called

Return a boolean as I'm doing.

This is a really simple example that demonstrates what I'm talking about.

```<code>import os

class DoSomething(object):

    def remove_file(self, filename):

        try:
            os.remove(filename)
        except OSError:
            return False

        return True

    def process_file(self, filename):

        do_something()

        if remove_file(filename):
            do_something_else()
</code>```

Although it's functional, I really dislike this manner of doing something, it "smells", and can sometimes result in a lot of nested ifs. But, I can't think of a simpler way.

I could turn to a more LBYL philosophy and use os.path.exists(filename) prior to attempting deletion but there's no guarantees the file won't have been locked in the meantime (it's unlikely but possible) and I still have to determine whether the deletion has been successful or not.

Is this an "acceptable" design and if not what would be a better way of designing this?

答:
You should return boolean when the method/function is useful in making logical decisions.

You should throw an exception when the method/function isn't likely to be used in logical decisions.

You have to make a decision about how important the failure is, and if it should be handled or not. If you could classify the failure as a warning, then return boolean. If the object enters a bad state that make future calls to it unstable, then throw an exception.

Another practice is to return objects instead of a result. If you call open, then it should return a File object or null if unable to open. This ensures the programmers has an object instance that is in a valid state that can be used.

EDIT:

Keep in mind that most languages will discard the result of a function when it's type is boolean or integer. So it's possible to call the function when there is no left hand assignment for the result. When working with boolean results, always assume the programmer is ignoring the returned value and use that to decide if it should rather be an exception.


问:
Who gets source code access with agpl
After reading for what seems days on the specifics of GPLv3 and more specifically AGPLv3, I have one question as far as distributing and to whom.

If I create a web app (server and client) for a client. They pay me, I hand over all source and ownership. The web app is currently only accessible to employees and contractors; but for the sake of argument, it could be anyone since it's on the internet.

The AGPLv3 code is not modified (in this case iText), it is used to generate a PDF from other text (and all this [could] happen in its own project/dll completely separated from the main web app). To who does the source have to be released and shared with:

Employees

Any user of the app

Any non-employee user (clause for distribution within an organization's employees)

答:
The AGPL has a clause in it that specifically closes the loophole of the application (because it is a web application) not actually being distributed.  All users are granted access to all of the application's source code.

However, if you can demonstrate that

iText is not required for your application to function, but merely adds an additional feature to it, and

You communicate "at arms length" with iText, and do not "link" your code with iText

then you might be able to assert that iText is a separate application, and therefore is subject to different distribution terms.  More info here: http://www.gnu.org/licenses/old-licenses/gpl-2.0-faq.html#GPLInProprietarySystem

All that said, if iText has licensed their software under the AGPL, it's a pretty strong indicator that they expect it to be used in a copyleft fashion under all circumstances.  Note that a commercial license of iText is available, which will release you from the AGPL's restrictions.

Title: Who gets source code access with agpl


问:
How to modularize and package a client-side Javascript library today?
I've been catching up with the modern client-side JS ecosystem and reading up on CommonJS and AMD (incl. associated tools - browserify, requirejs, onejs, jam, dozens of others).  If I'm writing a Javascript library, how do I modularize/package it such that it can be most broadly accessible (ideally by users who swear by CommonJS, AMD, and especially neither)?

Popular libraries like jQuery seem to just use old-school file concatenation for building itself and dynamically detect whether it should write to an exports or the global context.  I'm currently doing the same thing, but the main downside is that if I (unlike jQuery) depend on a few libraries, it's nice to not have to ask users to manually pre-include the transitive set.  (Though I currently just have two dependencies.)  And of course global namespace pollution.

Or perhaps it's cleanest to generate multiple versions of my library, for each context?

I'm also wondering about packaging and publishing.  There are several systems, but I believe the major one is bower, which is easy to deal with since all it does is fetch.  However, I'm wondering if I should also be targeting other package systems like component (which requires CommonJS).

Are there other relevant aspects I should be aware of?  Are there any good example projects to follow for all of this?

答:
I've always used to use build files but since I started my first nodejs project I started using  browserify. With browerify and other similar libraries your code is your build file.  I am taking advantage of a client and server library that can run on both but it can also work with purely client code.
To sum it up browserify gives you all the benefits of writing code in node (no anon functions to avoid globals, npm, simple requires) and it allows you to package that code to run on the client with one command and only load one file.

With browserify you can do something like (named app.js):

```<code>var MyLib = require('../myLib');

if(typeof window !== 'undefined') {
    window.MyLib = MyLib;
    window._ = require('underscore');
    window.$ = require('$');
    window.MyLib.myCan = require('./3rdParty/can/can');
}
</code>```

browserify app.js > client.js

Would produce something like:

```<code>[function(require,module,exports){
    window.MyLib = //MyLib code
},
function(require,module,exports){
     window._ = //_ code
},
function(require,module,exports){
    window.$ = //$ code
},
function(require,module,exports){
    window.MyLib.myCan = //can code
}
</code>```

The file that you would define could have all your 3rd party libs included and not clash with any of your developers that use it.

--Edit in respond to the comment (and a complete miss on the question)

I guess that would depend on your dependencies and how much time you want to spend making sure they work across all versions and libs.  If your dependencies are common and follow the same api from version to version you could go the Backbone route and just require the user to have $ and _.  I would suggest putting the more obscure libs as part of the bundled file.  The options don't have to be cut and dry either.  You could offer a pre-built or build your own package.

Body:
I've always used to use build files but since I started my first nodejs project I started using  browserify. With browerify and other similar libraries your code is your build file.  I am taking advantage of a client and server library that can run on both but it can also work with purely client code.
To sum it up browserify gives you all the benefits of writing code in node (no anon functions to avoid globals, npm, simple requires) and it allows you to package that code to run on the client with one command and only load one file.

With browserify you can do something like (named app.js):

var MyLib = require('../myLib');

if(typeof window !== 'undefined') {
    window.MyLib = MyLib;
    window._ = require('underscore');
    window.$ = require('$');
    window.MyLib.myCan = require('./3rdParty/can/can');
}

browserify app.js > client.js

Would produce something like:

[function(require,module,exports){
    window.MyLib = //MyLib code
},
function(require,module,exports){
     window._ = //_ code
},
function(require,module,exports){
    window.$ = //$ code
},
function(require,module,exports){
    window.MyLib.myCan = //can code
}

The file that you would define could have all your 3rd party libs included and not clash with any of your developers that use it.

--Edit in respond to the comment (and a complete miss on the question)

I guess that would depend on your dependencies and how much time you want to spend making sure they work across all versions and libs.  If your dependencies are common and follow the same api from version to version you could go the Backbone route and just require the user to have $ and _.  I would suggest putting the more obscure libs as part of the bundled file.  The options don't have to be cut and dry either.  You could offer a pre-built or build your own package.


问:
Find the count of each word in a string
I am in a search of a better performant algorithm to implement a program, to find the count of each word in a sentence i.e.., a String in the programming sense.

I know my algorithm is too basic and Noob. Here's my algorithm.

Read the String.

Tokenize the String with the delimiter, put each token in a list(ArrayList).

Iterate the generated list, in each iteration compare the current string with every other string of the list, if it matches increase the count of this string.

For each iteration, put the String and its count in a map.

Iterate the map and display, with key as string and value as its count.

What is the best approach than this?

答:
Replace steps 3 and 4 with the following

If string is not in the map, store it in the map with value Integer.valueOf(1)

If is already in the map, get the current value, increment it, and replace the mapping.

Title: Find the count of each word in a string


问:
I use an IDE (Eclipse) to develop software.  Why should I switch to vim or emacs?
My day job is  java/web developer. I have been using eclipse for ~5years. I think its excellent and I also use Webstorm for javascript and html/jsp.

I do on occasion need to ssh into server and mess around with config files; for this I use vi and it pains me. I have to get up a webpage listing the syntax/commands : press escape, then asterix, turn around three times and the text will be entered two lines above your cursor. Its so unintuitive to me, and I imagine anyone who grew up in the late eighties nineties.

Here are the main reasons I think eclipse is brilliant(and I assume other IDE's), and do not switch to emacs and/or vim.

Error highlighting with no need to
recompile project.

Code assist.

Refactoring.

Opening call hiearchy/Opening
declaration.

Fully integrated with source control.

Debugger is included.

availablity of 3rd party plugins - eg
findbugs/checkstyle.

One of the arguments I hear is that with emacs/vim you can create your own plugins - well OK, but you can do that in eclipse too. But you don't need to as everything is already there!  Its like saying buy this half built car, you can build the rest yourself.

Why are people using emacs/vim ? Do people who use it actually work on complex object-oriented projects in large organisations ?

What are the reasons to switch to vim/emacs. How would my productivity increase if I did switch?

答:
Both emacs and vim are very configurable and powerful editors, and both provide big productivity wins once the basic concepts are grasped.

Vi wins with what are essentially set-based operations. For example, changing all instances of "foo" to "bar" in a class definition is a one-liner.

Emacs is equally powerful, but you have to learn Emacs Lisp to use it to its full potential.

In either case, it's only worth switching if you plan to use emacs or vi for everything.


答:
The inefficient part of your algorithm is in fact the ArrayList, because it can't be traversed in a efficient way. The appropriate data structure is in your case a binary tree.

A very detailed discussion of binary trees: http://www.shiffman.net/teaching/a2z/concordance/

Title: Find the count of each word in a string

Body:
I am in a search of a better performant algorithm to implement a program, to find the count of each word in a sentence i.e.., a String in the programming sense.

I know my algorithm is too basic and Noob. Here's my algorithm.

Read the String.

Tokenize the String with the delimiter, put each token in a list(ArrayList).

Iterate the generated list, in each iteration compare the current string with every other string of the list, if it matches increase the count of this string.

For each iteration, put the String and its count in a map.

Iterate the map and display, with key as string and value as its count.

What is the best approach than this?


答:
There have been threads-via-blocks libraries for ages in cpp.
There's Intel's Thread Building Blocks that is quite good, and then there's similar things like OpenMP that allows you to abstract threading in a 'let the system do it for you' kind of way (this is supported by VC++, you have to set the /openmp flag in your builds)

Microsoft is also working on Casablanca, which might not be a truly generic task library, but is a framework for writing task-based systems (mainly for web app purposes) using something similar to Erlang's actor model

Title: Would Task-based programming in C++ require new language standard features?

Body:
So I saw this video on Youtube with all these C++ masters on GoingNative 2012 : Interactive panel where everybody could ask the questions.

This is the video I was talking about: GoingNative 2012 - Day 1 - Interactive Panel: The importance of being native

And at time 0:24:00 someone put a very interesting question:

We've been doing concurrent programming for some time using pthreads,
  using windows threads, and so on and I'm so happy that C++ and C
  caught up with concurrent programming, but it seems to me like it's
  already behind by five years or ten years because right now we have we
  have all these powerful multicores and the programming of these
  multicores really should not be based on threads, it should be
  task-based [...] and Microsoft has  the PPL library and so on and
  this is totally not reflecting in the C++ standard. [...] The only
  thing I'm afraid of is that the standard could be locked into threads
  and sort of make it very difficult to move to Task-Based
  Programming...

Now I'm quite new to these concepts and I'm a little confused. What is actually Task-Based Programming. Does this term refer to the same thing that Lock-Free Programming refers to? Are these two equivalent terms or are there any links between them?


答:
Create a Scanner for your InputStream, Reader, File, String, etc

Iterate over the tokens

If a word doesn't already exist in your Map, add it with a value of 1.

If a word already exists in the map, increment its value.

When done, close the Scanner.

Iterate over the map and display.

Your solution and @parsifal's take a couple of unnecessary steps that are avoided with this solution:

When using a Scanner to read an InputStream, Reader, or File, you don't need to read the whole thing into memory at once, making this solution work with very large inputs.

In addition to storing the entire input in a String, you duplicate the whole thing (minus spaces) in an ArrayList. In this solution there is no intermediate storage.

Here's a quick intro to Scanner.

Title: Find the count of each word in a string