答:
I work for a major insurance company and our source code goes up to 400MB of pure java files.
We have been developing the entire application without thinking about TDD. From january this year we started with junit testing for each individual component.

The best solution in our department was to use Mock objects on some JNI methods that were system dependable (written in C) and as such you could not exactly estimate the results every time on every OS. We didn't have any other option than to use mocked classes and specific implementations of JNI methods specifically for the purpose of testing the each individual module of the application for every OS we support.

But it was really fast and it has been working quite well so far. I recommend it - http://www.easymock.org/

OwnerDisplayName: BizzyDizzy


问:
How to deal with static utility classes when designing for testability
We are trying to design our system to be testable and in most parts developed using TDD. Currently we are trying to solve the following problem:

In various places it is necessary for us to use static helper methods like ImageIO and URLEncoder (both standard Java API) and various other libraries that consist mostly of static methods (like the Apache Commons libraries). But it is extremely difficult to test those methods that use such static helper classes.

I have several ideas for solving this problem:

Use a mock framework that can mock static classes (like PowerMock). This may be the simplest solution but somehow feels like giving up.

Create instantiable wrapper classes around all those static utilities so they can be injected into the classes that use them. This sounds like a relatively clean solution but I fear we'll end up creating an awful lot of those wrapper classes.

Extract every call to these static helper classes into a function that can be overridden and test a subclass of the class I actually want to test.

But I keep thinking that this just has to be a problem that many people have to face when doing TDD - so there must already be solutions for this problem.

What is the best strategy to keep classes that use these static helpers testable?

答:
The objects interact with each other to accomplish a goal, when you have object hard to test because of the enviroment(an webservice endpoint, dao layer accessing the DB, controllers handling http request parameters) or you want to test your object in isolation, then you mock those objects.

the necessity of mocking statics methods  is a bad smell, you have to design your application more Object Oriented, and unit testing  utility static methods do not add much value to the project, the wrapper class is a good approach depending on the situation, but try to test those objects that use the static methods.

OwnerDisplayName: Benedikt

ContentLicense: CC BY-SA 3.0

OwnerDisplayName: Diego Lins de Freitas


答:
(No "official" sources here, I'm afraid - it's not like there's a specification for how to test well. Just my opinions, which will hopefully be useful.)

When these static methods represent genuine dependencies, create wrappers. So for things like:

ImageIO

HTTP clients (or anything else network-related)

The file system

Getting the current time (my favourite example of where dependency injection helps)

... it makes sense to create an interface.

But many of the methods in Apache Commons probably shouldn't be mocked/faked. For example, take a method to join together a list of strings, adding a comma between them. There's no point in mocking these - just let the static call do its normal work. You don't want or need to replace the normal behaviour; you're not dealing with an external resource or something that's hard to work with, it's just data. The result is predictable and you'd never want it to be anything other than what it'll give you anyway.

I suspect that having removed all the static calls which really are convenience methods with predictable, "pure" outcomes (like base64 or URL encoding) rather than entry points into a whole big mess of logical dependencies (like HTTP) you'll find it's entirely practical to do the right thing with the genuine dependencies.

Title: How to deal with static utility classes when designing for testability

Body:
We are trying to design our system to be testable and in most parts developed using TDD. Currently we are trying to solve the following problem:

In various places it is necessary for us to use static helper methods like ImageIO and URLEncoder (both standard Java API) and various other libraries that consist mostly of static methods (like the Apache Commons libraries). But it is extremely difficult to test those methods that use such static helper classes.

I have several ideas for solving this problem:

Use a mock framework that can mock static classes (like PowerMock). This may be the simplest solution but somehow feels like giving up.

Create instantiable wrapper classes around all those static utilities so they can be injected into the classes that use them. This sounds like a relatively clean solution but I fear we'll end up creating an awful lot of those wrapper classes.

Extract every call to these static helper classes into a function that can be overridden and test a subclass of the class I actually want to test.

But I keep thinking that this just has to be a problem that many people have to face when doing TDD - so there must already be solutions for this problem.

What is the best strategy to keep classes that use these static helpers testable?

OwnerDisplayName: Jon Skeet


问:
(How can I / Am I allowed to) Use Google Maps as a Texture on an OpenGL object?
Note: I asked a very similar question on StackOverflow but did not get much attention, so was directed to http://programmers.stackexchange.com as licensing issues seem to have more interest here...

I am not an expert in Google Maps policies although I am aware that downloading / caching map tiles is not encouraged at all.

In Android, developers were given the MapActivity and MapView classes which attempt to provide all possible services for displaying map tiles and even modifying them on the fly if needed, but they are pretty useless for me as I would like to use map tiles as a texture on a 3D OpenGL object.

I'd like to know under which conditions the use of map tiles as an OpenGL texture is allowed.

Anyone?

UPDATE to clarify my question after Gavin's comment:

"Given that the Google Maps API does NOT provide a way to directly access map tiles as low level bitmaps, which is required by OpenGL texturing functions, is there any way to implement this without breaking Google licensing policies?"

答:
The Google Maps API licensing page explains this fairly well, to summarise, there are three types of license:

Google Maps API

The Google Maps API is a free service that lets you embed Google Maps in your freely accessible web pages or mobile apps.

Your service must be freely and publicly accessible to end users.

Google Maps API for Business

Google Maps API for Business provides enhanced features and added support to organizations who are adding maps to their fee-based websites or mobile apps, or to their internal websites.

OEM Licensing

You can license Google Maps as an embedded feature of your stand-alone software or device.

Your question does not make it clear exactly what your application does, so it is difficult to say which category you fall into. If in doubt, contact google and ask them.

Basically, if your application is for a mobile device and is free, then you can use the free Google Maps API. If  it is for a mobile device but you will charge a fee, then you need the Google Maps API for Business. If your application is not for a mobile device (possibly both free and paid for) then you need an OEM License. If your application is not for a mobile device, but is web connected, then it is a bit of a grey area, you may be able to use a free Google Maps API, or you may need an OEM License.

I suggest speaking to Google and explaining what you wish to do, they will then be able to advise you what type of licence is required.


问:
What metrics should be used to measure memory consumption of a program for performance test?
I am asked to provide performance statistics for a program, one of them being memory consumption. I noticed that in perfmon or in .NET API there is apparently many variable related to memory usage, such as private bit, working set, page file, etc.

What are the difference, and which one should we use for measuring performance? If the vendor claims that the memory consumption of the program is improved in version X, what value can be used to validate this?

答:
First off, you need to know whether the application is written in a .NET managed language or not, if not, some memory profiling options won't be available to you.

Secondly, what is it you are being asked to do? Monitor the program externally? In another application? From PerfMon.exe? Or add memory profiling into the application code itself?

If you are monitoring it externally and just want to check it's memory footprint, try using permon.exe / "Performance Monitor", and adding a counter for Process->Private Bytes and attach it to the process you want information about.

If you are monitoring it internally, it depends on the language, etc. so it's hard for me to be specific, let me know and I'll add more if needed.

Edit: Well it seems a bit pointless to me writing an application when there is a perfectly good one already there for you to use in PerfMon? But as a reference for what is what, take a look at the following:

https://stackoverflow.com/questions/1984186/what-is-private-bytes-virtual-bytes-working-set

http://dotnetdebug.net/2005/06/30/perfmon-your-debugging-buddy/

Otherwise just Google the name of the performance counter and I'm sure somewhere there will be a description of what it is / does.


问:
Is it wrong to use a boolean parameter to determine behavior?
I have seen a practice from time to time that "feels" wrong, but I can't quite articulate what is wrong about it. Or maybe it's just my prejudice. Here goes:

A developer defines a method with a boolean as one of its parameters, and that method calls another, and so on, and eventually that boolean is used, solely to determine whether or not to take a certain action. This might be used, for example, to allow the action only if the user has certain rights, or perhaps if we are (or aren't) in test mode or batch mode or live mode, or perhaps only when the system is in a certain state.

Well there is always another way to do it, whether by querying when it is time to take the action (rather than passing the parameter), or by having multiple versions of the method, or multiple implementations of the class, etc. My question isn't so much how to improve this, but rather whether or not it really is wrong (as I suspect), and if it is, what is wrong about it.

答:
Yes, this is likely a code smell, which would lead to unmaintainable code that is difficult to understand and that has a lower chance of being easily re-used.

As other posters have noted context is everything (don't go in heavy-handed if it's a one off or if the practice has been acknowledged as deliberately incurred technical debt to be re-factored later) but broadly speaking if there is a parameter passed into a function that selects specific behaviour to be executed then further step-wise refinement is required; Breaking up this function in to smaller functions will produce more highly cohesive ones.

So what is a highly cohesive function?

It's a function that does one thing and one thing only.

The problem with a parameter passed in as you describe, is that the function is doing more than two things; it may or may not check the users access rights depending on the state of the Boolean parameter, then depending on that decision tree it will carry out a piece of functionality.

It would be better to separate the concerns of Access Control from the concerns of Task, Action or Command.

As you have already noted, the intertwining of these concerns seems off.

So the notion of Cohesiveness helps us identify that the function in question is not highly cohesive and that we could refactor the code to produce a set of more cohesive functions.

So the question could be restated; Given that we all agree passing behavioural selection parameters is best avoided how do we improve matters?

I would get rid of the parameter completely. Having the ability to turn off access control even for testing is a potential security risk. For testing purposes either stub or mock the access check to test both the access allowed and access denied scenarios.

Ref: Cohesion (computer science)

ContentLicense: CC BY-SA 4.0


问:
What is the appeal of Systems Hungarian?
In a now deleted question titled "What naming guidelines do you follow?", the author says:

Also I prefer to code using hungarian notation from Charles Simonyi.

I've run in to several programmers who still prefer to use Hungarian, mostly of the Petzold/Systems Hungarian flavor.  Think dwLength = strlen(lpszName).

I've read Making Wrong Code Look Wrong, and I understand the rationale for Apps Hungarian, where domain-type information is included in the variable names.  But I don't understand the value in attatching the compiler type to the name.

Why do programmers still persist on using this style of notation?  Is it just inertia?  Are there any benefits that outweigh the decreased readability?  Do people just learn to ignore the decorators when reading the code, and if so, how do they continue to add value?

EDIT:
A lot of answers are explaining the history, or why it is no longer relevant, both of which are covered in the article I cited.

I'd really like to hear from anyone out there who still uses it.  Why do you use it?  Is it in your standard?  Would you use it if it wasn't required?  Would you use it on a new project?  What do you see as the advantages?

答:
If you come up with the right system of prefixes, you could spread the wear and tear of your keys, which would reduce spending on replacement keyboards.

I suppose I could expand on this.  I have used SH at my work place for the last, oh, ten years or so (because it's in our Standard).  It has never helped solve a problem.

On the other hand, I have used unadorned but well-named variables in my 'home code' for almost equally as long. I have never missed SH.

In both places, I have written protocol code that requires fixed size primitive types.  This is the most beneficial use case I can think of for SH.  It hasn't helped that I can tell when written with SH, and it hasn't hindered me when written without SH.

So, in conclusion, the only difference I can see is the wear and tear on your keyboard.

ContentLicense: CC BY-SA 2.5


问:
Programming language with pattern matching in trees
I'd like to prototype a computer algebra system. An equation would be represented by a tree and rules would be defined - similarly to mathematical axioms - by specifying a pattern (in the tree) and a restructuring rule for the matched part of the tree.

Can you suggest a programming language I could experiment with to test this approach (ideally not too experimental language)? Basically it should support high level data structures like lists (or actually trees) and make it easy to match the tree against a pattern and also replace part of a tree by a substitute. So it's about high level data structure pattern matching and easy modification of that.

EDIT: Of course I could take any programming language to write the program in the end, but I'm looking specifically for something which makes it easy to do first idea prototyping. I don't mind learning a new language (for fun).

答:
Can you suggest a programming language I could experiment with to test
  this approach (ideally not too experimental language)?

You are looking for a language but I think your question should be which type of programming language.

Having worked with Object-oriented (Imperative), Logic, Functional and Declarative programming languages, I would suggest something in the functional family.

If you want don't want to spend time parsing the input, and understand or can learn s-expressions, then I would suggest LISP. If you want something that also has types, which means you might have to either parse the input or enter the data in a form much closer to what the data structure definition then I would suggest maybe OCaml, Scheme or F#.

For why you should use a functional language over an object-oriented language see: OCaml for the Masses

As a general introduction to writing expression evaluator of algebraic data types in functional languages see Write Yourself a Scheme in 48 Hours


答:
There are many languages with built-in pattern matching support:

ML (all the dialects)

Haskell - pretty much the same approach as in ML, with one significant advantage, namely - Scrap your boilerplate library which allows to get rid of explicit recursion for most of the typical tree-walking tasks.

Any decent Lisp or Scheme, where an arbitrary complex pattern matching can be implemented with metaprogramming. Many implementations would already include a powerful pattern matching (e.g., Racket or Bigloo).

Mathematica. It is quite expensive, but worth looking at, at least as a source of ideas to be ported to the other languages. Its term rewriting features are especially useful for CAS applications: http://reference.wolfram.com/mathematica/guide/Rules.html

Prolog. Its approach to pattern matching (unification) is in general much slower than what ML would do, but in some cases might be extremely useful. Fortunately, Prolog is easy to embed into another languages (see Schelog).

Title: Programming language with pattern matching in trees

Body:
I'd like to prototype a computer algebra system. An equation would be represented by a tree and rules would be defined - similarly to mathematical axioms - by specifying a pattern (in the tree) and a restructuring rule for the matched part of the tree.

Can you suggest a programming language I could experiment with to test this approach (ideally not too experimental language)? Basically it should support high level data structures like lists (or actually trees) and make it easy to match the tree against a pattern and also replace part of a tree by a substitute. So it's about high level data structure pattern matching and easy modification of that.

EDIT: Of course I could take any programming language to write the program in the end, but I'm looking specifically for something which makes it easy to do first idea prototyping. I don't mind learning a new language (for fun).


问:
Algorithm which suggests synonyms based on some term?
Is there an algorithm which I can use in order to generate synonyms for some term (word) in respect of a spam. I am writing a simple spam filter.

For example, I set that the app must omit a word "viagra" and press a button which saves this term into a filter database. A script automatically creates synonyms of this word, such as: v.i.a.g.r.a, via_gra, via-gra, and similar. Or I filter a curse, and it generates all the tricks people use to have their curses appear in their comments.

答:
The bad news: if you want a spam filter, looking up words is definitely a bad approach.

For instance, you can have a perfectly valid and long message where at some point the word "fuck" is used. Likewise, you can have spam messages full of "valid" words.

The good news: spam filtering is a pattern recognition classic.

Just lookup "spam filter" and "classification" and you should get plenty of results. A good starting approach would be:
http://en.wikipedia.org/wiki/Bayesian_spam_filtering


问:
OOP :What are some of the situations in which class based design is better than interface based one?
I was reading  JDOM's website.

Why is the JDOM API defined in terms of concrete classes rather than interfaces?

Jason Hunter summarizes the arguments against an interface-based API for JDOM:

With interfaces everything becomes a factory, elements have to be 'imported' into new documents instead of just added, features like long-term serialization cannot be guaranteed, and the list goes on.

We started with interfaces actually. During our pre-release review to some peers we received the feedback we should try concrete classes. We did, and the design was much better for it.

I am a beginner designer. All the advice I have heard about till now is advising against using designing with concrete classes.

May be using concrete classes are appropriate in certain places. Are there any common class problems for which using concrete classes in design is okay?

答:
API design rules are really a specific thing. I'm not sure you should conclude anything from that FAQ in terms of how you should design your day-to-day code.

For your regular code, it's still true that you'll use interface or abstract class inheritance a lot more often than vanilla inheritance IMO.

To get a good understanding of that rule, you have to place yourself not from the standpoint of a derived class vs its superclass, but from the standpoint of an object that has a dependency to another object. It's almost always better to depend on an abstraction rather than a concrete implementation because it allows you to accept a whole series of different classes as dependencies, relying on their contract and not their implementation details.

The first use for this is often in unit tests - if you really want to unit test your class in complete isolation, you do that against fake implementations of your dependencies that are different from the real implementations that will be used in production.


问:
Domain-aware code text editors
General text editors don't change greatly. Syntax highlighting and code collapsing are not big changes really. If an editor is structure or domain aware, this usually comes with a different layouts - treeviews, context-menus, drag-and-drops and so on.
So are there good example to add more domain control when editing with caret, text selection and so on?

When I think about explaining this with example, what comes to mind:

Sync control (it's when you delete first i in
...
 this automatically changes to <dv></dv>

Read-only control (it's you're at "/" at the fragment above you can't edit, but if you select
 and press Del, both are deleted

Layered navigation. Probably different modes when the caret bypasses irrelevant layers  when you press Left, Right and so on. For example if you're in text navigation for html, then all tags are bypassed

Copy-paste control. Selected fragment should contain a valid sentence for domain and the place to insert to should also be compatible with it.

These are just examples for you to recall the real world editors where you met something similar.

Probably there are editors that allows one or several things from this list, but I suppose that partial solutions is no help and even can do harm and cause inconvenience. So the question is more about complex solution intended for overall improving of productivity in the general text editors.

答:
I developed a text editor that was 'domain aware' but it's probably best described as 'domain-specific' in that it was written specifically for XSLT.

It was built particularly with whitespace issues in mind. In XSLT, whitespace in the source code needs special attention because it will most likely end up in the result tree.

Most editors rely on the insertion of extra XML elements to separate code-formatting whitespace from whitespace intended for the output - this adds to the verbosity of the code and reduces readability. This new editor uses Virtual Formatting which avoids this issue by simply using dynamic margins to indent XSLT automatically.

The issue with this is users can't fully benefit from Virtual Formatting unless other editors also provide this option. Otherwise, as soon as a virtually-formatted XSLT file is opened by an ordinary XSLT editor a whole load of unwanted whitespace characters are added - to retain formatting.

I've failed to persuade other vendors to even consider this approach to formatting. What I've learnt from this is that text editors can't really change because any change would be disruptive. Most developer's want to use generic text editors that can work adequately with any grammar/syntax rather than use ones dedicated to a specific task.

Title: Domain-aware code text editors


问:
If you were the manager of a team of 25 developers, how would you motivate them?
Imagine yourself hired by a new startup backed with few millions coming from venture capitalists.

Your mission: organize the development of the next killer app.

25 developers is too much to take care of each individually, so what decision(s) you would make to motivate them?

I will appreciate any answers from stock options to free cookies ;)

Of course the trick here (unless you are really a manager of a such startup), is put yourself in the shoes of one of those programmers.

EDIT: it's an imaginary context. The purpose of this story is to stimulate your wishes. I want to capture what motivates developers.

答:
Get to know each and every developer individually, personally, and genuinely by meeting their needs on these dimensions:

Giving clear direction of responsibility and expectations (tell them what is needed)

Give access to the tools needed to do the job correctly (monitors, beefy systems)

Give them a way to measure their performance (geeks like graphs)

Give ample of opportunity to develop professional skills

Give them plenty of acknowledgment when they do a good job (who doesn't like praise)

Give them jobs that that will be successful at (what are they individually good at doing)

Give them a way to voice their opinions, ideas, and feelings (in a safe way)

Give ways to encourage and foster friendship (work culture)

Give them a reason to make quality products (pride in what they make)

Give a higher calling pointing out why what they do is significant to another person (there seems to be almost a 'spiritual' dimension to work)


问:
Dynamically load and call delegates based on source data
Assume I have a stream of records that need to have some computation.  Records will have a combination of these functions run Sum, Aggregate, Sum over the last 90 seconds, or ignore.

A data record looks like this:

```<code>Date;Data;ID
</code>```

Question

Assuming that ID is an int of some kind, and that int corresponds to a matrix of some delegates to run, how should I use C# to dynamically build that launch map?

I'm sure this idea exists... it is used in Windows Forms which has many delegates/events, most of which will never actually be invoked in a real application.

The sample below includes a few delegates I want to run (sum, count, and print) but I don't know how to make the quantity of delegates fire based on the source data.  (say print the evens, and sum the odds in this sample)

```<code>using System;
using System.Threading;
using System.Collections.Generic;
internal static class TestThreadpool
{

    delegate int TestDelegate(int  parameter);

    private static void Main()
    {
        try
        {
            // this approach works is void is returned.
            //ThreadPool.QueueUserWorkItem(new WaitCallback(PrintOut), "Hello");

            int c = 0;
            int w = 0;
            ThreadPool.GetMaxThreads(out w, out c);
            bool rrr =ThreadPool.SetMinThreads(w, c);
            Console.WriteLine(rrr);

            // perhaps the above needs time to set up6
            Thread.Sleep(1000);

            DateTime ttt = DateTime.UtcNow;
            TestDelegate d = new TestDelegate(PrintOut);

            List<IAsyncResult> arDict = new List<IAsyncResult>();

            int count = 1000000;

            for (int i = 0; i < count; i++)
            {
                IAsyncResult ar = d.BeginInvoke(i, new AsyncCallback(Callback), d);
                arDict.Add(ar);
            }

            for (int i = 0; i < count; i++)
            {
                int result = d.EndInvoke(arDict[i]);
            }

            // Give the callback time to execute - otherwise the app
            // may terminate before it is called
            //Thread.Sleep(1000);

            var res = DateTime.UtcNow - ttt;
            Console.WriteLine("Main program done----- Total time --> " + res.TotalMilliseconds);
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }

        Console.ReadKey(true);
    }

    static int PrintOut(int parameter)
    {
        // Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " Delegate PRINTOUT waited and printed this:"+parameter);
        var tmp = parameter * parameter;
        return tmp;
    }

    static int Sum(int parameter)
    {
        Thread.Sleep(5000); // Pretend to do some math... maybe save a summary to disk on a separate thread
        return parameter;
    }

    static int Count(int parameter)
    {
        Thread.Sleep(5000); // Pretend to do some math... maybe save a summary to disk on a separate thread
        return parameter;
    }

    static void Callback(IAsyncResult ar)
    {
        TestDelegate d = (TestDelegate)ar.AsyncState;
       //Console.WriteLine("Callback is delayed and returned") ;//d.EndInvoke(ar));
    }

}
</code>```

答:
Assuming that ID is an int of some kind, and that int corresponds to a matrix of some delegates to run, how should I use C# to dynamically build that launch map?

How is that dynamic? It sounds as though you simply want a Dictionary<int,Func<int,int>> where the ID is the key and the delegate is the value. Simple function composition (or perhaps just taking advantage of the multicast nature of C# delegates) will handle scenarios where you need multiple effects.


问:
Considering JCR as a NoSQL solution?
I'm evaluating some NoSQL solutions for a project of mine and JCR popped up during my searches as a document store. But it seems somehow of an obscure niche which didn't have the impact its designers hoped for.

I'm interested in the technology, but so far there does not seem to be a lot of resources out there to show it's potential (there is some info on the Jackrabbit site, but otherwise, pretty much scarce info).

Hopefully someone in the SE community could share from their experience with this technology.

What are its advantages/disadvantages? In what situations does this technology perform best?

答:
It looks like JCR is just a generic interface/API that a third-party could implement (similar to JMS). What you'd need to do is search for third party JCR support which it appears, your link on Wikipedia gives a few examples.

If you are creating an application that a customer would install on premise and needs to integrate with multiple document stores, JCR might be the path for you. However, if you're managing the stack from top to bottom, I'd say pick a store directly and use it directly for the time being.

Title: Considering JCR as a NoSQL solution?


答: I think Robert C Martins Clean code article states that you should eliminate boolean arguments where possible as they show a method does more than one thing.  A method should do one thing and one thing only I think is one of his mottos.</p>

Title: Is it wrong to use a boolean parameter to determine behavior?

Body:
I have seen a practice from time to time that "feels" wrong, but I can't quite articulate what is wrong about it. Or maybe it's just my prejudice. Here goes:

A developer defines a method with a boolean as one of its parameters, and that method calls another, and so on, and eventually that boolean is used, solely to determine whether or not to take a certain action. This might be used, for example, to allow the action only if the user has certain rights, or perhaps if we are (or aren't) in test mode or batch mode or live mode, or perhaps only when the system is in a certain state.

Well there is always another way to do it, whether by querying when it is time to take the action (rather than passing the parameter), or by having multiple versions of the method, or multiple implementations of the class, etc. My question isn't so much how to improve this, but rather whether or not it really is wrong (as I suspect), and if it is, what is wrong about it.

OwnerDisplayName: dreza


答:
I think the most important thing here is to be practical.

When the boolean determines the entire behavior, just make a second method.

When the boolean only determines a little bit of behaviour in the middle, you might want to keep it in one to cut down on code duplication. Where possible, you might even be able to split the method in three: Two calling methods for either boolean option, and one that does the bulk of the work.

For example:

private void FooInternal(bool flag)
{
  //do work
}

public void Foo1()
{
  FooInternal(true);
}

public void Foo2()
{
  FooInternal(false);
}
```

Of course, in practice you'll always have a point in between these extremes. Usually I just go with what feels right, but I prefer to err on the side of less code duplication.

Body:
I think the most important thing here is to be practical.

When the boolean determines the entire behavior, just make a second method.

When the boolean only determines a little bit of behaviour in the middle, you might want to keep it in one to cut down on code duplication. Where possible, you might even be able to split the method in three: Two calling methods for either boolean option, and one that does the bulk of the work.

For example:

private void FooInternal(bool flag)
{
  //do work
}

public void Foo1()
{
  FooInternal(true);
}

public void Foo2()
{
  FooInternal(false);
}

Of course, in practice you'll always have a point in between these extremes. Usually I just go with what feels right, but I prefer to err on the side of less code duplication.

OwnerDisplayName: Jorn


答:
Most of the time, I would consider this bad coding.  I can think of two cases, however, where this might be a good practice.  As there are a lot of answers already saying why it's bad, I offer two times when it might be good:

The first is if each call in the sequence makes sense in its own right.  It would make sense if the calling code might be changed from true to false or false to true, or if the called method might be changed to use the boolean parameter directly rather than passing it on.  The likelihood of ten such calls in a row is small, but it could happen, and if it did it would be good programming practice.

The second case is a bit of a stretch given that we're dealing with a boolean.  But if program has multiple threads or events, passing parameters is the simplest way to track thread/event specific data.  For example, a program may get input from two or more sockets.  Code running for one socket may need to produce warning messages, and one running for another may not.  It then (sort of) makes sense for a boolean set at a very high level to get passed through many method calls to the places where warning messages might be generated.  The data can't be saved (except with great difficulty) in any sort of global because multiple threads or interleaved events would each need their own value.

To be sure, in the latter case I'd probably create a class/structure whose only content was a boolean and pass that around instead.  I'd be almost certain to need other fields before too long--like where to send the warning messages, for instance.


问:
Agile - Spikes and the Overall Timeline
Team is starting on their first capital-A Agile project, and the project seems like it will fall in line nicely with the methodology (i.e. we can probably just grab an agile book and follow it like a recipe), with one bit of confusion:

The project involves three things that nobody on the team has any experience with: Integrate with the Foo Payroll System, be able to handle the file type XYZ89 (where "XYZ89" = some file type you've never heard of), and convert some other files so they can be handled by the Frobnobdicator.

As I understand it, standard Agile practice would be to schedule spikes for each of these, after which we can determine how long they're going to take (I'm not sure there's much of a chance that the client will decide not to do them, as they're pretty much solid requirements of the project)

So my questions are:

Do we do all the spikes up front in the first iteration to get a better estimate of the time it's going to take to do them and/or get a "walking skeleton" up and running?

If not, wouldn't the total project schedule be at the mercy of one of these spikes coming back with data that this particular story will take way longer than we ballparked?

What is the best practice way to handle multiple spikes when they are basically non-negotiable requirements of a project?

答:
You should be doing things in the order of the priority set by the product owner (or customer).  There's no sense in killing yourself over something that was really a nice-to-have. The idea is that if you run out of time and something doesn't get done, it should be the lowest priority items.

If they won't prioritize what they want, you are going to struggle.

If things are relatively equal, do not start with the hardest item--start with an easy win, which will give the team a chance to get used to working together using the new methodology and the customer some confidence they can deliver stuff this way.  Once that's established, tackle something difficult.  Measure the complexity of the difficult item against the complexity of the easier stuff you just did, and you'll start to get an idea of how long it may take to get through it.

Complex items aren't really "spikes".  They are simply things that take more effort to figure out.  Break them down into simpler tasks as much as you possibly can.

Title: Agile - Spikes and the Overall Timeline


问:
Should we always unit test bugs when correcting them?
When correcting bugs, it is encouraged where I work to first write a test that fails with the given bug, and then to fix the code until the test passes.
This follows TDD practices, and is supposed to be good practice, but I noticed it tends to produce cryptic tests that come really close to the implementation.

For instance, we had a problem when a job was sent, reached a certain state, was aborted, and retried. To reproduce this bug, a massive test was written with thread synchronization in it, lots of mocking and stuff... It did the job, but now that I am refactoring the code, I find it very tempting to just remove this mammoth, since it would really require a lot of work (again) to fit the new design. And it's just testing one small feature in a single specific case.

Hence my question : how do you test for bugs that are tricky to reproduce ? How do you avoid creating things that test the implementation, and hurt refactoring and readability ?

答:
Yes, in general you should. As with all guidelines, you'll need to use your best judgement when they run against other guidelines. For this scenario, the severity of the bug needs to be weighed against the work needed to implement the test and the quality of that test in being targeted to the business problem and catching regression of the bug's state.

I would tend to favor writing tests over not, since interruptions to run down bugs tend to have more overhead than simply developing and maintaining a unit test.


答:
The practice of writing a test to identify the defect is a good idea, since it allows you to identify exactly what steps are needed to reproduce the defect and verify that it has been fixed. In addition, these tests can be run as part of smoke testing or regression testing to ensure that later changes have not re-introduced an old defect into the system.

The first thing to consider is the level of the test needed. Perhaps the test to verify the fix would be more appropriate at a systems level, or maybe even an acceptance test that's done manually. I think it's more important to have a test that's documented and managed, regardless of how it's specifically implemented.

As far as how refactoring affects tests, it depends on the specific characteristics. In some cases, refactoring (or any type of work, such as new features) could make the tests no longer necessary. The problem, as it originally occurred, might no longer be possible. In that case, it might be wise to remove the test from the possible tests to make your test process (automated or manual) more lean. In other cases, there are multiple methods of performing the test and verifying the feature at a different level might be more appropriate. If the feature is minor, perhaps the test is no longer necessary at all.

You can also consider not only relying on testing, but logging as well. For example, capturing information at run-time (with varying levels of verbosity depending on the environment - more verbose during testing, less verbose during deployment), profiling the application, capturing dumps of the current state of the system. If you can find common triggers to the problem, you can use that to guide testing at all levels.

Title: Should we always unit test bugs when correcting them?

Body:
When correcting bugs, it is encouraged where I work to first write a test that fails with the given bug, and then to fix the code until the test passes.
This follows TDD practices, and is supposed to be good practice, but I noticed it tends to produce cryptic tests that come really close to the implementation.

For instance, we had a problem when a job was sent, reached a certain state, was aborted, and retried. To reproduce this bug, a massive test was written with thread synchronization in it, lots of mocking and stuff... It did the job, but now that I am refactoring the code, I find it very tempting to just remove this mammoth, since it would really require a lot of work (again) to fit the new design. And it's just testing one small feature in a single specific case.

Hence my question : how do you test for bugs that are tricky to reproduce ? How do you avoid creating things that test the implementation, and hurt refactoring and readability ?


问:
What is an Aguri tree?
Going through some old Hacker News items, I came across a post from a user that said

Aguri trees, which marry a bounded-size radix trie (like you'd use in a software routing table) to an LRU list, and automatically synthesize aggregates (like, 10.0.0.0/16 from 1,000 observations across all IPs) from the pattern of insertion. They're best known in traffic analysis, but we've used them on in runtime memory analysis as well.

~ tptacek

So I decided to look it up,

A quick Google Search leads me to a F1 driver.

A search on Wikipedia leads to a agricultural caste in India and some items from Japan

Stack Overflow hits 0 results https://stackoverflow.com/search?q=aguri site:stackoverflow.com/questions aguri

So I have finally linked it back to the user see he has a link on his blog

http://www.matasano.com/log/1009/aguri-coolest-data-structure-youve-never-heard-of/

But it's dead.

So, what is this Aguri data structure and if it is a real data structure, why is it not documented anywhere else?

答:
Very little really dies on the internet.  Archive.org just happens to have one single snapshot of that blog post from when it was live.  Copied here:

Some remedial computer science, for the PCI auditors in my audience.

I hand you an array of random integers. How can you tell if the number
  three is in it?

Well, there’s the obvious way: check the numbers sequentially until
  you find the “3” or exhaust the array. Linear search. Given 10
  numbers, you have to assume it could take 10 steps; N numbers, N
  steps.

Picture 1.png

Linear search is bad. It’s hard to do worse than linear. Let’s improve
  on it. Sort the array.

Picture 2.png

A sorted array suggests a different strategy: jump the middle of the
  array and see if the value you’re looking for is less than (to the
  left) or greater than (to the right). Repeat, cutting the array in
  half each time, until you find the value.

Binary search. Given 10 numbers, it will take as many as 3 steps —-
  log2 of 10 —- to find one of them in a sorted array. O(log n) search
  is awesome. If you have 65,000 elements, it’s only going to take 16
  steps to find one of them. Double the elements, and it’s 17 steps.

But sorted arrays suck; for one thing, sorting is more expensive than
  linear search. So we don’t use binary search much; instead, we use
  binary trees.

Picture 3.png

To search a binary tree, you start at the top, and ask yourself “is my
  key less than (left) or greater than (right) the current node”, and
  repeat until ok, ok, ok, you know this stuff already. But that tree is
  pretty, isn’t it?

Search with a (balanced) binary tree is O(log n), like binary search,
  varying with the number of elements in the tree. Binary trees are
  awesome: you get quick lookup and sorted traversal, something you
  don’t get out of a hash table. Binary trees are a better default table
  implementation than hash tables.
  2.

But binary trees aren’t the only tree-structured lookup mechanism.
  Binary radix tries, also called a PATRICIA trees, work like binary
  trees with one fundamental difference. Instead of comparing
  greater-than/less-than at each node, you check to see if a bit is set,
  branching right if it’s set and left if it isn’t.

Picture 4.png

I’m leaving out a lot about how binary radix tries work. This is a
  shame, because radix tries are notoriously underdocumented —-
  Sedgewick infamously screwed them up in “Algorithms”, and the
  Wikipedia page for them sucks. People still argue about what to call
  them! In lieu of an explanation of backlinks and bit-position-labelled
  edges, here’s a tiny Ruby implementation.

Here’s why radix tries are cool:

```<code>Search performance varies with the key size, not the number of elements in the tree. With 16 bit keys, you’re guaranteed 16 steps
</code>```

regardless of the number of the elements in the tree, without
  balancing.

```<code>More importantly, radix tries give you lexicographic matching, which is a puffed-up way of saying “search with trailing wildcard”, or
</code>```

“command-line-completion-style search”. In a radix tree, you can
  quickly search for “ro*” and get “rome” and “romulous” and “roswell”.

3.

I’ve lost you.

Let’s put this in context. Tries are a crucial data structure for
  Internet routing. The routing problem goes like this:

```<code>You have a routing table with entries for “10.0.1.20/32 -> a” and “10.0.0.0/16 -> b”.

You need packets for 10.0.1.20 to go to “a”

You need packets for 10.0.1.21 to to to “b”
</code>```

This is a hard problem to solve with a basic binary tree, but with a
  radix trie, you’re just asking for
  “1010.0000.0000.0000.0000.0001.0100” (for 10.0.1.20) and “1010.” (for
  10.0.0.0). Lexicographic search gives you “best match” for routing. You can try it in the Ruby code above; add *”10.0.0.0”.to_ip to the
  trie, and search for “10.0.0.1”.to_ip.

The correspondance between routing and radix tries is so strong that
  the most popular general-purpose radix trie library (the one from
  CPAN) is actually stolen out of GateD. It’s a mess, by the way, and
  don’t use it.

If you understand how a trie works, you also understand how regular
  expressions work. Tries are a special case of deterministic finite
  automata (DFAs), where branches are based exclusively on bit
  comparisons and always branch forwards. A good regex engine is just
  handling DFAs with more “features”. If my pictures make sense to you,
  the pictures in this excellent article on Thompson’s NFA-DFA reduction
  algorithm will too, and that article will make you smarter.
  4.

You’re a network operator at a backbone ISP. Your world largely
  consists of “prefixes” —- IP network/netmask pairs. The netmasks in
  those prefixes are hugely important to you. For instance, 121/8
  belongs to Korea; 121.128/10 belongs to Korea Telecom, 121.128.10/24
  belongs to a KT customer, and 121.128.10.53 is one computer inside
  that customer. If you’re tracking down a botnet or a spamming
  operation or worm propagation, that netmask number is pretty important
  to you.

Unfortunately, important though they are, nowhere on an IP packet is
  there stamped a “netmask” —- netmasks are entirely a configuration
  detail. So, when you’re watching traffic, you essentially have this
  data to work with:

ips.png

Surprisingly, given enough packets to look at, this is enough
  information to guess netmasks with. While working at Sony, Kenjiro Cho
  came up with a really elegant way to do that, based on tries. Here’s
  how:

Take a basic binary radix trie, just like the ones used by software
  routers. But bound the number of nodes in the tree, say to 10,000. On
  a backbone link, recording addresses out of IP headers, you’ll exhaust
  10,000 nodes in moments.

Store the list of nodes in a list, sorted in LRU order. In other
  words, when you match an IP address with a node, “touch” the node,
  sticking it at the top of the list. Gradually, frequently seen
  addresses bubble up to the top, and infrequently seen nodes sink to
  the bottom.

Picture 6.png

Now the trick. When you run out of nodes and need a new one, reclaim
  from the bottom of the list. But when you do, roll the data from the
  node up into its parent, like so:

Picture 5.png

10.0.1.2 and 10.0.1.3 are sibling /32s, the two halves of 10.0.1.2/31. To reclaim them, merge them into 10.0.1.2/31. If you need to reclaim
  10.0.1.2/31, you can merge it with 10.0.1.0/31 to form 10.0.1.0/30.

Do this over, say, a minute, and the standout sources will defend
  their position in the tree by staying at the top of the LRU list,
  while ambient /32 noise bubbles up to /0. For the raw list of IP’s
  above, with a 100 node tree, you get this.

Cho calls this heuristic Aguri.
  5.

Aguri is BSD licensed. You can go download it, and a driver program
  that watches packets via pcap, from Cho’s old home page.
  6.

I’m going somewhere with this, but I’m 1300 words into this post now,
  and if you’re an algorithms person you’re tired of me by now, and if
  you’re not, you’re tired of me by now. So, let Aguri sink in, and I’ll
  give you something cool and useless to do with it later this week.

There are numerous links scattered in there.  Unfortunately, Archive.org does not keep the images, only text, so several of them have been lost.  Here's the ones that it does have archived:

Wikipedia's article on Trie trees

Wikipedia's article on Radix trees

Code for a "Crappy Binary Radix Tree"

Speed comparison of regex matching engines

Kenjiro Cho

A raw list of ips

Output using that list of ips

More code

Title: What is an Aguri tree?

Body:
Very little really dies on the internet.  Archive.org just happens to have one single snapshot of that blog post from when it was live.  Copied here:

Some remedial computer science, for the PCI auditors in my audience.

I hand you an array of random integers. How can you tell if the number
  three is in it?

Well, there’s the obvious way: check the numbers sequentially until
  you find the “3” or exhaust the array. Linear search. Given 10
  numbers, you have to assume it could take 10 steps; N numbers, N
  steps.

Picture 1.png

Linear search is bad. It’s hard to do worse than linear. Let’s improve
  on it. Sort the array.

Picture 2.png

A sorted array suggests a different strategy: jump the middle of the
  array and see if the value you’re looking for is less than (to the
  left) or greater than (to the right). Repeat, cutting the array in
  half each time, until you find the value.

Binary search. Given 10 numbers, it will take as many as 3 steps —-
  log2 of 10 —- to find one of them in a sorted array. O(log n) search
  is awesome. If you have 65,000 elements, it’s only going to take 16
  steps to find one of them. Double the elements, and it’s 17 steps.

But sorted arrays suck; for one thing, sorting is more expensive than
  linear search. So we don’t use binary search much; instead, we use
  binary trees.

Picture 3.png

To search a binary tree, you start at the top, and ask yourself “is my
  key less than (left) or greater than (right) the current node”, and
  repeat until ok, ok, ok, you know this stuff already. But that tree is
  pretty, isn’t it?

Search with a (balanced) binary tree is O(log n), like binary search,
  varying with the number of elements in the tree. Binary trees are
  awesome: you get quick lookup and sorted traversal, something you
  don’t get out of a hash table. Binary trees are a better default table
  implementation than hash tables.
  2.

But binary trees aren’t the only tree-structured lookup mechanism.
  Binary radix tries, also called a PATRICIA trees, work like binary
  trees with one fundamental difference. Instead of comparing
  greater-than/less-than at each node, you check to see if a bit is set,
  branching right if it’s set and left if it isn’t.

Picture 4.png

I’m leaving out a lot about how binary radix tries work. This is a
  shame, because radix tries are notoriously underdocumented —-
  Sedgewick infamously screwed them up in “Algorithms”, and the
  Wikipedia page for them sucks. People still argue about what to call
  them! In lieu of an explanation of backlinks and bit-position-labelled
  edges, here’s a tiny Ruby implementation.

Here’s why radix tries are cool:

Search performance varies with the key size, not the number of elements in the tree. With 16 bit keys, you’re guaranteed 16 steps

regardless of the number of the elements in the tree, without
  balancing.

More importantly, radix tries give you lexicographic matching, which is a puffed-up way of saying “search with trailing wildcard”, or

“command-line-completion-style search”. In a radix tree, you can
  quickly search for “ro*” and get “rome” and “romulous” and “roswell”.

3.

I’ve lost you.

Let’s put this in context. Tries are a crucial data structure for
  Internet routing. The routing problem goes like this:

You have a routing table with entries for “10.0.1.20/32 -> a” and “10.0.0.0/16 -> b”.

You need packets for 10.0.1.20 to go to “a”

You need packets for 10.0.1.21 to to to “b”

This is a hard problem to solve with a basic binary tree, but with a
  radix trie, you’re just asking for
  “1010.0000.0000.0000.0000.0001.0100” (for 10.0.1.20) and “1010.” (for
  10.0.0.0). Lexicographic search gives you “best match” for routing. You can try it in the Ruby code above; add *”10.0.0.0”.to_ip to the
  trie, and search for “10.0.0.1”.to_ip.

The correspondance between routing and radix tries is so strong that
  the most popular general-purpose radix trie library (the one from
  CPAN) is actually stolen out of GateD. It’s a mess, by the way, and
  don’t use it.

If you understand how a trie works, you also understand how regular
  expressions work. Tries are a special case of deterministic finite
  automata (DFAs), where branches are based exclusively on bit
  comparisons and always branch forwards. A good regex engine is just
  handling DFAs with more “features”. If my pictures make sense to you,
  the pictures in this excellent article on Thompson’s NFA-DFA reduction
  algorithm will too, and that article will make you smarter.
  4.

You’re a network operator at a backbone ISP. Your world largely
  consists of “prefixes” —- IP network/netmask pairs. The netmasks in
  those prefixes are hugely important to you. For instance, 121/8
  belongs to Korea; 121.128/10 belongs to Korea Telecom, 121.128.10/24
  belongs to a KT customer, and 121.128.10.53 is one computer inside
  that customer. If you’re tracking down a botnet or a spamming
  operation or worm propagation, that netmask number is pretty important
  to you.

Unfortunately, important though they are, nowhere on an IP packet is
  there stamped a “netmask” —- netmasks are entirely a configuration
  detail. So, when you’re watching traffic, you essentially have this
  data to work with:

ips.png

Surprisingly, given enough packets to look at, this is enough
  information to guess netmasks with. While working at Sony, Kenjiro Cho
  came up with a really elegant way to do that, based on tries. Here’s
  how:

Take a basic binary radix trie, just like the ones used by software
  routers. But bound the number of nodes in the tree, say to 10,000. On
  a backbone link, recording addresses out of IP headers, you’ll exhaust
  10,000 nodes in moments.

Store the list of nodes in a list, sorted in LRU order. In other
  words, when you match an IP address with a node, “touch” the node,
  sticking it at the top of the list. Gradually, frequently seen
  addresses bubble up to the top, and infrequently seen nodes sink to
  the bottom.

Picture 6.png

Now the trick. When you run out of nodes and need a new one, reclaim
  from the bottom of the list. But when you do, roll the data from the
  node up into its parent, like so:

Picture 5.png

10.0.1.2 and 10.0.1.3 are sibling /32s, the two halves of 10.0.1.2/31. To reclaim them, merge them into 10.0.1.2/31. If you need to reclaim
  10.0.1.2/31, you can merge it with 10.0.1.0/31 to form 10.0.1.0/30.

Do this over, say, a minute, and the standout sources will defend
  their position in the tree by staying at the top of the LRU list,
  while ambient /32 noise bubbles up to /0. For the raw list of IP’s
  above, with a 100 node tree, you get this.

Cho calls this heuristic Aguri.
  5.

Aguri is BSD licensed. You can go download it, and a driver program
  that watches packets via pcap, from Cho’s old home page.
  6.

I’m going somewhere with this, but I’m 1300 words into this post now,
  and if you’re an algorithms person you’re tired of me by now, and if
  you’re not, you’re tired of me by now. So, let Aguri sink in, and I’ll
  give you something cool and useless to do with it later this week.

There are numerous links scattered in there.  Unfortunately, Archive.org does not keep the images, only text, so several of them have been lost.  Here's the ones that it does have archived:

Wikipedia's article on Trie trees

Wikipedia's article on Radix trees

Code for a "Crappy Binary Radix Tree"

Speed comparison of regex matching engines

Kenjiro Cho

A raw list of ips

Output using that list of ips

More code


问:
Should these concerns be separated into separate objects?
I have objects which implement the interface BroadcastInterface, which represents a message that is to be broadcast to all users of a particular group. It has a setter and getter method for the Subject and Body properties, and an addRecipientRole() method, which takes a given role and finds the contact token (e.g., an email address) for each user in the role and stores it. It then has a getContactTokens() method.

BroadcastInterface objects are passed to an object that implements BroadcasterInterface. These objects are responsible for broadcasting a passed BroadcastInterface object. For example, an EmailBroadcaster implementation of the BroadcasterInterface will take EmailBroadcast objects and use the mailer services to email them out.

Now, depending on what BroadcasterInterface implementation is used to broadcast, a different implementation of BroadcastInterface is used by client code. The Single Responsibility Principle seems to suggest that I should have a separate BroadcastFactory object, for creating BroadcastInterface objects, depending on what BroadcasterInterface implementation is used, as creating the BroadcastInterface object is a different responsibility to broadcasting them.

But the class used for creating BroadcastInterface objects depends on what implementation of BroadcasterInterface is used to broadcast them. I think, because the knowledge of what method is used to send the broadcasts should only be configured once, the BroadcasterInterface object should be responsible for providing new BroadcastInterface objects.

Does the responsibility of “creating and broadcasting objects that implement the BroadcastInterface interface” violate the Single Responsibility Principle?

(Because the contact token for sending the broadcast out to the users will differ depending on the way it is broadcasted, I need different broadcast classes—though client code will not be able to tell the difference.)

答:
I don't know PHP, but OO-wise you have a problem here.  If something implements the BroadcastInterface, it should be good for anything that expects a BroadcastInterface instance.

First suggestion:  create A, B, C, ... versions of each BroadcastInterface and BroadcasterInterface (BroadcastIntefaceA, BIB, BIC, and BerIA, BerIB, and BerIC.)  These can extend the original interfaces, but they will keep your relationships straight; the correct BI will go with the correct BerI, or, in most languages I know, you'll get a compiler error.  Otherwise, things will be hopelessly confused instead of merely confused.  Probably you want each BerI extention to produce the appropriate BI extention.

Second suggestion:  skip the extensions.  Take the code in the BI implementations that make them behave differently and put it in the BerI implementors.  Now you don't have to worry about it at all.  And the interfaces tell all the story that anybody using them needs to know.

I don't know PHP or your program well enough to say which, if either, solution is the best.  (If I were to take charge of your code, I'd do anything to make the second suggestion work, though.)  But interfaces need to tell all the story anyone needs to know.  The code using the interface should not know anything more about the implementor than what is in the interface.  The implementor should know nothing about the user beyond what it picks up through the interface.


答: I think the best practice - one I'm embarrassed to admit I don't often follow - is to create a system or integration test that demonstrates the problem observed in production, then research to find the unit(s) responsible for the problem, and then write unit tests for those units that demonstrate the problem at the unit level.  Once you have the unit tests, fix the units, and run all the tests.  At this point, it may be prudent to discard the original test - because it may be fragile and/or slow - but keep the unit tests in your automated suite for the sake of regression and coverage.


问:
How to represent a Rubik's Cube in a data structure
If I am attempting to simulate a Rubik's Cube, how would you create a data structure to store the cube's state in memory, with X number of tiles per side?

Things to consider:

the cube can be of any size

it is a Rubik's cube, so layers can be rotated

答:
How about nodes and pointers?

Assuming there is always 6 faces, and that 1 node represents 1 square on 1 face:

```<code>r , g , b
r , g , b
r , g , b
|   |   |
r , g , b - r , g , b
r , g , b - r , g , b
r , g , b - r , g , b
</code>```

A node has a pointer to each node next to it. A circle rotation just migrates the pointer (Number of nodes/Number of faces)-1 nodes over, in this case 2. Since all rotations are circle rotations, you just build one rotate function. It is recursive, moving each node one space, and checking if it has moved them enough, since it will have collected the number of nodes, and there is always four faces. If not, increment the number of times moved value and call rotate again.

Don't forget it's doubly linked, so update the newly pointed nodes as well. There will always be Height*Width number of nodes moved, with one pointer updated per node, so there should be Height*Width*2 number of pointers updated.

Since all the nodes point to each other, just walk around on circle updating each node as you come to it.

This should work for any sized cube, without edge cases or complex logic. It's just a pointer walk/update.

Body:
How about nodes and pointers?

Assuming there is always 6 faces, and that 1 node represents 1 square on 1 face:

r , g , b
r , g , b
r , g , b
|   |   |
r , g , b - r , g , b
r , g , b - r , g , b
r , g , b - r , g , b

A node has a pointer to each node next to it. A circle rotation just migrates the pointer (Number of nodes/Number of faces)-1 nodes over, in this case 2. Since all rotations are circle rotations, you just build one rotate function. It is recursive, moving each node one space, and checking if it has moved them enough, since it will have collected the number of nodes, and there is always four faces. If not, increment the number of times moved value and call rotate again.

Don't forget it's doubly linked, so update the newly pointed nodes as well. There will always be Height*Width number of nodes moved, with one pointer updated per node, so there should be Height*Width*2 number of pointers updated.

Since all the nodes point to each other, just walk around on circle updating each node as you come to it.

This should work for any sized cube, without edge cases or complex logic. It's just a pointer walk/update.


问:
Wrong use of CSS3 Animations or not?
Well, I started using some CSS3 animations a couple of days ago. After hardcoding I've started trying different tools like Adobe Edge Preview version.

I made a short animation to get the functionality of the tool
http://things.eyemade.ch/css3edge/

After that someone at Twitter took a look at it and said that it is wrong using divs to paint things like these. But I'm not sure about that. Things changed over the last years and if we keep in mind this stuff is going to be used in many web/mobile games, is it really wrong to use divs this way nowadays?

答:
Things changed over the last years and if we keep in mind this stuff is going to be used in many web/mobile games, is it really wrong to use divs this way nowadays?

[emphasis mine]

Yes, using divs simply for the sake of producing animation is the wrong approach. It doesn't detract from the elegance or beauty of your animation, but it's simply the wrong tool for the job.

The purpose of CSS animations are to provide animations that are associated with a particular style. Adding a sliding or fade effect to a drop-down menu would be an example where CSS animations are part of a style. CSS-Tricks uses animations all over the place, such as the header menu color changes when the page loads. These effects are part of the style of the page, and are not tied-in to the markup

The example you created is strongly tied to the elements in the HTML, and none of it is meaningful content (semantically transparent). It would be better to store the animation in a separate non-looping .gif, or SVG which can be animated and styled with CSS & JavaScript.

What are the [effects] of wrong semantics with this animation for the [end user]?

For a visually impaired user, using the wrong semantics means that they will have a confusing experience. They may have to navigate through a number of nonsensical items that exist solely for the purpose of displaying an animation. Alternatively they may skip over the animation completely and not understand content that references it.

An  has an [alt] attribute for the purpose of explaining its content in context. If you're using a bunch of
s then you should be sure to add [title] and [role="img"] attributes on the containing
 (best explained in the ARIA spec).

For a sighted user, there probably wont be any issue at all. Beyond accessibility there isn't really an issue with using CSS animations as a way create a stand-alone animation. It doesn't make it a good tool to use. As an analogy, if you need to nail two boards together, you can use the handle of a screwdriver instead of a hammer. Both will get the job done under normal circumstances; however, one tool is obviously better suited for use with nails.

Title: Wrong use of CSS3 Animations or not?

Body:
Things changed over the last years and if we keep in mind this stuff is going to be used in many web/mobile games, is it really wrong to use divs this way nowadays?

[emphasis mine]

Yes, using divs simply for the sake of producing animation is the wrong approach. It doesn't detract from the elegance or beauty of your animation, but it's simply the wrong tool for the job.

The purpose of CSS animations are to provide animations that are associated with a particular style. Adding a sliding or fade effect to a drop-down menu would be an example where CSS animations are part of a style. CSS-Tricks uses animations all over the place, such as the header menu color changes when the page loads. These effects are part of the style of the page, and are not tied-in to the markup

The example you created is strongly tied to the elements in the HTML, and none of it is meaningful content (semantically transparent). It would be better to store the animation in a separate non-looping .gif, or SVG which can be animated and styled with CSS & JavaScript.

What are the [effects] of wrong semantics with this animation for the [end user]?

For a visually impaired user, using the wrong semantics means that they will have a confusing experience. They may have to navigate through a number of nonsensical items that exist solely for the purpose of displaying an animation. Alternatively they may skip over the animation completely and not understand content that references it.

An <img> has an [alt] attribute for the purpose of explaining its content in context. If you're using a bunch of <div>s then you should be sure to add [title] and [role="img"] attributes on the containing <div> (best explained in the ARIA spec).

For a sighted user, there probably wont be any issue at all. Beyond accessibility there isn't really an issue with using CSS animations as a way create a stand-alone animation. It doesn't make it a good tool to use. As an analogy, if you need to nail two boards together, you can use the handle of a screwdriver instead of a hammer. Both will get the job done under normal circumstances; however, one tool is obviously better suited for use with nails.


答:
You are to motivate developers to write the next killer app?

Perhaps a good place to start would be to let them KNOW that they will do so, in a way so they can see the long term perspective on this.  Such a goal should be highly motivating on its own - IF it really is a killer app.

Then show them in action that you actually mean it!

Title: If you were the manager of a team of 25 developers, how would you motivate them?

Body:
Imagine yourself hired by a new startup backed with few millions coming from venture capitalists.

Your mission: organize the development of the next killer app.

25 developers is too much to take care of each individually, so what decision(s) you would make to motivate them?

I will appreciate any answers from stock options to free cookies ;)

Of course the trick here (unless you are really a manager of a such startup), is put yourself in the shoes of one of those programmers.

EDIT: it's an imaginary context. The purpose of this story is to stimulate your wishes. I want to capture what motivates developers.


答:
I'm surprised no one has mentioned named-parameters.

The problem I see with boolean-flags is that they hurt readability.  For example, what does true in

myObject.UpdateTimestamps(true);
```

<p>do?  I have no idea.  But what about:</p>

<pre class="lang-cs prettyprint-override"><code>myObject.UpdateTimestamps(saveChanges: true);
</code>```

Now it's clear what the parameter we're passing is meant to do:  we're telling the function to save its changes.  In this case, if the class is non-public, I think the boolean parameter is fine.

Of course, you can't force the users of your class to use named-parameters.  For this reason, either an enum or two separate methods are usually preferable, depending on how common your default case is.  This is exactly what .Net does:

//Enum used
double a = Math.Round(b, MidpointRounding.AwayFromZero);

//Two separate methods used
IEnumerable<Stuff> ascendingList = c.OrderBy(o => o.Key);
IEnumerable<Stuff> descendingList = c.OrderByDescending(o => o.Key);
```

Body:
I'm surprised no one has mentioned named-parameters.

The problem I see with boolean-flags is that they hurt readability.  For example, what does true in

myObject.UpdateTimestamps(true);

do?  I have no idea.  But what about:

myObject.UpdateTimestamps(saveChanges: true);

Now it's clear what the parameter we're passing is meant to do:  we're telling the function to save its changes.  In this case, if the class is non-public, I think the boolean parameter is fine.

Of course, you can't force the users of your class to use named-parameters.  For this reason, either an enum or two separate methods are usually preferable, depending on how common your default case is.  This is exactly what .Net does:

//Enum used
double a = Math.Round(b, MidpointRounding.AwayFromZero);

//Two separate methods used
IEnumerable<Stuff> ascendingList = c.OrderBy(o => o.Key);
IEnumerable<Stuff> descendingList = c.OrderByDescending(o => o.Key);


答:
The way I have handled these shady unknowns in my project plan before is to try and setup time for the development team to do prototypes of the unknown functionality before hand.  This gives the benefit of making clearly known what will be required to do the specialized tasks, proves that these are technically feasible, and educates the rest of the team on the possible pitfalls to avoid when active development starts.

This is why many Agile projects usually start with a, what I like to call, Sprint 0.

Think of it as lacing your running shoes, stretching, and putting bandaids on your nipples right before you start a marathon.  This time can be used to do the initial project planning and user story creation, design and architecture rollout, software framework creation and the developers can work on any prototypes and proof of concepts for any new technology or unknown technical challenges that will make user story point estimatation much easier.

Title: Agile - Spikes and the Overall Timeline

Body:
Team is starting on their first capital-A Agile project, and the project seems like it will fall in line nicely with the methodology (i.e. we can probably just grab an agile book and follow it like a recipe), with one bit of confusion:

The project involves three things that nobody on the team has any experience with: Integrate with the Foo Payroll System, be able to handle the file type XYZ89 (where "XYZ89" = some file type you've never heard of), and convert some other files so they can be handled by the Frobnobdicator.

As I understand it, standard Agile practice would be to schedule spikes for each of these, after which we can determine how long they're going to take (I'm not sure there's much of a chance that the client will decide not to do them, as they're pretty much solid requirements of the project)

So my questions are:

Do we do all the spikes up front in the first iteration to get a better estimate of the time it's going to take to do them and/or get a "walking skeleton" up and running?

If not, wouldn't the total project schedule be at the mercy of one of these spikes coming back with data that this particular story will take way longer than we ballparked?

What is the best practice way to handle multiple spikes when they are basically non-negotiable requirements of a project?


问:
Working machines of developers - in what ways are they usually standardized or restricted?
My boss wants to introduce new guidelines for the computers in our company. This means that the software environments will be completely standardized with a predefined set of tools. The goal is that all machines are completely reproducable and exchangable.

I'm wondering what the guidelines for developer's computers are in large companies, such as Google or Microsoft, especially companies which are certified according to some standard (e.g. ISO 9001). Do they allow developers to install software from the internet if they need it for some small task? (e.g. a code compare tool, CygWin, Windows Service Packs) or do they really want all needed tools in a fixed, predefined environment where all proposed changes must be discussed with a system administrator first?

答:
You're really asking several separate, but related, questions here.

Hardware

First: every company I've ever worked for had some kind of standardization of desktop machines.  At a minimum, the hardware and OS were standardized across large groups (possibly in rolling categories: you get this year's machine when you start, and then 2 years later you get that year's machine, etc.).

As for what the hardware is like: a great company will give everybody in the building awesome hardware with fast CPUs, giant monitors, and huge amounts of RAM, even if they don't need it.  A good company will at least make sure that you get hardware that is adequate to your job (which at a minimum means that engineers will get bigger screens and more RAM than the receptionist does).

Standard Software

Not only that, but every company I've ever worked for had some kind of standard software set up as well.  At a minimum, that means things like email/calendar/groupware, office software, etc.  Everybody gets the same thing by default; at some companies you can get something else if you have a justifiable reason (although there may be lots of paperwork involved).  Plus of course you'll get the company's standard line-of-business software (although these days those applications are often web-based).  You'll usually be given these applications, and you're usually stuck with them.

Specialized Software

Then there is specialized software that you need to do your job: compilers, IDEs, image editing tools, etc.  Regardless of whether we're talking about free software (e.g. Eclipse) or expensive software (e.g. Visual Studio, Photoshop), the company will usually standardize on a version.  So everybody who gets Visual Studio gets 2010, not 2008 (or something like that).

Inevitably, this leads to there being some officially-sanctioned place for the standard versions of things to sit -- if for no other reason than to prevent everybody from re-downloading Eclipse.  Likewise, for software that has update servers or repositories, it's common for the company to run its own internal mirror repository (and possibly to block access to external mirrors) to ensure that (1) big packages are only downloaded once, and (2) everybody gets the same version.

Generally, any software that's in a company officially-sanctioned repository (where that may be an OS package repository, or just a file share with installers, or even just a file cabinet with install disks) can be installed on your computer.  Most places I've worked allow you to self-serve install this kind of software, regardless of whether it's free software or paid.

What About Everything Else?

But that brings us to what appears to be your real question, which is twofold:

What about software that isn't officially sanctioned (yet)?

What kind of customizations can I make to the software?  (Or, equivalently, what kind of administrative rights do I have on my own machine?)

For the first question, it depends on the company, and the software in question.  I've heard that some companies are pretty draconian about non-sanctioned software, but everywhere I've worked the policies have been pretty relaxed, especially for engineers.  Sometimes a particular software package is disallowed because it hogs company resources (e.g. peer-to-peer file sharing) or is fundamentally insecure (e.g. various types of remote PC access software) -- in that case, there is usually a company-sanctioned alternative.

For everything else, there's usually some kind of approval process.  At some companies, this is as simple as asking your manager, "hey, can I install this software?", whereas at other companies the software may need to have several levels of sign-off.  Expensive software and software that communicates with external services are the most likely to be carefully scrutinized, as well they should.

The second question is more about how much freedom an individual employee should have to make changes to their own machine.  At most places I've worked, engineers are given pretty broad leeway, with the caveat that certain changes will "void your warranty" -- the company helpdesk won't support you anymore, and  you'll have to deal with any issues on your own.  Non-technical staff usually have less leeway, mainly because the helpdesk doesn't trust them to not break something.

For example, at my current job (at a large software company mentioned in your question) I don't have root access to my own machine, but I do have sudo access to do most everything I need.  At a previous job at a smaller company where we were on Windows, I was in the Administrators group on my own machine, so I had pretty free reign.


问:
Understanding C++ for windows desktop application
I've been programming C++ for almost a year, and I've written complex programs however there are a couple of programming features of C++ which I didn't cover up (Classes & pointers), however I felt ready to develop a desktop application. I didn't get any books nor did I find any REAL documentation. I said to myself "Practicing is the most important thing in programming. I'll do that".

Obviously I didn't learn much. After 4 months of programming in Visual studio C++/CLI I barely understand what I'm doing. I know how to do very basic operations, converting data types, but I am clueless on how the program works, how I add anything except events or how I change my GUI in code and not in the GUI builder.

What should I do? Practice didn't really help, I only know some very easy things since I started working with Visual Studio, but the rest of the concepts leave me clueless. Should I hit the books, or should I just keep practicing?

答:
Sounds you realized the flaw in your own original thinking. I've always liked this quote (do not remember who said it) which seems to fit very nicely here:

"Practice doesn't make it perfect; perfect practice makes it perfect".

Meaning that if you don't have enough skills to know what you are practicing, you might be doing more damage than good.

Go back and start reading books. They'll show you step-by-step what it takes to get an app up and running. The books won't make you an expert but they'll give you a much better perspective on what it is you should be practicing.

Btw, C++/CLI is a really bad environment for what you are trying to accomplish. As far as I can tell that technology is best for interoperability layers between managed and native code.  If you don't need interoperability, stick with C++ if you want to write native apps or pick up C# if you want to write managed apps.

As far as GUI desktop apps go, I would recommend you pick up C# with WPF. I can name several very good books on that but you'd also have to concentrate more on C# itself. And the fact that you skimmed over classes tells me there's a ton of language itself (both C++ and C#) that you should learn.

If you want to stick with C++ the best choice I can think of is the Qt library. That is until Windows 8 and next visual studio come out and introduce XAML to C++ environment.


答: Yes, you should hit the books. And start with C++ books that cover classes and pointers. Make sure you know these topics well. Then you will want to go for an introductory Microsoft Visual C++ book. Practice is important, but if you don't know what you're doing, practice won't get you anywhere.</p>

Title: Understanding C++ for windows desktop application

Body:
I've been programming C++ for almost a year, and I've written complex programs however there are a couple of programming features of C++ which I didn't cover up (Classes & pointers), however I felt ready to develop a desktop application. I didn't get any books nor did I find any REAL documentation. I said to myself "Practicing is the most important thing in programming. I'll do that".

Obviously I didn't learn much. After 4 months of programming in Visual studio C++/CLI I barely understand what I'm doing. I know how to do very basic operations, converting data types, but I am clueless on how the program works, how I add anything except events or how I change my GUI in code and not in the GUI builder.

What should I do? Practice didn't really help, I only know some very easy things since I started working with Visual Studio, but the rest of the concepts leave me clueless. Should I hit the books, or should I just keep practicing?


答:
I might be so crazy as to suggest you abandon VS entirely and move over to something like Eclipse, mingw, etc...  Maybe even go all out and use Notepad++.

Why?  Because VS hides too much important stuff.  As you mention...you've written this app but don't know the first thing about how it works.  You can't really do that if you're doing all the underlying stuff yourself.  You'll be writing stuff by hand, looking up how to do things in the API docs...etc...  You'll have to.

When you can do all that fairly easily, then think about bringing VS back into the picture.  You might have decided by that point though that it's easier not having to do battle with some massive monstrosity all the time though and chose an IDE that works a touch better.

One thing though...the VS debugger is one of the best around.  It's hard to replace.  If you use the VS compiler (not the IDE) you can still use the IDE for debugging your program.  Up to you whether you want to fight that hard though.


答:
You know, I believe that every thing should be take part in whenever we need that.
How does it matter if there is concept out of your defined world and also you have no idea about it?
I think you should learn each concept just when you need that of face a problem.
Ok. In this method. You can define a new project have some real problem. Then try to solve them and give a solution.
I think this is the best practice to learn things.</p>


答:
C++/CLI is very bad and not useful, for anything except interop, and has little to do with C++.

Just to note, classes are the single most important thing in C++. If you can't use classes, you can only write tiny little toy programs.


问:
Creating alternate keys with Visio ERD diagrams
I'm trying out Visio for the first time today, creating ERD's. Is it possible to specify alternate keys in addition to PK's in Visio ERD diagrams. I can't see any way to define more than one key on a table.

Any ideas? Cheers.

答:
One way to do this is by creating a Unique Index on the column.

Click the table on design surface to select the table

Click Indexes

Create new index column, by default indexes are non-unique, the next step fixes this

In the 2nd drop-down list, select Unique Index (VISIO offer 3 types)

There should be a way to display AKn of the left hand column of the design surface, but I don't know how to do this.


答:
Yes, you should.

Write unit tests for existing code base. When fixing a bug, you need to make sure that your unit test fails - this will give you confidence that you are indeed working on a bug. You then need to re-factor and make the test pass by fixing the bug.

This is not a TDD practice though. In TDD tests drive your design, but in your case the design has already been decided upon.


答:
A possible solution is toy create a task for doing a proof of concept to figure out how to solve the problem and time box it, then add that story in to a sprint with other stories.

You are sill delivering value and a product at the end of the sprint, even if it's a hack console app.  The idea is you're not sinking the entire team's productivity, if you run out of time, you add another similar task to next sprint.

Title: Agile - Spikes and the Overall Timeline


问:
Why is Global State so Evil?
Before we start this, let me say I'm well aware of the concepts of Abstraction and Dependency Injection. I don't need my eyes opened here.

Well, most of us say, (too) many times without really understanding, "Don't use global variables", or "Singletons are evil because they are global". But what really is so bad about the ominous global state?

Let's say I need a global configuration for my application, for instance system folder paths, or application-wide database credentials.

In that case, I don't see any good solution other than providing these settings in some sort of global space, which will be commonly available to the entire application.

I know it's bad to abuse it, but is the global space really THAT evil? And if it is, what good alternatives are there?

答:
Very briefly, it makes program state unpredictable.

To elaborate, imagine you have a couple of objects that both use the same global variable.  Assuming you're not using a source of randomness anywhere within either module, then the output of a particular method can be predicted (and therefore tested) if the state of the system is known before you execute the method.

However, if a method in one of the objects triggers a side effect which changes the value of the shared global state, then you no longer know what the starting state is when you execute a method in the other object.  You can now no longer predict what output you'll get when you execute the method, and therefore you can't test it.

On an academic level this might not sound all that serious, but being able to unit test code is a major step in the process of proving its correctness (or at least fitness for purpose).

In the real world, this can have some very serious consequences.  Suppose you have one class that populates a global data structure, and a different class that consumes the data in that data structure, changing its state or destroying it in the process.  If the processor class executes a method before the populator class is done, the result is that the processor class will probably have incomplete data to process, and the data structure the populator class was working on could be corrupted or destroyed.  Program behaviour in these circumstances becomes completely unpredictable, and will probably lead to epic lossage.

Further, global state hurts the readability of your code.  If your code has an external dependency that isn't explicitly introduced into the code then whoever gets the job of maintaining your code will have to go looking for it to figure out where it came from.

As for what alternatives exist, well it's impossible to have no global state at all, but in practice it is usually possible to restrict global state to a single object that wraps all the others, and which must never be referenced by relying on the scoping rules of the language you're using.  If a particular object needs a particular state, then it should explicitly ask for it by having it passed as an argument to its constructor or by a setter method.  This is known as Dependency Injection.

It may seem silly to pass in a piece of state that you can already access due to the scoping rules of whatever language you're using, but the advantages are enormous.  Now if someone looks at the code in isolation, it's clear what state it needs and where it's coming from.  It also has huge benefits regarding the flexibility of your code module and therefore the opportunities for reusing it in different contexts.  If the state is passed in and changes to the state are local to the code block, then you can pass in any state you like (if it's the correct data type) and have your code process it.  Code written in this style tends to have the appearance of a collection of loosely associated components that can easily be interchanged.  The code of a module shouldn't care where state comes from, just how to process it.  If you pass state into a code block then that code block can exist in isolation, that isn't the case if you rely on global state.

There are plenty of other reasons why passing state around is vastly superior to relying on global state.  This answer is by no means comprehensive.  You could probably write an entire book on why global state is bad.

Title: Why is Global State so Evil?


问:
How do you manage feature requests and software changes?
I am a Software Engineer and over the past few years I have become the de-facto software project manager simply because there isn't one. So to keep our sanity in the R&D/Engineering department, customers have become accustomed to coming to me with their requests. I have no experience in this realm so it is my first time acting as a project manager for software projects. I have managed other things but not software.

So, how do you manage software projects and mark priorities? Requests come in at infrequent intervals so we very well could be working on something for someone else and then another person comes in with a "rush" job that needs working on. Is it easier to just say First Come, First Serve or is it the person with the most money?

答: What we ended coming up with was we would now have bi-monthly sales/engineering meetings to discuss current projects and upcoming or future feature requests. The sales engineers will become project managers and at least they will be in tune with the latest product offerings. In the past it was just easy to pass it along to Engineering and forget about it. This will likely lessen the load a software engineer has to do and put the onus on sales and management to use our time wisely.</p>


答:
Since your whole damn app can be using it, it's always incredibly hard to factor them
back out again. If you ever change anything to do with your global, all your code needs changing. This is a maintenance headache- far more than simply being able to grep for the type name to find out which functions use it.

They're bad because they introduce hidden dependencies, which break multithreading, which is increasingly vital to increasingly many applications.

The state of the global variable is always completely unreliable, because all of your code could be doing anything to it.

They're really hard to test.

They make calling the API hard. "You must remember to call SET_MAGIC_VARIABLE() before calling API" is just begging for someone forget to call it. It makes using the API error-prone, causing difficult-to-find bugs. By using it as a regular parameter, you force the caller to properly provide a value.

Just pass a reference into functions which need it. It's not that hard.

Title: Why is Global State so Evil?

Body:
Before we start this, let me say I'm well aware of the concepts of Abstraction and Dependency Injection. I don't need my eyes opened here.

Well, most of us say, (too) many times without really understanding, "Don't use global variables", or "Singletons are evil because they are global". But what really is so bad about the ominous global state?

Let's say I need a global configuration for my application, for instance system folder paths, or application-wide database credentials.

In that case, I don't see any good solution other than providing these settings in some sort of global space, which will be commonly available to the entire application.

I know it's bad to abuse it, but is the global space really THAT evil? And if it is, what good alternatives are there?


答:
If you say "state", that is usually taken to mean "mutable state". And global mutable state is totally evil, because it means that any part of the program can influence any other part (by changing the global state).

Imagine debugging an unknown program: You find that function A behaves a certain way for certain input parameters, but sometimes it works differently for the same parameters. You find that it uses the global variable x.

You look for places that modify x, and find that there are five places that modify it. Now good luck finding out in what cases function A does what...

Title: Why is Global State so Evil?


答:
You sort of answered your own question. They're difficult to manage when 'abused,' but can be useful and [somewhat] predictable when used properly, by someone who knows how to contain them. Maintenance and changes to/on the globals is usually a nightmare, made worse as the size of the application increases.

Experienced programmers who can tell the difference between globals being the only option, and them being the easy fix, can have minimal problems using them. But the endless possible issues that can arise with their use necessitates the advice against using them.

edit: To clarify what I mean, globals are unpredictable by nature. As with anything unpredictable you can take steps to contain the unpredictability, but there's always limits to what can be done. Add to this the hassle of new developers joining the project having to deal with relatively unknown variables, the recommendations against using globals should be understandable.

Title: Why is Global State so Evil?


答: If you're developing a desktop application that is UI-heavy, and maybe does lots of database access, I'd start by asking whether C++ is the best tool in the first place.</p>


答:
Well, for one, you can run in to exactly the same issue that you can with singletons.  What today looks like a "global thing I only need one of" will suddenly turn in to something you need more of down the road.

For instance, today you create this global config system because you want one global configuration for the entire system.  A few years down the road, you port to another system and someone says "hey, you know, this might work better if there were one general global configuration and one platform specific configuration."  Suddenly you have all this work to make your global structures not global, so you can have multiple ones.

(This isn't some random example...this happened with our configuration system in the project I am currently in.)

Considering that the cost of making something non-global is usually trivial, it's silly to do so.  You're just creating future problems.

Title: Why is Global State so Evil?


答:
The thing here is, are you doing C++ development, or developing in some framework/toolkit?

See, you can do desktop apps in C++ - we've used MFC for donkeys years, and while that is now obsolete, the point is that you're 'doing MFC development', not strictly C++ development, it just happens that your MFC apps are written using C++.

So, today, what are you using? There are several toolkits to use, probably the best is Qt which has some good tutorials. If you prefer to use a C-style paradigm, then maybe GTK+ is a good choice. If you want to only use Microsoft technologies (some do, sigh) then HTML is the current choice for Metro apps, and you're sort-of out of luck with C++ GUIs, you can write WPF using C++ in Windows 8 but not before then.

So its great that you're learning something  new (a lot of people say this on this site, but they generally mean "learn some new C# tech") and I hope you enjoy C++ GUI programming  - Qt is a joy to use, and the new QML features are in a different league to WPF.

PS. The way to learn is to use the GUI builder to create a very simple program, then look at what it generates and extend it manually. I learned a lot of stuff that way, and it taught me a lot more than I realised.