问:
Main class passes dbConn obj to all its services, I need to change the dbConn for one of its services. - suggestion for design pattern
There is this main class

and there are several services ( which uses db connection to retrieve data )

These services are initialized in the main class
db properties are obtained from the property file and then

dbconnection is opened by calling a method dbOpen() written in the main class
and the resultant connection object is set to the service objects by iterating through the list of services and by calling setConnection method on the service

note: that the services are instantiated in the main class and the main class is not a superclass for services.

I also need to mention that there is this recycle db connection scenario only main class is aware of.

```<code>/** connects to DB, optionally recycling existing connection),
     * throws RuntimeException if unable to connect */
    private void connectDb(boolean recycle) {
        try {
            if (recycle) {
                log.status( log.getSB().append("Recycling DB Connection") );
                closeDb();
            }
            openDb();
            for ( int i = 0 ; i < service.length ; i++ )
            {
                service[i].setConnection(db);
            }
        }
</code>```

One of the service needs to use a different database, what is the best design pattern to use?

答:
I would recommend that you create service objects after you have established connection to the database and provide your db connection object as a parameter to a service constructor.

And when you call connectDb(true) in order to re-cycle connection, you do something as the following:

```<code>private void connectDb(boolean recycle) {
   if (recycle) {
       // move this loop to closeDb() method:
       for (Service i : services) {
          i.closeConnection() // guarantee that all transactions are committed, etc.
       }
       closeDb();
   }
   openDb();
   // move the following loop to openDb() method
   // or even better create ServiceFactory class that obtain appropriate connection from the main class before creating a service.
   for ( int i = 0 ; i < services.length ; i++ ) {
      // here you create your service classes as you have created them before:
      services[i] = new Service(db);
      // the old service instances will be destroyed by system garbage collector...
   }
</code>```

This approach is cleaner and will work well (with minor adaptations) if one day your application become multithreading and the services will run in parallel.

Body:
I would recommend that you create service objects after you have established connection to the database and provide your db connection object as a parameter to a service constructor.

And when you call connectDb(true) in order to re-cycle connection, you do something as the following:

private void connectDb(boolean recycle) {
   if (recycle) {
       // move this loop to closeDb() method:
       for (Service i : services) {
          i.closeConnection() // guarantee that all transactions are committed, etc.
       }
       closeDb();
   }
   openDb();
   // move the following loop to openDb() method
   // or even better create ServiceFactory class that obtain appropriate connection from the main class before creating a service.
   for ( int i = 0 ; i < services.length ; i++ ) {
      // here you create your service classes as you have created them before:
      services[i] = new Service(db);
      // the old service instances will be destroyed by system garbage collector...
   }

This approach is cleaner and will work well (with minor adaptations) if one day your application become multithreading and the services will run in parallel.


问:
How do you evolve & version an interface?
Say you have an interface IFoo:

```<code>public interface IFoo {
    void Bar(string s);
    int Quux(object o);
}
</code>```

In version 2 of your API, you need to add a method Glarg to this interface. How do you do so without breaking your existing API users and maintaining backwards compatibility? This is mainly aimed at .NET, but can apply to other frameworks & languages as well.

答:
DirectX added version numbers to its interfaces. In your case, the solution would be something like

```<code>public interface IFoo2 : IFoo
{
    void Glarg();
}
</code>```

The API would still refer to IFoo, and to IFoo2 only in methods etc where IFoo2 functionality is required.

API implementation should check in existing (=version 1) methods whether an IFoo parameter object actually implements IFoo2, if method semantics are different for IFoo2.

ContentLicense: CC BY-SA 3.0

Body:
DirectX added version numbers to its interfaces. In your case, the solution would be something like

public interface IFoo2 : IFoo
{
    void Glarg();
}

The API would still refer to IFoo, and to IFoo2 only in methods etc where IFoo2 functionality is required.

API implementation should check in existing (=version 1) methods whether an IFoo parameter object actually implements IFoo2, if method semantics are different for IFoo2.


答:
Public interface changes involve breakage. The common strategy is to do these only on major versions and after a freeze period (so it doesn't happen on a whim). You may get away without breaking your clients if you are adding you additions into a new interface (and your implementation can provide both on the same class). That's not ideal, and if you keep doing it you will have a mess.

With other kinds of modification though (removing methods, changing signatures), your are stuck.

Title: How do you evolve & version an interface?

Body:
Say you have an interface IFoo:

```<code>public interface IFoo {
    void Bar(string s);
    int Quux(object o);
}
</code>```

In version 2 of your API, you need to add a method Glarg to this interface. How do you do so without breaking your existing API users and maintaining backwards compatibility? This is mainly aimed at .NET, but can apply to other frameworks & languages as well.


答:
Adding a new method (or methods) to your API should be done in such a way that it does not have any side effects on the existing API. Most importantly, someone who continues to use the old API as if the new API does not exist, should be unaffected by it. Using the old API should not have unexpected side effects on the new API either.

If any of the existing methods in the API are superseded by the new ones, do not remove them straight away. Mark them as deprecated and provide an explanation as to what should be used instead. That gives users of your code warning that future versions may no longer support it instead of breaking their code without warning.

If the new and old APIs are incompatible and cannot live together without unwanted side effects, separate them and document that if the new API is to be adopted, the old API must be retired completely. This is less desirable as there will always be someone that attempts to use both and gets frustrated when it doesn't work.

Since you asked about .NET specifically you may want to read this article about deprecation in .NET, which links to the ObsoleteAttribute (used in the following example):

```<code>using System;

public sealed class App {
   static void Main() {
      // The line below causes the compiler to issue a warning:
      // 'App.SomeDeprecatedMethod()' is obsolete: 'Do not call this method.'
      SomeDeprecatedMethod();
   }

   // The method below is marked with the ObsoleteAttribute.
   // Any code that attempts to call this method will get a warning.
   [Obsolete("Do not call this method.")]
   private static void SomeDeprecatedMethod() { }
}
</code>```

Body:
Adding a new method (or methods) to your API should be done in such a way that it does not have any side effects on the existing API. Most importantly, someone who continues to use the old API as if the new API does not exist, should be unaffected by it. Using the old API should not have unexpected side effects on the new API either.

If any of the existing methods in the API are superseded by the new ones, do not remove them straight away. Mark them as deprecated and provide an explanation as to what should be used instead. That gives users of your code warning that future versions may no longer support it instead of breaking their code without warning.

If the new and old APIs are incompatible and cannot live together without unwanted side effects, separate them and document that if the new API is to be adopted, the old API must be retired completely. This is less desirable as there will always be someone that attempts to use both and gets frustrated when it doesn't work.

Since you asked about .NET specifically you may want to read this article about deprecation in .NET, which links to the ObsoleteAttribute (used in the following example):

using System;

public sealed class App {
   static void Main() {
      // The line below causes the compiler to issue a warning:
      // 'App.SomeDeprecatedMethod()' is obsolete: 'Do not call this method.'
      SomeDeprecatedMethod();
   }

   // The method below is marked with the ObsoleteAttribute.
   // Any code that attempts to call this method will get a warning.
   [Obsolete("Do not call this method.")]
   private static void SomeDeprecatedMethod() { }
}


问:
Asserting in public methods
I'm a fan of using assertions in the code to check for preconditions. The question is whether is it wise to use assertions in public methods to check the precondition?

My personal opinion is, that if my method can not handle the absence of a parameter (or some invalid value of it) and it is part of an API but does not rely on user input, then the issue (bad parameter) must be handled during the development process (at least by the integration tests) and not later when the software is used on field. For this reason I do use assertions even in public methods.

I mean something like this:

```<code>public class SomeMagic implements MagicAPI {

    public WoW doSomeMagic( Stuff source ) {
        assert source != null : "Incorrect use of the API";

        // if assertions are deactivated (should be the case in production environment)
        // this line will throw a NpEx
        if ( source.isPlainStuff() ) {
            // some magic with a plain stuff
        }

        return Wow.beSurprised;
    }
}
</code>```

答:
In my opinion the visibility of your methods doesn't matter at all. After all, all your private methods are ultimately called from public methods in every case, or they wouldn't be needed!

To be sure, a failed precondition to a private method is not always caused by a failed precondition to a public method, but often it is, and anyway the point of assertions is not to keep score in a match of blame-game between the library developer and the application developer. If a precondition is violated, there is a programming error somewhere, and you either want to be informed of that by a runtime crash or you don't. That's the question that decides whether to assert or not.

Title: Asserting in public methods


问:
Examples of operator overloading, which make sense
While I learning C#, I found that, the C# supports operator overloading. I have problem with good example which:

Make sense (ex. adding class named sheep and cow)

Is not an example of concatenation of two strings

Examples from Base Class Library are welcome.

答:
The Point Struct in the System.Drawing namespace uses overloading to compare two different locations using operator overloading.

```<code> Point locationA = new Point( 50, 50 );
 Point locationB = new Point( 50, 50 );

 if ( locationA == locationB )
    Console.WriteLine( "Their locations are the same" );
 else
    Console.WriteLine( "Their locations  are different" );
</code>```

As you can see, it is much easier to compare the X and Y co-ordinates of two locations using the overload.

Body:
The Point Struct in the System.Drawing namespace uses overloading to compare two different locations using operator overloading.

 Point locationA = new Point( 50, 50 );
 Point locationB = new Point( 50, 50 );

 if ( locationA == locationB )
    Console.WriteLine( "Their locations are the same" );
 else
    Console.WriteLine( "Their locations  are different" );

As you can see, it is much easier to compare the X and Y co-ordinates of two locations using the overload.


答:
It's context sensitive. I once tried to create a "guideline" when to use assertions vs error handling. I called it a "degree of trust" trade-off and illustrated like this:

```<code>!!!!!!!!!!!!!    a) user input
...!!!!!!!!!!    b) external data input (network, ...)
......!!!!!!!    c) internal data input (other process)
*.........!!!    d) library (external)
**..........!    e) library (internal)
****.........    f) public functions (team)
********.....    g) public functions (own code)
************.    h) private functions

! extra validation needed (anything can be thrown in), never ever any assumptions!
. standard validation
* assertions only possible
</code>```

In your case (internal library API?) I would tend to validate more than use assertions. It's very difficult to anticipate all (ab)uses of library by caller code and integration testing coverage tends to be patchy. If there's no limitation you can also leave assertions in the production code to keep validation (they would turn into exception).

Title: Asserting in public methods

Body:
I'm a fan of using assertions in the code to check for preconditions. The question is whether is it wise to use assertions in public methods to check the precondition?

My personal opinion is, that if my method can not handle the absence of a parameter (or some invalid value of it) and it is part of an API but does not rely on user input, then the issue (bad parameter) must be handled during the development process (at least by the integration tests) and not later when the software is used on field. For this reason I do use assertions even in public methods.

I mean something like this:

```<code>public class SomeMagic implements MagicAPI {

    public WoW doSomeMagic( Stuff source ) {
        assert source != null : "Incorrect use of the API";

        // if assertions are deactivated (should be the case in production environment)
        // this line will throw a NpEx
        if ( source.isPlainStuff() ) {
            // some magic with a plain stuff
        }

        return Wow.beSurprised;
    }
}
</code>```

Body:
It's context sensitive. I once tried to create a "guideline" when to use assertions vs error handling. I called it a "degree of trust" trade-off and illustrated like this:

!!!!!!!!!!!!!    a) user input
...!!!!!!!!!!    b) external data input (network, ...)
......!!!!!!!    c) internal data input (other process)
*.........!!!    d) library (external)
**..........!    e) library (internal)
****.........    f) public functions (team)
********.....    g) public functions (own code)
************.    h) private functions

! extra validation needed (anything can be thrown in), never ever any assumptions!
. standard validation
* assertions only possible

In your case (internal library API?) I would tend to validate more than use assertions. It's very difficult to anticipate all (ab)uses of library by caller code and integration testing coverage tends to be patchy. If there's no limitation you can also leave assertions in the production code to keep validation (they would turn into exception).


答:
In version 2 of your API, you need to add a method Glarg to this interface.

Why?

The interfaces defined for use with an API have two entirely different roles:

Dependency inversion - such interfaces are consumed by your API. They allow client code to create plugins etc.

Abstraction - such interfaces are returned by your API and hide implementation details of the returned objects.

Now for a given version of an API, the same interface may act as both. Still, in future versions, this can be decoupled.

You want to extract more information from the interface you consume. To enhance performance, or add flexibility or whatever. Define a new interface, possibly derived from the old one, and build a separate method consuming it. AFAIK most .NET languages allow method overloading, so this can happen without adding much clutter.

You want to "return more", i.e. the abstraction of a "richer" object from your API. Here you're having two choices:

You can reasonably assume, that client code will not have its own implementors of the interface. Under this assumption it is safe to add your extensions to the existing interface.

Define a new interface, if possible derived from the previous one. If such derivation is impossible, create separate methods to query for instances of the new interface or use composition:

```<code>interface MyNewInterface extends MyOldInterface {
     FancyNewInterface getFancyShit();
}
</code>```

Body:
In version 2 of your API, you need to add a method Glarg to this interface.

Why?

The interfaces defined for use with an API have two entirely different roles:

Dependency inversion - such interfaces are consumed by your API. They allow client code to create plugins etc.

Abstraction - such interfaces are returned by your API and hide implementation details of the returned objects.

Now for a given version of an API, the same interface may act as both. Still, in future versions, this can be decoupled.

You want to extract more information from the interface you consume. To enhance performance, or add flexibility or whatever. Define a new interface, possibly derived from the old one, and build a separate method consuming it. AFAIK most .NET languages allow method overloading, so this can happen without adding much clutter.

You want to "return more", i.e. the abstraction of a "richer" object from your API. Here you're having two choices:

You can reasonably assume, that client code will not have its own implementors of the interface. Under this assumption it is safe to add your extensions to the existing interface.

Define a new interface, if possible derived from the previous one. If such derivation is impossible, create separate methods to query for instances of the new interface or use composition:

interface MyNewInterface extends MyOldInterface {
     FancyNewInterface getFancyShit();
}


问:
Why do people still say Java is slow?
For a long time in SO and in other places Java has the reputation of being slow. From jokes to many comments in questions and answers, people still believe Java is slow based solely on experience with it in the 90s.

This is my issue: we have disproved (most) of the reasons that people believe Java is slow. Outside of small things, Java is pretty fast.

So why is it that people still refuse to believe Java is fast now? Is it part of their mindset that anything thats not C/C++ is slow? Is it because people don't check over time? Is it because people are just biased?

答:
Simple, canonical Java code tends to be on par with or faster than simple, canonical C/C++/D code.  Simple, canonical code tends to perform a lot of memory allocations unnecessarily, not be particularly tuned to any CPU architecture, not have tons of low level optimizations done to it, etc.  Java's HotSpot GC is nothing short of amazing, and the VM optimizations tend to be better than what a static compiler could do.

On the other hand, if you really need performance and are willing to hand-tune stuff to get it, C/C++/D provides many more opportunities for this.  You can't use inline assembler in Java.  You can't use dirty type punning tricks to treat floating point numbers as arrays of bits.  You can't use custom memory management schemes that may be faster than the GC for your specific use case.  You can't allocate nearly as much on the stack in Java as in C/C++/D.  In Java the only way to get anything roughly equivalent to higher order functions is with interfaces and runtime binding.  In D and (I think, correct me if I'm wrong) C++, you can pass functions to templates, allowing for binding to happen at compile time without loss of flexibility.

Title: Why do people still say Java is slow?

ContentLicense: CC BY-SA 2.5


问:
What is sharding in MongoDB?
I came across sharding in MongoDB but did not get what exactly is it. What I understood is it's better to have more small servers than a huge one for data storage and when the data exceeds the capacity of one server you can use another machine to store data. Can anyone give some more idea about sharding?</p>

答:
In a database a shard is when you break up a set of data across multiple servers. So for example if you had users could you put those with a name starting with A-E on one, server, F - K on a second and so on. That way the load of dealing with the operations on those users will be broken up across several servers. The reason you want to do this is because it is possible that you have too many users to put them all on one machine. By doing this it is possible to scale the system as large as you need by just adding more shards. If everything was one one server then you would be limited in scale to how big a server you can buy.

Of course you don't really want to break it up by letters of the alphabet you would want to use something that would on average make each shard have an approximately equal share of the work, but that is a detail (If an important one)

ContentLicense: CC BY-SA 4.0

Title: What is sharding in MongoDB?


答:
If you are familiar with the mathematical vector you might see a use in overloading the + operator. You could add a vector a=[1,3] with b=[2,-1] and get c=[3,2].

Overloading the equals (==) can also be a useful (even though it's probably better to implement a equals() method). To continue the vector examples:

```<code>v1=[1,3]
v2=[1,3]
v1==v2 // True
</code>```

Title: Examples of operator overloading, which make sense

Body:
While I learning C#, I found that, the C# supports operator overloading. I have problem with good example which:

Make sense (ex. adding class named sheep and cow)

Is not an example of concatenation of two strings

Examples from Base Class Library are welcome.

Body:
If you are familiar with the mathematical vector you might see a use in overloading the + operator. You could add a vector a=[1,3] with b=[2,-1] and get c=[3,2].

Overloading the equals (==) can also be a useful (even though it's probably better to implement a equals() method). To continue the vector examples:

v1=[1,3]
v2=[1,3]
v1==v2 // True


问:
Where to define view-specific data objects in Rails
Background: there are several places in our app where we want to display date-oriented information on a calendar. The event_calendar gem looks nice and has lots of reviews, so it's what I'm planning to use. However, it's designed to work with a model. I'm not going to update our existing models to meet its needs, so will create a DTO class and a helper function to construct an array of instances from our existing models.

My question is: where should that DTO class live? It seems like it should be defined inside ViewHelper, but that will violate DRY as soon as I use the calendar for two models (note: the helper functions will differ, it's just the DTO class that will remain the same).

So, is there a standard place in the Rails directory tree where non-model-related classes live?

Or is there a better/more idiomatic way to do this? One thought that I had was to make my helper function decorate the existing model instances with the methods that event_calendar wants to see.

答:
If you find you are repeating yourself a lot, you might want to take a look at the cells gem. Cells are basically mini-controllers that are especially useful when creating widgets and the like.

The readme sums it up nicely:

Say you’re writing a Rails online shop - the shopping cart is
  reappearing again and again in every view. You’re thinking about a
  clean solution for that part. A mixture of controller code,
  before-filters, partials and helpers?

No. That sucks. Take Cells.


答:
I think you've got it right. Asserts are for failing fast after a programmer error is detected.

If you know the application will crash or otherwise be left in a bad/unknown state, then assert.

Title: Asserting in public methods


问:
How to map TFS to two local directories
I am working with a web application, using TFS.  Every time I build the site it takes an unproductivly long time to start up again.  I would like to have a second mapping of the site on my c drive, where I would only get latest and build once a day, so this version would always be fast.  This would be like a "readonly" directory as I wouldn't personally make any edits to it.

Please let me know if this possible, or if you have any alternative.

答:
One workspace does not allow the same TFS folder to be mapped to more than one local directory.

However you can have two or more workspaces for one computer, and each workspace can map a TFS folder to a different local folder. What revisions of files are in each workspace is tracked separately (to keep each up to date you need to do a get in each: easy with 'tf get' from the command line).

Title: How to map TFS to two local directories


答:
I suspect mine may be a minority view, but personally I view asserts in anything other performance bottlenecks as a premature optimization.

Generally if a pre-condition is worth checking in debug mode it is worth checking in release mode. Of course if you have profiled your code and discovered that you need to wring every last clock cycle out of a function then asserts bridge the gap between no pre-condition checking (which may be necessary if you need to meet a timing constraint even in debug mode) and speed in release mode.

i.e. don't disable pre-condition checks unless you have to

Title: Asserting in public methods


答:
In case of a public library (that some other people will also use) you should throw an exception instead of putting assert. This is also the way how Java API is designed.

And one day your code may be turned into a library...

So I personally always throw IllegalArgumentException in such cases
or as in your specific example it can also be NullPointerException.

Title: Asserting in public methods


答: TFS has a build agent built in, you can create a build to run daily or nearly any other way you can think of, though you would have to set up something to be a build server i believe.</p>

Title: How to map TFS to two local directories

Body:
I am working with a web application, using TFS.  Every time I build the site it takes an unproductivly long time to start up again.  I would like to have a second mapping of the site on my c drive, where I would only get latest and build once a day, so this version would always be fast.  This would be like a "readonly" directory as I wouldn't personally make any edits to it.

Please let me know if this possible, or if you have any alternative.


问:
Help needed with class design and structure
This question is mostly about the best way to approach this problem. Any input is appreciated.

The Problem

In my application i need to send some data to a number of different destinations (we will call them receivers from now on) using different protocols (http post, ftp, soap services). Each of the different receivers respond differently and some processing needs to be done on each response to work out what happened. This response processing can become quite complex.

My application also needs to do take different actions based on the receiver.

My Solution

My plan is to create a separate class for each receiver that implements an interface and use Factory design pattern to decide which class to load based on the receiver. Each receiver has a unique name (which is stored in the database for other reasons) which i plan to use to decide which receiver to load. I'll pass this to the factory constructor.

Currently i plan to have my interface implement these methods

prepareData()

sendData()

handleResult()

I'd also like a wrapper for these function such as process() which would just return a boolean based on wether the send sent. I'm not sure where i would fit this in though.

Thanks

答: You can also check out the Template Method Pattern, this will help you encapsulate the process/algorithm. </p>


问:
SCRUM from scratch, with no base framework established?
We are a small group of 5 people that is about to start a new project. This is the first project where we will go all-in on scrum.

We are struggling a bit with how we are going to establish a base for the project (frameworks and the like). Such tasks are not something the user will benifit from directly, so we are having a hard time figuring out how we write user stories for it.

So in general, how do you use scrum, when you are starting a project from scratch, with no frameworks and no base library in place?

答:
These are the pre-requsites that we established before implementing SCRUM in our team. Once you are done with the list , then you can roll out the process and tools for actual scrum.

Team members are highly or moderately skilled.

Team is tightly knit.

Information exchange among team members is fast, consistent and free flow.

Team is co-located.

Business is highly involved with team.

Architecture ( Business, Information as well Technical) is well defined.

Infrastructure is up and running – Dev, test and UAT environment.

Automated build and release.

High level of test automation.

Team’s dependency on external world is minimum (ideally zero).

Participating systems count is minimal.

Requirements are stable at higher levels so product backlog has minimum changes.

Team members are autonomous to take decision on what user story should be part of sprint/scrum as well as total numbers of scrums/sprint needed to achieve stated goal.

Other two important parts:

Select the people for the roles ( Scrum master, Product owner and the team)

Have your white board ,stickers ready.


答:
I don't think that a lot of of agile methods handle the activities that are typically part of project inception well. Many of the common frameworks (XP, Scrum, Kanban) don't address this concern, but some of the scaled frameworks (Disciplined Agile Delivery, SAFe) do to some extent.

Some people advocate for a concept of an initial increment (in Scrum, a sprint) that is designed to set up your project. This is often called Increment Zero (or, in Scrum, Sprint 0). However, it's not a formal part of Scrum and purists say that the first Increment should be potentially releasable.

Such an increment is used to set up the team's environment - set up your development, test, and production environments, configure your supporting tools and scripts, and establish your working environments with burndown charts and backlogs. If anyone on the team is not familiar with the development tools being used, this is where they learn the basics to function and begin producing output in the first iteration.

Along side this, you'll often be starting to write your first user stories and prioritizing your product backlog, since there isn't a sprint backlog at this point. Whoever is the Product Owner will be devising stories. If this person is new to Scrum, they would be learning how to write good user stories that the team can work with, as well. Don't emphasize getting all of the stories, but you'll want enough to kick off the first development iteration.

Different teams handle Sprint 0 differently. Some might timebox it at the same duration as any other sprint. Others might make it a little longer or a little shorter depending on the needs of the team. Since this is your first attempt at Scrum, I might make it longer, especially if you have a shorter iterations as part of your development cycle. If you are planning on two week iterations, make it 3 weeks.

As far as formulating the tasks, I wouldn't necessarily formulate them as user stories. You could, from the perspective of team members and various roles (Product Owner, ScrumMaster, developer, tester, designer, technical writer, and so on). However, Sprint 0 is for the team, not for the customer or the user. A simple list of tasks and activities would suffice.

Title: SCRUM from scratch, with no base framework established?

Body:
We are a small group of 5 people that is about to start a new project. This is the first project where we will go all-in on scrum.

We are struggling a bit with how we are going to establish a base for the project (frameworks and the like). Such tasks are not something the user will benifit from directly, so we are having a hard time figuring out how we write user stories for it.

So in general, how do you use scrum, when you are starting a project from scratch, with no frameworks and no base library in place?


问:
How to Console.WriteLine from [TestMethod]?
I am trying to show some information from a [TestMethod] method.

Usually we use NUnit and a line with Console.WriteLine runs fine and we can see it in 'output' window, but on this project we must to use Testing tools embebed with VS2010 and Console.WriteLine doesn't run because we cannot see anything.

答:
Why do you need to "see anything"?

You should just use asserts to validate the test has worked correctly.


答:
You can set the standard output and input of Console to be a TextWriter / TextReader and perform asserts based on the content of those.

http://msdn.microsoft.com/en-us/library/system.console.setout.aspx

Title: How to Console.WriteLine from [TestMethod]?

Body:
I am trying to show some information from a [TestMethod] method.

Usually we use NUnit and a line with Console.WriteLine runs fine and we can see it in 'output' window, but on this project we must to use Testing tools embebed with VS2010 and Console.WriteLine doesn't run because we cannot see anything.


答:
I agree with the previous poster that if you need to verify something you assert it...

However... Your Console.WriteLine() message will show, after your test has completed double click the test result line in the Test Results tab, this will open the results for the individual test which contains a "Standard Console Output" section which has your Console.WriteLine() messages.


问:
Does giving a developer a slower development machine result in faster/more efficient code?
Suppose I give my developers a screaming fast machine.  WPF-based VS2010 loads very quickly.  The developer then creates a WPF or WPF/e application that runs fine on his box, but much slower in the real world.

This question has two parts...

1) If I give a developer a slower machine, does that mean that the resulting code may be faster or more efficient?

2) What can I do to give my developers a fast IDE experience, while giving 'typical' runtime experiences?

Update:

For the record, I'm preparing my even-handed response to management. This isn't my idea, and you folks are helping me correct the misguided requests of my client.  Thanks for giving me more ammunition, and references to where and when to approach this.  I've +1'ed valid use cases such as:

- specific server side programming optimizations

- test labs

- the possibly buying a better server instead of top of the line graphics cards

答:
The run-time speed on developer machine is so irrelevant, unless you want to revenge or punish your developer for writing slow code and for ignorance of target deployment environment.

As the manager, you should make sure the developers knows the objective of the project and always ensure they are on track. About the target machine issue we are discussing, it could be prevented by early and frequently testing on slow machine, not by giving them slow machine to use and be suffering.

The slow run-time speed also slow down development, as most programmers are using code-and-test method. If the run-time is slow, their task will be slow too.


问:
Pattern for group of entities with one required primary member
Given a parent entity with a collection of child entities where there must be exactly one primary child of the group?

To make the question more concrete, I've seen a number of ways that this pattern might come up -- a group of people where one person is the leader or the contact details for a person where one is primary. Here are two different approaches that I've seen.

1. Flag the member as primary
In this approach, a field is added on the member to designate it as primary. The advantage is that it is simple to implement and avoids additional relationships. The disadvantage is that it is more difficult to enforce in the data model that one and only one member is primary and from an object perspective, potentially puts the responsibility on the child that should be on the parent.

2. Additional association
In this approach the parent tracks the primary member of the group and stores the id of the child. This is in addition to the children storing the id of the parent as a member of the group. This makes it explicit in the data model that there is only one primary member and an index can be added to enforce it. The disadvantage is that it requires two relationships and there is a chance that they can disagree (parent points to a child that doesn't belong to the parent).

It seems to me that this is a common pattern and must be documented as a design pattern or model pattern in an architecture book somewhere. A similar pattern might be where the collection is a history and there is one current, but that is a bit easier as each member would have a date range that can be indexed. Are there better approaches? Or can someone point to where this pattern might be documented more formally?

答:
I would go with option (1) because in addition to the features you have correctly identified, it takes little processing specially when the number of children is small. You only need to access the child table in case of Insert, Read or Update.

The problem with (2) is that whenever you update the child or insert a new primary child, the parent has to be updated. While this can be done in many ways, it looks like it has no special practical value and also, the column would not logically belong to the parent.

Other problems with approach (2):

Approach (2) represents a 1-1 relationship on the data model (which is usually recommended to be avoided).

If you delete the row designated as a primary child from the children table, what will you do for the parent row? This requires 2 updates.

This pattern is a sort of a special case from the m-m to pattern, but it would be too complex to implement an m-m pattern for this case. The special case being that the intersection table is a singleton.


问:
Using php functions, reserved words as local identifiers
I'm thinking of some of the array functions. "key", "each", "pos", "range". These are often very useful as local identifiers! I have also seen code that (ab)uses $return, $list, $array, $string. What are other PHP programmers views on this?

Local identifiers only! I wouldn't use them as members or method names of a class, even less global variables.

答:
I don't see any problem with (ab)using identifiers like $key, $array, $return, etc.

The fact is, $key is not the same symbol name as key(). $namespace is not the same as namespace: they don't write the same, and they don't mean the same. I'd say this is a nice feature of PHP, and Perl too.

It clearly demonstrates your intention:

```<code>$string = 'yay';   // I'd be very surprised if referencing this returned a float

$array[] = 'baz';  // I know that it is an array, and not a ArrayAccess object, etc.

$key = 'bar';      // I know this refers to an array key, or a cache key, or more generally
                   // some sort of unique identifier

$return = 'hello'; // I know this is going to be returned at some point
</code>```

Body:
I don't see any problem with (ab)using identifiers like $key, $array, $return, etc.

The fact is, $key is not the same symbol name as key(). $namespace is not the same as namespace: they don't write the same, and they don't mean the same. I'd say this is a nice feature of PHP, and Perl too.

It clearly demonstrates your intention:

$string = 'yay';   // I'd be very surprised if referencing this returned a float

$array[] = 'baz';  // I know that it is an array, and not a ArrayAccess object, etc.

$key = 'bar';      // I know this refers to an array key, or a cache key, or more generally
                   // some sort of unique identifier

$return = 'hello'; // I know this is going to be returned at some point


问:
Do I need to test everything?
I'm going to start my first real project in Ruby on Rails, and I'm forcing myself to write TDD tests. I don't see real advantages in writing tests, but since it seems very important, I'll try.

Is it necessary to test every part of my application, including static pages?

答: If you're truly using the TDD methodology then you don't write code without first having a unit test you are trying to make pass.</p>

Title: Do I need to test everything?


问:
How do you measure the effectiveness of your hiring & interview process?
Although I've seen many discussions on how to do an interview and develop your brand, I haven't seen many discussions on how to determine if your hiring & interview process is actually working well. I think this question has two parts:

How do you know your hiring process is getting the right candidates to apply and go through the interview process?

Of the people that you end up interviewing, how can you tell that the ones you choose to hire are better (on average) than those that you rejected?

I suppose the "extreme" cases - when you end up with a superstar or a total dud - are pretty obvious, but what about the rest?

答:
Lead time is an important metric.

Measure the total time from the day a need for a new open position is established to the new employee's starting date.  The lead time for an existing employee to leave a company may be as short as two weeks (the "two-week notice"), so if your lead time to hire measures in months, that's a problem.

There are numerous and sometimes creative ways companies can waste time in the process.  If you know what your typical lead time is and it is indeed too long, you can find ways to shorten it.  Consider if a particular time interval is value-adding; if it is not value-adding, it's waste.

Lead time has nothing to do with the quality of candidates or new hires, but if it is too long, it affects quality indirectly, as better candidates find work elsewhere.

ADDED: some time after I wrote this, I discovered this blog post - basically how to do lean HR and recruiting and eliminate waste from it.  It's endorsed by some of the best in business.

ADDED: Since I posted this answer, I have lost one referral.  A very qualified candidate took less than two weeks from the resume submission to onboarding (at a different company, obviously).  If your time from resume submission to scheduling a phone interview is two weeks, that's as if such candidates don't exist at all.


答:
It's always a cost-benefit analysis. What's the cost of the feature breaking to you? If the cost is high, then test well and thoroughly. If the cost is low, test lightly or not at all.

There's also the cost of time-to-market to consider. Maybe it's better for you to deliver a mostly working feature than to be late delivering a completely working feature.

It's almost impossible to answer these questions in the general IMO.

I think it's more important to preserve the ability to test in the case that some feature turns out to be more important than you originally realized.

Title: Do I need to test everything?

Body:
I'm going to start my first real project in Ruby on Rails, and I'm forcing myself to write TDD tests. I don't see real advantages in writing tests, but since it seems very important, I'll try.

Is it necessary to test every part of my application, including static pages?


问:
Options within OpenCV related to image difference analysis and reporting
Scenario: Stationary view with sequential timestamped samples in 2D-color where the comparison is only done between one pair of neighboring samples.

Background:

Have never used OpenCV before,

Limited understanding of computer vision,

Moderate experience scripting programs.

Questions:

Given the information provided, what additional information would be of use?

What existing related analysis and reporting solutions within OpenCV should I look into more?

UPDATES:

What is the source of these images? I've abstracted the intent of a problem to the degree in an attempt to avoid skewing how the answers conceptualize the related solutions. Disclosure-of-Problem-Domain: It's possible that I'm wrong about the value of abstracting the problem domain, and since it's already been guessed, I'll confirm the domain is any high-value automated GUI testing that is of relatively low-complexity. Currently, seems like simple regression testing based on pixel-for-pixel change which is then sorted by the percentage of pixels change on a pair-by-pair basis would be quick and produce value, but the template matching suggested by Martin Beckett might allow for cross-platform testing, though again not knowing much about OpenCV, or the domain of computer vision, it's hard to say complex or valuable such an approach might be currently.

What is the same? Depends on the solutions OpenCV offers in the context of image difference analysis and reporting. Any artifacts related to the capture would/should be accounted for in the comparison analysis. Ideally, difference reporting should by default (or predictive coding) only profile material significant state changes in a way that allows the manual response to them to be prioritized.

What are the circumstances of the image capture? All pairs are sampled within a highly controlled environment with the same stationary view/angle, lighting, exposures, focus, etc.

答:
You have pairs of images that you want to compare?

What is the source of these images?

ie. Screen shots of a gui testing app or low quality noisy CCTV

What are the circumstances of the image?

Is it the same calibrated fixed camera at the same angle.
Are these hand held shots at different exposures, focus and angle

What constitutes 'the same' ?

ie. Every pixel value identical.
The art work isn't missing.
It's the same person.
They are both pictures of a tree

It basically comes down to two approaches, histogram and structure.

Histogram approaches just count the number of pixels of each colour in the two images. If you are only trying to find the pair that are a face then having a similar percentage of skin coloured pixels is probably good enough. For skin you often do this in a different colour space.

Structure means looking for particular shapes and objects in the scene. There is an opencv Tutorial on template matching. But this normally requires high quality very similar images (same angle, scale, exposure). Or there are more complex procedures to identify features and look for patterns in the ratio of various distances - this is how most biometrics work.

edit: If you are comparing very similar images, eg screen shots from a gui test tool, and you only need to know if two are identical then you need to calculate a hash of the image and compare that.

Simplest is just a histogram of pixel values - but this wouldn't detect if an identical window had moved on screen for example.
The next easiest is a list of features found by SURF


答: I would say "yes". If you have tests covering even the simplest features and code, then you can have confidence that adding new code doesn't cause in-place code to quit working. Similarly, putting in a test for every bug you encounter keeps regressions from creeping back in.</p>

Title: Do I need to test everything?


答:
TDD isn't about testing, it's about design.  Writing the tests forces you to think about how the class is supposed to work and what kind of interface you need.  The tests are a happy side effect that makes it easier to refactor later.

So, with that in mind, what is the behavior of a static page and what is the interface?

My first response would be "none" and "none".

Title: Do I need to test everything?


答:
Yes, you should test everything...

You won't necessary be able to write automated tests for everything.  For your static pages, look into using Selenium http://seleniumhq.org/ for making sure things are correct.

From my experience, some front end things are next to impossible to write test cases for but that is why you would actually want to test using the Mark 1 eyeball.

Title: Do I need to test everything?


答:
Track the primary object on the parent object

My reason for this is that your parent object has two attributes: A list of children and a primary child. Since both are attributes of the parent object, the parent object should contain these properties.

The only time I would put an IsPrimary property on a child object is if the child object actually needed to know if it was a primary object or not, and even then child objects should not need to be aware of other child objects to maintain it's values, so a parent object should still be responsible for setting the IsPrimary property.

If you're concerned about your child objects referencing the wrong Parent object, then have the parent object set the Parent property on all children when they get added to the parent object's child collection.

As for a name for this, I don't know. Sounds like a ComboBox or ListBox - something that holds items and allows for one to be selected.

Title: Pattern for group of entities with one required primary member

Body:
Given a parent entity with a collection of child entities where there must be exactly one primary child of the group?

To make the question more concrete, I've seen a number of ways that this pattern might come up -- a group of people where one person is the leader or the contact details for a person where one is primary. Here are two different approaches that I've seen.

1. Flag the member as primary
In this approach, a field is added on the member to designate it as primary. The advantage is that it is simple to implement and avoids additional relationships. The disadvantage is that it is more difficult to enforce in the data model that one and only one member is primary and from an object perspective, potentially puts the responsibility on the child that should be on the parent.

2. Additional association
In this approach the parent tracks the primary member of the group and stores the id of the child. This is in addition to the children storing the id of the parent as a member of the group. This makes it explicit in the data model that there is only one primary member and an index can be added to enforce it. The disadvantage is that it requires two relationships and there is a chance that they can disagree (parent points to a child that doesn't belong to the parent).

It seems to me that this is a common pattern and must be documented as a design pattern or model pattern in an architecture book somewhere. A similar pattern might be where the collection is a history and there is one current, but that is a bit easier as each member would have a date range that can be indexed. Are there better approaches? Or can someone point to where this pattern might be documented more formally?


答:
Testing is as important as coding. You must heard the saying "If something can go wrong, it will". INMO, Out of the many techniques of software engineering that are employed to enhance quality, Testing is the most valuable one in helping you find problems early.

While testing everything is not possible (specially with small teams and large systems), it does not mean you skip testing altogether. Is testing worth it? See the section "Finding faults early" in See Wiki-SoftwareTesting.

Title: Do I need to test everything?


答:
The reason they bother me is not because they are reserved words within the language itself, but rather that they are too general. What does the $array contain? What is it an array of?

$list, $string, $array, $key, etc are far too generic and not descriptive enough variable names to be useful. Especially when debugging someone else's code.

Even in the context of local variables, having more descriptive variable names would make understanding what the code is doing much much faster.

Title: Using php functions, reserved words as local identifiers

Body:
I'm thinking of some of the array functions. "key", "each", "pos", "range". These are often very useful as local identifiers! I have also seen code that (ab)uses $return, $list, $array, $string. What are other PHP programmers views on this?

Local identifiers only! I wouldn't use them as members or method names of a class, even less global variables.


答:
"key", "each", "pos", "range". These are often very useful as local
  identifiers!

Disagree. They are too generic as pointed by another answer. To generic variable is not a good variable, unless the program is one page long.

The good thing is PHP allows them to be used as variables and do not give you some strange error as in .NET. If php is intellegent enough to know what is a variable and what is not, it is a good thing.

```<code>Should I use it as variable or function names?
</code>```

The whole purpose of writing good code is that it should be clean, easy to read and maintain and with less confusion. You would be adding to confusion if you use reserved keywords as variable names and function names. Keeping in traditions with other languages, it is a bad practice to use keywords as variable names etc. In short, you should be consistent, do not use keywords purpose other than keywords (and also to comply with other languages), but if you want to, you can.

Here is a quick program that I wrote which is perhaps only possible in PHP :)

```<code><?
$n1= 2;
$n2= 5;

echo "The sum of $n1 and $n2 is ".addnumbers($n1,$n2);

function addnumbers($a, $b)
{
  $return = $a+$b;

  return $return;
}
?>
</code>```

Body:
"key", "each", "pos", "range". These are often very useful as local
  identifiers!

Disagree. They are too generic as pointed by another answer. To generic variable is not a good variable, unless the program is one page long.

The good thing is PHP allows them to be used as variables and do not give you some strange error as in .NET. If php is intellegent enough to know what is a variable and what is not, it is a good thing.

Should I use it as variable or function names?

The whole purpose of writing good code is that it should be clean, easy to read and maintain and with less confusion. You would be adding to confusion if you use reserved keywords as variable names and function names. Keeping in traditions with other languages, it is a bad practice to use keywords as variable names etc. In short, you should be consistent, do not use keywords purpose other than keywords (and also to comply with other languages), but if you want to, you can.

Here is a quick program that I wrote which is perhaps only possible in PHP :)

<?
$n1= 2;
$n2= 5;

echo "The sum of $n1 and $n2 is ".addnumbers($n1,$n2);

function addnumbers($a, $b)
{
  $return = $a+$b;

  return $return;
}
?>


问:
Communicating details of method result?
I have code like this (pseudocode)

```<code>foreach(Box box in boxes)
{
    if(boxFilter.PassesFilter(box))
    {
      // do something useful
    }
    else
    {
      Log.Log(format("Box %s was rejected", box.BoxId))
    }
}
</code>```

But now I'm thinking I'd like the log message to have more information such as "Box 1 rejected because too tall" or 'Box 549 rejected: 25" height exceeds Max height of 24"'.

What's the best idiom to get this information into the log?  Do I have to create a FilterResult object that is returned from the PassesFilter method? Or I guess I could also throw an exception and catch it and log it? Or something else?

I happen to be using C++.

Update

In addition to logging I might want to also present a message to the user in the UI.

答:
For these situations, You can come up with a Response class which has a list of warnings, errors and information messages.

In this way, You can keep on adding errors to this response and return it back to the caller.

Also you dont have to add code in all the methods for logging errors. In a higher level(facade caller), you can add a check that if the response has errors or warnings, You can log them all.

Something like this (pseudo)

public class Response {

```<code>List<String> errors;
List<String> warnings;
List<String> infos;

}
</code>```

In your code

```<code>foreach(Box box in boxes)
{
    if(boxFilter.PassesFilter(box))
    {
      // do something useful
    }
    else
    {
      response.addError(format("Box %s was rejected", box.BoxId))
      return response;
    }
}
</code>```

--- In a higher level for all callers

```<code>If(response.hasErrors or warnings) {

logger.log(response.getErrors());
logger.log(response.getWarnings());

}
</code>```

Title: Communicating details of method result?

Body:
For these situations, You can come up with a Response class which has a list of warnings, errors and information messages.

In this way, You can keep on adding errors to this response and return it back to the caller.

Also you dont have to add code in all the methods for logging errors. In a higher level(facade caller), you can add a check that if the response has errors or warnings, You can log them all.

Something like this (pseudo)

public class Response {

List<String> errors;
List<String> warnings;
List<String> infos;

}

In your code

foreach(Box box in boxes)
{
    if(boxFilter.PassesFilter(box))
    {
      // do something useful
    }
    else
    {
      response.addError(format("Box %s was rejected", box.BoxId))
      return response;
    }
}

--- In a higher level for all callers

If(response.hasErrors or warnings) {

logger.log(response.getErrors());
logger.log(response.getWarnings());

}


问:
How do you find time to work on Open Source Projects?
A bit of background: I've got a small open source project that I've started on, a basic framework which provides an object oriented means of generating HTML code (since I don't really like HTML, and I do like PHP). It has some released source, and a few downloads, but primarily, the project is for me, with the Open Source portion just being a side benefit.

The original project which caused me to be able to develop on this project has mostly gone into hibernation for the time being, which means that all the development I get to sink into it at this point is personal time only. Unfortunately, I'm currently working toward my bachelor's degree, studying for certifications, and I have a three month old baby at home. In short, by the time I get around to "me time", I rarely feel like doing work, but rather usually feel like just chilling out.

So, if there's anyone else out there who feels like they're in a similar position, what strategies have you used to keep yourself motivated toward working on the project? I would really like to at least be able to work on this until I have 100% spec coverage, but I haven't committed source in months. Anyone out there who can help?

答:
Chilling out might not be such a bad idea. Young babies take a lot of energy, so you might consider saying to yourself "OK, 3 month break from non-essential programming".

Take the time to relax while you can, and either wait for inspiration to strike (rather than trying to squeeze it out), or write down (in prose or code) some rough ideas on where you'd like the project to be, or how you'd like the code to look.


问:
How do you evolve & version an interface?
Say you have an interface IFoo:

```<code>public interface IFoo {
    void Bar(string s);
    int Quux(object o);
}
</code>```

In version 2 of your API, you need to add a method Glarg to this interface. How do you do so without breaking your existing API users and maintaining backwards compatibility? This is mainly aimed at .NET, but can apply to other frameworks & languages as well.

答:
An interface is a contract, therefore it should not have versioning.  What happens if a football player gets a new contract?  Is the old one still valid?  No.  If one changes the interface, the contract changes and the previous contract (interface) is no longer valid.

Although you could use the IFoo2 strategy, eventually that will become messy when you have:

IFoo2

IFoo3

IFoo4

etc.

Yuck.

An API is different.  I give library of code to use.  Next month I give you an updated library.  As another poster has said, don't break what I am already using, just add new functionality/methods.

If you want to version something, use an abtract class instead of an interface.


问:
Evolutionary behavioural programming resources
A while ago I made Conway's Game of Life. I'd like to make something similar (in C++), where each cell would exhibit behaviours such as:

Movement

Reproduction

Killing of other cells (moving onto another cell, for example)

Over time, the cells would 'learn', and I'd (hopefully) end up with a set of behaviours that are beneficial to the ecosystem as a whole, rather than the individual cell.

I'm 100% sure that this isn't new, but I don't know:

What technical terms cover what it is I'm trying to do (what keywords cover my aim such that I can search for other implementations),

Resources, preferably online, although dead-tree style is also good, which would be beneficial reading for this type of programming.

How I should implement this (#2 would help with this); I can modify my cells to do some things (moving, for example), but I'm not sure how I should implement the learning; should I be using a genetic algorithm or is some other type of evolutionary algorithm better suited?

答: What you seem to be looking for is the science of cellular automata. A good introduction you may find in the wiki. A common way but not the only one to implement these is by using finite state machines. You cab certainly choose genetic algorithms to implement learning, but first try to figure out what exactly you want. With these concepts you should be able to find resources and books.</p>


问:
Is the Waterfall software development methodology still viable?
In my experience, it seems as though the Waterfall model has proven to be too inflexible and non-responsive to requirements changes to be considered a viable method in the modern world of software development. The growth and proven track record of more agile, iterative methods seems to indicate that there is no reason why anyone should be following a process of rigid blocks that assumes little to no changes from project inception to product delivery.

Is is the waterfall development methodology still viable for delivering software systems, with respect to time, cost, and quality?

答:
To who?  Most of the managers I have dealt with still use the Waterfall Software Dev Process for scheduling, and up levels seem to like it for easy of scheduling.

Practically, very few developers I know believe it works or is even valid.


答: The mythical waterfall process that is most often compared against agile never existed and therefore can not be considered dead. Real waterfall processes are still alive and well, and excelling at delivering on time on budget software that meets user expectations.</p>

Title: Is the Waterfall software development methodology still viable?

Body:
In my experience, it seems as though the Waterfall model has proven to be too inflexible and non-responsive to requirements changes to be considered a viable method in the modern world of software development. The growth and proven track record of more agile, iterative methods seems to indicate that there is no reason why anyone should be following a process of rigid blocks that assumes little to no changes from project inception to product delivery.

Is is the waterfall development methodology still viable for delivering software systems, with respect to time, cost, and quality?


问:
what's the most efficient emacs workflow for compilation and interactive execution cycles (C++/makefile)
I try not to cross-post, but the only response I got at stack-exchange was to post here...

What's the preferred practice for a compile-run cycle in emacs?

Previously, I used alt-x compile (mapped to F12) with make as my compile command. Within the Makefile I had an entry which would run the program that was compiled. This worked fine when my programs were non-interactive, but the compilation buffer is non-interactive.

Of course I could open a shell and run the executable, but I'd like to automate the compile-run cycle as much as possible and I assume there must be a standard practice for this and I'm guessing my executing-from-the-makefile method is a kluge...

C-u F12 works, but I'm wondering if that's the best approach for doing this (and if so, how can I bind F12 to be equivalent to C-u alt-x compile instead of just alt-x compile?).

答:
Here's how I do it:

Use emacs in completely default settings. No special key bindings.

Open terminal (and keep it open) and type "make" in it for compilation.

for executing the program, ./main seems to be the most common way for me

editing a new file is either c-x c-f, or most commonly in terminal "emacs foo.cc"

Move mouse cursor between emacs window and terminal window depending on whether you want to edit or compile

This approach has several advantages: several emacs instances are possible without confusing  which window is meant for compilation, and no .emacs file copying is required when you move from one computer to next and debugging with valgrind or gdb is also easy when terminal window is open

Unfortunately there is exception to nice rule of no special key bindings. goto-line is so important feature that it needs to be bind to key c-x g and c-c g.

I mostly use the following commands from emacs:

```<code>C-x c-f find a file
C-x C-s save a file
esc-<   beginning of file,
C-s     search
c-x c-c exit emacs
c-x 2   split screen
c-x 0   remove split screen
c-x b   switch to another buffer
C-k     kill line
C-y     yank
</code>```

Body:
Here's how I do it:

Use emacs in completely default settings. No special key bindings.

Open terminal (and keep it open) and type "make" in it for compilation.

for executing the program, ./main seems to be the most common way for me

editing a new file is either c-x c-f, or most commonly in terminal "emacs foo.cc"

Move mouse cursor between emacs window and terminal window depending on whether you want to edit or compile

This approach has several advantages: several emacs instances are possible without confusing  which window is meant for compilation, and no .emacs file copying is required when you move from one computer to next and debugging with valgrind or gdb is also easy when terminal window is open

Unfortunately there is exception to nice rule of no special key bindings. goto-line is so important feature that it needs to be bind to key c-x g and c-c g.

I mostly use the following commands from emacs:

C-x c-f find a file
C-x C-s save a file
esc-<   beginning of file,
C-s     search
c-x c-c exit emacs
c-x 2   split screen
c-x 0   remove split screen
c-x b   switch to another buffer
C-k     kill line
C-y     yank


问:
What can programmers learn from the construction industry?
When talking with colleagues about software design and development principles, I've noticed one of the most common sources for analogies is the construction industry.  We build software and we consider the design and structure to be the architecture.

One of the best ways to learn (or teach) are through analyzing analogies - what other analogies can be drawn from construction?  (whether already in common use in software or not).

Please provide a description, or your personal experience, regarding how the programming concept is similar to the construction concept.

[Credit to Programming concepts taken from the arts and humanities for the idea]

答:
Repetitive strain injuries

They're an occupational hazard in both industries, and precautions must be taken to prevent them. Once they start, they're difficult to cure.


问:
How should I setup a UI for editing a binary tree?
I need to allow the user to create an binary tree. I have a Backbone Model populating properly from the database, the problem I am stuck on is how do I setup the ui elements in a way that is fairly easy to use?

The general idea is I want to create a boolean expression that contains logic and tokens. The tokens will be replaced later at runtime with appropriate model data when the expression is evaluated.

You end up with a final expression like this:

```<code>((({Claim.State})=(TX))||(({Claim.PolicyState})!=(UT)))
</code>```

Ie, Evaluate to true if the State = TX or the Policy State is not UT

Each expression can be a terminating node, and will have a value, or will have no value, and the left and right will point to the next respective expressions and an Operator

The database structure looks something like this:

State Check: Left: 2 Right: 3 Operator: OR

State is TX: Left: 4 Right 5 Operator: Equals

State not UT: Left: 6 Right 7: Operator: Not

Claim State: Left: nil Right: nil Value: {Claim.State}

Texas Literal: Left: nil Right: nil Value: "TX"

Policy State: Left: nil Right: nil Value: {Claim.PolicyState}

Utah Literal: Left: nil Right: nil Value: "UT"

I am imaging something like for the Above expression, making a panel with 3 select lists, and a Label above it:

```<code>----------------------------------------------------------------
Name: |State Check|                     [.] Value [0] Expression
            Left (Edit/New)   Operator Right (Edit/New)
Expression: [ State is TX ]   [ Or ]   [ State is not UT ]
(Save)
----------------------------------------------------------------
</code>```

At this point I'm stuck. What should happen when say, the user wants to edit the left hand value? Do I open a new popup window to rerender the same form, just starting with 2 instead of 1 for the starting expression key?

Should I replace the existing form with the new values, and somehow keep track of where the user is in reference to the starting expression?

Maybe slide a new editor panel down below the current?

What do you guys think? I'm really stuck on what to do.

答:
Right. This should really be on UX, but I'll tell you where I think you're going wrong.

THE USER DOES NOT WANT TO "EDIT A BINARY TREE"

The user has no particular concept of left-hand values or nodes. Those are based inside your implementation approach to the problem.

The user has a task to complete. You need to consider what they will generally try to do (the use-case in UML or "user story" in agile), and build your UI around them accomplishing that task in the minimal number of actions.

For example, when you shop online, you don't deal with Secure Socket Layers,  Network Encryption or the structure of Amazon's databases or php scripts.

You put your shipping and payment details into a page and hit enter. You check the order and hit "Confirm"

Once you've done that once, the next time you want to do it, the process is optimised to reduce the number of payment steps you need to perform by loading your details already, so you just click to confirm.

You can even skip the confirmation step with 1-Click, so it's literally "find thing. press button. await delivery"

This is the approach you should be taking. Check what your user is trying to achieve. What do they load up your application and/or webpage to try and do, in the most general terms (e.g. Make a claim, organise a set of claims, handle a claim), and go from there.

If you get stuck with this approach, the UX people can help you, but always think "user interaction", not "ui interaction with backend".


问:
How is software for machines such as ATMs or TVs built?
As a beginner programmer I've only worked with programming computer based applications, but a question has been coming to my head very often since I started programming and I can't get it answered properly.

Machines don't act on their own, that's the programmer's job, he tells it what to do and when to do it, but my curiosity lies beneath computers. I'll take the examples of an ATM software on this post but keep in mind there are many others such as a washing machine display, or a TV, mobile phone, you name it.

How exactly is the software for these kind of machines built? I imagine it can't be identical to computer-based programming. What language do they use to make such things work and how does one get the job done? Are there programmers specialized on this kind of programming? What is the process of making these machines come to life?

答:
These types of devices are programmed using embedded programming.  This is a very low-level type of programming that deals heavily with logic and gates.

If you are interested in learning embedded programming hands-on, I would recommend looking into arduino.


答: There is definitely an embedded angle here. But these days you are seeing more and more advanced platforms on what would traditionally be called embedded devices. For example, LG and Samsung TVs both now have APIs and app stores. Sony TVs will be running Android.</p>

Title: How is software for machines such as ATMs or TVs built?

Body:
As a beginner programmer I've only worked with programming computer based applications, but a question has been coming to my head very often since I started programming and I can't get it answered properly.

Machines don't act on their own, that's the programmer's job, he tells it what to do and when to do it, but my curiosity lies beneath computers. I'll take the examples of an ATM software on this post but keep in mind there are many others such as a washing machine display, or a TV, mobile phone, you name it.

How exactly is the software for these kind of machines built? I imagine it can't be identical to computer-based programming. What language do they use to make such things work and how does one get the job done? Are there programmers specialized on this kind of programming? What is the process of making these machines come to life?


答:
As others have mentioned, in Ruby on Rails testing it is far more important than in (most) other languages. This is due to the lack of a compiler.

Languages such as Delphi, C++, VB.NET, etc... are compiled languages, and your compiler will pick up a lot of mistkes such as typos in calls to a method. In Ruby on Rails you will only know if there is a typo or a mistake in your code if that particular line of code is run or you are using an IDE that shows visual warnings.

As EVERY single line of code is important (otherwise it wouldn't be there) you should test every method you write. This is a lot simpler than it sounds if you follow some basic TBDD tools.

I found that Ryan Bates' Rails Cast on How I test was invaluable to me and really highlighted the simplicity of TBDD if done correctly.

Title: Do I need to test everything?


答:
It's known as Embedded Systems or Embedded Software Development. I'd recommend this book if you want to know more about the general process without going too much toward any one architecture. It even gives you a real time operating system to play with.

Embedded Programming is very architecture dependent. You are typically working under serious response, program size, error recovery, and cost constraints. For instance you might have a z80 (8 bit processor, they are everywhere) and perhaps a couple of kilobytes of memory to play with. You might only have a ROM to tell the system what to do and how to set up the program. It might also only be a couple of kilobytes in size. Why so little memory? Well if you manufacture 15 million of the little suckers; every penny becomes $150,000.

I'd suggest fiddling with something like Arduino or Scribbler Robots if you want to learn more by doing. As far as Languages go, C, C++ and Assembly are the typical set though Java can be used (and was in fact originally designed for this domain if you can stomach that thought) Others could definitely be used as well, I've known of Lisp and ML both being deployed.

Learn as much as you can about architecture as well because like I said, memory allocation and bitwise operations start getting really important.


问:
Scrum for specialists teams
Scrum is best for teams with generalists members, that is teams where 2 people at least can do the same tasks. My main concern is to find good solutions to adapt scrum (what to keep, what to remove, what to improve) for teams made of specialists?

Suppose you have a team of 5 developers (not real, just for the example):

One mathematician with strong skills in C;

One DB developer;

One Web Developer;

One UX/GUI developer;

One software architect;

Here, all are specialists and no one can replace someone else (I don't care about the risks of building such a team, I want to focus on scrum). So, in a scrum context, here are my thoughts:

Useless spring plannings: indeed, when the mathematician says that a specific task is worth 2 points, nobody can vote against him;

Useless team velocity metric: as everybody can allocate any number of points to his own tasks, computing velocity makes not sense;

Replace daily scrum meetings with weekly (longer) scrum meetings: as each member of the team is working on his own tasks, daily scrum meetings should be really important to keep a "team spirit". However, daily scrum meetings are supposed to last around 15 minutes. This is clearly not sufficient to understand what the others are doing and will do. Moreover, the mathematician will most of the time answer the same things: "I am still doing %&Lo( + ?$$+&)"... Weekly meetings would give more time. To keep the same meetings time between "initial" scrum meetings and "weekly" scrum meetings, each weekly scrum meeting should last (5 days a week, with 4 weeks sprints, with sprint meetings lasting 4 hours and daily meetings lasting 15 minutes): (4*60 + 20*15)/ 4 => 2h-2h30 which seems reasonable.

Or is scrum still usable? Maybe another agile technique should be used?

答:
Scrum is certainly still appropriate for your situation, but so could other frameworks.

To deliver new features you are likely to need all or many of these skills.  In order for the team to make decisions that impact one another and work together they'll need to communicate.  The longer the time between Scrum meetings, the longer a negative plan can stray the team.  By meeting daily, the team can address these situations quickly and come up with a new plan.

I would like to address some specific topics you bring up as well:

Cross Functional Teams
A team would be considered cross-functional if it has all of the skills needed to deliver on a sprint goal and/or product backlog item.  This does not mean that there are 2 people for every job.

Sizing
It's important to remember that we are sizing a business problem or need, not a solution or part of a solution.  For instance, Integrate social media/Twitter into our e-commerce site is a problem which requires UX, UI Design, Programming, Database, and knowledge of the Twitter API.  A team should be sizing that as a unit since they are, as a team, going to be delivering this functionality.  This size is not going to be 100% accurate, but we do find that, in aggregate, forecasts based on relative sizing are more accurate.  This means that some will be high, some will be low and taken together the calculated forecast is more accurate than estimated duration.

Useless spring plannings
Sprint planning is a time to collaborate as a Scrum Team (Development Team + Product Owner + Scrum Master) in determine what should be produced and coming up with a plan for how to begin.  Some teams will break these Product Backlog Items chosen into tasks while others will come up with their own way to progress, like tests that must pass (think XP).

This is a two way collaboration.  Assigning the team a set of PBI's and saying "go" is a dictator's role.  The team is negotiating with the Product Owner to maximize the time in the sprint.

Useless Team Velocity Metric
With teams sizing problems and needs of the business that cut through the architecture/system and past experience telling us how many of those the team have been delivered in a consistent time box (sprint), we can now provide a team forecast for the remainder of the backlog.

Again, no two sprints will be the same and the smaller the sample set of Product Backlog items you use, the less spread out the error in estimates will be.  Think of it like the stock market; it has always gone up, but that doesn't mean we don't have down years.  At  the aggregate you can make money, but on any given month, quarter, year you will guess wrong.

Replace daily scrum meetings with weekly (longer) scrum meetings
The Daily Scrum is there to provide the team with a 24hr feedback cycle and opportunity to plan for the next 24 hours.  Nothing more, nothing less.  The "Three Questions" are meant to help facilitate that effort.

If you don't have any feedback for 5 days, I believe your tasks are not fine grained enough.  This is simply my opinion, but it is based on my experience as a coach and team member.  Teams should be talking, planning, and integrating their efforts FAR more often.

Conclusion
Scrum is meant to facilitate learning and balancing that learning with delivery (where real learning happens).  Experiment with your processes and tools over time and use Scrum to inspect the impact.  Try moving from daily to weekly Scrums and see if it helps or hurts the teams ability to deliver the right functionality.  That may work for you.

OwnerDisplayName: Korchkidu

Title: Scrum for specialists teams

OwnerDisplayName: Ryan Cromwell


答:
If you have specialist with qualifications like the ones you described, your assumption that each one is working on his own task, with seldom need to communicate to the others, is IMHO wrong. In fact, to realize a new feature (a "user story"), you often will have to

change your database

add or change the GUI or the Web interface

combine this with the correct business logic (where, perhaps, you "mathematician" comes in)

make sure that all those changes work well together

So I guess they will have to communicate much more as in a team of generalist, where everyone could work on a different application / user story, making all the necessary changes to all application layers by himself. Thus, all the team activities from Scrum you listed above make a lot of sense for such a team.

Title: Scrum for specialists teams

Body:
Scrum is best for teams with generalists members, that is teams where 2 people at least can do the same tasks. My main concern is to find good solutions to adapt scrum (what to keep, what to remove, what to improve) for teams made of specialists?

Suppose you have a team of 5 developers (not real, just for the example):

One mathematician with strong skills in C;

One DB developer;

One Web Developer;

One UX/GUI developer;

One software architect;

Here, all are specialists and no one can replace someone else (I don't care about the risks of building such a team, I want to focus on scrum). So, in a scrum context, here are my thoughts:

Useless spring plannings: indeed, when the mathematician says that a specific task is worth 2 points, nobody can vote against him;

Useless team velocity metric: as everybody can allocate any number of points to his own tasks, computing velocity makes not sense;

Replace daily scrum meetings with weekly (longer) scrum meetings: as each member of the team is working on his own tasks, daily scrum meetings should be really important to keep a "team spirit". However, daily scrum meetings are supposed to last around 15 minutes. This is clearly not sufficient to understand what the others are doing and will do. Moreover, the mathematician will most of the time answer the same things: "I am still doing %&Lo( + ?$$+&)"... Weekly meetings would give more time. To keep the same meetings time between "initial" scrum meetings and "weekly" scrum meetings, each weekly scrum meeting should last (5 days a week, with 4 weeks sprints, with sprint meetings lasting 4 hours and daily meetings lasting 15 minutes): (4*60 + 20*15)/ 4 => 2h-2h30 which seems reasonable.

Or is scrum still usable? Maybe another agile technique should be used?


问:
Simple & short license notice for proprietary code
I have written several Java utilities that I am now consolidating in a single, more organized code base. I have never distributed this code, so the only copies are currently in my possession.

While I will probably release the whole thing or most parts of it under an open source license, I'd like at the moment to keep my options open and protect my work in case of inadvertent disclosure e.g. in the case of my having to use it on a computer that I do not own. I might also want to allow people, such as potential employers, to look at the code.

It seems that the simplest way to establish authorship is a license header in the source code files. On the other hand I absolutely detest mile-long headers, especially when I am forced to scroll-down to get to the code - or when the header is larger than the actual code.

Therefore I am trying to write a license header that is as short as possible, while covering most bases. I am currently considering something along these lines:

```<code>/*
 * Copyright (c) 2012 John Doe <john.doe@example.com>
 *
 * All rights reserved. No warranty, explicit or implicit, provided.
 */
</code>```

Basically I want to establish that:

I am the author of the code.

It cannot be distributed or used in any manner, shape or form. Note that I am mostly trying to defend against well-meant ignorance, rather than people that would outright ignore the rights of the author.

I am not liable if anyone does use the code and their grandmother sets the house on fire or their pet squirrel ends up in Antarctica.

Is this simple copyright notice sufficient to communicate my intent to the vast majority of well-intentioned people that might read it? More specifically:

Is the liability aspect completely covered?

Does All rights reserved cover both use and distribution? If so, do most people realize that, or should I make it more clear?

答:
Is this simple copyright notice sufficient to communicate my intent .... well-intentioned people?

well-intentioned people? - Yes

Is the liability aspect completely covered?

Unless you have an infinite amount of lawyers, or are in command of a carrier battle group then you are never completely covered. But to reasonable people - yes

Does All rights reserved cover both use and distribution?

All would seem to mean all, at least to reasonable people. To lawyers? Who knows!


答:
To answer the question, think about "what could go wrong here". In particular, if you change the "code" (markup/whatever), how will you have confidence that you haven't broken the page. Well, for a static page:

it might not render

it might render incorrectly

the JS might not load

the paths for images might not work

the links might be broken

Personally, I would recommend:

write a selenium [1] test that checks for one string you expect on the page (near the bottom if possible). This validates that it renders.

check there are no JS errors (I think selenium allows this)

run the static pages through a html validator, and if possible, a link checker.

I haven't found a tool I like to validate JS, but you might find success with jslint or jshint.

The take away here is that you want something that is repeatable, easy to use, and will run automatically in your test runner.

Title: Do I need to test everything?


答:
I am the author of the code.

This is done with a copyright notice and is completely different from the licence. Copyright says who owns it, the licence says who can use it.

Is the liability aspect completely covered?

I suggest adding something like, "In no event shall the author be liable for any claim or damages."

Does All rights reserved cover both use and distribution? If so, do most people realize that, or should I make it more clear?

It's fine, although again I suggest adding "this is proprietary software."

Ask a lawyer if it really matters to you, although in your case I think it's unnecessary.

Title: Simple & short license notice for proprietary code

Body:
I have written several Java utilities that I am now consolidating in a single, more organized code base. I have never distributed this code, so the only copies are currently in my possession.

While I will probably release the whole thing or most parts of it under an open source license, I'd like at the moment to keep my options open and protect my work in case of inadvertent disclosure e.g. in the case of my having to use it on a computer that I do not own. I might also want to allow people, such as potential employers, to look at the code.

It seems that the simplest way to establish authorship is a license header in the source code files. On the other hand I absolutely detest mile-long headers, especially when I am forced to scroll-down to get to the code - or when the header is larger than the actual code.

Therefore I am trying to write a license header that is as short as possible, while covering most bases. I am currently considering something along these lines:

```<code>/*
 * Copyright (c) 2012 John Doe <john.doe@example.com>
 *
 * All rights reserved. No warranty, explicit or implicit, provided.
 */
</code>```

Basically I want to establish that:

I am the author of the code.

It cannot be distributed or used in any manner, shape or form. Note that I am mostly trying to defend against well-meant ignorance, rather than people that would outright ignore the rights of the author.

I am not liable if anyone does use the code and their grandmother sets the house on fire or their pet squirrel ends up in Antarctica.

Is this simple copyright notice sufficient to communicate my intent to the vast majority of well-intentioned people that might read it? More specifically:

Is the liability aspect completely covered?

Does All rights reserved cover both use and distribution? If so, do most people realize that, or should I make it more clear?


答:
TDD Tests can also be living specifications if written that way.
The names of the test methods should make sense to a business user.</p>

Title: Do I need to test everything?


问:
Is Multithreading Appropriate for Setting up Multiple Windows in the Same Application?
I am currently working with a Qt Application which tries to use multi threading to accomplish two task

To Prevent the Main Thread's Event Loop from being blocked

To increase computation efficiency

You would think it is a good idea, but it turns out that this might be inefficient. In Qt, the client is not permitted to instantiate a QWidget subclass  only in the main thread.

The code I have seen so far seems really messy. The program has a "executive thread", in other words a background thread that manages user request (ie button click for a new gui panel), and of course there are 3 other thread (networking, script processing, and ofcourse the Main Thread)

The setup is kind of funky to say the least, the action event (ie Button Click) is signaled to the executive thread, which then sends a functor to the main thread to instantiate the user requested gui panel.

The above described make no sense. I am guessing that the original designers were concerned about the thread being blocked, but that shouldn't matter. Regardless of what thread instantiated in, it still ends up back in the main thread, and blocking it anyway.

This might not the be the best design choice, or is it? I am not sure, maybe there is someone here more experience that can shed light on this. I personally think it would be better to let one thread handle all user interaction, and any intensive user processing should can be threaded.

The other threaded parts make sense, having a seperate thread for processing scripts, networking actually could increase efficiency, while not blocking the main event loop so the gui can remain interactive.

Also could some one also elaborate on when Multithreading is a good choice in GUI, and in regular circumstances?

Thanks

答:
Typically I use threads for work displayed by a GUI, not for handling the GUI itself.  Otherwise all sorts of problems like you have here pop up.

You realize this in this quote "I personally think it would be better to let one thread handle all user interaction, and any intensive user processing should can be threaded." and I believe that is the way you should take this.

The GUI thread will use proxies whose job is to mediate between GUI stuff and asynchronous results coming from worker thread(s).  Your proxy can immediately create the GUI elements while providing a temporary display of "working..." or something similar while waiting for the worker thread it's representing to finish and pass over the data.

I don't have a handy answer to threading GUIs, it sounds like a complex problem and I don't have experience using a system like that.


答:
I've seen two ATMs opened up in Denver, Colorado.  Both were (then) Compass Bank ATMs, and both were Windows XP under the hardened case.  I did get to ask the tech what, specifically, one of them ran, and he said something like "XP Embedded".

So, I bet ATM programming is less like embedded programming these days, and more like standard Windows development.


答:
Also could some one also elaborate on when Multithreading is a good choice in GUI, and in regular circumstances?

In stock market applications (and other real-time applications) you may need more than 1 thread. You have 1 thread for user input, output and another that updates scrolling ribbons or progress bars on the GUI, and probably a third that updates graphical charts with streamed data. However, I guess it is not a common practice to have more than 1 thread for the GUI as this post suggests: stovf-threading.

Title: Is Multithreading Appropriate for Setting up Multiple Windows in the Same Application?

Body:
I am currently working with a Qt Application which tries to use multi threading to accomplish two task

To Prevent the Main Thread's Event Loop from being blocked

To increase computation efficiency

You would think it is a good idea, but it turns out that this might be inefficient. In Qt, the client is not permitted to instantiate a QWidget subclass  only in the main thread.

The code I have seen so far seems really messy. The program has a "executive thread", in other words a background thread that manages user request (ie button click for a new gui panel), and of course there are 3 other thread (networking, script processing, and ofcourse the Main Thread)

The setup is kind of funky to say the least, the action event (ie Button Click) is signaled to the executive thread, which then sends a functor to the main thread to instantiate the user requested gui panel.

The above described make no sense. I am guessing that the original designers were concerned about the thread being blocked, but that shouldn't matter. Regardless of what thread instantiated in, it still ends up back in the main thread, and blocking it anyway.

This might not the be the best design choice, or is it? I am not sure, maybe there is someone here more experience that can shed light on this. I personally think it would be better to let one thread handle all user interaction, and any intensive user processing should can be threaded.

The other threaded parts make sense, having a seperate thread for processing scripts, networking actually could increase efficiency, while not blocking the main event loop so the gui can remain interactive.

Also could some one also elaborate on when Multithreading is a good choice in GUI, and in regular circumstances?

Thanks


问:
How to organize a framework based project in Git
Ok, so I have what appears to be a complex situation, and I'm wondering how to best organize it. I have limited experience with Git so I might be missing system.

I have a framework developed internally. This framework is being used my ProjectX, ProjectY, and ProjectZ. If I update the core components of the framework (Located in /core and /resources) I want it updated for all of my projects. However I want to be able to update the custom components of each project and have that tracked in Git as well (All custom content is located in /app).

So I'm thinking on our central server we should have a Git repository just for the core framework. This will contain the following:

```<code>core/*
resources/*
.htaccess
index.php
</code>```

Then each of our projects will have their own repository on the server containing the app/ folder.

Would this work with Git locally however? Can we pull the contents of two repositories to one folder? We might have /home/brandon/projects/ProjectX.

Just looking for input on how to organize this. Also, how would we push to the live/test environments? Would SSHing into the production environment and pulling from the central repository be the way to go?

答:
Including the framework can be part of the build rather than part of the repository. When you build the app, the framework files get copied into your local working copy, so that anything that depends on the framework will work. Add the framework folders to your .gitignore file so they will not be included in the project specific repo.

For framework changes, use a separate repo that includes the framework folders and a simple test app so you can see the changes as you work on them.

Ignoring the framework files in the project repo is optional, but if you include them in the project, you need to be a bit more careful about not making framework changes directly in the project.

You also have the option of using submodules, but that works best if the framework is a subfolder of the project rather than the other way around.


问:
Dictionary vs List
So I ran into a Dictionary<int, int> today at work. This just seemed weird to me because I would have probably just used a List<int> instead. Is there a difference and would there be a use case where one structure would be preferred over the other?

答:
You would use a Dictionary<int, int> if your indexes have a special meaning besides just positional placement.

The immediate example that comes to mind is storing an id column and an int column in a database. For example, if you have a [person-id] column and a [personal-pin] column, then you might bring those into a Dictionary<int, int>. This way pinDict[person-id] gives you a PIN, but the index is meaningful and not just a position in a List<int>.

But really, any time you have two related lists of integers, this could be an appropriate data structure.

Title: Dictionary vs List