答:
Inheritance is a tool.  If it makes your life easier, use it.  The problem is, it's not always clear when to use it and when to use composition.

Consider:  What can you inherit?

1) Data : In C++-like languages, you can inherit the data from you parent object and access it.

2) Interface:  This is usually why you want to inherit.  It's what Java has the notion of interfaces.

3) Code: If you parent defines a "default" version of the code you want, you get the code (and the interface).

So, consider how you use an Item.

You may want to use inheritance because all of your items have the same kind of data:  location, weight, mobility, status.  Having all of your items inherit from a base class with those attributes will make it easy to think
about all Items.  This is a good reason to use inheritance: common data that all items have.

```<code>  class BaseItem {
      string location;  //What room is the item in?
      int weight;       // for encumbrance
      bool mobility;    // can I move this item?
      bool status;      // dead or alive
  }

  class ArmorItem : public Item {
      int damageReduction;  // ... plus all the other attributes above
  }

  class WeaponItem : public Item {
      int damage; // how much damage this does
  }
</code>```

Consider for the next example:
Are you using it in loops where you do the same thing over and over to it?  (This is usually interface inheritance with polymorphism and the reason to use inheritance).  In this case, all items inherit the interface of the base class:

```<code> for item in inventory :
      item.print_description()    # All different item types may describe themselves differently

  for item in inventory :
       damage_reduction += item.damage_reducer(CURRENT_DAMAGE_TYPE)   # Some items do nothing, armor items reduce damage
</code>```

Basically, if you do the same thing over and over to all sorts of different items, and you want different behaviors for the different types of items, inheritance does make sense.

The examples above are usually the canonical ways to use inheritance. Occasionally, you can use inheritance to give you something where almost everything you want is someplace, but not everything.  For example, you want all the interface of a complex number class, but you want just one more method which gives you the magnitude2 of the complex.  You can inherit from complex (mycomplex) and add a new method.  You get all the interface, code, and data from the complex, but augment the class with something you want.

Other discussion on inheritance:

liskov substitution principle
Prefer composition to inheritance

People are jumpy about inheritance because it can make code very hard to
maintain.   But if you can use inheritance because it makes your code simpler, isn't that what tools are for?

Title: Am I overusing Inheritance or this is exactly what it is here for?

Body:
I have a class called BagItem and another class called EquipmentItem both classes are exact the same in methods, etc, with the exception of 1 property.

BagItem have:

```<code>public InventoryBagType BagType { get; private set; }
</code>```

EquipmentItem have:

```<code>public InventoryEquipmentType EquipmentType { get; private set; }
</code>```

I guess I should mention, BagItem refer to items that are in the character's bag while EquipmentItem I should have probably named it EquippedItem which refer to item currently equipped by the character.

From those 2 classes I have other classes that inherit from one or another.

Then from EquipmentItem for example I have CombatEquipmentItem which inherits from EquipmentItem and CombatEquipmentItem only have one extra property.

```<code>public CombatEquipmentType SlotType { get; private set; }
</code>```

At this point I don't know if CombatEquipmentItem will have or not more properties or methods, neither if either BagItem or EquipmentItem will either.

I was considering creating yet another class InventoryItem that would keep all the common entries from BagItem and EquipmentItem and they would inherit from it and by its turn CombatEquipmentItem from it.

Should I eliminate BagItem and EquipmentItem for InventoryItem and keep both the properties there and either set one or another as null based on the item and inherit anything else from it or should I move forward with yet another class or my design is bad from the begin and how it should have been written as?

Body:
Inheritance is a tool.  If it makes your life easier, use it.  The problem is, it's not always clear when to use it and when to use composition.

Consider:  What can you inherit?

1) Data : In C++-like languages, you can inherit the data from you parent object and access it.

2) Interface:  This is usually why you want to inherit.  It's what Java has the notion of interfaces.

3) Code: If you parent defines a "default" version of the code you want, you get the code (and the interface).

So, consider how you use an Item.

You may want to use inheritance because all of your items have the same kind of data:  location, weight, mobility, status.  Having all of your items inherit from a base class with those attributes will make it easy to think
about all Items.  This is a good reason to use inheritance: common data that all items have.

  class BaseItem {
      string location;  //What room is the item in?
      int weight;       // for encumbrance
      bool mobility;    // can I move this item?
      bool status;      // dead or alive
  }

  class ArmorItem : public Item {
      int damageReduction;  // ... plus all the other attributes above
  }

  class WeaponItem : public Item {
      int damage; // how much damage this does
  }

Consider for the next example:
Are you using it in loops where you do the same thing over and over to it?  (This is usually interface inheritance with polymorphism and the reason to use inheritance).  In this case, all items inherit the interface of the base class:

 for item in inventory :
      item.print_description()    # All different item types may describe themselves differently

  for item in inventory :
       damage_reduction += item.damage_reducer(CURRENT_DAMAGE_TYPE)   # Some items do nothing, armor items reduce damage

Basically, if you do the same thing over and over to all sorts of different items, and you want different behaviors for the different types of items, inheritance does make sense.

The examples above are usually the canonical ways to use inheritance. Occasionally, you can use inheritance to give you something where almost everything you want is someplace, but not everything.  For example, you want all the interface of a complex number class, but you want just one more method which gives you the magnitude2 of the complex.  You can inherit from complex (mycomplex) and add a new method.  You get all the interface, code, and data from the complex, but augment the class with something you want.

Other discussion on inheritance:

liskov substitution principle
Prefer composition to inheritance

People are jumpy about inheritance because it can make code very hard to
maintain.   But if you can use inheritance because it makes your code simpler, isn't that what tools are for?


问:
What is the difference between Requirements Elicitation and Requirements Analysis in the real world?
What is the difference between Requirements Elicitation and Requirements Analysis?</p>

答:
Requirements Elicitation: the process through which the customers, buyers, or users of a software system discover, reveal, articulate, and understand their requirements.

Requirements analysis: the process of reasoning about the requirements that have been elicited; it involves activities such as examining requirements for conflicts or inconsistencies, combining related requirements, and identifying missing requirements.

Requirements specification: the process of recording the requirements in one or more forms, including natural language and formal, symbolic, or graphical representations; also, the product that is the document produced by that process.

Requirements validation: the process of confirming with the customer or user of the software that the specified requirements are valid, correct,
and complete.

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 3.0


问:
Do people in non-English-speaking countries code in English?
I've heard it said (by coworkers) that everyone "codes in English" regardless of where they're from. I find that difficult to believe, however I wouldn't be surprised if, for most programming languages, the supported character set is relatively narrow.

Have you ever worked in a country where English is not the primary language?

If so, what did their code look like?

答:
I have always coded in English. Also, I never wanted to code like this either:

```<code>क = 1;
कुल = 0;
जब तक क छोटा है 10 से  {
    कुल += क;
}
छापो कुल
</code>```

```<code>कार्य खाली मुख्य ( )      अंक समय       लिखें "Enter current time"
     पढें समय        अगर [ समय < 12 ]
        लिखें "Good Morning"
  वरनाअगर [ समय >= 12 और समय < 16 ]
           लिखें "Good Afternoon"
  वरना              लिखें "Good Evening"
  खत्म अगर
खत्म कार्य
</code>```

Body:
I have always coded in English. Also, I never wanted to code like this either:

क = 1;
कुल = 0;
जब तक क छोटा है 10 से  {
    कुल += क;
}
छापो कुल

कार्य खाली मुख्य ( )      अंक समय       लिखें "Enter current time"
     पढें समय        अगर [ समय < 12 ]
        लिखें "Good Morning"
  वरनाअगर [ समय >= 12 और समय < 16 ]
           लिखें "Good Afternoon"
  वरना              लिखें "Good Evening"
  खत्म अगर
खत्म कार्य


问:
Using Autoincrement Primary keys as Foreign Keys
When creating a table, there is an option for us to set the numeric primary key as autoincrement where its value increases whenever a new data in inserted.

This primary number can be used for setting the relationship of a table where it is assigned as a foreign key to that table.

So my question is it a good practice for us to use the autoincrement numeric primary as foreign key or should we use the programmatically generated code.

e.g.
for a table products we have the fields id (autoincrement primary key), productCode (program generated unique item code. field property also set to unique), Description. and we are going to create a relationship to a transactions table. What field should be used as foreign key: autoid or productCode?

答:
100 % of the world has lost data at some point and when this happens it can essentially isolate the FK based table. DB guys will promise you this can never happen and tout all sorts of recovery capabilities and backing up and logging concepts but it happens. I would say it's a fair shot 50/50 in my experience of enterprise systems either changing business logic that affects your key structure versus data issues that affect your key structure.  You have to remember that this includes bad business logic inserting garbage data that now has run a big muk with your auto incremented keys. </p>

<p>Either option can handle integrity ie ACID equally well and come with their own challenges.Really the situation your in should be looked at to see what works best. I would say it is easier to restore integrity to completely controllable data that is logical than it is auto incremented keys.  </p>

Body:
100 % of the world has lost data at some point and when this happens it can essentially isolate the FK based table. DB guys will promise you this can never happen and tout all sorts of recovery capabilities and backing up and logging concepts but it happens. I would say it's a fair shot 50/50 in my experience of enterprise systems either changing business logic that affects your key structure versus data issues that affect your key structure.  You have to remember that this includes bad business logic inserting garbage data that now has run a big muk with your auto incremented keys.

Either option can handle integrity ie ACID equally well and come with their own challenges.Really the situation your in should be looked at to see what works best. I would say it is easier to restore integrity to completely controllable data that is logical than it is auto incremented keys.


问:
Don't quite understand check and set in concurrency
I don't entirely understand check and set behaviour.. here is an example:

```<code>    public static void main(String[] args) {

    List<String> list = Collections.synchronizedList(new ArrayList<>());

    String abc = "123";

    if (!list.contains(abc)) {
        list.add(abc);

        // ... some several lines of code

        list.remove(abc);

    }

}
</code>```

What I don't quite understand...

So I understand that contains and add should be in a synchronized(list) block...

but what about remove?

if not, then what if it was:

```<code>if (list.contains(abc)) {
   list.add(abc);
   list.remove(abc);
}
</code>```

?

I understand that code doesn't make much sense but I just am using it as an example... Does remove have to be in the synchronized block here?

答: You should probably read Java Concurrency in Practice by Brian Goetz and others</p>


问:
Should actions / methods be conjugated in comments?
For example, which of the following is correct ?

```<code>// Return hello
      -- or --
// Returns hello

function greeting()
{
  return "Hello";
}
</code>```

I personally never conjugate them but I am wondering how right or wrong this does sounds to a native english speaker. I have been unable to find a real recommendation about it.

Another example:

```<code>// Find the first entry (implicit "to find the first entry")
      -- or --
// Finds the first entry (implicit "this finds the first entry")

function findFirst(array)
{
  return array[0];
}
</code>```

答:
If you have some doubts about naming and documenting, check out how top developers do it. You can find good examples in official documentation for different tools, libraries, frameworks, languages etc.

For example,

MSDN Stack<T> documentation

PHP.net mysqli::ping documentation

Description of the methods contains conjugated forms such as "Specifies", "Returns", "Removes" or "Determines", while comments within methods use imperative forms - "check connection", "check if server is alive", "close connection", "Create a copy of the stack".

So, I'd write your code like this:

// Returns hello
function greeting()
{
  return "Hello";
}

// Starts foo-ing
function foo()
{
   // Show greeting message
   greeting();
}
```

Upd:
And this makes sense, because comments before functions and methods tell us what the functions do:

Foo() returns the state

Bar() checks the value

while comments in functions show us the steps of the algorithm:

Get the state

Check the value

Initiate the module

Body:
If you have some doubts about naming and documenting, check out how top developers do it. You can find good examples in official documentation for different tools, libraries, frameworks, languages etc.

For example,

MSDN Stack<T> documentation

PHP.net mysqli::ping documentation

Description of the methods contains conjugated forms such as "Specifies", "Returns", "Removes" or "Determines", while comments within methods use imperative forms - "check connection", "check if server is alive", "close connection", "Create a copy of the stack".

So, I'd write your code like this:

// Returns hello
function greeting()
{
  return "Hello";
}

// Starts foo-ing
function foo()
{
   // Show greeting message
   greeting();
}

Upd:
And this makes sense, because comments before functions and methods tell us what the functions do:

Foo() returns the state

Bar() checks the value

while comments in functions show us the steps of the algorithm:

Get the state

Check the value

Initiate the module


问:
Why no developer API in C++ for Google or Yahoo mail?
I was trying to do some C++ coding that can send files from my laptop to my webmail account. It took me about 10 minutes to realize that there is no easy way to do this. Look into these links:

GMAIL: http://code.google.com/apis/gmail/oauth/code.html

YAHOO: http://developer.yahoo.com/mail/

I am trying to understand why PHP or Python or Java support exist but no C++. No flame wars, I love all programming languages and their creators equally but I am curious to understand the logic behind such implementation choices.

答: C++ has its strengths and weaknesses. One weakness is that its library is very thin. Email involves a lot of protocols, HTTP/S, SMTP, POP3, IMAP, etc. I don't see how you can support these protocols easily in a standardized way with C++.</p>

ContentLicense: CC BY-SA 2.5


答:
Unfortunately, there is no real rule that states what you are asking about.

Personally, my comments behaviors depend on the programming language I am coding with. As I develop for example in Python, I can show that your first option (return) is rather favored in this programming language: If you check PEP 0008 and read the whole comments paragraphs, you will see we rather use your first option:

x = x + 1                 # Increment

x = x + 1                 # Compensate for border

"""Return a foobang

Optional plotz says to frobnicate the bizbaz first. """

Title: Should actions / methods be conjugated in comments?

Body:
For example, which of the following is correct ?

```<code>// Return hello
      -- or --
// Returns hello

function greeting()
{
  return "Hello";
}
</code>```

I personally never conjugate them but I am wondering how right or wrong this does sounds to a native english speaker. I have been unable to find a real recommendation about it.

Another example:

```<code>// Find the first entry (implicit "to find the first entry")
      -- or --
// Finds the first entry (implicit "this finds the first entry")

function findFirst(array)
{
  return array[0];
}
</code>```


问:
Code readability on non-trivial loop variables
My co-worker and I discussing about the code readability on simple loops. Suppose a method takes an integer parameter and does some operation on the elements of an array depending on the parameter. e.g

For the sake of simplicity, assume array bounds are negligible and there is no error generated by the codes I presented below.

```<code>function doSomeOp(targetIndex) {
  for(var i = targetIndex + 5; i < someArray.length; i++) {
    someArray[i] = 42;
  }
}
</code>```

as opposed to;

```<code>function doSomeOp(targetIndex) {
  for(var i = targetIndex; i < someArray.length; i++) {
    someArray[i + 5] = 42;
  }
}
</code>```

Is there any advantage to define the loop parameter to simpler values like "0", "targetIndex", "array.length" and then define business logic when using that loop parameter?

答:
"For the sake of simplicity, assume array bounds are negligible and there is no error generated by the codes I presented below."

So You've introduced an error into your program by forgetting to add the -5 because the second needs it in two places.

Also, this is just imho, but the first loop works more like my mind works when interacting with loop (and works more like if you changed it out for an iterator).

To the extent the this incredibly marginal issue matters, the first is better.

```<code>// The second fixed:
function doSomeOp(targetIndex) {
  for(var i = targetIndex; i < someArray.length - 5; i++) {
    someArray[i + 5] = 42;
  }
}
</code>```

Body:
"For the sake of simplicity, assume array bounds are negligible and there is no error generated by the codes I presented below."

So You've introduced an error into your program by forgetting to add the -5 because the second needs it in two places.

Also, this is just imho, but the first loop works more like my mind works when interacting with loop (and works more like if you changed it out for an iterator).

To the extent the this incredibly marginal issue matters, the first is better.

// The second fixed:
function doSomeOp(targetIndex) {
  for(var i = targetIndex; i < someArray.length - 5; i++) {
    someArray[i + 5] = 42;
  }
}


答:
Conjugation being very rudimentary in English, I would say it doesn't make much of a difference. It might as well be the imperative, particularly if the method is a command in the context of command-query separation. Personally, that is how I read it, because in Slovak, my native language, buttons are commonly labeled with the imperative (which is morphologically clearly distinct from the infinitive in that language).

```<code>// Find the first entry (implicit "onward, contraption, find me the first entry!")

function findFirst(array)
{
   return array[0];
}
</code>```

However, if the method name is well chosen, you don't need to rephrase it as a sentence. Instead you document side effects, usage and what not, in which case the imperative is inadequate and one would use the 3rd person indicative. People will of course have dozens of different opinions of this and some will start religious wars over it. Ideally you can let someone else review the code and if they understand what a method does based on its name + documentation, then you have done it right, otherwise not. Further distinctions border on bikeshedding.

Just an example of a method not quite well named:

```<code>function greeting()
{
   return "Hello";
}
</code>```

The name in itself leaves multiple options open. Does this actually perform the greeting? Or does it give me a value suitable to greet others?

If performed the greeting itself, then I would call it greet (or performGreeting if no suitable verb is available or the verb is ambiguous) and otherwise makeGreeting (or produceGreeting or provideGreeting or somesuch).

Body:
Conjugation being very rudimentary in English, I would say it doesn't make much of a difference. It might as well be the imperative, particularly if the method is a command in the context of command-query separation. Personally, that is how I read it, because in Slovak, my native language, buttons are commonly labeled with the imperative (which is morphologically clearly distinct from the infinitive in that language).

// Find the first entry (implicit "onward, contraption, find me the first entry!")

function findFirst(array)
{
   return array[0];
}

However, if the method name is well chosen, you don't need to rephrase it as a sentence. Instead you document side effects, usage and what not, in which case the imperative is inadequate and one would use the 3rd person indicative. People will of course have dozens of different opinions of this and some will start religious wars over it. Ideally you can let someone else review the code and if they understand what a method does based on its name + documentation, then you have done it right, otherwise not. Further distinctions border on bikeshedding.

Just an example of a method not quite well named:

function greeting()
{
   return "Hello";
}

The name in itself leaves multiple options open. Does this actually perform the greeting? Or does it give me a value suitable to greet others?

If performed the greeting itself, then I would call it greet (or performGreeting if no suitable verb is available or the verb is ambiguous) and otherwise makeGreeting (or produceGreeting or provideGreeting or somesuch).


答:
Hypothesis: because web APIs are primarily used to integrate their respective services with other web applications. Therefore it is logical to conclude those other services are written in some web-relevant languages. C++ is not one of them.

Anyway APIs here do not seem to be language-specific. They're just offering you a bunch of client libraries out of courtesy, not for all possible languages, but for a narrow selection of the most requested ones. If there isn't one for your needs, nothing prevents you from writing your own client library - maybe even publishing it to make people's lives better. Or maybe there is already one - just google for it.

Title: Why no developer API in C++ for Google or Yahoo mail?

Body:
I was trying to do some C++ coding that can send files from my laptop to my webmail account. It took me about 10 minutes to realize that there is no easy way to do this. Look into these links:

GMAIL: http://code.google.com/apis/gmail/oauth/code.html

YAHOO: http://developer.yahoo.com/mail/

I am trying to understand why PHP or Python or Java support exist but no C++. No flame wars, I love all programming languages and their creators equally but I am curious to understand the logic behind such implementation choices.


问:
What could "move an instruction without a 16-bit bus" mean?
Spoiler alert! This question (and, possibly, answers) could contain spoilers regarding "Halt and Catch Fire" TV series.

Background

I'm a web deleloper and do not have a CS degreee, so my understanding about hardware is at How Do Computers Work? level.

Question context

Here's a dialog from episode 102 between a hacker (Cameron Howe), which was hired by Cardiff Electric (fictional company) to write BIOS code via Clean room design, and an IBM lawyer (the story takes place in 1984):

Lawyer (passing to Cameron a binder with printed IBM's BIOS code): You were hired to write a replica of our BIOS code, but you won't be looking at our BIOS code.

Cameron: Look, I don't need to look at your BIOS, because I'm not interested in copying garbage. Sure, I might decide I want to spend
the rest of my natural life waiting to move an instruction without a 16-bit bus, but other than that, I'm not looking at that binder.

Question

Does a phrase in bold have any meaning in real world, or it is just a fantasy of a screenwriter? AFAIK, it is related to a CPU architecture and not BIOS itself? If her task is to write a BIOS code, why she would be concerned about that?

答: Speaking as someone with extensive experience of low-level programming and some cpu architecture background, the phrase seems to be utterly meaningless in the context given. I therefore imagine it is simply technobabble, not intended to actually be understood by anyone.</p>


问:
Tab management code in single-page applications acceptable violations of the DRY principle?
I have an AngularJS-based single-page app that allows the user to operate multiple items at the same time. I decided to use a multi-tab UI implemented in custom code.

However, the user begin to ask for more and more tab management features like rearranging, going back to the last tab after closing, etc. and it feels like I am just duplicating tab management features of the browser.

Unfortunately, it is difficult to span one Angular application across mutliple tabs, so is this kind of reinventing the wheel acceptable?

(I tried to look for existing widgets with these features, but can't find one fits the bill perfectly.)

答:
Duplication of programming constructs is bad, but it's not as bad as failing to fulfil a requirement. If the sane way of providing functionality is to repeat blocks of code and there is no way around it, then the correct thing to do is to repeat them.

It can, however, be an indicator that you should ditch your coding environment for one that does have a way around it.


答:
This is really a summing up of Developer Art's Point:

Nobody (with few exceptions) should write web applications in C++!


问:
Should I unit test my subclasses or my abstract parent class?
I have a skeletal implementation, as in Item 18 from Effective Java (extended discussion here).
It is an abstract class that provides 2 public methods methodA() and methodB() that call subclasses methods to "fill the gaps" that I can't define in an abstracted manner.

I developed it first by creating a concrete class and writing unit tests for it. When the second class came, I was able to extract common behavior, implement the "missing gaps" in the second class and it was ready (of course, the unit tests were created for the second subclass).

Time went by and now I have 4 subclasses, each implementing 3 short protected methods that are very specific to their concrete implementation, while the skeletal implementation does all the generic work.

My problem is that when I create a new implementation, I write the tests all over again:

Does the subclass calls a given required method?

Does a given method has a given annotation?

Do I get the expected results from the method A?

Do I get the expected results from the method B?

While see advantages with this approach:

It documents the subclass requirements through tests

It may fail fast in case of a problematic refactoring

Test the subclass as a whole and through their public API ("does methodA() work?" and not "does this protected method work?")

The problem I have is that the tests for a new subclass are basically a no-brainer:
 - The tests are all the same in all subclasses, they just change the return type of the methods (the skeleton implementation is generic) and the properties I check on the assert part of the test.
 - Usually the subclasses have no tests that are specific for them

I like the way the tests focus on the result of the subclass itself and protects it from refactoring, but the fact that implementing the test became just "manual work" makes me think I am doing something wrong.

Is this issue common when testing class hierarchy? How can I avoid that?

ps: I thought about testing the skeleton class, but it also seems strange creating a mock of an abstract class to be able to test it. And I think that any refactoring on the abstract class that changes behavior that is not expected by the subclass would not be noticed as fast. My guts tell me that testing the subclass "as a whole" is the preferred approach here, but please feel free to tell me I am wrong :)

ps2: I've googled and found many questions about the subject. One of them is this one which has a great answer from Nigel Thorne, my case would be his "number 1." That would be great, but I can't refactor at this point, so I would have to live with this problem.
If I could refactor, I would have each subclass as a strategy. That would be OK, but I would still test the "main class" and test the strategies, but I would not notice any refactoring that breaks the integration between main class and strategies.

ps3: I've found some answers saying that "it is acceptable" to test the abstract class. I agree that this is acceptable, but I would like to know which is the preferred approach in this case (I am still starting with unit tests)

答:
I can't see how you'd write tests for an abstract base class; you can't instantiate it, so you cannot have an instance of it to test.  You could create a "dummy", concrete subclass just for the purposes of testing it - not sure how much use that would be.  YMMV.

Every time you create a new implementation (class), then you should be writing tests that exercise that new implementation.  Since parts of the functionality (your "gaps") are implemented within each subclass, this is absolutely necessary; the output of each of the inherited methods may (and probably should) be different for each new implementation.


答:
I'd do neither. The type of comments you are describing are simply there to describe what badly named methods are doing. They are noise.

Instead of calling a method findFirst and then having a comment that described what findFirst means, call the method findFirstEntry and remove the comment.

The purpose of well written code is to tell other developers (and the compiler) what that code does. If additional explanations of why it does it a certain way, or how a necessarily complicated piece of code works, then add clearly written comments. If the code is clear, don't clutter it with pointless comments that just repeat the code.


问:
Could an instance be equal to some other instance of a more specific type?
I've read this article: How to Write an Equality Method in Java.

Basically, it provides a solution for an equals() method that supports inheritance:

```<code>Point2D twoD   = new Point2D(10, 20);
Point3D threeD = new Point3D(10, 20, 50);
twoD.equals(threeD); // true
threeD.equals(twoD); // true
</code>```

But is it a good idea? these two instances appears to be equal but may have two different hash codes. Isn't that a bit wrong?

I believe this would be better achieved by casting the operands instead.

答: The rule is, whenever you override hashcode(), you override equals(), and vice versa. Whether this is a good idea or not depends on the intended usage. Personally, I would go with a different method (isLike() or similar) to achieve the same effect.


答:
This should not be equality because it breaks transitivity. Consider these two expressions:

```<code>new Point3D(10, 20, 50).equals(new Point2D(10, 20)) // true
new Point2D(10, 20).equals(new Point3D(10, 20, 60)) // true
</code>```

Since equality is transitive, this should mean that the following expression is also true:

```<code>new Point3D(10, 20, 50).equals(new Point3D(10, 20, 60))
</code>```

But of course - it isn't.

So, your idea of casting is correct - expect that in Java, casting simply means casting the type of the reference. What you really want here is a conversion method that'll create a new Point2D object from a Point3D object. This would also make the expression more meaningful:

```<code>twoD.equals(threeD.projectXY())
</code>```

Title: Could an instance be equal to some other instance of a more specific type?

Body:
I've read this article: How to Write an Equality Method in Java.

Basically, it provides a solution for an equals() method that supports inheritance:

```<code>Point2D twoD   = new Point2D(10, 20);
Point3D threeD = new Point3D(10, 20, 50);
twoD.equals(threeD); // true
threeD.equals(twoD); // true
</code>```

But is it a good idea? these two instances appears to be equal but may have two different hash codes. Isn't that a bit wrong?

I believe this would be better achieved by casting the operands instead.

Body:
This should not be equality because it breaks transitivity. Consider these two expressions:

new Point3D(10, 20, 50).equals(new Point2D(10, 20)) // true
new Point2D(10, 20).equals(new Point3D(10, 20, 60)) // true

Since equality is transitive, this should mean that the following expression is also true:

new Point3D(10, 20, 50).equals(new Point3D(10, 20, 60))

But of course - it isn't.

So, your idea of casting is correct - expect that in Java, casting simply means casting the type of the reference. What you really want here is a conversion method that'll create a new Point2D object from a Point3D object. This would also make the expression more meaningful:

twoD.equals(threeD.projectXY())


答:
Typically you would create a base class to enforce an interface. You want to be testing that interface, not the details below. Therefore, you should create tests that instantiate each class individually but only test through the base class's methods.

The advantages of this method is that because you tested the interface, you can now refactor underneath the interface. You may find that code in a child class should be in the parent, or vice versa. Now your tests will prove that you didn't break behavior when you move that code.

In general, you should test code how it's intended to be used. That means avoiding testing private methods, and often means that your unit under test may be a bit larger than you originally thought - perhaps a group of classes rather than a single class. Your goal should be to isolate changes so that you rarely have to change a test when you refactor in a given scope.

Title: Should I unit test my subclasses or my abstract parent class?

Body:
I have a skeletal implementation, as in Item 18 from Effective Java (extended discussion here).
It is an abstract class that provides 2 public methods methodA() and methodB() that call subclasses methods to "fill the gaps" that I can't define in an abstracted manner.

I developed it first by creating a concrete class and writing unit tests for it. When the second class came, I was able to extract common behavior, implement the "missing gaps" in the second class and it was ready (of course, the unit tests were created for the second subclass).

Time went by and now I have 4 subclasses, each implementing 3 short protected methods that are very specific to their concrete implementation, while the skeletal implementation does all the generic work.

My problem is that when I create a new implementation, I write the tests all over again:

Does the subclass calls a given required method?

Does a given method has a given annotation?

Do I get the expected results from the method A?

Do I get the expected results from the method B?

While see advantages with this approach:

It documents the subclass requirements through tests

It may fail fast in case of a problematic refactoring

Test the subclass as a whole and through their public API ("does methodA() work?" and not "does this protected method work?")

The problem I have is that the tests for a new subclass are basically a no-brainer:
 - The tests are all the same in all subclasses, they just change the return type of the methods (the skeleton implementation is generic) and the properties I check on the assert part of the test.
 - Usually the subclasses have no tests that are specific for them

I like the way the tests focus on the result of the subclass itself and protects it from refactoring, but the fact that implementing the test became just "manual work" makes me think I am doing something wrong.

Is this issue common when testing class hierarchy? How can I avoid that?

ps: I thought about testing the skeleton class, but it also seems strange creating a mock of an abstract class to be able to test it. And I think that any refactoring on the abstract class that changes behavior that is not expected by the subclass would not be noticed as fast. My guts tell me that testing the subclass "as a whole" is the preferred approach here, but please feel free to tell me I am wrong :)

ps2: I've googled and found many questions about the subject. One of them is this one which has a great answer from Nigel Thorne, my case would be his "number 1." That would be great, but I can't refactor at this point, so I would have to live with this problem.
If I could refactor, I would have each subclass as a strategy. That would be OK, but I would still test the "main class" and test the strategies, but I would not notice any refactoring that breaks the integration between main class and strategies.

ps3: I've found some answers saying that "it is acceptable" to test the abstract class. I agree that this is acceptable, but I would like to know which is the preferred approach in this case (I am still starting with unit tests)


问:
Are there any pitfalls when replacing a Python module using sys.modules?
In a current project of mine, I have decided to not put any significant amount of code in __init__.py files, simply because I don't like them. In my head, an __init__.py file is just there to inform Python that the folder is a module. I keep forgetting that they might contain lots of code just like any other Python module.

In this project I have decided to create a "main" submodule whenever I'm tempted to put significant amounts of code in an __ini__.py file, then I import the "main" submodule in __init__.py and replace the module.

For example, say I have a module named alpha:

```
alpha/
  __init__.py
```

And I want to put a few constants and helper methods under the alpha module. Instead of putting the code into __init__.py I create a new module called (for example) main:

```
alpha/
  __init__.py
  main.py
```

Then I put my stuff in that module. Then I just put this into __init__.py:

```<code>import sys
import alpha.main

sys.modules["alpha"] = alpha.main
</code>```

Now I can put stuff into alpha/main.py:

```<code>author = "John Hancock"
maintainer = "John Hancock"
</code>```

And access it like this:

```<code>import alpha

print(alpha.maintainer)
</code>```

It works perfectly, and I'm loving that I don't have to edit __init__.py files anymore.

However, this kind of "magic" always gives me the feeling that a more experienced Python ninja would chop me in the face if he caught me.

This convention seems completely innocuous to me, but could it come back to bite me in the ass later? Are there any pitfalls I should look out for?

答:
An alternative that doesn't abuse python so much, is to put the following in your __init__.py

```<code>from .main import *
</code>```

Its not quite the same as replacing the module, but I would suspect it will work in most cases.

However, I would take the theory that you shouldn't do it. Pretending that your code is in the root of the alpha module when it is isn't just confusing.

Body:
An alternative that doesn't abuse python so much, is to put the following in your __init__.py

from .main import *

Its not quite the same as replacing the module, but I would suspect it will work in most cases.

However, I would take the theory that you shouldn't do it. Pretending that your code is in the root of the alpha module when it is isn't just confusing.


问:
How important are daily builds?
One of the criteria of the Joel Test is daily builds. The idea is that if the build is broken, whoever broke it is around to fix it up. If the build cannot be fixed, everyone will have to check out an old version and work on that. I can understand how this can be pretty bad on centralised version control where it is important to avoid merging and branching as much as possible, but this only sounds like a minor nuisance for distributed version control. Do you agree with this? Are there other reasons why daily builds are important?</p>

答:
Ideally, unless you're building something massive that takes over half a day to build, you would build more than once a day.  Once you've set-up a continuous integration server, such as Hudson or TeamCity, the builds will happen automatically, typically every hour or on every commit, and you'll will be notified if there are any problems.

It's a good way to catch errors early, especially if you are also running automated tests as part of the build.  It's particularly useful for finding configuration errors where the build works on one developer's machine but doesn't work elsewhere because something was omitted from the repository or the environment.

The more advanced continuous integration servers also allow you to track metrics over time (e.g. code coverage percentage, build time, lines of code, etc.)

Title: How important are daily builds?


答:
I walk away from reading the article thinking about the wisdom of Alan J. Perlis:

Epigram 9. It is better to have 100 functions operate on one data structure than 10 functions on 10 data structures.

The fact that getting "equality" right is the sort of problem that keeps Martin Ordersky inventor of Scala up at night should give pause about whether overriding equals in an inheritance tree is a good idea.

What happens when we're unlucky to get a ColoredPoint is that our geometry fails because we used inheritance to proliferate data types rather than making one good one. This despite having to go back and modify the root node of the inheritance tree to make equals work. Why not just add a z and a color to Point?

The good reason would that Point and ColoredPoint operate in different domains...at least if those domains never mingled. Yet if that's the case, we don't need to override equals. Comparing ColoredPoint and Point for equality only makes sense in a third domain where they're allowed to mingle. And in that case, it's probably better to have the "equality" tailored to that third domain rather than trying to apply equality semantics from one or the other or both of the unmingled domains. In other words "equality" should be defined local to the place where we've got mud flowing in from both sides because we may not want ColoredPoint.equals(pt) to fail against instances of Point even if the author of ColoredPoint thought it was a good idea six months ago at 2am.


问:
Why is deletion usually much harder to implement than insertion in many data structures?
Can you think of any specific reason why deletion is usually significantly harder to implement than insertion for many (most?) data structures?

Quick example: linked lists. Insertion is trivial, but deletion has a few special cases that make it significantly harder. Self-balancing binary search trees such as AVL and Red-black are classic examples of painful delete implementation.

I would like to say it has to do with the way most people think: it is easier for us to define things constructively, which leads nicely to easy insertions.

答:
On top of all mentioned issues there is data referential integrity involved.
For most properly build data structure like databases in SQL, Oracle referential integrity is very important.

To make sure that you do not accidentally destroy it lot of different things invented.

For example cascade on delete which not just delete what ever you attempt to delete but also triggers cleanup of related data.

This clean up database from junk data as well as keep integrity of the data intact.

For example you have tables wit parents and kinds as related records in second table.

Where parent is main table. If you do not have reinforced referential integrity in place you can delete any records in any table and later on you would not know how to get full family information because you have data in child table and nothing in parent table.

That is why referential integrity check will not let you delete record from the parent table until records from child table cleaned up.

And that is why in most data sources it is more difficult to delete data.


问:
Is it always possible to separate multiple conditions in an IF statement into individual statements?
I'm trying to find the simplest way to model user-defined conditional statements without resorting to text parsing. This is fairly easy when there is only one condition in the statement because you can split that into an operand, a comparison operator, and a value to compare with. Just store those three and you can let the user use dropdown boxes to select values and an operator from a predefined list.

In this example imagine the code snippet text is a dropdown box and bold text is uneditable:

IF (select value) is (select comparison operator) (enter value) then...

Clarification - so the bit between IF and IS is a dropdown box with an object's member or database field in, the comparison operator is a dropdown box with options such as "equal to" or "greater than", and the final box is a typeable text box where the user can enter the value manually.

But occasionally they will need to test multiple conditions before executing whatever action they define. Microsoft Dynamics CRM does this quite well with their business rules (which is similar to what I am trying to achieve) as you can see here.

In simple examples, you can rearrange it into nested if statements, although you may end up repeating yourself if using a lot of ORs. It's not the prettiest solution in the world but at the end of the day it works and you don't run the risk of allowing the user to type badly formed input. I anticipate complex multiple conditional logic to be an edge case for this project so the messiness is (mostly) justified.

The million dollar question is are there any cases where conditional logic cannot be represented like this?

EDIT in order to explain how this question is not a duplicate of this one, that question is not (as far as I can tell) asking the same thing. Although both questions deal with evaluating unknown variations of Boolean expressions, I am asking if my solution will allow me to represent all feasible expressions with a particular method, while that question is asking about unit testing for Boolean expressions with many inputs.

答:
Nested conditions along the lines of ((foo or bar) and baz) are hard to comprehend, and I understand that you want to avoid them. Indeed, you can avoid the logical operators and, or and not if you allow conditionals to be nested:

if (foo and bar) then action is equivalent to

```<code>if (foo) then
  if (bar) then
    action
</code>```

if (foo or bar) then action is equivalent to

```<code>if (foo) then
  action
otherwise
  if (bar) then
    action
</code>```

if (not foo) then action is equivalent to

```<code>if (foo) then
  nothing
otherwise
  action
</code>```

if ((foo or bar) and baz) then action is equivalent to

```<code>if (foo) then
  if (baz) then
    action
otherwise
  if (bar) then
    if (baz) then
      action
</code>```

or

```<code>if (baz) then
  if (foo) then
    action
  otherwise
    if (bar) then
      action
</code>```

This isn't exactly easy to understand either, and requires a lot of repetition.

It might be much simpler to allow one if … then … to have multiple conditions that can be combined via any of, all of and none of quantifiers (these correspond to the mathematical quantifiers ∃ there exists, ∀ for all, and ∄ there does not exist). This is easy to introduce into a form-based interface, and drastically increases power and usability of your rules. However, they are not quite as powerful as arbitrarily-nested conditions. This can be resolved by introducing user-defined variables or virtual fields. With variables, sub-conditions can be combined, named, and re-used.

Using these two improvements, a conditional if ((foo or bar) and baz) then action might become

```
yes/no <b>field</b> foo-or-bar
  <b>is any of</b> <i>foo</i>
         <b>or</b> <i>bar</i>

<b>if all of</b> foo-or-bar
      <b>and</b> <i>baz</i>
<b>then</b>
  <i>action</i>
```

where foo, bar, baz are arbitrary atomic conditions. This achieves the same expressivity as nested condition expressions, without requiring users to repeat their conditions and actions.

Body:
Nested conditions along the lines of ((foo or bar) and baz) are hard to comprehend, and I understand that you want to avoid them. Indeed, you can avoid the logical operators and, or and not if you allow conditionals to be nested:

if (foo and bar) then action is equivalent to

if (foo) then
  if (bar) then
    action

if (foo or bar) then action is equivalent to

if (foo) then
  action
otherwise
  if (bar) then
    action

if (not foo) then action is equivalent to

if (foo) then
  nothing
otherwise
  action

if ((foo or bar) and baz) then action is equivalent to

if (foo) then
  if (baz) then
    action
otherwise
  if (bar) then
    if (baz) then
      action

or

if (baz) then
  if (foo) then
    action
  otherwise
    if (bar) then
      action

This isn't exactly easy to understand either, and requires a lot of repetition.

It might be much simpler to allow one if … then … to have multiple conditions that can be combined via any of, all of and none of quantifiers (these correspond to the mathematical quantifiers ∃ there exists, ∀ for all, and ∄ there does not exist). This is easy to introduce into a form-based interface, and drastically increases power and usability of your rules. However, they are not quite as powerful as arbitrarily-nested conditions. This can be resolved by introducing user-defined variables or virtual fields. With variables, sub-conditions can be combined, named, and re-used.

Using these two improvements, a conditional if ((foo or bar) and baz) then action might become

yes/no field foo-or-bar
  is any of foo
         or bar

if all of foo-or-bar
      and baz
then
  action

where foo, bar, baz are arbitrary atomic conditions. This achieves the same expressivity as nested condition expressions, without requiring users to repeat their conditions and actions.


问:
Entity Framework in n-tier application confusion
I'm building a rather large (web) application where I'm using Entity Framework to communicate with the database.

My solution is set up in layers like so:

Client

Website (MVC web application)

Server

BusinessLogic (contains, well, business logic. There's a lot of business rules involved in this project)

Repository (contains repository classes for querying the database using EF)

Interfaces (interfaces for defining the repository classes, i.e. IFirmRepository)

Model (contains my edmx file, view models, enums etc)

So, the client/UI knows about the business logic layer where the business classes needed for a given view is injected into the MVC controllers. The business logic layer knows about interfaces and model and the repository implements the interfaces.

Been developing for the last week using this approach, I have a feeling that it's not quite "correct" since:

The repository classes becomes bloated with a lot of methods where I need to use the Include()method to be able to work with the disconnected entities in my business logic layer

For every query, I'm using a new context: using(var ctx = new MyContext()) and a single business logic method might be calling more than one repository method which makes for N number of new MyContext() which isn't ideal, I guess?

Relating to the above: I've read about having one context per http request is the way to go when it comes to websites, which my approach seems to "violate"?

Out of curiousity, I tried to simply make use of the MyContextdirectly in a business logic class, making the query for the object(s) needed and then performing business logic. Doing this felt very smooth/easy and made the repository seem like a lot more work than needed and almost redundant.

So, I guess different projects needs different approaches when it comes to the architecture, but before I scratch my repository completely and making use of the entity framework context directly in my business logic classes, I'd like your opinion on this. It kinda feels wrong (in the sense that I'm violating something) to scratch the repository, but on the other hand, it's so easy to simply do the magic without first defining the method in an interface, then implementing it as a repository and then make use of it in a business logic class.

So, what is your opinion on this? :-) Am I completely off the record here, or?

Thanks in advance.

答:
Go ahead and scratch the repository. If you're using Entity Framework, you don't need it. It's just a pointless layer of abstraction. I'd recommend going with a service/provider pattern. Create an interface that lays out an API that you application can utilize. The interface will be the only thing you work with directly in your web application. You'll use dependency injection to sub in a concrete implementation.

As far as that goes, you'll want to create a one or more classes that implement this interface, but only one per discrete access method, i.e. Entity Framework. You might have another if you want to work with a Web Api, for example. This implementation should be generic, but rather than having the entire class take a type parameter, instead, you'll want the individual method implementations to be generic. This allows you to instantiate one instance that can work with your entire context and any entity that it contains.

Your entities, too, should implement interfaces, so that your service implementation can reuse code. For example, instead of having GetPublishedFoos and GetPublishedBars, you can simply have GetPublished<TEntity>, where TEntity : IPublishable. If you're smart about how you set up your interfaces, your service won't need a ton of methods.


问:
Separation of retrieving data and business objects between DAL and BLL Layers
I did some research before posting this question. Among other questions or post, one of those is provided below. I could not get a clear mind how to determine..

Business Objects within a Data Access Layer

I have a Repository and the Business Layers call the repository to retrieve the data. For example, say I have the following classes for BLL and DAL:

```<code>class BllCustomer
{
    public int CustomerId {get; set;}
    public String Name {get; set;}
    public BllAddress Address {get; set;}
}

class BllAddress
{
     public int AddressId {get; set;}
     public String Street {get; set;}
     public String City {get; set;}
     public String ZipCode {get; set; }
}

class DalCustomer
{
    public int CustomerId {get; set;}
    public String Name {get; set;}
    public int AddressID {get; set;}
}

class DalAddress
{
     public int AddressId {get; set;}
     public String Street {get; set;}
     public String City {get; set;}
     public String ZipCode {get; set; }
}
</code>```

If the BLL wants to retrieve a Customer object, it would call GetCustomerById(customerId) in DAL.

The following are my concerns I could not get a clear mind:

I cannot see how to determine what object the GetCustomerById in DAL should return? Should it return BllCustomer or DalCustomer?

Where should be the retrieving (and/or converting to Business object) of the address associated with the customer?

If the DAL returns Dal objects then, the logic to retrieve and fill in the Address can only be in the BLL. If the DAL returns BLL objects, then the logic to retrieve and fill in the Address can be either in the BLL or DAL. Currently the DAL is returning the Business Objects and the logic to fill it in is in the DAL.

From what I read, I guess there is no right or wrong. From the link included above, there are people saying one way and the others are saying the other way. But how do I determine which would works best for my case?

Any help would be appreciated.

答:
DAL should be independent from BL and BL dependent on DAL. Your UI should only Access data via BL. Its good practice if you return DataTable or DataRow from DAL and then Convert DataTable/DataRow into BL object(s). When your UI needs to access the data it can access from BL. So UI will independent from column name and Database type(SQL Server, Oracle..). This way your UI will totally independent from DAL. Personally I prefer class name like "CustomerBL", Don't use the BL word in the begging of class name.

Below see Sample Code.

```<code>//Customer Class
class BllCustomer
{
    public int CustomerId { get; set; }
    public String Name { get; set; }
    public BllAddress Address { get; set; }

    public static BllCustomer GetByCustomerId(int id)
    {
        DataRow dr = DalCustomer.GetByCustomerId(id);
        if (dr == null)
            return null;
        BllCustomer oCust = new BllCustomer();
        oCust.CustomerId = int.Parse(dr["CustomerId"].ToString());
        //Do for other class members and load values

        return oCust;
    }
}

class DalCustomer
{

    public static DataRow GetByCustomerId(int id)
    {
        //Get Data row from Database and return Datarow
        DataRow CustomerRow = GETFROMDATABASE("SELECT * from CUSTOMER");
        return CustomerRow;
    }
}
</code>```

Body:
DAL should be independent from BL and BL dependent on DAL. Your UI should only Access data via BL. Its good practice if you return DataTable or DataRow from DAL and then Convert DataTable/DataRow into BL object(s). When your UI needs to access the data it can access from BL. So UI will independent from column name and Database type(SQL Server, Oracle..). This way your UI will totally independent from DAL. Personally I prefer class name like "CustomerBL", Don't use the BL word in the begging of class name.

Below see Sample Code.

//Customer Class
class BllCustomer
{
    public int CustomerId { get; set; }
    public String Name { get; set; }
    public BllAddress Address { get; set; }

    public static BllCustomer GetByCustomerId(int id)
    {
        DataRow dr = DalCustomer.GetByCustomerId(id);
        if (dr == null)
            return null;
        BllCustomer oCust = new BllCustomer();
        oCust.CustomerId = int.Parse(dr["CustomerId"].ToString());
        //Do for other class members and load values

        return oCust;
    }
}

class DalCustomer
{

    public static DataRow GetByCustomerId(int id)
    {
        //Get Data row from Database and return Datarow
        DataRow CustomerRow = GETFROMDATABASE("SELECT * from CUSTOMER");
        return CustomerRow;
    }
}


问:
When returning from a period of not programming, do you find you've improved?
It seems as though whenever I take an extended break from programming—whether to pursue other interests or simply because I fall out of the habit for a while—I invariably find that when I return to a project and set to coding, I come with an abundance of new ideas, novel approaches, and just plain better code. It may be because I have a lot of other creative interests besides programming, and my mind likes to find correlation and crossover between them, so while I'm doing one thing, in the back of my mind I'm usually also applying it to another.

So what's your experience? Do you ever return from a break (whether intentional or not) feeling not only refreshed, but also somehow noticeably improved? Is it actually the norm?

答:
Depends on the nature of the break. If it is because of meetings, annual reviews, documentation, user training, etc., I may not come back as fresh as a true vacation. Returning with the feeling of needing to catch-up may provide motivation/kick-in-the-pants, but doesn't usually help come up with new ideas/creativity.

There is merit to keeping sharp and being in the habit of coding regularly. A lay-off may make it difficult to get back into the grind.

My preference is to work aggressively if I know there is a time to take a break ahead.


答:
When the old programming gods were inventing object-oriented programming with classes, they decided when it came to composition and inheritance to have two relationships for an object: "is a" and "has a".

This partially solved the problem of subclasses being different than parent classes but made them usable without breaking code. Because a subclass instance "is a" superclass object and can be substituted directly for it, even though the subclass has more member functions or data members, the "has a" guarantees it will  perform all the functions of the parent and have all of its members. So you could say a Point3D "is a" Point , and a Point2D "is a" Point if they both inherit from Point. Additionally a Point3D could be a subclass of Point2D.

Equality between classes is problem domain-specific, however, and the above example is ambiguous as to what the programmer needs for the program to work correctly. Generally, math-domain rules are followed and values of data would generate equality if you limit the scope of the comparision to just in this case two dimensions, but not if you compare all the data members.

So you get a table of narrowing equalities:

```<code>Both objects have same values, limited to subset of shared members

Child classes can be equal to parent classes if parent and childs
data members are the same.

Both objects entire data members are the same.

Objects must have all same values and be similar classes.

Objects must have all same values and be the same class type.

Equality is determined by specific logical conditions in the domain.

Only Objects that both point to same instance are equal.
</code>```

You generally pick the most strict rules that you can that still will perform all the necessary functions in your problem domain. The built-in equality tests for numbers are designed to be as restrictive as they can be for math purposes, but the programmer has many ways around that if that is not the goal, including rounding up/down , truncation, gt,lt,etc.
Objects with timestamps are often compared by their generation time and so each instance must be unique so comparisons get very specific.

The design factor in this case is to determine efficient ways to compare objects. Sometimes a recursive comparison of all objects data members is what you must do, and that can get very expensive if you have lots and lots of objects with lots of data members. Alternatives are to only compare relevant data values, or have the object generate a hash value of its data members concerned for a quick comparison with other similar objects, keep collections sorted and pruned to make comparisons faster and less cpu intensive, and perhaps allow objects that are identical in data to be culled and a duplicate pointer to a single object be put in its place.

Body:
When the old programming gods were inventing object-oriented programming with classes, they decided when it came to composition and inheritance to have two relationships for an object: "is a" and "has a".

This partially solved the problem of subclasses being different than parent classes but made them usable without breaking code. Because a subclass instance "is a" superclass object and can be substituted directly for it, even though the subclass has more member functions or data members, the "has a" guarantees it will  perform all the functions of the parent and have all of its members. So you could say a Point3D "is a" Point , and a Point2D "is a" Point if they both inherit from Point. Additionally a Point3D could be a subclass of Point2D.

Equality between classes is problem domain-specific, however, and the above example is ambiguous as to what the programmer needs for the program to work correctly. Generally, math-domain rules are followed and values of data would generate equality if you limit the scope of the comparision to just in this case two dimensions, but not if you compare all the data members.

So you get a table of narrowing equalities:

Both objects have same values, limited to subset of shared members

Child classes can be equal to parent classes if parent and childs
data members are the same.

Both objects entire data members are the same.

Objects must have all same values and be similar classes.

Objects must have all same values and be the same class type.

Equality is determined by specific logical conditions in the domain.

Only Objects that both point to same instance are equal.

You generally pick the most strict rules that you can that still will perform all the necessary functions in your problem domain. The built-in equality tests for numbers are designed to be as restrictive as they can be for math purposes, but the programmer has many ways around that if that is not the goal, including rounding up/down , truncation, gt,lt,etc.
Objects with timestamps are often compared by their generation time and so each instance must be unique so comparisons get very specific.

The design factor in this case is to determine efficient ways to compare objects. Sometimes a recursive comparison of all objects data members is what you must do, and that can get very expensive if you have lots and lots of objects with lots of data members. Alternatives are to only compare relevant data values, or have the object generate a hash value of its data members concerned for a quick comparison with other similar objects, keep collections sorted and pruned to make comparisons faster and less cpu intensive, and perhaps allow objects that are identical in data to be culled and a duplicate pointer to a single object be put in its place.


问:
Why can't socket-communication use process_id instead of port_number?
nowadays, I am studying OS.

In Communication in Client-Server Systems chapter, I've heard that using process-id instead of port-number has problems.

But I don't understand why it does.

I think using ip+pid is possible because each process has their own process-id (pid). Is my thought wrong?

答:
The first and foremost issue stability. Port 25 is SMTP. Port 70 is gopher. Port 80 is http. And so on. These are established, known and assigned numbers. They have meaning between systems that are dissimilar.

The port number needs to be stable. You can't always run the mail process as process 25. You've got no guarantee about what order it launches in and in the event you have to kill and restart it, you have no guarantee on what process ID it would be.

Next off, consider that not all systems that have ports have processes (or processes that have a number). Consider a hypothetical web server appliance.  You stick a USB drive in it, it serves files from it. That's it. One process, that just keeps serving files - would that be port 1? or would it need to be assigned some number that has meaning to others? Or my ancient Macintosh Plus that ran system 6 and had a web server. No numbers. So you need some other way to designate the port that a given bit of code is listening to.

There are applications that have multiple numbers. That web server not only listens on port 80, but 443 and maybe 8080 (not to mention the "this machine has multiple IP addresses, this process running on the machine listens to 80 on this, and 80 and 443 on that one, and 8080 on this other one"). If the system was bound to a process id it couldn't listen to different ports for different protocols.

By having assigned numbers, there is consistency across the network. Telnet is port 23. That telnet program opens up a connection to port 23 and knows what protocol is associated with what listens there. FTP listens uses ports 20 and 21 for different parts of its protocol - again, consistency.  Having a consistent set of rules, numbers, and protocols is what makes the internet go 'round.


问:
Why is the minus sign, '-', generally not overloaded in the same way as the plus sign?
The plus sign + is used for addition and for string concatenation, but its companion: the minus sign, -, is generally not seen for trimming of strings or some other case other than subtraction. What could be the reason or limitations for that?

Consider the following example in JavaScript:

var a = "abcdefg";
var b = "efg";

a-b == NaN
// but
a+b == "abcdefgefg"
```

答:
Because concatenation of any two valid strings is always a valid operation, but the opposite is not true.

```<code>var a = "Hello";
var b = "World";
</code>```

What should a - b be here?  There's really no good way to answer that question, because the question itself isn't valid.

Body:
Because concatenation of any two valid strings is always a valid operation, but the opposite is not true.

var a = "Hello";
var b = "World";

What should a - b be here?  There's really no good way to answer that question, because the question itself isn't valid.


问:
Sharing Unit Tests between several language implementations of one spec?
JsonLogic is a data format (built on top of JSON) for storing and sharing rules between front-end and back-end code.  It's essential that the same rule returns the same result whether executed by the JavaScript client or the PHP client.

Currently the JavaScript client has tests in QUnit, and the PHP client has tests in PHPunit.  The vast majority of tests are "given these inputs (rule and data), assert the output equals the expected result."

As the test set grows (and certainly as we add parsers in other languages) how can we maintain just one standard set of test data and expected results that each get executed in each language's testing framework?

答:
A simple approach would be to just write one JSON file like:

```<code>[
    [ rule, data, expected ],
    [ rule, data, expected ]
]
</code>```

And then in each language, download the file, parse it, and test it, row by row.

My first inclination was to use a CSV (I'm back now to edit that answer), but as soon as the test data includes objects and arrays, suddenly you have a CSV with JSON in the cells, and it becomes eye-stabbingly frustrating to maintain.

Body:
A simple approach would be to just write one JSON file like:

[
    [ rule, data, expected ],
    [ rule, data, expected ]
]

And then in each language, download the file, parse it, and test it, row by row.

My first inclination was to use a CSV (I'm back now to edit that answer), but as soon as the test data includes objects and arrays, suddenly you have a CSV with JSON in the cells, and it becomes eye-stabbingly frustrating to maintain.


答:
"-" is used in some compound words (for example, "on-site") for joining the different parts into the same word. Why don't we use "-" for joining different strings together in programming languages? I think it would make perfect sense! To hell with this + nonsense!

However, let's try looking at this from a bit more abstract angle.

How would you define string algebra? What operations would you have, and what laws would hold for them? What would their relations be?

Remember, there may be absolutely no ambiguity! Every possible case must be well defined, even if it does mean saying it is not possible to do this! The smaller your algebra is, the easier this is done.

For example, what does it actually mean to add or subtract two strings?

If you add two strings (for example, let a = "aa" and b = "bb"), would you get aabb as the result of a + b?

How about b + a? Would that be bbaa? Why not aabb? What happens if you subtract aa from the result of your addition? Would your string have a concept of negative amount of aa in it?

Now go back to the beginning of this answer and substitute spaceshuttle instead of the string. To generalize, why is any operation defined or not defined for any type?

The point I'm trying to make is, that there is nothing stopping you from creating an algebra for anything. It might be hard to find meaningful operations, or even useful operations for it.

For strings, concatenating is pretty much the only sensible one I've ever come across. Doesn't matter what symbol is used to represent the operation.

Title: Why is the minus sign, '-', generally not overloaded in the same way as the plus sign?

Body:
The plus sign + is used for addition and for string concatenation, but its companion: the minus sign, -, is generally not seen for trimming of strings or some other case other than subtraction. What could be the reason or limitations for that?

Consider the following example in JavaScript:

var a = "abcdefg";
var b = "efg";

a-b == NaN
// but
a+b == "abcdefgefg"
```


答:
Because the - operator for string manipulation does not have enough "semantic cohesion."  Operators should only be overloaded when it is absolutely clear what the overload does with its operands, and string subtraction doesn't meet that bar.

Consequently, method calls are preferred:

public string Remove(string source, string toRemove)
public string Replace(string source, string oldValue, string newValue)
```

<p>In the C# language, we use <code>+</code> for string concatenation because the form</p>

<pre class="lang-cs prettyprint-override"><code>var result = string1 + string2 + string3;
</code>```

instead of

var result = string.Concat(string1, string2, string3);
```

<p>is convenient and arguably easier to read, even though a function call is probably more "correct," from a semantic standpoint.  </p>

<p>The <code>+</code> operator can really only mean one thing in this context.  This isn't as true for <code>-</code>, since the notion of subtracting strings is ambiguous (the function call <code>Replace(source, oldValue, newValue)</code> with <code>""</code> as the <code>newValue</code> parameter removes all doubt, and the function can be used to alter substrings, not just remove them).</p>

<p>The problem, of course, is that the operator overload is dependent on the types being passed to the operator, and if you pass a string where a number should have been, you may get a result you didn't expect.  In addition, for many concatenations (i.e. in a loop), a <code>StringBuilder</code> object is preferable, since each use of <code>+</code> creates a brand new string, and performance can suffer.  So the <code>+</code> operator isn't even appropriate in all contexts.</p>

<p>There are operator overloads that have better semantic cohesiveness than the <code>+</code> operator does for string concatenation.  Here's one that adds two complex numbers:</p>

<pre class="lang-cs prettyprint-override"><code>public static Complex operator +(Complex c1, Complex c2)
{
    return new Complex(c1.real + c2.real, c1.imaginary + c2.imaginary);
}
</code>```

Body:
Because the - operator for string manipulation does not have enough "semantic cohesion."  Operators should only be overloaded when it is absolutely clear what the overload does with its operands, and string subtraction doesn't meet that bar.

Consequently, method calls are preferred:

public string Remove(string source, string toRemove)
public string Replace(string source, string oldValue, string newValue)

In the C# language, we use + for string concatenation because the form

var result = string1 + string2 + string3;

instead of

var result = string.Concat(string1, string2, string3);

is convenient and arguably easier to read, even though a function call is probably more "correct," from a semantic standpoint.

The + operator can really only mean one thing in this context.  This isn't as true for -, since the notion of subtracting strings is ambiguous (the function call Replace(source, oldValue, newValue) with "" as the newValue parameter removes all doubt, and the function can be used to alter substrings, not just remove them).

The problem, of course, is that the operator overload is dependent on the types being passed to the operator, and if you pass a string where a number should have been, you may get a result you didn't expect.  In addition, for many concatenations (i.e. in a loop), a StringBuilder object is preferable, since each use of + creates a brand new string, and performance can suffer.  So the + operator isn't even appropriate in all contexts.

There are operator overloads that have better semantic cohesiveness than the + operator does for string concatenation.  Here's one that adds two complex numbers:

public static Complex operator +(Complex c1, Complex c2)
{
    return new Complex(c1.real + c2.real, c1.imaginary + c2.imaginary);
}


答:
One of the things I like about that show is although it plays fast and loose with some historical details, it actually does a pretty good job at avoiding technobabble.

One of the main jobs of a BIOS is to load the operating system (move/load its instructions) from a long-term storage like a disk to be executed.  Sometimes, especially back then, you had a mismatch between your processor's native word size (say 16 bits) and the size of the connection, called a bus, between the processor and the disk (say 8 bits).  One way to speed up the transfer is to use a 16-bit bus, but that would make the hardware more expensive.

Cameron is insulting IBM's inefficient and inelegant way at which their BIOS programmers decided to handle that data transfer.  She's scoffing at how slow their code is, and saying the only way she would look at it was if she felt like growing old waiting for their slow code to finish.  She is saying they rely too much on expensive hardware rather than good programming.

The same theme comes up several times as she's working on the code.  She thinks it can be done much more efficiently.

Title: What could "move an instruction without a 16-bit bus" mean?

Body:
Spoiler alert! This question (and, possibly, answers) could contain spoilers regarding "Halt and Catch Fire" TV series.

Background

I'm a web deleloper and do not have a CS degreee, so my understanding about hardware is at How Do Computers Work? level.

Question context

Here's a dialog from episode 102 between a hacker (Cameron Howe), which was hired by Cardiff Electric (fictional company) to write BIOS code via Clean room design, and an IBM lawyer (the story takes place in 1984):

Lawyer (passing to Cameron a binder with printed IBM's BIOS code): You were hired to write a replica of our BIOS code, but you won't be looking at our BIOS code.

Cameron: Look, I don't need to look at your BIOS, because I'm not interested in copying garbage. Sure, I might decide I want to spend
the rest of my natural life waiting to move an instruction without a 16-bit bus, but other than that, I'm not looking at that binder.

Question

Does a phrase in bold have any meaning in real world, or it is just a fantasy of a screenwriter? AFAIK, it is related to a CPU architecture and not BIOS itself? If her task is to write a BIOS code, why she would be concerned about that?


问:
Can I use dynamic packages in Delphi if I plan to build my application for cross platform usage?
Now I'm thinking about the architecture of my program. I plan to provide access not only for Desktop usage, but for mobile platforms as well.

I want to create a bpl package as separate file. That is I want to have in Windows version next files: program.exe + logic.bpl. It can be usefull because logic.bpl may be often modified, as it is a very important part of my program.

Besides other programmers (my friends) will be able to develop their own logic and replace the logic.bpl file to their own. So, there are next questions:

Will I have any problems with compiling the program for Android, iOS?

How can I build the program with packages for Windows and without packages for mobile platforms with minimal changes in the code?

In the case of dll use instead of bpl, are there any advantages/disadvantages for cross platform programming?

答:
No, you can't.

BPLs are for windows only. A BPL is just a Windows DLL, which is a binary for the Intel 80386 (x86) or AMD64 (x64) instruction set.

There are no DLL at all on iOS or Android, and if there ever are in the future, they certainly will not be in PE format, or binary compatible.


问:
Alternative way to expose you're returning Nothing in a method
I'm kind of in an impasse here.

Lets say I have module A which exposes some methods returning objets and module B that uses said methods from Module A. Module A will have situations when it will have to return Nothing.

The problem is: Of course I don't want to return Nothing. Many, many books, top-coders and heuristics will tell you. However, the use of exception is not allowed due to massive use of Module A. That would apparently kill performances.

At last, we do not want to use auto-instanciated objet and have to check inside state to know if it's in fact Nothing (like a check-null...)

What would be an alternative for Module A to expose it can return something empty (or nothing) and for everyone using it like Module B to be needed to check such case (like signed exceptions try-catch)?

Any help will be really appreaciated! I'm pretty much out of solution and I want to do something clean that will be able to evoluation without causing unwanted behaviours and errors. Thanks

--EDIT--

To close this question, project managers decided to return Nothing everywhere. They accept to have some production crash due to forgotten nothing-check...
From what I gathered during this timelaps, I'd say that the best alternative would be the Try-object patern, because it forces the client to check the why is the return a boolean and how to use the call... at least on first use.

答:
You can return either a thing or nothing, so somehow B has to know.
You can return a list with 0 or 1 element, and B could, for example, treat it uniformaly. In pseudo-code:

```<code>// Inside one of B's method
foreach(x : A.getThings()) {
    this.doAction(x);
}
</code>```

Body:
You can return either a thing or nothing, so somehow B has to know.
You can return a list with 0 or 1 element, and B could, for example, treat it uniformaly. In pseudo-code:

// Inside one of B's method
foreach(x : A.getThings()) {
    this.doAction(x);
}


答:
In short, there aren’t any particularly useful subtraction-like operations on strings that people have wanted to write algorithms with.

The + operator generally denotes the operation of an additive monoid, that is, an associative operation with an identity element:

A + (B + C) = (A + B) + C

A + 0 = 0 + A = A

It makes sense to use this operator for things like integer addition, string concatenation, and set union because they all have the same algebraic structure:

```<code>1 + (2 + 3) == (1 + 2) + 3
1 + 0 == 0 + 1 == 1

"a" + ("b" + "c") == ("a" + "b") + "c"
"a" + "" == "" + "a" == "a"
</code>```

And we can use it to write handy algorithms like a concat function that works on a sequence of any “concatenable” things, e.g.:

```<code>def concat(sequence):
    return sequence.reduce(+, 0)
</code>```

When subtraction - gets involved, you usually talk about the structure of a group, which adds an inverse −A for every element A, so that:

A + −A = −A + A = 0

And while this makes sense for things like integer and floating-point subtraction, or even set difference, it doesn’t make so much sense for strings and lists. What is the inverse of "foo"?

There is a structure called a cancellative monoid, which doesn’t have inverses, but does have the cancellation property, so that:

A − A = 0

A − 0 = A

(A + B) − B = A

This is the structure you describe, where "ab" - "b" == "a", but "ab" - "c" is not defined. It’s just that we don’t have many useful algorithms that use this structure. I guess if you think of concatenation as serialisation, then subtraction could be used for some kind of parsing.

Body:
In short, there aren’t any particularly useful subtraction-like operations on strings that people have wanted to write algorithms with.

The + operator generally denotes the operation of an additive monoid, that is, an associative operation with an identity element:

A + (B + C) = (A + B) + C

A + 0 = 0 + A = A

It makes sense to use this operator for things like integer addition, string concatenation, and set union because they all have the same algebraic structure:

1 + (2 + 3) == (1 + 2) + 3
1 + 0 == 0 + 1 == 1

"a" + ("b" + "c") == ("a" + "b") + "c"
"a" + "" == "" + "a" == "a"

And we can use it to write handy algorithms like a concat function that works on a sequence of any “concatenable” things, e.g.:

def concat(sequence):
    return sequence.reduce(+, 0)

When subtraction - gets involved, you usually talk about the structure of a group, which adds an inverse −A for every element A, so that:

A + −A = −A + A = 0

And while this makes sense for things like integer and floating-point subtraction, or even set difference, it doesn’t make so much sense for strings and lists. What is the inverse of "foo"?

There is a structure called a cancellative monoid, which doesn’t have inverses, but does have the cancellation property, so that:

A − A = 0

A − 0 = A

(A + B) − B = A

This is the structure you describe, where "ab" - "b" == "a", but "ab" - "c" is not defined. It’s just that we don’t have many useful algorithms that use this structure. I guess if you think of concatenation as serialisation, then subtraction could be used for some kind of parsing.


问:
Use of electronics in programming
Does a programmer need to have a deep understanding of digital electronics. Theoretical v/s practical. As what they teach us at college is pretty basic?

If yes, then do all kinds of programmers (software developers/web developers/app developers) need
it (deep understanding),
should a security enthusiast (hacker) have good knowledge of digital electronics?

答: "deep understanding" - no. Is it helpful? - yes. You will get exposed to boolean algebra and Karnaugh maps in particular, which I have found helpful. You will get to really, really know your ANDs and ORs, but not exclusively.</p>

Title: Use of electronics in programming


答:
Depending on what expertise the programmer wants to have the answer can vary. If the programmer is specializing in drivers on specialized hardware then a deep understanding may well be required. On the other hand, a web developer may have no need to get deeply into the hardware side and may just use abstractions in their career.

What you are taught in college should give you practice to know how you'll learn about a set that may well evolve over time. As new hardware is created, there can often be the challenge of how will you learn the new styles for things. Consider how there are so many gestures in mobile development that may not have existed 15 years ago.

Different specializations can require different levels would be the short answer here as while it can help to know about things, how you measure depth is also important. For example, are we talking about designing CPUs and GPUs here or just using what is already out on the market? What level of depth do you mean here? Would a Ph.D. in quantum mechanics be necessary or is it enough to know how electrons would hold a charge?

Title: Use of electronics in programming

Body:
Does a programmer need to have a deep understanding of digital electronics. Theoretical v/s practical. As what they teach us at college is pretty basic?

If yes, then do all kinds of programmers (software developers/web developers/app developers) need
it (deep understanding),
should a security enthusiast (hacker) have good knowledge of digital electronics?


答:
One solution is to use Null Object Pattern in Module A.
Instead of returning null, Module A will return another type that is a 'type-safe' representation of "Nothing".  </p>

Title: Alternative way to expose you're returning Nothing in a method

Body:
I'm kind of in an impasse here.

Lets say I have module A which exposes some methods returning objets and module B that uses said methods from Module A. Module A will have situations when it will have to return Nothing.

The problem is: Of course I don't want to return Nothing. Many, many books, top-coders and heuristics will tell you. However, the use of exception is not allowed due to massive use of Module A. That would apparently kill performances.

At last, we do not want to use auto-instanciated objet and have to check inside state to know if it's in fact Nothing (like a check-null...)

What would be an alternative for Module A to expose it can return something empty (or nothing) and for everyone using it like Module B to be needed to check such case (like signed exceptions try-catch)?

Any help will be really appreaciated! I'm pretty much out of solution and I want to do something clean that will be able to evoluation without causing unwanted behaviours and errors. Thanks

--EDIT--

To close this question, project managers decided to return Nothing everywhere. They accept to have some production crash due to forgotten nothing-check...
From what I gathered during this timelaps, I'd say that the best alternative would be the Try-object patern, because it forces the client to check the why is the return a boolean and how to use the call... at least on first use.


答:
The computing world is a world of layers.

Using semiconductor physics transistors can be design and built.

Using transistors logic gates can be built.

Using logic gates combinatorial logic and flip-flops can be built.

From combinatorial logic and flip flops we build digital logic systems like processors and perhiperals

Those processors interpret a machine code and communicate with the perhiperals through memory mapped registers (or occasionally registers in a specific "IO map".

We use compilers and operating systems to abstract the details of the hardware

We use high level interpreted or jit compiled languages with automated memory management to abstract things even more.

Someone working in an interpreted scripting language is going to find information about semiconductor physics totally irrelevant but knowing a layer or two below the layer you are working at is often useful in understanding why things are the way they are and what solutions are likely to be efficient.

Title: Use of electronics in programming


问:
In Scrum, are story points assigned at different planning poker sessions worth the same?
As far as I understand, a planning poker session usually is started by picking one item and assigning it a value (say, 1). This item will then serve as a reference for the rest of the session. From then on, all values will be relative to the first one.

Question 1: There seems to be no frame of reference to compare this session to past planning poker sessions, though. If the first item picked and assigned a '1' at session A is actually a bit harder to complete than the first item picked and assigned a '1' at session B, then points at session A and B will be of different value. This means that the total amount of points completed in sprint A and sprint B will not be comparable, defeating the whole purpose of estimation. Where is my mistake?

Question 2: Say the team uses the typical numbers (...13, 20, 40, 100). They decide that item1 = 20 and item2 = 40. Does this only mean item1 < item2 or does it also mean that item2 will take twice as long to complete?

答:
Depends on the team. In the past, I'm used to there being a general idea of what a single point was worth that was consistent across sessions. Of course, there is also something to be said for estimates getting a little better initially as a story may be estimated poorly in the first few sessions that after doing a dozen of them the estimates may be more accurate later. Your mistake is assuming that the frame of reference isn't there when it may be there, especially in the beginning for planning and computing velocity.

No, it means that item2 is approximately twice as complex as item1 and will likely require greater resources. The higher estimates can be fuzzier but can be a ballpark that would put it between what your statements are as if item2 was 100 that would also imply that it is going to take longer but also means it may be worth restating so that it isn't as large of a black box. The high estimates can serve as a warning that something has too many pieces to it in some cases.


答:
Question 1: There seems to be no frame of reference to compare this session to past planning poker sessions, though. If the first item picked and assigned a '1' at session A is actually a bit harder to complete than the first item picked and assigned a '1' at session B, then points at session A and B will be of different value. This means that the total amount of points completed in sprint A and sprint B will not be comparable, defeating the whole purpose of estimation. Where is my mistake?

It's better to have the same reference for each scrum session. Burndown statistics will be useless, unless points from all sprints are worth (roughly) the same.

Question 2: Say the team uses the typical numbers (...13, 20, 40, 100). They decide that item1 = 20 and item2 = 40. Does this only mean item1 < item2 or does it also mean that item2 will take twice as long to complete?

It means it will take roughly twice as long. It's just an estimate. It can take twice as long, it can take the same amount of time if it's overestimated, it can take 3 times as long if its underestimated, but it probably shouldn't take 10 times as long, or half the time of item1.

Title: In Scrum, are story points assigned at different planning poker sessions worth the same?

Body:
As far as I understand, a planning poker session usually is started by picking one item and assigning it a value (say, 1). This item will then serve as a reference for the rest of the session. From then on, all values will be relative to the first one.

Question 1: There seems to be no frame of reference to compare this session to past planning poker sessions, though. If the first item picked and assigned a '1' at session A is actually a bit harder to complete than the first item picked and assigned a '1' at session B, then points at session A and B will be of different value. This means that the total amount of points completed in sprint A and sprint B will not be comparable, defeating the whole purpose of estimation. Where is my mistake?

Question 2: Say the team uses the typical numbers (...13, 20, 40, 100). They decide that item1 = 20 and item2 = 40. Does this only mean item1 < item2 or does it also mean that item2 will take twice as long to complete?


答:
Stories in the backlog for the same team should be sized consistently, regardless of which planning poker session they were sized in. This consistent sizing is what permits the team to establish their velocity. A good habit for a new team is to identify the "typical" story of each size so you have a concrete reference when sizing up a new story.

As for question 2, the implication is that the effort for item2 is about twice as much as item1. Story size doesn't accurately correlate to the amount of time to complete although your team should develop a sense of how long a story of a particular size will take. As part of your retrospective you should review your point estimates, the actual duration and effort to implement the story, and feed that back into future planning poker sessions.


问:
Handling thousands of cassandra insert/updates
I have mobile app with backend server running in nodejs with cassandra as database. The app is like social network where you can share pictures and follow other people. Some operation like updating username, the nodejs runs select query to find all pictures shared by user and updates the username there and some other tables wherever username is present and then finally returns.

Sometimes it ends up updating 5-10k records and takes around 15-20 secs.  I tried running those updates on different tables in parallel fashion using async library, could not get significant improvements. How to handles this scenario where client app shouldn't have to wait for that long?  Also how does facebook handles this kind of scenario?

答:
If you need to SELECT before UPDATE you are doing it wrong. Cassandra is faster at writing than it is at reading. You will never get 100k writes / s if you need to read before write.

I suggest you would use an id for the user. In that case you would not need to update all the other tables when the username changes.

Finally, if you don't want to do any of the above, you could try to optimize by:

Using BATCHes for the updates. This would eliminate overhead.

Make sure you are not using LWT. Read there why.

You could also reduce the consistency to one, but I guess you don't want to do that since it means loosing consistency. The data you read before the write would not be the "latest" representation.

You will have to ask Facebook on how they do it. As far as I now they're not using Cassandra any more.


答:
Question 1: There seems to be no frame of reference to compare this session to past planning poker sessions, though.

There should be. Have your scrum master bring in one medium sized story from the previous sprint. You then have a reference point from which to start. When you point a new story, start by asking if the story is bigger than, smaller than, or about the same size as the story from the previous sprint. Use that information to size appropriately.

Question 2: Say the team uses the typical numbers (...13, 20, 40, 100). They decide that item1 = 20 and item2 = 40. Does this only mean item1 < item2 or does it also mean that item2 will take twice as long to complete?

It only means that item 1 < item 2. From a practical point of view you can maybe think 2 is roughly twice as big, but that's only a very, very rough estimate. It could be that an 8 point story is 10 or 15 times as big as a 1. As the numbers get bigger, the greater the chance that the estimation is wrong. This is arguably why waterfall fails us -- we try to estimate projects that are several months long. Humans suck at that, but we're pretty good at judging just a single day's worth of work.

For example, given a 1 point story, you are probably quite accurate on that assessment. It's hard to be off too far when you think the work will take about a day or less. However, if you have another story that you've pointed at 8 or 13 or 40 or 100 -- whatever scale you use -- you will be much more likely to be wrong. That is why stories should be kept as small as possible.