答:
What I'm wondering about specifically is using the operator to set an object to itself unless it's null.

The ?? operator is called the null-coalescing operator and is used to define a default value for nullable value types or reference types. It returns the left-hand operand if the operand is not null; otherwise it returns the right operand.

myObject = myObject ?? new myObject(); - instantiate default value of object

More details and code sample about null-coalescing operator - MSDN article.

If you check for more than nullable condition, as an alternative you may use Ternary operator.

Ternary operator

You may also look at ?: Operator. It is called Ternary or conditional operator. The conditional operator (?:) returns one of two values depending on the value of a Boolean expression.

A nullable type can contain a value, or it can be undefined. The ?? operator defines the default value to be returned when a nullable type is assigned to a non-nullable type. If you try to assign a nullable value type to a non-nullable value type without using the ?? operator, you will generate a compile-time error. If you use a cast, and the nullable value type is currently undefined, an InvalidOperationException exception will be thrown.

A code example from MSDN - ?: Operator (C# Reference):

```<code>int? input = Convert.ToInt32(Console.ReadLine());
string classify;

// ?: conditional operator.
classify = (input.HasValue) ? ((input < 0) ? "negative" : "positive") : "undefined";
</code>```

Title: Instantiating Null Objects with Null-Coalescing Operator

Body:
Consider the following typical scenario:

```<code>if(myObject == null) {
    myObject = new myClass();
}
</code>```

I'm wondering what is thought of the following replacement using the null-coalescing operator:

```<code>myObject = myObject ?? new myClass();
</code>```

I'm not sure whether I should be using the second form. It seems like a nice shorthand, but the myObject = myObject construct at the beginning seems like it could be a bit of a code-smell.

Is this a reasonable thing to do, or is there a better shorthand that I am missing?  Or maybe, "It's three lines, get over it!"?

Edit:
As has been mentioned, perhaps calling this a typical scenario is something of an overstatement. I usually find that I encounter this situation when I'm retrieving an entity from a database that has a child reference type property that may or may not be populated yet:

```<code>myClass myObject = myClassService.getById(id);
myObject.myChildObject = myObject.myChildObject ?? new myChildClass();
</code>```

Body:
What I'm wondering about specifically is using the operator to set an object to itself unless it's null.

The ?? operator is called the null-coalescing operator and is used to define a default value for nullable value types or reference types. It returns the left-hand operand if the operand is not null; otherwise it returns the right operand.

myObject = myObject ?? new myObject(); - instantiate default value of object

More details and code sample about null-coalescing operator - MSDN article.

If you check for more than nullable condition, as an alternative you may use Ternary operator.

Ternary operator

You may also look at ?: Operator. It is called Ternary or conditional operator. The conditional operator (?:) returns one of two values depending on the value of a Boolean expression.

A nullable type can contain a value, or it can be undefined. The ?? operator defines the default value to be returned when a nullable type is assigned to a non-nullable type. If you try to assign a nullable value type to a non-nullable value type without using the ?? operator, you will generate a compile-time error. If you use a cast, and the nullable value type is currently undefined, an InvalidOperationException exception will be thrown.

A code example from MSDN - ?: Operator (C# Reference):

int? input = Convert.ToInt32(Console.ReadLine());
string classify;

// ?: conditional operator.
classify = (input.HasValue) ? ((input < 0) ? "negative" : "positive") : "undefined";


问:
Design Pattern for data import of various source types and to various destination types
I have to design and build an import script (in C#) that can handle the following:

read data from various sources (XML, XSLX, CSV)

verify data

write the data to various object types (customer, address)

The data will come from a number of sources but a source will always have one import format (either csv, xml, xslx). Import formats can vary from source to source. New import formats may be added in the future.
The destination object types are always the same (customer, addres and some more).

I've been thinking about using generics and I read something about the factory pattern but I'm a pretty big noob in this area so any advice is more than welcome.

What is an appropriate design pattern to solve this problem?

答:
The obvious thing is to apply Strategy pattern. Have a generic base class ReadStrategy and for each input format a subclass like XmlReadStrategy, CSVReadStrategy etc. This will allow you to change the import processing independently from the verfication processing and the output processing.

Depending on the details it may be also possible to keep most parts of the import generic and exchange only parts of the input processing (for example, reading of one record). This may lead you to Template Method pattern.

ContentLicense: CC BY-SA 3.0


答:
What is an appropriate design pattern to solve this problem?

C# idioms involve using the built in serialization framework to do this. You annotate the objects with metadata, and then instantiate different serializers that use those annotations to rip out data to put into the right form, or vice versa.

Xml, JSON, and binary forms are most common, but I would not be surprised if others already exist in a nice packaged form for you to consume.

Title: Design Pattern for data import of various source types and to various destination types

Body:
I have to design and build an import script (in C#) that can handle the following:

read data from various sources (XML, XSLX, CSV)

verify data

write the data to various object types (customer, address)

The data will come from a number of sources but a source will always have one import format (either csv, xml, xslx). Import formats can vary from source to source. New import formats may be added in the future.
The destination object types are always the same (customer, addres and some more).

I've been thinking about using generics and I read something about the factory pattern but I'm a pretty big noob in this area so any advice is more than welcome.

What is an appropriate design pattern to solve this problem?


问:
Is Java still king of cross-platform compatibility? Is the answer still Swing?
So basically, my company is looking to create an app that can be distributed on Linux, Mac OS X, and Windows. We are hoping for a cross platform solution. I have experience working with Java Swing years ago and thought it was reasonable, but not great. It assuredly did however work on all platforms just fine. Is Java and Swing still the end all be all of code once run everywhere, or are there other options for desktop apps?</p>

答:
You have basically three practical choices:

Java, or a language that runs on the Java platform like Scala or Groovy

HTML5, Javascript, CSS3 and Canvas (which will run on pretty much any modern browser),  or

Cross-Platform tools such as Xamarin and Appcelerator

I would avoid Swing.  It's too labor-intensive, and there are far better alternatives out there.

If you're just looking for desktop compatibility, your choices become much broader, as Jimmy Hoffa correctly points out.


答:
A suitable pattern for an importing utility that you may need to extend in the future would be to use MEF - you can keep memory use low by loading the converter you need on the fly from a lazy list, create MEF imports that are decorated with attributes that help select the right converter for the import you are trying to perform and provides an easy way of separating the different importing classes out.

Each MEF part can be built to satisfy an importing interface with some standard methods that convert a row of the import file to your output data or override a base class with the basic functionality.

MEF is an framework for creating a plug-in architecture - its how outlook and Visual Studio are built, all those lovely extensions in VS are MEF parts.

To build a MEF (Managed Extensability Framework) app start with including a reference to System.ComponentModel.Composition

Define interfaces to spec out what the converter will do

```<code>public interface IImportConverter
{
    int UserId { set; }
    bool Validate(byte[] fileData, string fileName, ImportType importType);
    ImportResult ImportData(byte[] fileData, string fileName, ImportType importType);
}
</code>```

This can be used for all the file types you want to import.

Add attributes to a new class that define what the class will "Export"

```<code>[Export(typeof(IImportConverter))]
[MyImport(ImportType.Address, ImportFileType.CSV, "4eca4a5f-74e0")]
public class ImportCSVFormat1 : ImportCSV, IImportConverter
{
 ...interface methods...
}
</code>```

This would define a class that will import CSV files (of a particular format : Format1) and has a custom attributes that sets MEF Export Attribute Metadata. You'd repeat this for each format or file type you want to import. You can set custom attributes with a class like:

```<code>[MetadataAttribute]
[AttributeUsage(AttributeTargets.All, AllowMultiple = false)]
public class ImportAttribute : ExportAttribute
{
    public ImportAttribute(ImportType importType, ImportFileType fileType, string customerUID)
        : base(typeof(IImportConverter))
    {
        ImportType = importType;
        FileType = fileType;
        CustomerUID = customerUID;
    }

    public ImportType ImportType { get; set; }
    public ImportFileType FileType { get; set; }
    public string CustomerUID { get; set; }
}
</code>```

To actually use the MEF converters you need to import the MEF parts you create when your converting code is run :

```<code>[ImportMany(AllowRecomposition = true)]
protected internal Lazy<IImportConverter, IImportMetadata>[] converters { get; set; }
AggregateCatalog catalog = new AggregateCatalog();
</code>```

catalog collects the parts from a folder, default is app location.

converters is a lazy list of the imported MEF parts

Then when you know what sort of file you want to convert (importFileType and importType ) get a converter from the list of imported parts in converters

```<code>var tmpConverter = (from x in converters
                    where x.Metadata.FileType == importFileType
                    && x.Metadata.ImportType == importType
                    && (x.Metadata.CustomerUID == import.ImportDataCustomer.CustomerUID)
                    select x).OrderByDescending(x => x.Metadata.CustomerUID).FirstOrDefault();

if (tmpConverter != null)
{
     var converter = (IImportConverter)tmpConverter.Value;
     result = converter.ImportData(import.ImportDataFile, import.ImportDataFileName, importType);
....
}
</code>```

The call to converter.ImportData will use the code in the imported class.

Might seem like a lot of code and it can take a while to get your head round whats going on but its extremely flexible when it comes to adding new converter types and can even allow you to add new ones during runtime.

Body:
A suitable pattern for an importing utility that you may need to extend in the future would be to use MEF - you can keep memory use low by loading the converter you need on the fly from a lazy list, create MEF imports that are decorated with attributes that help select the right converter for the import you are trying to perform and provides an easy way of separating the different importing classes out.

Each MEF part can be built to satisfy an importing interface with some standard methods that convert a row of the import file to your output data or override a base class with the basic functionality.

MEF is an framework for creating a plug-in architecture - its how outlook and Visual Studio are built, all those lovely extensions in VS are MEF parts.

To build a MEF (Managed Extensability Framework) app start with including a reference to System.ComponentModel.Composition

Define interfaces to spec out what the converter will do

public interface IImportConverter
{
    int UserId { set; }
    bool Validate(byte[] fileData, string fileName, ImportType importType);
    ImportResult ImportData(byte[] fileData, string fileName, ImportType importType);
}

This can be used for all the file types you want to import.

Add attributes to a new class that define what the class will "Export"

[Export(typeof(IImportConverter))]
[MyImport(ImportType.Address, ImportFileType.CSV, "4eca4a5f-74e0")]
public class ImportCSVFormat1 : ImportCSV, IImportConverter
{
 ...interface methods...
}

This would define a class that will import CSV files (of a particular format : Format1) and has a custom attributes that sets MEF Export Attribute Metadata. You'd repeat this for each format or file type you want to import. You can set custom attributes with a class like:

[MetadataAttribute]
[AttributeUsage(AttributeTargets.All, AllowMultiple = false)]
public class ImportAttribute : ExportAttribute
{
    public ImportAttribute(ImportType importType, ImportFileType fileType, string customerUID)
        : base(typeof(IImportConverter))
    {
        ImportType = importType;
        FileType = fileType;
        CustomerUID = customerUID;
    }

    public ImportType ImportType { get; set; }
    public ImportFileType FileType { get; set; }
    public string CustomerUID { get; set; }
}

To actually use the MEF converters you need to import the MEF parts you create when your converting code is run :

[ImportMany(AllowRecomposition = true)]
protected internal Lazy<IImportConverter, IImportMetadata>[] converters { get; set; }
AggregateCatalog catalog = new AggregateCatalog();

catalog collects the parts from a folder, default is app location.

converters is a lazy list of the imported MEF parts

Then when you know what sort of file you want to convert (importFileType and importType ) get a converter from the list of imported parts in converters

var tmpConverter = (from x in converters
                    where x.Metadata.FileType == importFileType
                    && x.Metadata.ImportType == importType
                    && (x.Metadata.CustomerUID == import.ImportDataCustomer.CustomerUID)
                    select x).OrderByDescending(x => x.Metadata.CustomerUID).FirstOrDefault();

if (tmpConverter != null)
{
     var converter = (IImportConverter)tmpConverter.Value;
     result = converter.ImportData(import.ImportDataFile, import.ImportDataFileName, importType);
....
}

The call to converter.ImportData will use the code in the imported class.

Might seem like a lot of code and it can take a while to get your head round whats going on but its extremely flexible when it comes to adding new converter types and can even allow you to add new ones during runtime.


问:
Instantiating Null Objects with Null-Coalescing Operator
Consider the following typical scenario:

```<code>if(myObject == null) {
    myObject = new myClass();
}
</code>```

I'm wondering what is thought of the following replacement using the null-coalescing operator:

```<code>myObject = myObject ?? new myClass();
</code>```

I'm not sure whether I should be using the second form. It seems like a nice shorthand, but the myObject = myObject construct at the beginning seems like it could be a bit of a code-smell.

Is this a reasonable thing to do, or is there a better shorthand that I am missing?  Or maybe, "It's three lines, get over it!"?

Edit:
As has been mentioned, perhaps calling this a typical scenario is something of an overstatement. I usually find that I encounter this situation when I'm retrieving an entity from a database that has a child reference type property that may or may not be populated yet:

```<code>myClass myObject = myClassService.getById(id);
myObject.myChildObject = myObject.myChildObject ?? new myChildClass();
</code>```

答:
I don't think that scenario is (or at least should be) typical.

If you want the default value of some field not to be null, then set it in the field initializer:

```<code>myClass myObject = new myClass();
</code>```

Or, if the initialization is more complicated, set it in the constructor.

If you want to create myClass only when you actually need it (e.g. because creating it takes a long time), then you can use Lazy<T>:

```<code>Lazy<myClass> myObject = new Lazy<myClass>();
</code>```

(This calls the default constructor. If the initialization is more complicated, pass lambda that creates myClass to the Lazy<T> constructor.)

To access the value, use myObject.Value, which will call the initialization if this is the first time you're accessing myObject.Value.

Body:
I don't think that scenario is (or at least should be) typical.

If you want the default value of some field not to be null, then set it in the field initializer:

myClass myObject = new myClass();

Or, if the initialization is more complicated, set it in the constructor.

If you want to create myClass only when you actually need it (e.g. because creating it takes a long time), then you can use Lazy<T>:

Lazy<myClass> myObject = new Lazy<myClass>();

(This calls the default constructor. If the initialization is more complicated, pass lambda that creates myClass to the Lazy<T> constructor.)

To access the value, use myObject.Value, which will call the initialization if this is the first time you're accessing myObject.Value.


问:
When do 'static functions' come into use?
OK, I've learned what a static function is, but I still don't see why they are more useful than private member functions. This might be kind of a newb-ish question here, but why not just replace all private member functions with static functions instead?</p>

答:
I would like to point out another use of static f().

http://www.parashift.com/c++-faq/named-ctor-idiom.html

Boils down to this: static functions allow you to create "Named Constructors", i.e you name your static function with suitable and self-documenting name, and this static function calls one of the constructors (since constructors have identical names, and you can have a lot of them, it gets hard to distinguish between them).


问:
Should you keep a copy of all the code you write?
I know the company you work for owns the code and obviously you will get arrested if you try to sell it. But is it uncommon for developers to keep a personal copy of the code they wrote (for future reference)?

Apparently this guy was sent to prison for copying source code.

答:
I don't keep code for a simple reason: The company paid me to write the code for them. I give them my code, and they give me my paycheck. The guy who made my lunch, does not get to keep part of it for themselves, why would code be different?

Also, the point made before, I walk out of job, all those headaches stay there, new job, new start, but with a bit more experience and understanding of the types of problems in that old job's domain.


问:
Worst coding standard you've ever had to follow?
Have you ever had to work to coding standards that:

Greatly decreased your productivity?

Were originally included for good reasons but were kept long after the original concern became irrelevant?

Were in a list so long that it was impossible to remember them all?

Made you think the author was just trying to leave their mark rather than encouraging good coding practice?

You had no idea why they were included?

If so, what is your least favorite rule and why?

Some examples here

答:
Insisting that all braces be followed by comment for what the brace ends:

e.g:

```<code>for (int i = 0; i < 10; i++)
{
    if (foo > bar)
    {
        printf("Foo greater than bar");
    } // End If (foo > bar)

    while (baz)
    {
       farb();
    } // End while (baz)
} // End For
</code>```

Body:
Insisting that all braces be followed by comment for what the brace ends:

e.g:

for (int i = 0; i < 10; i++)
{
    if (foo > bar)
    {
        printf("Foo greater than bar");
    } // End If (foo > bar)

    while (baz)
    {
       farb();
    } // End while (baz)
} // End For

ContentLicense: CC BY-SA 2.5


问:
Diagramming messages on a service bus
I'm looking for a way to clearly diagram how multiple applications communicate via a service bus. The best I've come up with so far is a sequence diagram, but I really don't like that. Sequence diagrams necessarily relate some sort of sequence, and that's really not what I want. Furthermore, since every service communicates with the service bus and sequence diagrams place each service on a separate column, as the number of services increases, you end up with a lot of overlapping arrows.

For example, given 4 services FOO, BAR, BAZ, and QUX:

FOO publishes messages of type publish and regen.

BAR publishes messages of type requeue.

BAZ subscribes to messages of type publish, regen, and requeue, and publishes messages of type transmit.

QUX subscribes to messages of type transmit.

Any service can publish any message type at any time (there is no implied sequence).

What kind of diagram should I use to clearly and unambiguously represent this information?

Here's the best I've come up with so far:

答:
I'm looking for a way to clearly diagram how multiple applications
  communicate via a service bus.

That would be awesome. Unfortunately, I don't think it is possible for configurations of any complexity. A sequence diagram for simple scenarios is probably as good as anything else.

Components on a bus both publish and subscribe to messages. Some of the messages may be causally related, forming a protocol. It it difficult to show this graphically, especially the causal relations, when there is more than one protocol in play on the bus.

Electrical bus diagrams have been around for a long time

but they deal with a quantity of a uniform commodity (electrical power) not discrete signals.

I like to show messages sent (on the right) and received (on the left) by each component (and the subchannel/topic structure, if applicable), but again for anything but the simplest of scenarios the diagrams quickly become cluttered and nearly useless.

So let's go back to a more fundamental question: what is the purpose of the diagram? What are you trying to show?

If you are trying to show causal relations between components and messages, then diagramming one protocol at a time using a sequence diagram (or equivalent) should be fine.

If you just want to show the protocols for reference, then putting messages sent and received by each component should be sufficient documentation, but causal/temporal relationships are lost.

Good luck, and please let us know if you find or invent anything better!

Title: Diagramming messages on a service bus


问:
Zero-knowledge code hosting?
In light of recent revelations about widespread government monitoring of data stored by online service providers, zero-knowledge services are all the rage now.

A zero-knowledge service is one where all data is stored encrypted with a key that is not stored on the server. Encryption and decryption happens entirely on the client side, and the server never sees either plaintext data or the key. As a result, the service provider is unable to decrypt and provide the data to a third party, even if it wanted to.

To give an example: SpiderOak can be viewed as a zero-knowledge version of Dropbox.

As programmers, we rely heavily on, and trust some of our most sensitive data - our code - to a particular class of online service providers: code hosting providers (like Bitbucket, Assembla, and so on). I am of course talking about private repositories here - the concept of zero-knowledge does not make sense for public repositories.

My questions are:

Are there any technological barriers to creating a zero-knowledge code hosting service? For example, is there something about the network protocols used by popular version control systems like SVN, Mercurial, or Git that would make it difficult (or impossible) to implement a scheme where the data being communicated between the client and the server is encrypted with a key the server does not know?

Are there any zero-knowledge code hosting services in existence today?

答:
As I understand it, the way git pull works is that the server sends you a pack file that contains all the objects that you want, but don't have currently. And vice versa for git push.

I think you couldn't do it like this directly (because this means the server has to understand the objects). What you could do instead is to let the server work just with a series of encrypted pack files.

To do pull, you download all the pack files that were added since your last pull, decrypt them and apply to your git repo. To do push, you first have to do pull, so that you know the state of the server. If there are no conflicts, you create a pack file with your changes, encrypt it and upload it.

With this approach, you would end up with large number of tiny pack files, which would be quite inefficient. To fix that, you could download a series of pack files, decrypt, combine them into one pack file, encrypt and upload them to the server, marking them as a replacement for that series.

Title: Zero-knowledge code hosting?


问:
Who created the idea(s) of the first loop constructs?
```<code>while (1) {
      if (1+1==2) {
             print "Yes, you paid attention in Preschool!";
      } else {
             print "Wait... I thought 1+1=2";
      }
 }
</code>```

As a developer, we all have to use loops very frequently. We know that. What I was wondering was, who thought of the idea to have loops? What language introduced loops? What was the first loop construct? Was it a while loop? A for loop? etc?

答:
The work of both Liebniz and Newton contains algorithms with loop constructs.  Liebniz built a mechanical calculator and speculated (as Lovelace did years later) about a machine to perform more sophisticated analysis.  His notes on these ideas are sketchy, but they describe stuctured logic with loops.

However, the idea of repetition sequences and count controlled loops, as well as what we would call while loops are discussed in the work of the man for whom algorithms are named: Muhammad ibn Musa al-Khwarizmi from the ninth Century.  His second book, al-Kitab al-mukhtasar fi hisab al-jabr wa'l-muqabala (الكتاب المختصر في حساب الجبر والمقابلة) (A Compendium on Calculation by Completion and Balancing) was known to Newton, Liebniz, Babbage, Lovelace, etc.

Of course al-Khwarizmi relied, in part, on the ancient Greeks. At some point we probably get back to Adam and Eve's version of rinse, lather, repeat.

For more about Al-Khwārizmī and his work see:

http://www-groups.dcs.st-andrews.ac.uk/history/Mathematicians/Al-Khwarizmi.html


问:
Sorting with continous input
I'm designing (not writing, yet) a task scheduler system for a complex video game. The rest of the program passes it objects containing a function and some metadata including an estimation of how much time is left before the data is needed (which can change, of course). The scheduler is responsible for prioritizing these tasks and calling the function.

The algorithm I've designed for this problem is pretty simple; it just sorts its list of task objects, pops one off the top, calls it, and repeats. Of course it's actually more complex than that (has to handle situations where things just can't get done on time, telling other parts of the code that their task just got bumped down the list...), but that's the gist of it.

I'd like some advice on the subject of how I'm going to sort that list. This loop will, obviously, be running constantly while the program is running. I'm thinking I'll use a slight modification of a bubble sort algorithm, running one pass on each iteration. The list won't be properly sorted for the first few cycles, but since the list will likely be very small when the program is started I expect it will be able to reliably get things into position as fast as they come in.

Has anyone done this before, and how did it work? Are there better ways I could do this?

答:
You should be using a Priority Queue here.  A Priority Queue is a queue in which items added to the queue have a priority, and whenever you get an item, you get the item with the minimum (or maximum, depending on implementation) priority.

Priority Queues are generally implemented using a min-heap (or max-heap).  It will logically represent the data as a completely balanced tree in which each node is "less than" all of its children.  It's not technically a binary search tree, in which the data is fully sorted.  (Which is a viable alternative that is only slightly more expensive.)  Since the data isn't actually completely sorted it means the only real meaningful operations you can perform are "Give me the lowest value" and "add this new value to the collection".  (Incidentally, those are exactly the two operations that you need.)  Both of which can be performed in O(log(n)) time.  Because the min-heap ensures that the tree is always entirely balanced there is very little variance in the best/worst case.  Even it's worst case is quite low, unlike a binary search tree which, if it gets unbalanced, can devolved into O(n) operatiosn.

Title: Sorting with continous input


问:
Method visibility for testing partial mocks
I'm currently writing unit tests to test behavior of a method and would like to partially mock the methods calling injected properties.  For example:

```<code>public void doSomething() {
  int complicatedInt = 1 + 1;
  if(getProperty().someBooleanReturn()) {
    ... etc. ...
  }
}
</code>```

So obviously I want to mock the getProperty() method in order to expect the someBooleanReturn().  My question is, since I don't want the getter to be visible to other classes, but visible to unit tests, I've currently been making these methods package-private (default scope).  Is there a standard for these types of operations?

Thanks!

答: Having a class and a test class in the same package (possibly in different jars), combined with default visibility, is a standard way to get access to a class internals.</p>


问:
Python datetime timedelta attributes
In the python datetime module, timedelta objects take weeks, days, hours, minutes, seconds, and microseconds as arguments upon instantiation. However, after the timedelta is created, the only two attributes it has of the former listed are days, seconds, and microseconds.

Why is this?

答:
Probably to keep the size of the object small.
In the documentation is clearly stated that all the arguments are converted into those three units.</p>

Title: Python datetime timedelta attributes


问:
Breaking down a complex story at project start
I'm trying to get to grips with agile project management (with Pivotal Tracker) but keep finding myself running into walls when trying to define the first few stories of a project. Take for example this very simple story:

"A user should be able to tag a product"

Assuming I've already defined "product" elsewhere, this story would possibly involve writing a polymorphic tagging system under the hood, on completion of that system id be able to finally add the ability to tag a product.

My problem is with the amount of work hidden in this story. I can define tasks to get the story done but stories as a whole are supposed to be 1-2 days work? I don't feel right about the story just revealing the tip of the iceberg but that's the only part that relates to the User.

How do you overcome this kind of thing? What are the best practices?

UPDATE 25/08 Thanks to everyone for your guidance, I've taken all advice onboard on how to define stories. I am now switching to Jira Grasshopper which has better support for tasks within stories (assignment, estimates etc) and tracking of development tasks once the sprint has began.

答:
There are books written for the sole purpose of finding out the correct way to describe and break down your requirements. So it is not an easy task.

Often times I find development teams striving for complex solutions instead of the most simple ones. This could be due to the story itself or because the team wants to go for an overly complex solution that not only solves this story but lays the groundwork for stories x, y and z as well. This is good intention, but bloats scope where the same job can be done with less work. It is always hard to judge how much design has to go into a story to not ruin future stories by messing up the design. This decision is for the team to make.

As a product owner you can only influence this by breaking down stories into smaller pieces. You should ask yourself: Is the story the smallest solution that we can think of right now? Can we break it down into reduced feature sets that some day will become the "big flexible tagging system I have always wanted". You could start with a tag system for just a single tag, then extend it to include a list of preselected tags, and then let user define tags, etc.

For the dev team it boils down to: Can we find a simpler approach to realize the story, but still have a solid architecture that accomplishes the job today while not compromising future features.

If you are open to accept intermediate solutions and the development team also tries to offer the most simple, yet good solution then you will probably find the sweet spot in where the size of the stories you want to do is right (the smaller the better). This is not to say that you only have small stories. Some are bigger than others, this is just a fact that you need to accept, or if they are too big, then break down stories into smaller pieces.

OwnerDisplayName: matthewrk


问:
What do you do to estimates for agile stories where developers are pair programming?
If it was a 2-point story for one person, would you double it if people are pairing?

Pairing isn't always necessarily done 100% of a dev task, so it seems that doubling the story points seems wrong.  And it might not be obvious how much of the task will require pairing until the end, so you wouldn't know what the points the story should be until you've finished - and it seems strange to change an estimate midway through a sprint.

However, if velocity is going to be an accurate representation of how much work we can get through during a sprint, it seems right to change the estimates if more than one person is working on a task.  But also, this seems like it adds a lot of admin overhead.

Thoughts?

答:
The way I understand it, a story-point is an estimate of relative effort, not man-hours. The effort required of a story isn't going to change just because a pair is working on it, so it doesn't make sense for the story points to change...

Also, velocity is derived from the history of what got done in the previous sprint(s). If you pair on some stories and not on others, over time the average velocity will reflect your average sprint capacity, automatically taking into account your team's pairing habits. There's no need to manually adjust sprint estimates based on how much you think you're going to pair on certain tasks next sprint.

Indeed, it's these manual tinkerings that most often cause scrum efforts to be derailed, because nobody trusts the 'estimates' anymore, due to all of the 'gaming' of the numbers.


问:
Why is a small fixed vocabulary seen as an advantage to RESTful services?
So, a RESTful service has a fixed set of verbs in its vocabulary. A RESTful web service takes these from the HTTP methods. There are some supposed advantages to defining a fixed vocabulary, but I don't really grasp the point. Maybe someone can explain it.

Why is a fixed vocabulary as outlined by REST better than dynamically defining a vocabulary for each state? For example, object oriented programming is a popular paradigm. RPC is described to define fixed interfaces, but I don't know why people assume that RPC is limited by these contraints. We could dynamically specify the interface just as a RESTful service dynamically describes its content structure.

REST is supposed to be advantageous in that it can grow without extending the vocabulary. RESTful services grow dynamically by adding more resources. What's so wrong about extending a service by dynamically specifying a per-object vocabulary? Why don't we just use the methods that are defined on our objects as the vocabulary and have our services describe to the client what these methods are and whether or not they have side effects?

Essentially I get the feeling that the description of a server side resource structure is equivalent to the definition of a vocabulary, but we are then forced to use the limited vocabulary in which to interact with these resources.

Does a fixed vocabulary really decouple the concerns of the client from the concerns of the server? I surely have to be concerned with some configuration of the server, this is normally resource location in RESTful services. To complain at the use of a dynamic vocabulary seems unfair because we have to dynamically reason how to understand this configuration in some way anyway. A RESTful service describes the transitions you are able to make by identifying object structure through hypermedia.

I just don't understand what makes a fixed vocabulary any better than any self-describing dynamic vocabulary, which could easily work very well in an RPC-like service. Is this just a poor reasoning for the limiting vocabulary of the HTTP protocol?

Reflection

Just to clarify my thoughts a little better than I have done. Suppose you are designing any general purpose API, maybe not even web facing. Would you be happy if someone said you can only use these method names on your objects? REST isn't restricted to HTTP, but consider the situation where every API you write, web facing or otherwise simply consisted of objects containing GET POST PUT and DELETE methods. So that object.foo method you wanted to define isn't possible. You have to define a new object called foo, and call its GET method. That's essentially how REST works, and it makes me a little uncomfortable to think about it. You don't have any better generic understanding of what foo does, you were just forced to create a new object for what is essentially a method on a parent object. Furthermore your API is no less complex, you have just hidden interface complexity by creating more objects. RESTful web services force us to adopt an interface which may or may not be sufficient in the context of the API we are exposing. Perhaps there is a good reason for doing this with web facing APIs, but a good reason to not adopt standard interfaces for every object in every general purpose API. A practical example would be appreciated.

答:
Consider a language where all constructs (such as functions) are objects. Then the RESTful verbs are simply calling conventions and assignment statements. For JavaScript you could define a fixed verb syntax like INVOKE for calling a function, DELETE (the same as delete in js) for deleting an object on another object, SET for assigning a value and RETURN for returning a value. We could use the HTTP verbs to mean the equivalent POST - invoke function, PUT - assign value, GET - return a value, - DELETE - delete an object. I was caught up in the idea that the HTTP methods were actually describing object methods, actual object interfaces, that I failed to see that it could actually describe much lower level concepts, such as the basic language constructs which are clearly fixed and finite in all sane languages. HTTP verbs define the object manipulation syntax and the higher level object structure defines the API methods.

And of course it's helpful for routing/proxying to have a fixed vocabulary to reflect on.


答:
Simple is good.

There are cases when you need extra verbs and complexity, but most problems can be trimmed down to simple CRUD actions on resources, and that's what REST tries to promote. When you think about most web applications, in the end they read and persist records in a data store, which use the same very simple actions.

object.foo() is all good, but what does it do? What is it returning? Is it modifying the state of object or any of its dependencies? Can you call it twice and get the same result or is it going to give you two different values? If you have object.bar() as well, do they need to be called in a specific order?

There is a lot of knowledge required in using a rich API, and they usually have their own conventions (i.e. setFoo is going to mutate the object, getBar is probably idempotent, dispose() or destroy() means no other calls on the same object will be possible, etc...)

Title: Why is a small fixed vocabulary seen as an advantage to RESTful services?

Body:
So, a RESTful service has a fixed set of verbs in its vocabulary. A RESTful web service takes these from the HTTP methods. There are some supposed advantages to defining a fixed vocabulary, but I don't really grasp the point. Maybe someone can explain it.

Why is a fixed vocabulary as outlined by REST better than dynamically defining a vocabulary for each state? For example, object oriented programming is a popular paradigm. RPC is described to define fixed interfaces, but I don't know why people assume that RPC is limited by these contraints. We could dynamically specify the interface just as a RESTful service dynamically describes its content structure.

REST is supposed to be advantageous in that it can grow without extending the vocabulary. RESTful services grow dynamically by adding more resources. What's so wrong about extending a service by dynamically specifying a per-object vocabulary? Why don't we just use the methods that are defined on our objects as the vocabulary and have our services describe to the client what these methods are and whether or not they have side effects?

Essentially I get the feeling that the description of a server side resource structure is equivalent to the definition of a vocabulary, but we are then forced to use the limited vocabulary in which to interact with these resources.

Does a fixed vocabulary really decouple the concerns of the client from the concerns of the server? I surely have to be concerned with some configuration of the server, this is normally resource location in RESTful services. To complain at the use of a dynamic vocabulary seems unfair because we have to dynamically reason how to understand this configuration in some way anyway. A RESTful service describes the transitions you are able to make by identifying object structure through hypermedia.

I just don't understand what makes a fixed vocabulary any better than any self-describing dynamic vocabulary, which could easily work very well in an RPC-like service. Is this just a poor reasoning for the limiting vocabulary of the HTTP protocol?

Reflection

Just to clarify my thoughts a little better than I have done. Suppose you are designing any general purpose API, maybe not even web facing. Would you be happy if someone said you can only use these method names on your objects? REST isn't restricted to HTTP, but consider the situation where every API you write, web facing or otherwise simply consisted of objects containing GET POST PUT and DELETE methods. So that object.foo method you wanted to define isn't possible. You have to define a new object called foo, and call its GET method. That's essentially how REST works, and it makes me a little uncomfortable to think about it. You don't have any better generic understanding of what foo does, you were just forced to create a new object for what is essentially a method on a parent object. Furthermore your API is no less complex, you have just hidden interface complexity by creating more objects. RESTful web services force us to adopt an interface which may or may not be sufficient in the context of the API we are exposing. Perhaps there is a good reason for doing this with web facing APIs, but a good reason to not adopt standard interfaces for every object in every general purpose API. A practical example would be appreciated.


问:
C++ Linkage Languages other than C?
The C++ language allows intermixing of both C++ and C in one source file. For example,

```<code>extern "C" {
    struct bar { /* ... */ }
}
</code>```

Does C++ or has it ever supported any other "linkage languages" other than C? e.g. extern "Pascal" or extern "Haskell"

答:
In many (most) environments "extern "C" is the default linking convention for any language on the system.

So depending on the operating system and the implementation of the "foreign" language "extern C" is all you need to call a program in another compiled language.

Title: C++ Linkage Languages other than C?


答:
You are going overboard with fancy concepts was too soon.  Generics - when you see a case use them, but otherwise don't worry.  Factory pattern - way too much flexibility ( and added confusion ) for this yet.

Keep it simple. Use fundamental practices.

Try to imagine the common things between doing a read for XML, a read for CSV whatever.  Things like, next record, next line.  Since New formats may be added, try to imagine commonality that the to be determined format would have with the known ones. Use this commonality and define an 'interface' or a contract that all formats must adhere to.   Though they adhere to the common ground, they all may have their specific internal rules.

For validating the data, try to provide a way to easily plug in new or different validator code blocks.  So again, try to define an interface where each validator, responsible for a particular kind of data construction adheres to a contract.

For creating the data constructions you will probably be constrained by whoever designs the suggested output objects more than anything.  Try to figure out what the next step for the data objects is, and are there any optimizations you can make by knowing the final use.   For example if you know the objects are going to be used in an interactive application, you could help the developer of that app by providing 'summations' or counts of the objects or other kinds of derived information.

I'd say most of these are Template patterns or Strategy patterns.  The whole project would be an Adapter pattern.


答:
No! C++ only support C as a  "linkage languages".

extern "C" {
struct bar { /* ... */ }
}

The syntax as above means that do not change the name of variable,struct or function. Because C++ maybe change the name of variable,struct or function to implement Class ,Namespace and function overloading.

If you do not do this,the linker maybe can not find out the object of variable,struct of function.

C++ is designed to be compatible with C. The extern "C" is the way to implement compatible with C.

Title: C++ Linkage Languages other than C?

Body:
The C++ language allows intermixing of both C++ and C in one source file. For example,

```<code>extern "C" {
    struct bar { /* ... */ }
}
</code>```

Does C++ or has it ever supported any other "linkage languages" other than C? e.g. extern "Pascal" or extern "Haskell"


问:
What are the advantages/disadvantages of using objects as parameters to other object methods?
I'm mostly thinking of PHP here, but if you want to refer to other languages that's fine.

An object has a method that requires data contained in another class of object.

Should I extract that data from the other object into a variable and then send just that data to the requesting object?

Or should I pass the entire data-containing object into the data-requiring object, and then have the requesting object perform the data extraction operations?

I'm asking because I'm working on a big project that I've written 100% of the code for, and some of my early code takes string or numeric arguments, but my later code seems to be leaning toward passing around objects. As I bump into some old code, I'm wondering if I should convert it to object parameters.

答:
I think as with every CS question, it depends.

If you are planning to use a lot of the functionality provided by the passed class it is great:

this is basically how you can have common functions like sort, which can take any type of object and as long as it has the required methods implemented it will work.

passing objects facilitates programming to an interface

If you are just extracting one (lets say integer) thing and using the receiving classes methods to operate on it, it is bad:

you may unintentionally copy the object while passing

if you don't use the whole object the code can be misleading

So I advise you to look at your functions on a case by case basis and not make generalizations for your whole code base.


答:
extern "C" may be the only required one:

Every implementation shall provide for linkage to functions written in the C programming language, "C", and linkage to C++ functions, "C++".

However others can exist as per this quote:

The string-literal indicates the required language linkage. This International Standard specifies the semantics for the string-literals "C" and "C++". Use of a string-literal other than "C" or "C++" is conditionally- supported, with implementation-defined semantics. [ Note: Therefore, a linkage-specification with a string- literal that is unknown to the implementation requires a diagnostic. — end note ] [ Note: It is recommended that the spelling of the string-literal be taken from the document defining that language. For example, Ada (not ADA) and Fortran or FORTRAN, depending on the vintage. — end note ]

Title: C++ Linkage Languages other than C?


答:
I think that you can set an object as a property of class,and you can pass an object as an argument of method.
Choice  which one   is determined  in the scene.

If your instance use the data or function of an object,you should set the object as a property of your instance.For example,"Proxy Pattern",you always call an object's method to accomplish tasks.

But if your instance use the data of function of any object,you should pass one object as an argument of a method.For example,"Visitor Pattern", your class visit a different object everytime.So you should pass an object as argument.

Title: What are the advantages/disadvantages of using objects as parameters to other object methods?

Body:
I'm mostly thinking of PHP here, but if you want to refer to other languages that's fine.

An object has a method that requires data contained in another class of object.

Should I extract that data from the other object into a variable and then send just that data to the requesting object?

Or should I pass the entire data-containing object into the data-requiring object, and then have the requesting object perform the data extraction operations?

I'm asking because I'm working on a big project that I've written 100% of the code for, and some of my early code takes string or numeric arguments, but my later code seems to be leaning toward passing around objects. As I bump into some old code, I'm wondering if I should convert it to object parameters.


答: I think the best rule of thumb is to only send as a parameter what is actually needed.  The reason is re-use.  If you only need an integer as a parameter, passing in an object means that the same method cant (without some type wrangling) work in some other context when you want to use that same method but dont have an instance of the required type of object to use as a parameter.


问:
Method vs Function vs Procedure
Simple question, but I often hear these three terms defined with such ferocity, but which have been known to me to mean different things over the years.

What are the "correct" definitions of "Procedures", "Methods", "Function", "Subroutines", etc?

答:
A function is something that takes a bunch of inputs and returns one or more values. If the returned values are entirely determined by the inputs, and the function doesn't have any side effects (logging, perhaps, or causing state changes outside itself), then it's called a pure function.

A procedure is a function that doesn't return a value. In particular, this means that a procedure can only cause side effects. (That might include mutating an input parameter!)

A method is a function that closes over a set of variables, that is, a closure. It takes zero or more input parameters, has access to this set of variables, and returns zero or more values. In OO languages these methods are attached to objects or classes.

In most mainstream OO languages, those closed-over variables are called the member fields, or instance variables, of an object. A method can be a pure function, an impure function or a procedure.

The latter definition leads to the object = struct + closures correspondence.

Title: Method vs Function vs Procedure


答:
Compare:

```<code>public function ReceiveData($s) {
    $data = ExtractData($s)
    ProcessData($data)
}
...
$destination.ReceiveData($source)
</code>```

With:

```<code>$destination.ProcessData(ExtractData($source))
</code>```

The latter has several concrete advantages:

Testability. It's easier to unit test ExtractData and ProcessData separately rather than one method (ReceiveData) that does both.

Reusability. If you have a different kind of $source that $destination might want to receive, then you can still use ProcessData by simply using a different ExtractData function (or even the same ExtractData function if the two kinds of $source have a common interface).

Readability. Using ExtractData as an argument to ProcessData makes the data extraction explicit, rather than an implicit part of ReceiveData.

This relates to the single responsiblity principle (a method should only have one responsiblity).

Body:
Compare:

public function ReceiveData($s) {
    $data = ExtractData($s)
    ProcessData($data)
}
...
$destination.ReceiveData($source)

With:

$destination.ProcessData(ExtractData($source))

The latter has several concrete advantages:

Testability. It's easier to unit test ExtractData and ProcessData separately rather than one method (ReceiveData) that does both.

Reusability. If you have a different kind of $source that $destination might want to receive, then you can still use ProcessData by simply using a different ExtractData function (or even the same ExtractData function if the two kinds of $source have a common interface).

Readability. Using ExtractData as an argument to ProcessData makes the data extraction explicit, rather than an implicit part of ReceiveData.

This relates to the single responsiblity principle (a method should only have one responsiblity).


答:
It depends, and I try to discuss this by using a more real-world example.

For example, lets say you have a Person object with attributes like FirstName, Surname, NameAffix, DateOfBirth, Gender. And you are going to create some methods to process that data (for example, for a formatted report).

First, lets think of a method GetFullPersonNameFormatted, which should return a combination of FirstName, Surname and NameAffix in a specificially formatted string (assume that it does not make sense to put that method directly into the Person class for some reasons). Shall you pass the attributes one-by-one or the whole Person object? Well, I probably would pass the Person object at a whole, since this method creates an abstractions on persons, and if the Person changes internally, I only want to change GetFullPersonNameFormatted internally, not the calling code.

Now lets think of a method GetDateOfBirthFormatted, it should return the date-of-birth in a specificially formatted way. Shall you pass the attribute, or the whole Person object? I probably would start with a more general method FormatDate(date), not specificially for Persons, which would be much more reusable that a  method GetDateOfBirthFormatted(person), but it may also make sense to have additionally a

```<code> string GetDateOfBirthFormatted(Person person)
 {
        return FormatDate(person.DateOfBirth);
 }
</code>```

method for the same reason as in the first example: to create an abstraction on persons. If you really need that method, depends (for example, if there would be just one call to GetDateOfBirthFormatted in your whole program, you may better avoid creating that method and directly use FormatDate(person.DateOfBirth) instead.

So the answer for "should your method take the whole object or not?" depends mostly on "how much does your method need from that object?", but also on "what kind of abstraction you are going to create?". A big indicator for better using objects is when you have lots of methods getting the same group of attributes over and over again, for example, when you pass FirstName, Surname, NameAffix into several methods. This may also be an indicator that these attributes belong to a newly-to-create class (think of a program where you don't have a Person class so far: methods like that may be an indicator that you should create one).

There can be another reason not to pass objects, but only attributes: decoupling. Lets say the GetFullPersonNameFormatted is in module A, and the class definition of Person is in module B, and the call to GetFullPersonNameFormatted is in module C which references A and B. If you do not want to reference B from A, to keep those two modules completely independent from each other, then you need to define GetFullPersonNameFormatted without any Person parameter.

To summarize: it is not always a simple black-and-white decision, and there are different shades of grey.

Body:
It depends, and I try to discuss this by using a more real-world example.

For example, lets say you have a Person object with attributes like FirstName, Surname, NameAffix, DateOfBirth, Gender. And you are going to create some methods to process that data (for example, for a formatted report).

First, lets think of a method GetFullPersonNameFormatted, which should return a combination of FirstName, Surname and NameAffix in a specificially formatted string (assume that it does not make sense to put that method directly into the Person class for some reasons). Shall you pass the attributes one-by-one or the whole Person object? Well, I probably would pass the Person object at a whole, since this method creates an abstractions on persons, and if the Person changes internally, I only want to change GetFullPersonNameFormatted internally, not the calling code.

Now lets think of a method GetDateOfBirthFormatted, it should return the date-of-birth in a specificially formatted way. Shall you pass the attribute, or the whole Person object? I probably would start with a more general method FormatDate(date), not specificially for Persons, which would be much more reusable that a  method GetDateOfBirthFormatted(person), but it may also make sense to have additionally a

 string GetDateOfBirthFormatted(Person person)
 {
        return FormatDate(person.DateOfBirth);
 }

method for the same reason as in the first example: to create an abstraction on persons. If you really need that method, depends (for example, if there would be just one call to GetDateOfBirthFormatted in your whole program, you may better avoid creating that method and directly use FormatDate(person.DateOfBirth) instead.

So the answer for "should your method take the whole object or not?" depends mostly on "how much does your method need from that object?", but also on "what kind of abstraction you are going to create?". A big indicator for better using objects is when you have lots of methods getting the same group of attributes over and over again, for example, when you pass FirstName, Surname, NameAffix into several methods. This may also be an indicator that these attributes belong to a newly-to-create class (think of a program where you don't have a Person class so far: methods like that may be an indicator that you should create one).

There can be another reason not to pass objects, but only attributes: decoupling. Lets say the GetFullPersonNameFormatted is in module A, and the class definition of Person is in module B, and the call to GetFullPersonNameFormatted is in module C which references A and B. If you do not want to reference B from A, to keep those two modules completely independent from each other, then you need to define GetFullPersonNameFormatted without any Person parameter.

To summarize: it is not always a simple black-and-white decision, and there are different shades of grey.


问:
Which one subsumes the other: class-based object-orientation or prototypal inheritance?
In this talk: http://www.youtube.com/watch?v=hQVTIJBZook, Douglas Crockford claims that class-based object-orientation can be represented in terms of prototypal inheritance. The construction he gives is something like:

```<code>var theObject = function() {
  var private1 = ...;
  var private2 = ...;
  ...
  return {
    public1: ...,
    public2: ...,
    ...
  };
};
</code>```

He also claims that the converse is not true: prototypal inheritance cannot be in general encoded using class-based constructs only. I have been thinking about it for a while, and it seems to me that both claims are wrong.

The supposed "encoding" of class-based object-orientation is wrong from an operational semantics point of view. In a typical class-based object-oriented language, member variables and functions are known to exist, so they can be directly used. The prototypal "encoding" relies on testing at runtime whether a member is present in an object/hashtable. Ergo, the semantics are different.

Prototypal inheritance actually can be encoded in a class-based object-oriented language.

I will use C++ as an example, but any other class-based object-oriented language could be used.

```<code>struct prototypal
{
  std::shared_ptr<prototypal> base;
  std::unordered_map<std::string, boost::any> members;

  boost::any & operator [] (const std::string & key)
  {
    auto it = members.find (key);
    if (it == members.end ())
    {
      if (base)
        return (*base) [key];
      else
        throw std::logic_error { "Member not found." };
    }
    else
      return *it;
  }
};
</code>```

Is my analysis wrong? Am I missing something?

答:
In dynamic languages, the check is always runtime. So in dynamic languages a class based inheritance is basically special case of protoptypal one where the objects used as prototypes are considered a special kind of animal, class objects.

Dynamic languages with class-based inheritance like perl, python or ruby, there are various semantic restrictions that prevent you from using arbitrary stuff as class. That is I think what they mean; there are always some hooks that actually allow using arbitrary prototypes in those languages, but they are beyond scope of "class-based constructs".

This relies on the fact that in dynamic languages a class is not a type in sense similar to how built-in types are. All objects are just associative arrays and the class only describes which keys are to be expected there.

In static languages however a prototype inheritance can't be used at all, because the compiler needs to know which members exist and thus needs the class to be a type while instances are just objects. So they inherently need two kinds of animals and prototypal inheritance is not possible at all.

You can implement an associative array in statically typed language and you can implement inheritance for it either "class" based or prototypal, but it won't be the real classes. All the instances will be of the same static type. That's what you are doing with your example.

So in 1 for dynamic languages they are right, but for static languages you are right. For 2 it makes no sense for static languages and for dynamic languages they are right for suitable definition of "class-based constructs" (which I would not consider a well defined construct).


答:
As already stated in the another answer, stories are usually estimated in relative sizes. Therefore it shouldn't make any difference.

Maybe the fact you think you need to pair specific stories shows that they're a different level of complexity compared to the others and should consider putting more effort into their estimation.

Your team seem unconvinced by the value of pair programming - as you say in the comments. You should think about how you'd change that. Consider doing a trial of exclusively using pair programming and one without. Of course, it won't be conclusive but it should help your team gain a better understanding.

I find TDD really helps facilitate pair programming. The method of coming up with a test first helps the pair easily decide on their goal.

I found not pair programming (with TDD) was a false economy. We had a faster velocity until a build up of hidden bugs caused us to break down and deliver nothing because of a need to fix bugs.

When we pair programmed, our velocity was 15% slower but then at the end of each release, we had completely eliminated a class of bug. It was more predictable.

Doing pair programming with TDD requires discipline. And we all know being disciplined is hard and your team might not want to be but then you have to convince them.

Title: What do you do to estimates for agile stories where developers are pair programming?

Body:
If it was a 2-point story for one person, would you double it if people are pairing?

Pairing isn't always necessarily done 100% of a dev task, so it seems that doubling the story points seems wrong.  And it might not be obvious how much of the task will require pairing until the end, so you wouldn't know what the points the story should be until you've finished - and it seems strange to change an estimate midway through a sprint.

However, if velocity is going to be an accurate representation of how much work we can get through during a sprint, it seems right to change the estimates if more than one person is working on a task.  But also, this seems like it adds a lot of admin overhead.

Thoughts?


问:
Importance of diffing and merging for design specifications documentation
The context of this question is choosing tools for writing design specifications for software projects.

These documents will be written and maintained by architects and developers, I'm not talking about marketing requirements. Some of them may be shared outside the team, but only in a processed, non-editable form (PDF, all the docs are assumed being able to be exported to this format).

These are architecture documents, describing the structure of code components, implementation methods, protocols, data formats, etc. They take the form of text with diagrams and identifier names and the occasional code snippets, this isn't about API documentation that might be generated from source files.

The docs will be under source control, fortunately nobody here needs to be educated about that. It's inevitable that versioning will arise over time: we do maintain old versions of the software. Issue tracking might not be adhered to as strictly for documentation as for code.

How important is it to be able to easily compare and merge such documents? We have diverging opinions in the team, ranging from “nobody ever merges documentation and if needed Word has a merge tool” to “merging is crucial and git merge must work”. Note “Word has a merge tool” is something that I quote but don't agree with, having had the painful experience of merging two bugfixes that I had made to two copies of the same document

I have a vague memory of a rule in some company (Google, perhaps, since it's so often cited) that “if you can't merge it, it doesn't exist”, but I'm unable to find it now.

I'm looking for either well-reasoned arguments, or authoritative-looking (and preferably motivated) citations.

答:
For discussion in your case, it is important to take into account that diff feature is already available in your "setup" (more on that below).

Consider re-focusing discussion regarding diffs to how easy you need it to be, or more precisely, do you need "extra" usability features provided by diff tools targeted at working with code (more on that below).

Diff capability is there due to the fact that all the docs are assumed being able to be exported to PDF. Thing is, there are tools 1, 2 capable to produce PDF diffs.

For the sake of completeness it is worth noting that PDF also can be saved as plain text, which in theory would make things essentially the same as working with routine code diffs, but since all my attempts to use it led to meaningless garbage, I won't go further here.

In my experience, working with PDF diffs was pretty much close to regular code diffs, in the sense that one can refer, describe and discuss these in a meaningful way. "In 7th diff at page 654, word foo should be replaced with bar". Reviewing some 200-300 diffs in 2-3 files as a matter of 2-3 hours has been perfectly doable this way.

Adding that PDF also supports 3 annotations, reviewing PDF diffs may feel almost like working with a real code review tool like Cricible or Code Collaborator.

The question you should ask here is, again, how easy you need it to be? Does anticipated usage of doc diff involve scenarios where code review tools offer substantial benefit over PDF diffs?

Say, having 2-3 "rounds" review of 1000 diffs in 100 files in a day is perfectly sensible with a decent code review tool, but I can not even imagine this to be done with PDF diffs, as there is unlikely a demand in a tool capable of that, given typical PDF usage.


问:
What are the differences between functional, operational and technical requirements?
I have done tasks based on Java, but my seniors assigned me to collect requirements for creating a globalized bug tracking tool.

I have read many types of requirements from Wikipedia
and the mindtools website, but it was very confusing.

What are the exact differences between functional requirements, operational requirements and technical requirements?

答:
Functional requirements: What the system is supposed to do, process orders, send bills, regulate the temperature etc. etc.

Operational requirements: These are about how to run the system. Logging, startup/shutdown controls,  monitoring, resource consumption, back up, availability etc.etc.

Technical requirements: These are about how the system is built. Which language, which OS, standards to be adhered to etc.

These days "operational' and "technical" requirements are usually bundled together as "non-functional requirements"—mainly to stop silly arguments as to whether "system will respond to a user request within 1 second" is an operational or technical requirement.

OwnerDisplayName: vijaya kumar

ContentLicense: CC BY-SA 4.0


问:
What to do when you're faced with a problem that you can't solve quickly?
I'm a beginner learning Java and after reading the docs I'm trying to solve some of the problems at codingbat.com. Some I managed to solve pretty quickly in a matter of seconds but some not quite. The problems themselves are easy (example http://codingbat.com/prob/p126212) but I sometimes have a hard time finding the solutions. In part because I think of the best possible solution and automatically discard the ones that might work but aren't so elegant and in part because I can't find the right algorithm. This is either due to my inexperience (I have used PHP for web development for about 2 months so I'm not a total beginner - even worked with one framework to build a website) or due to my inability to think of a good algorithm.

I normally don't look at the solutions. I sometimes get stuck even for 1 1/5 hours at simple problems and some of them I eventually solve but some I can't so I eventually look at the solution.

Is it normal/good/bad to concentrate this long if I find a problem I can't solve? I might overreact but should this be so hard for me? Is there such thing as not being able to think of algorithms even with much learning and reading?

Thank you all in advance.

答:
From what you've said in your question, the issue isn't that you can't solve the problems, it's that you can't think of an elegant solution that would work, so you give up. The main problem with this approach is that you're not really learning anything. </p>

<p>A better approach would be to try one of the not so elegant possible solutions. If it doesn't work, it's not the end of the world, just move on to plan B. If it does work, you now have the chance to make it more elegant. Either way, you will have learned something, and this approach will serve you better if and when you write code for a living.  Remember: you can't improve what's not there. </p>

OwnerDisplayName: Mash

Body:
From what you've said in your question, the issue isn't that you can't solve the problems, it's that you can't think of an elegant solution that would work, so you give up. The main problem with this approach is that you're not really learning anything.

A better approach would be to try one of the not so elegant possible solutions. If it doesn't work, it's not the end of the world, just move on to plan B. If it does work, you now have the chance to make it more elegant. Either way, you will have learned something, and this approach will serve you better if and when you write code for a living.  Remember: you can't improve what's not there.


问:
Data Aggregation of CSV files java
I have k csv files (5 csv files for example), each file has m fields which produce a key and n values. I need to produce a single csv file with aggregated data.

I'm looking for the most efficient solution for this problem, speed mainly. I don't think by the way that we will have memory issues. Also I would like to know if hashing is really a good solution because we will have to use 64 bit hashing solution to reduce the chance for a collision to less than 1% (we are having around 30000000 rows per aggregation).

For example

```<code>file 1: f1,f2,f3,v1,v2,v3,v4
        a1,b1,c1,50,60,70,80
        a3,b2,c4,60,60,80,90

file 2: f1,f2,f3,v1,v2,v3,v4
        a1,b1,c1,30,50,90,40
        a3,b2,c4,30,70,50,90

result: f1,f2,f3,v1,v2,v3,v4
        a1,b1,c1,80,110,160,120
        a3,b2,c4,90,130,130,180
</code>```

algorithm that we thought until now:

hashing (using concurentHashTable)

merge sorting the files

DB: using mysql or hadoop or redis.

The solution needs to be able to handle Huge amount of data (each file more than two million rows)

a better example: file 1

```<code>country,city,peopleNum
england,london,1000000
england,coventry,500000
</code>```

file 2:

```<code>country,city,peopleNum
england,london,500000
england,coventry,500000
england,manchester,500000
</code>```

merged file:

```<code>country,city,peopleNum
england,london,1500000
england,coventry,1000000
england,manchester,500000
</code>```

The key is: country,city. This is just an example, my real key is of size 6 and the data columns are of size 8 - total of 14 columns.

We would like that the solution will be the fastest in regard of data processing.

答:
I would use a database to store the results (and handle the transactions) and then just write a small script which reads a file and inserts and/or updates the data accordingly (line per line).
You can then run the script in parallel on all your input files and fork off as much as your machine can take, or even run it on multiple machines.

The database will be the bottleneck, though.

Title: Data Aggregation of CSV files java


答:
If a language misses a feature which other languages have, you can often simulate that feature - that's true, I am sure you know that one can for example simulate objects and classes in C.

In your 2nd example, you "simulate" prototypal inheritance, but that does not make it a real feature of C++. That means, where things will work seamlessly in Javascript, in C++ you will have to add a lot of more code on your own to make your simulation complete (and it will still be a proprietary extension of yours, which will "feel" artificial for most other C++ guys).

The first example shows the standard way of creating more than one object of the same kind in Javascript - this does not "feel" like an artifical simulation of class based inheritance, and it will mostly serve the same purpose as classes in C++ from a practical point of view - to create many objects of the same type. Of course, there are semantic differences, as Jan Hudec explained from the fact that the one language is statically typed, and the other dynamically, but I guess Crockford has primarily the real-world usage in his focus.

Title: Which one subsumes the other: class-based object-orientation or prototypal inheritance?

Body:
In this talk: http://www.youtube.com/watch?v=hQVTIJBZook, Douglas Crockford claims that class-based object-orientation can be represented in terms of prototypal inheritance. The construction he gives is something like:

```<code>var theObject = function() {
  var private1 = ...;
  var private2 = ...;
  ...
  return {
    public1: ...,
    public2: ...,
    ...
  };
};
</code>```

He also claims that the converse is not true: prototypal inheritance cannot be in general encoded using class-based constructs only. I have been thinking about it for a while, and it seems to me that both claims are wrong.

The supposed "encoding" of class-based object-orientation is wrong from an operational semantics point of view. In a typical class-based object-oriented language, member variables and functions are known to exist, so they can be directly used. The prototypal "encoding" relies on testing at runtime whether a member is present in an object/hashtable. Ergo, the semantics are different.

Prototypal inheritance actually can be encoded in a class-based object-oriented language.

I will use C++ as an example, but any other class-based object-oriented language could be used.

```<code>struct prototypal
{
  std::shared_ptr<prototypal> base;
  std::unordered_map<std::string, boost::any> members;

  boost::any & operator [] (const std::string & key)
  {
    auto it = members.find (key);
    if (it == members.end ())
    {
      if (base)
        return (*base) [key];
      else
        throw std::logic_error { "Member not found." };
    }
    else
      return *it;
  }
};
</code>```

Is my analysis wrong? Am I missing something?


答:
Back in the day, there were no C++ compilers. The C++ code you wrote would be turned into C by a program called CFront. Now, obviously C doesn't have OO capabilities in itself, but somehow the C++ constructs were still turned into C code and your C++ programs were compiled and ran.

This is what he's talking about - you can replicate a C++ class by creating a plain struct and populating it with function pointers to the class methods. You can create a set of function pointers that refer to base classes functions too, so all the OO features that are not present in C can be replicated in C.

This function pointer approach is prototyping. Its a form of fundamental programming that might not be as easy as a language that wraps it up so the compiler handles creating these constructs - so a high level language cannot replicate the low-level features simply because it only provides an easy way of doing things and the compiler will mange them down to low-level features that you do not have access to. Conversely, the low-level language can provide the high-level constructs even though you will have a harder time coding them.

(note, this doesn't necessarily apply to C and C++ as C++ still offers the low-level features, but I hope it demonstrates my answer).


问:
How do you convince development teams to move to a new version of middleware?
I'm working on a project to update our (out of support) middleware stack to a stable but supported version.  There are several teams with applications running on the version we currently have in production and understandably nobody wants to carry the risk of being the first to run on the newer version.

What strategies have you used or found most compelling to move to a new release like this in the past?

There are some performance and functional benefits offered by the newer version but there isn't really any major technical incentive for the teams to move that's a must-have right now.  This is mainly being driven by the cost of extended support for the old version and also a desire by the infrastructure teams to be running on a supported version with the improved management offered by the newer version.

It's more of a people question than a technology question.

答:
In short: There are quite different approaches on how you convince the software developers and/or the project managers to introduce something new or upgrade application.

Thus, software developers are interested in saving time, and useful features while doing some common and challenging tasks with different flavor, and PMs are interested in saving costs of the ongoing operations by proposed new/upgrade implementation.

Only main and important dis-advantage comes forward from QA team members, when the current application testing is not automated by scripts. The QA team may naturally oppose this changes.

There are related SE questions on How to convince your work place to make some changes with arguments:

How to Convince management to upgrade to .Net 4.0

How to convince a colleague that code duplication is bad?

How to convince management that QA is important?

How to convince people to comment their code


答:
Take a break every now and then. It's good that you aren't looking at the solutions right off the bat, but if you are well and truly stuck go ahead. You will still learn even if you did not find the solution yourself.

I've heard that it takes 10 years to master a skill (don't have a source for that, sorry). So, don't worry if it seems to take you a long time at first. By the way, 1.5 hours is not a long time to be figuring out a problem. If you continue in programming you will find problems that may take you days, even weeks to figure out. Keep on driving at the problems, and you will find as the months go by that it becomes easier and easier.

As far as "Is there such thing as not being able to think of algorithms even with much learning and reading?" is concerned, practice makes perfect. There are only a limited number of basic data structures, and the algorithms for working with them are the same for any implementation. Once you learn, really learn to apply a few algorithms, you will remember them and be able to use the knowledge in other problems. Over time this knowledge base builds up to the point where problems appear to all be variations on a theme rather than disconnected.

Title: What to do when you're faced with a problem that you can't solve quickly?

Body:
I'm a beginner learning Java and after reading the docs I'm trying to solve some of the problems at codingbat.com. Some I managed to solve pretty quickly in a matter of seconds but some not quite. The problems themselves are easy (example http://codingbat.com/prob/p126212) but I sometimes have a hard time finding the solutions. In part because I think of the best possible solution and automatically discard the ones that might work but aren't so elegant and in part because I can't find the right algorithm. This is either due to my inexperience (I have used PHP for web development for about 2 months so I'm not a total beginner - even worked with one framework to build a website) or due to my inability to think of a good algorithm.

I normally don't look at the solutions. I sometimes get stuck even for 1 1/5 hours at simple problems and some of them I eventually solve but some I can't so I eventually look at the solution.

Is it normal/good/bad to concentrate this long if I find a problem I can't solve? I might overreact but should this be so hard for me? Is there such thing as not being able to think of algorithms even with much learning and reading?

Thank you all in advance.


问:
Is SQLite a sensible option for data logging?
I am trying to setup a small data-logging application under linux. The data arrives via serial port, and from there it should be pumped to logging and to graphical display.

The logging functionality is there for initialization purposes of the graphing functionality, after a reboot.

The data arrives every second and is composed of 1 number of 5 decimal digit precision, and should be logged for 2 years. My current free space is about 15GB.

The languages of the project so far are bash and python.

My objectives are to make simple but robust (maybe some live backups to a flash drive?) logging system, that is also fast and easy to read from python and write from bash.

Is SQLite suitable for this (I have never used it)? Is a text file in my home directory suitable for this?

答: Both options seem valid to me. In such cases, a useful rule to apply is to do the Simplest Thing That Could Possibly Work. Text files are easier to get started with and are expected to work reasonably well at least in the beginning. Once requirements arise that are better satisfied using a database, it will be trivial to import them. Using this strategy, you postpone design decisions as long as possible (but not longer than that). As such, you don't do unnecessary work. When, if ever, it will be needed, you will have a much better understanding of what exactly it is you need. Hence, you are more likely to build the Right Thing and not waste time building the Wrong Thing.</p>


答:
My favorite way to reduce this is to think this way.

If I can use MSPaint to get a screenshot of what the user sees that's functional.

As soon as I involve a computer, a computer language, a computer network.  It tends towards a technical specification.

Sometimes there's a lot of overlap.  like I can draw a picture of a 747, but that is actually more of a technical spec, because the assumption is that the thing flies.

But really, users and management would be perfectly happy if it flew using fairy dust instead of jet fuel.  So that's the functional part.  But actually it's a quite technical picture.

Hope I haven't gone too far afield, but that's how I think about it.

Title: What are the differences between functional, operational and technical requirements?

Body:
I have done tasks based on Java, but my seniors assigned me to collect requirements for creating a globalized bug tracking tool.

I have read many types of requirements from Wikipedia
and the mindtools website, but it was very confusing.

What are the exact differences between functional requirements, operational requirements and technical requirements?


问:
Passing an object into a method which changes the object, is it a common (anti-) pattern?
I am reading about common code smells in Martin Fowler's Refactoring book. In that context, I was wondering about a pattern I am seeing in a code base, and wether one could objectively consider it an anti-pattern.

The pattern is one where a object is passed as an argument to one or more methods, all of which change the object's state, but none of which return the object. So it is relying on the pass by reference nature of (in this case) C#/.NET.

```<code>var something = new Thing();
// ...
Foo(something);
int result = Bar(something, 42);
Baz(something);
</code>```

I find that (especially when methods are not named appropriately) I need to look into such methods to understand if the object's state has changed. It makes code comprehension more complex, since I need to track multiple levels of the call-stack.

I'd like to propose to improve such code to return another (cloned) object with the new state, or anything that is needed to change the object at the call-site.

```<code>var something1 =  new Thing();
// ...

// Let's return a new instance of Thing
var something2 = Foo(something1);

// Let's use out param to 'return' other info about the operation
int result;
var something3 = Bar(something2, out result);

// If necessary, let's capture and make explicit complex changes
var changes = Baz(something3)
something3.Apply(changes);
</code>```

To me it seems the first pattern is chosen on the assumptions

that it is less work, or requires less lines of code

that it allows us to both change the object, and return some other piece of information

that it is more efficient since we have less instances of Thing.

I illustrate an alternative, but to propose it, one needs to have arguments against the original solution. What, if any, arguments can be made to make the case that the original solution is an anti-pattern?

And what, if anything, is wrong with my alternative solution?

答:
I think it's fine to change state of the object in some scenarios. For example, I have a list of users and I want to apply different filters to the list before returning it to the client.

```<code>var users = Dependency.Resolve<IGetUsersQuery>().GetAll();

var excludeAdminUsersFilter = new ExcludeAdminUsersFilter();
var filterByAnotherCriteria = new AnotherCriteriaFilter();

excludeAdminUsersFilter.Apply(users);
filterByAnotherCriteria.Apply(users);
</code>```

And yes, you can make this pretty by moving filtering into another method, so you'll end up with something on the lines of:

```<code>var users = Dependency.Resolve<IGetUsersQuery>().GetAll();
Filter(users);
</code>```

Where Filter(users) would execute above filters.

I don't remember where exactly I came across this before, but I think it was referred to as filtering pipeline.

Body:
I think it's fine to change state of the object in some scenarios. For example, I have a list of users and I want to apply different filters to the list before returning it to the client.

var users = Dependency.Resolve<IGetUsersQuery>().GetAll();

var excludeAdminUsersFilter = new ExcludeAdminUsersFilter();
var filterByAnotherCriteria = new AnotherCriteriaFilter();

excludeAdminUsersFilter.Apply(users);
filterByAnotherCriteria.Apply(users);

And yes, you can make this pretty by moving filtering into another method, so you'll end up with something on the lines of:

var users = Dependency.Resolve<IGetUsersQuery>().GetAll();
Filter(users);

Where Filter(users) would execute above filters.

I don't remember where exactly I came across this before, but I think it was referred to as filtering pipeline.


问:
Backlog item with preparation for future sprint Scrum
I'm currently at the beginning of a build. We are requiring a lot of back end functionality around Clients/Users/Groups/Roles.

However, these aren't required for Sprint 1 which is acting as a MVP release. But I want to ensure we are preparing for this enhanced back-end in the future.

This is easiest by defining an interface to the User Management system without actually building all of it yet. How would you organise this in a Scrum project environment?

Obviously, in order to decide how the interface needs to look. We need to decide on it's functionality. But in doing so, we'll be getting very close to speccing the entire thing out. Which isn't required for several months!

(This is a Team Foundation Scrum 3.0 workflow for those interested)

答:
Taking an agile approach to this I would not do as you suggest and build the mock interface prior to starting work.  I would evolve the interface as you progress.

First of all focus on the most valuable stories (and it is VITAL that these meet INVEST
principles).

The tricky bit here is how you build your stories, and getting the definition right with both the team/s and the product owner is essential.  This will make or break the project.  There are two options I would consider for this, lets take for example the story 'As a user I want to log-in'. (I know this is a terribly formed user story, but it gets my point across simply). There are two options for defining this, and either approach could be better depending on how your team/teams are working on the project:

The 'pure' Scrum option - how I would do it if you are a single Scrum team.

Specify technical requirements as acceptance criteria of the story.  Eg. The login must be secure using XXX encryption, password strength etc.

As you build this story you design the aspects touched on by the story - eg. A users and passwords in the DB, and all the required fields.  If another story in the future means this will need refactoring, this is included in the size of that story.  Also, unit tests are essential to ensure that refactoring doesn't break existing functionality. This is probably the best approach if there is only 1 scrum team on the product, as it is best to get everything production quality as you go.

The Commercial Scrum option - how I would have done this in a company with multiple Scrum teams, that are not purely cross functional.

Ignore the tecnhical requirements, and separate them into a separate story.  Eg. a 'login' button is created that always passes, and lets you into the system to continue.  This means the 'front end' team (or sprint) can continue working and delivering further value, and a separate story holds the technical requirements and DB design of logging in. It is vital that everyone knows the functionality doesn't exist yet.

The main advantages to the second option are:

One team can build the UI while another team builds the DB. They can then carry on with other stories.

Stakeholders can see progress much earlier and get a feel for what you are building, which can influence design from an early stage.

The big risk is people believing progress is further than anticipated, because you have something that looks 'nearly done' but doesn't actually deliver value.  This is why the first option is more 'pure' Scrum.


问:
What is your favorite whiteboard interview problem?
Just as the title says, what is your favorite whiteboard interview problem, and why has it proven effective for you?

Junior, senior, Java, C, Javascript, PHP, SQL, pseudo-code, etc.

答:
I use a problem that is relevant to my programming domain.

If I develop web applications, I want to see how they might draw up a web form that deletes records, and what approach they might take to removing the record from the database, for example.  This tells me if they know basic database principles, how they interact with the user to verify deletion, and if they know what a soft delete is.

I don't have a favorite.  The problem I choose will vary greatly depending on the job.

I don't care whether they can solve the problem completely or not in an interview, what technologies and languages they use, or how crappy their code looks on a whiteboard.  I am looking for a thought pattern; I want to see if they know how to think through and solve problems.


问:
Recommended sprint length when adopting Agile?
I'm new to a small development company (half a dozen programmers and should grow to possibly a dozen eventually).  We also have a few external contractors working with us (just to add a bit of complication).

I would like to slowly start adopting Agile, or more importantly short sprints.  I was curios to know, from past experience, what would you recommend that our initial sprint length (in weeks) be?

Maybe I can even go as far as asking what is the sprint length of a very mature and experienced Agile team (shorter [2 weeks] or longer sprints [4 weeks])?

My initial thought was to use a shorter sprint, say 2 weeks and then in time, once we get the hang of things and all has smoothed out, we could simply double it to 4 weeks.

答:
Having implemented Scrum in a few teams I would suggest starting with two week sprints.  This is because it gives you a lot of retrospective meetings, allowing you to identify and discuss process improvements, so you can hone your actual Scrum processes quickly.

Once the team are comfortable with Scrum and how things work (maybe 5 sprints) I would suggest the team to try a three week sprint, and then see how it goes in the retrospective.  From here most teams I have seen will opt to keep three week sprints.  After a few you could offer the suggestion of a four week sprint if you think it worthwhile, but it is vital it is the teams decision.  Most teams I have worked with settle on three weeks.

There are many advantages and disadvantages to differing lengths:

Frequency of retrospectives and reviews.  2 weeks allows more frequent feedback from business and team, so story priorities may change, as well as development processes within the Scrum process.  At an early stage, regular retrospectives are extremely useful.

Pressure on team. With short sprints release is always just around the corner, and depending on the individuals in the team 2 week sprints can be very stressful. On the other hand 4 weeks (or longer) can lead to relaxing at the start. This is why personally I prefer 3 week sprints once the team is settled.

Unforseen Complexity.  If a task is larger than anticipated, a short sprint makes it harder to make up lost time. This can lead to not delivering everything comitted, and potentially demoralise the team.  This is more applicable in small teams.

Rhythm. So long as the meetings are well run, shorter sprints provide a good rhythm to the team, while it can be harder to get into the groove when you only have a four weekly meeting.

Achievement.  With 2 week sprints, the end of the sprint may not feel particularly special.  With longer sprints, you get a real sense of achievement and reason to celebrate.  I find teams still feel like it is a celebration with a 3 week sprint.