问:
RESTful API design. What should I return if there are no rows?
I'm currently coding an API for a social network with the Slim Framework. My question is: What are the best practices when there are no rows to return in the json structure?

Lets say that this call /v1/get/movies returns 2 rows from the table movie names:

```<code>[
    {"name": "Ghostbusters"},
    {"name": "Indiana Jones"}
]
</code>```

But, then I call /v1/get/books and there are no rows in that table. Should I just return an empty structure?

```<code>[
]
</code>```

...or would it be better a message and an error code?

```<code>[
    "errors": {
        "message": "no matches found",
        "code": 134
    }
]
</code>```

Which is a better practice? (the API will be used in iOS and Android apps) Thanks!

答:
First of all, having get in your URL is not RESTful, GET is implied by the HTTP method.

If you're requesting a collection like GET api/movies return a 200 OK with an empty array [].

If you're requesting a specific movie like GET api/movies/1 (where 1 is the id) and it doesn't exist, return a 404 Not Found.

Why?
You are requesting resources. When you are requesting the collection, the resource itself (the collection) exists. Therefor, a 404 is wrong. But if you request a specific movie and it doesn't exist, the resource requested doesn't exist, and you have to return a 404.


问:
Is there anything that can be done with recursion that can't be done with loops?
There are times where using recursion is better than using a loop, and times where using a loop is better than using recursion. Choosing the "right" one can save resources and/or result in fewer lines of code.

Are there any cases where a task can only be done using recursion, rather than a loop?

答:
Are there any cases where a task can only be done using recursion,
  rather than a loop?

You can always turn recursive algorithm into a loop, which uses a Last-In-First-Out data structure (AKA stack) to store temporary state, because recursive call is exactly that, storing current state in a stack, proceeding with the algorithm, then later restoring the state. So short answer is: No, there are no such cases.

However, an argument can be made for "yes". Let's take a concrete, easy example: merge sort. You need to divide data in two parts, merge sort the parts, and then combine them. Even if you don't do an actual programming language function call to merge sort in order to do merge sort on the parts, you need to implement functionality which is identical to actually doing a function call (push state to your own stack, jump to start of loop with different starting parameters, then later pop the state from your stack).

Is it recursion, if you implement the recursion call yourself, as separate "push state" and "jump to beginning" and "pop state" steps? And the answer to that is: No, it still isn't called recursion, it is called iteration with explicit stack (if you want to use established terminology).

Note, this also depends on definition of "task". If task is to sort, then you can do it with many algorithms, many of which don't need any kind of recursion. If task is to implement specific algorithm, like merge sort , then above ambiguity applies.

So let's consider question, are there general tasks, for which there are only recursion-like algorithms. From comment of @WizardOfMenlo under the question, Ackermann function is a simple example of that. So the concept of recursion stands on its own, even if it can be implemented with a different computer program construct (iteration with explicit stack).

ContentLicense: CC BY-SA 3.0


问:
Private variables and the old FORTRAN common blocks
This is a question that perplexes me about object oriented programming.
In some OOP languages (e.g. C++) a member function can access private variables of the class without restriction. That means one can define methods that take no arguments and change the private variables. Isn't this considered bad programming practice? Lots of thought has gone into how function arguments can be passed by value or reference, and what that implies about program complexity.

I would like to make this question less about opinion and more about facts. Let's consider the goto statement. The goto statement has been deprecated as bad programming practice in favor of structured programming. Did any objective data go into that decision? It appears to be intuitive that goto is problematic, but is there a factual basis for the deprecation? Were programs studied, surveys conducted, etc.?

Getting back to my question about member functions, is there an objective basis for answering this question? Should member functions of a class be allowed to manipulate variables not in the argument list? Has there been research to determine this question? Is there a branch of computer science research that attempts to determine best practices in language design based on objective criteria?

Thank you.

答:
Despite being over-hyped by the industry, object-oriented programming's saving grace has been that it tends to to encourage programmers to write code that is easier to follow for other programmers, with fewer comments.

In terms of code reuse and code simplicity, OOP unfortunately tends to provide limited advantages, and perversely ends up usually resulting in more lines of code.  One of the biggest advantages of OOP is reducing the reliance on long, redundant, picky argument lists for functions.  When you have a function with 8 arguments, 6 of them shared with a dozen other functions, that's when this advantage appears.

The drawback of trying to track mutable state or global-like variables is one that continues to dog OOP.  For these sorts of reasons, Functional Programming languages like Haskell, Erlang, F#, and Scala have continued to garner press and use in recent years.  We also see Functional Programming features, like treating functions as first-class citizens, making their way into OOP languages in recent years.

In terms of best practices, most OOP theorists would probably say that class properties should be used sparingly, that functions should be kept small, and class properties should only be writable from within the class (aside from being passed at instantiation).  While this addresses the disadvantages, it doesn't enforce best practices.  The result of this and other controversial features in OOP (like inheritance) is that there can be a lot of debate and confusion about how best to implement OOP.


答:
There are a few important differences between private members of a class and global variables.

Global variables are accessible by any part of the code, as long as the author of the code knows the name of the global variable. Private members are only accessible to member functions of the same class.

Furthermore, in most OO languages, member variables are by default instance members and the member functions can only access instance members of objects that are passed into the function (either implicitly by calling the member on an object or explicitly).

This means that effectively, your proposal is already part of most OO languages, except that the private members aren't passed in individually, but rather en-bloc (by means of the this or self pointer/reference).

Title: Private variables and the old FORTRAN common blocks

Body:
This is a question that perplexes me about object oriented programming.
In some OOP languages (e.g. C++) a member function can access private variables of the class without restriction. That means one can define methods that take no arguments and change the private variables. Isn't this considered bad programming practice? Lots of thought has gone into how function arguments can be passed by value or reference, and what that implies about program complexity.

I would like to make this question less about opinion and more about facts. Let's consider the goto statement. The goto statement has been deprecated as bad programming practice in favor of structured programming. Did any objective data go into that decision? It appears to be intuitive that goto is problematic, but is there a factual basis for the deprecation? Were programs studied, surveys conducted, etc.?

Getting back to my question about member functions, is there an objective basis for answering this question? Should member functions of a class be allowed to manipulate variables not in the argument list? Has there been research to determine this question? Is there a branch of computer science research that attempts to determine best practices in language design based on objective criteria?

Thank you.


问:
Entire webpage obfuscation
I want to obfuscate all the webpages of my website. I Googled through some free tools like HTML and Javascript obfuscation but don't know how effective they are.

First of all, does it makes sense to obfuscate a webpage that could comprise of variety of codes like Javascript, PHP etc.

Secondly, how effective is this method?

答:
The best security against information being wrongfully used is to avoid sending the information over a public communications network.

If that is not an option, you have to consider who and what you are trying to protect against.

If you want to be safe from third-parties snooping the traffic between your website and your customers, then don't bother with obfuscating the webpages, but use a secure connection instead.

If you don't want your users to access some information that is needed by the browser for displaying the page or generating the next request, then encryption won't help you (the browser needs to be able to decrypt the information anyway) and obfuscation might at best slow someone down but it won't stop them obtaining the information.

For really sensitive information, you could store it locally on the server and only give out a (one time) unique ID for accessing the information on the next request.

As a sidenote, using obfuscation might make people more interested in knowing what you are trying to hide.

Title: Entire webpage obfuscation

ContentLicense: CC BY-SA 2.5


答:
There's a difference between recursive functions and primitive recursive functions. Primitive recursive functions are those that are calculated using loops, where the maximum iteration count of each loop is calculated before the loop execution starts. (And "recursive" here has nothing to do with the use of recursion). </p>

<p>Primitive recursive functions are strictly less powerful than recursive functions. You would get the same result if you took functions that use recursion, where the maximum depth of the recursion has to be calculated beforehand. </p>

Title: Is there anything that can be done with recursion that can't be done with loops?

Body:
There are times where using recursion is better than using a loop, and times where using a loop is better than using recursion. Choosing the "right" one can save resources and/or result in fewer lines of code.

Are there any cases where a task can only be done using recursion, rather than a loop?

Body:
There's a difference between recursive functions and primitive recursive functions. Primitive recursive functions are those that are calculated using loops, where the maximum iteration count of each loop is calculated before the loop execution starts. (And "recursive" here has nothing to do with the use of recursion).

Primitive recursive functions are strictly less powerful than recursive functions. You would get the same result if you took functions that use recursion, where the maximum depth of the recursion has to be calculated beforehand.


答:
I recommend 200 + empty array, since it simplifies the handling by all the clients of the API. 200 + array means "I returned all the data that is there". Both to the code delivering the data and the code processing it, the number of items would be irrelevant.

Every other status code needs to be properly documented and properly delivered by the server and properly processed by the client, and we all know how likely this is to happen.

There was a suggestion to return status 204 + empty body. That means you force every single client to process status 204 correctly. Moreover you force them to handle non-JSON replies! I hope everyone realises that just because a request got an answer, it doesn't mean the answer came from the server when http is used, and just a check that the response is JSON handles many of those cases.

Title: RESTful API design. What should I return if there are no rows?

Body:
I'm currently coding an API for a social network with the Slim Framework. My question is: What are the best practices when there are no rows to return in the json structure?

Lets say that this call /v1/get/movies returns 2 rows from the table movie names:

```<code>[
    {"name": "Ghostbusters"},
    {"name": "Indiana Jones"}
]
</code>```

But, then I call /v1/get/books and there are no rows in that table. Should I just return an empty structure?

```<code>[
]
</code>```

...or would it be better a message and an error code?

```<code>[
    "errors": {
        "message": "no matches found",
        "code": 134
    }
]
</code>```

Which is a better practice? (the API will be used in iOS and Android apps) Thanks!


答: If you are returning JSON , it is better to always return count and error message and maybe a Boolean that indicated if there is error or no , that is my standard three meta values returned with each list of rows . </p>


问:
How to handle Data Fetching for Circular Object References in OOP Domain Models
I'm trying to put together some basic models in OOP (C#), and apparently I've got the wrong idea.

If I have a Workman's Comp case, it is applied to a Patient.  It also has one or more PatientVisits applied to the case.  Each PatientVisit though, also has a Patient associated with it, and of course a Patient can have any number of Visits associated with it.

My original thought was to create basic, real-world reflections of the business models by doing something like:

```<code>class Patient {
        int ID;
        string FirstName;
        string LastName;

        List<Visit> Visits;
    }

    class Visit {
        int ID;
        DateTime VisitDate;
        Patient Patient;

        List<DxCode> DxCodes;
    }

    class WCCase {
        int ID;
        Patient Patient;
        DateTime DateEntered;

        List<Visit> Visits;
    }
</code>```

I naively thought that'll be nice, I'll just load up my model and have everything at hand, very semantic and representative of the domain/real-world, right?

So, I can go the opposite route and fill the parent object and store lists of IDs for related models:

```<code>class Patient {
    int ID;
    string FirstName;
    string LastName;

    List<int> VisitIDs;

    public static Patient GetPatient(int id) {}
}

class Visit {
    int ID;
    DateTime VisitDate;
    int PatientID;

    List<DxCode> DxCodes;

    public Static Visit GetVisit(int id) {}
}

class WCCase {
    int ID;
    int PatientID;
    DateTime DateEntered;

    List<int> VisitIDs;

    public static case GetCase(int id) {}
}
</code>```

This of course allows me to load everything on demand (get an ID and grab the object through it's Get*() method), but seems a bit of a step away from the idea of a nicely representative real-world model and more like a mirror of a database table representation.

I'm guessing there must be some middle ground, but I'd sure like some advice on finding it...  Can anyone give some basic examples of how we'd model this without going nuts with references and circulars, etc?

Thanks in advance.

答:
Addressing the Basic Question

if I load a business entity into an object, and it has child objects as well, should I "fill out" all of the child models as well, or leave them null until needed, or...? [reference]

It depends. (thanks Bob?)

Lazy Loading & Eager Loading

Whatever. This is an implementation detail. It should not drive domain design. I am not saying either of the (as of this writing) two answers is wrong. I'm saying this aspect should be better incapsulated and then exposed in domain terms.

Encapsulating Data Fetching

... but seems a bit of a step away from the idea of a nicely representative real-world model and more like a mirror of a database table representation.

I'm guessing there must be some middle ground ...

Domain Analysis

As with any good Gummit bureaucracy you are just a number to them. And so a workers comp thing is who you are, what you do, what they do (to you), etc. This thing sounds like a class and this thing is a number. But it is not an int, it is a "Workers Comp Case File" let's say.

Further, we have all these circular references. Nothing wrong with these per-se from an OO design perspective.

```<code>public class WorkersCompCaseFile {
    public int ID { get; protected set; }
    public Patient { get; protected set; }
    public Visits { get; protected set; }
    public WCCase { get; protected set; }

    // here we can load things as desired, and change that
    // implementation isolated from the domain entities involved.

    //Case-wide functionalities
    public bool SuspectFraud() {
        // lots of object instantiation for complex analysis
    }
}

// CLIENT
WorkersCompCaseFile myHardCase = new WorkersCompCaseFile();
if( myHardCase.HasVisits )
    myHardCase.SuspectFraud();  // yeah, everyone is guilty of something.
</code>```

Data Points

We created the proper context to ensure proper global state.

Lazy/Eager load as needed

Components do not have to construct pieces of, nor continuously examine, the larger context state.

With this simple encapsulation - framework - there are so many design possibilities.

IDataFetch interface that all classes implement. There could be delegates or event handlers so WorkersCompCaseFile transparently does it for it's components.

protected vice public properties

the case file totally controls component construction

protected int ID - do not expose the ID period. It's an internal unifying concept.

Patient, Visit, all have a reference to their containing WorkersCompCaseFile

Patient.Visits is a pass-through reference to the case file object.

Components might not have an ID property at all.

Least Knowledge Principle: The case file exposes components on their behalf. e.g.

MyHardCase.Name vice MyHardCase.Patient.Name

The client is blissfully ignorant of internal object instantiation and nullness.

Internal components can be equally, mutually ignorant.

Body:
Addressing the Basic Question

if I load a business entity into an object, and it has child objects as well, should I "fill out" all of the child models as well, or leave them null until needed, or...? [reference]

It depends. (thanks Bob?)

Lazy Loading & Eager Loading

Whatever. This is an implementation detail. It should not drive domain design. I am not saying either of the (as of this writing) two answers is wrong. I'm saying this aspect should be better incapsulated and then exposed in domain terms.

Encapsulating Data Fetching

... but seems a bit of a step away from the idea of a nicely representative real-world model and more like a mirror of a database table representation.

I'm guessing there must be some middle ground ...

Domain Analysis

As with any good Gummit bureaucracy you are just a number to them. And so a workers comp thing is who you are, what you do, what they do (to you), etc. This thing sounds like a class and this thing is a number. But it is not an int, it is a "Workers Comp Case File" let's say.

Further, we have all these circular references. Nothing wrong with these per-se from an OO design perspective.

public class WorkersCompCaseFile {
    public int ID { get; protected set; }
    public Patient { get; protected set; }
    public Visits { get; protected set; }
    public WCCase { get; protected set; }

    // here we can load things as desired, and change that
    // implementation isolated from the domain entities involved.

    //Case-wide functionalities
    public bool SuspectFraud() {
        // lots of object instantiation for complex analysis
    }
}

// CLIENT
WorkersCompCaseFile myHardCase = new WorkersCompCaseFile();
if( myHardCase.HasVisits )
    myHardCase.SuspectFraud();  // yeah, everyone is guilty of something.

Data Points

We created the proper context to ensure proper global state.

Lazy/Eager load as needed

Components do not have to construct pieces of, nor continuously examine, the larger context state.

With this simple encapsulation - framework - there are so many design possibilities.

IDataFetch interface that all classes implement. There could be delegates or event handlers so WorkersCompCaseFile transparently does it for it's components.

protected vice public properties

the case file totally controls component construction

protected int ID - do not expose the ID period. It's an internal unifying concept.

Patient, Visit, all have a reference to their containing WorkersCompCaseFile

Patient.Visits is a pass-through reference to the case file object.

Components might not have an ID property at all.

Least Knowledge Principle: The case file exposes components on their behalf. e.g.

MyHardCase.Name vice MyHardCase.Patient.Name

The client is blissfully ignorant of internal object instantiation and nullness.

Internal components can be equally, mutually ignorant.


问:
Communicating to an Object from another without coupling in java?
So I have a Person object, and a GumballMachine object. The behavior I'm searching for is, in the intent to avoid unnecessary coupling, have the method insertCoin() called from within the Person object, which will then call the insertCoin() within the GumballMachine to receive a Gumball.

What is a proper design-pattern, or solution that avoids coupling, and keeps these two objects as oblivious to each other as possible while having a type of "Bridge" between them?

答:
OK, here is a different take on the question.

An object oriented principle is to minimize coupling.  I agree that it is often a good idea.  But another important programming principle is to minimize complexity.  The answer by cricket_007 does a good job of reducing coupling, but it does add more code.  I don't know the specifics of your application, but there may be times when it is better to go with the simpler but more coupled code.  This is especially true if the application is going to be fairly small.


问:
Generics vs common interface?
I don't remember when I wrote generic class last time. Every time I think I need it after some thinking I make a conclusion I don't.

The second answer to this question made me to ask for clarification (since i can't comment yet, i made a new question).

So let's take given code as an example of case where one needs generics:

```<code>public class Repository<T> where T : class, IBusinessOBject
{
  T Get(int id)
  void Save(T obj);
  void Delete(T obj);
}
</code>```

It has type constraints: IBusinessObject

My usual way of thought is: the class is constrained to use IBusinessObject, so are the classes that use this Repository are. Repository stores these IBusinessObjects, most likely clients of this Repository will want to get and use objects through IBusinessObject interface. So why not just to

```<code>public class Repository
{
  IBusinessOBject Get(int id)
  void Save(IBusinessOBject obj);
  void Delete(IBusinessOBject obj);
}
</code>```

Tho, the example is not good, as it is just another collection type and generic collection is classics. In this case type constraint looks odd too.

In fact the example class Repository<T> where T : class, IBusinessbBject looks
pretty much similar to class BusinessObjectRepository to me. Which is the thing generics are made to fix.

The whole point is: are generics good for anything except collections and don't type constraints make generic as specialized, as the use of this type constraint instead of generic type parameter inside the class does?

答:
The whole point is: are generics good for anything except collections
  and don't type constraints make generic as specialized, as the use of
  this type constraint instead of generic type parameter inside the
  class does?

No. You're thinking too much about Repository, where it is pretty much the same. But that's not what the generics are there for. They're there for the users.

The key point here isn't that Repository itself is more generic. It's that the users are more specialized- i.e., that Repository<BusinessObject1> and Repository<BusinessObject2> are different types, and furthermore, that if I take a Repository<BusinessObject1>, I know that I will get BusinessObject1 back out from Get.

You cannot offer this strong typing from simple inheritance. Your proposed Repository class does nothing to prevent people confusing repositories for different kinds of business object or guaranteeing the correct kind of business object coming back out.

Title: Generics vs common interface?


问:
Using BSD licensed source code in a product under a new license and a hypothetical scenario
Let me describe a hypothetical scenario, I wish to know if my reasoning is correct.

I use source code X, licensed by author Y under the BSD-3 license, in my source code. I intend to adhere to their BSD-3 license.

Then I sell my product under my custom closed source license. My product does not include any source code. My product's license does not contain any part of Y's license. My product has a warranty and that is stated in my license. Y's copyright notice, the list of conditions, and the disclaimer (i.e. the entire text of their BSD-3 license), is included in the every copy of documentation of my product, as per the second condition of BSD-3.

Are those two statements valid while at the same time not violating Y's license:

My product is licensed under my license only.

The disclaimer (written in UPPERCASE) of BSD-3 license is only relevant so that it absolves author Y of any liability, and doesn't have any effect on my license.

答:
Y's license needs to be reproduced in every copy of your product, whether your product is distributed in source code form or in compiled binary form, not just in every copy of documentation of your product.

From http://opensource.org/licenses/BSD-3-Clause:

Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

This means that if you don't supply documentation with your binary-based distribution, that distribution still must contain a reproduction of Y's license.  By reproducing Y's license along side your license, your product is licensed to your users with multiple licenses that apply in conjunction.

--- Edit ---
Because the license must be reproduced (not just "documented") whenever Y's intellectual property is redistributed, this further means that it is binding on your users.  As such it applies particularly if your users redistribute your binary (say as a derivative work that has different purpose and documentation).  One thing you could consult legal advice about is whether your users could reference your binary instead of redistributing it, and thus not be bound to reproduce Y's BSD license since they would not redistributing your binary.


答:
1) Yes, if you put license L1 on your program P1, then P1 is licensed under L1, and that's it.

However, it is possible that you are not legally allowed to use license L1. In particular, if one of your dependencies has a license L2, it may state that L1 must meet some specific conditions, or perhaps that L1 must be L2 and nothing else. When people talk about licenses being "compatible" with each other, this is the sort of issue they're talking about. In this case, L2 is the BSD-3 license, which imposes no restrictions at all on what license you use for L1.

In practice, assuming your license is super-restrictive, this means that anyone who downloads your program may not take out that dependency from your program and use it in their own work. They would have to go get that dependency from a distribution with a more permissive license before they could use it in their own work.

2) Yes, the disclaimer is merely saying that you cannot sue the library author for anything. It's not imposing any additional conditions on what you can do with the software, much less what license you may use for derivative works.

P.S. Like everyone else is saying, you need to include a full copy of the BSD-3 license in your distribution of your program, no matter what license you choose for your program. I think the other answers are assuming that "documentation" is not distributed with the program and thus including the license in your documentation isn't good enough; hopefully you meant documentation that comes with the program.

Title: Using BSD licensed source code in a product under a new license and a hypothetical scenario

Body:
Let me describe a hypothetical scenario, I wish to know if my reasoning is correct.

I use source code X, licensed by author Y under the BSD-3 license, in my source code. I intend to adhere to their BSD-3 license.

Then I sell my product under my custom closed source license. My product does not include any source code. My product's license does not contain any part of Y's license. My product has a warranty and that is stated in my license. Y's copyright notice, the list of conditions, and the disclaimer (i.e. the entire text of their BSD-3 license), is included in the every copy of documentation of my product, as per the second condition of BSD-3.

Are those two statements valid while at the same time not violating Y's license:

My product is licensed under my license only.

The disclaimer (written in UPPERCASE) of BSD-3 license is only relevant so that it absolves author Y of any liability, and doesn't have any effect on my license.


答:
Let's first talk about pure parametric polymorphism and get into bounded polymorphism later.

Parametric Polymorphism

What does parametric polymorphism mean? Well, it means that a type, or rather type constructor is parameterized by a type. Since the type is passed in as a parameter, you cannot know in advance what it might be. You cannot make any assumptions based on it. Now, if you don't know what it might be, then what is the use? What can you do with it?

Well, you could store and retrieve it, for example. That's the case you already mentioned: collections. In order to store an item in a list or an array, I need to know nothing about the item. The list or array can be completely oblivious to the type.

But what about the Maybe type? If you are not familiar with it, Maybe is a type which maybe has a value and maybe doesn't. Where would you use it? Well, for example, when getting an item out of a dictionary: the fact that an item might not be in the dictionary is not an exceptional situation, so you really shouldn't throw an exception if the item isn't there. Instead, you return an instance of a subtype of Maybe<T>, which has exactly two subtypes: None and Some<T>. int.Parse is another candidate of something that really should return a Maybe<int> instead of throwing an exception or the whole int.TryParse(out bla) dance.

Now, you might argue that Maybe is kinda-sorta like a list which can only have zero or one elements. And thus kinda-sorta a collection.

Then what about Task<T>? It's a type which promises to return a value at some point in the future, but doesn't necessarily have a value right now.

Or what about Func<T, …>? How would you represent the concept of a function from one type to another type if you cannot abstract over types?

Or, more generally: considering that abstraction and reuse are the two fundamental operations of software engineering, why wouldn't you want to be able to abstract over types?

Bounded Polymorphism

So, let's now talk about bounded polymorphism. Bounded polymorphism is basically where parametric polymorphism and subtype polymorphism meet: instead of a type constructor being completely oblivious about its type parameter, you can bind (or constrain) the type to be a subtype of some specified type.

Let's go back to collections. Take a hashtable. We said above that a list doesn't need to know anything about its elements. Well, a hashtable does: it needs to know that it can hash them. (Note: in C#, all objects are hashable, just like all objects can be compared for equality. That's not true for all languages, though, and is sometimes considered to be design mistake even in C#.)

So, you want to constrain your type parameter for the key type in the hashtable to be an instance of IHashable:

```<code>class HashTable<K, V> where K : IHashable
{
  Maybe<V> Get(K key);
  bool Add(K key, V value);
}
</code>```

Imagine if instead you had this:

```<code>class HashTable
{
    object Get(IHashable key);
    bool Add(IHashable key, object value);
}
</code>```

What would you do with a value you get out of there? You can't do anything with it, you only know it's an object. And if you iterate over it, all you get yielded is a pair of something you know is an IHashable (which doesn't help you much because it only has one property Hash) and something you know is an object (which helps you even less).

Or something based on your example:

```<code>class Repository<T> where T : ISerializable
{
    T Get(int id);
    void Save(T obj);
    void Delete(T obj);
}
</code>```

The item needs to be serializable because it is going to be stored on disk. But what if you have this instead:

```<code>class Repository
{
    ISerializable Get(int id);
    void Save(ISerializable obj);
    void Delete(ISerializable obj);
}
</code>```

With the generic case, if you put a BankAccount in, you get a BankAccount back, with methods and properties like Owner, AccountNumber, Balance, Deposit, Withdraw, etc. Something you can work with. Now, the other case? You put in a BankAccount but you get back a Serializable, which has just one property: AsString. What are you going to do with that?

There are also some neat tricks you can do with bounded polymorphism:

F-bounded polymorphism

F-bounded quantification is basically where the type variable appears again in the constraint. This can be useful in some circumstances. E.g. how do you write an ICloneable interface? How do you write a method where the return type is the type of the implementing class? In a language with a MyType feature, that's easy:

```<code>interface ICloneable
{
    public this Clone(); // syntax I invented for a MyType feature
}
</code>```

In a language with bounded polymorphism, you can do something like this instead:

```<code>interface ICloneable<T> where T : ICloneable<T>
{
    public T Clone();
}

class Foo : ICloneable<Foo>
{
    public Foo Clone()
    {
        // …
    }
}
</code>```

Note that this is not as safe as the MyType version, because there is nothing stopping someone from simply passing the "wrong" class to the type constructor:

```<code>class EvilBar : ICloneable<SomethingTotallyUnrelatedToBar>
{
    public SomethingTotallyUnrelatedToBar Clone()
    {
        // …
    }
}
</code>```

Abstract Type Members

As it turns out, if you have abstract type members and subtyping, you can actually get by completely without parametric polymorphism and still do all the same things. Scala is heading in this direction, being the first major language that started out with generics and then trying to remove them, which is exactly the other way around from e.g. Java and C#.

Basically, in Scala, just like you can have fields and properties and methods as members, you can also have types. And just like fields and properties and methods can be left abstract to be implemented in a subclass later, type members can also be left abstract. Let's go back to collections, a simple List, that would look something like this, if it were supported in C#:

```<code>class List
{
    T; // syntax I invented for an abstract type member
    T Get(int index) { /* … */ }
    void Add(T obj) { /* … */ }
}

class IntList : List
{
    T = int;
}
// this is equivalent to saying `List<int>` with generics
</code>```

Title: Generics vs common interface?

Body:
I don't remember when I wrote generic class last time. Every time I think I need it after some thinking I make a conclusion I don't.

The second answer to this question made me to ask for clarification (since i can't comment yet, i made a new question).

So let's take given code as an example of case where one needs generics:

```<code>public class Repository<T> where T : class, IBusinessOBject
{
  T Get(int id)
  void Save(T obj);
  void Delete(T obj);
}
</code>```

It has type constraints: IBusinessObject

My usual way of thought is: the class is constrained to use IBusinessObject, so are the classes that use this Repository are. Repository stores these IBusinessObjects, most likely clients of this Repository will want to get and use objects through IBusinessObject interface. So why not just to

```<code>public class Repository
{
  IBusinessOBject Get(int id)
  void Save(IBusinessOBject obj);
  void Delete(IBusinessOBject obj);
}
</code>```

Tho, the example is not good, as it is just another collection type and generic collection is classics. In this case type constraint looks odd too.

In fact the example class Repository<T> where T : class, IBusinessbBject looks
pretty much similar to class BusinessObjectRepository to me. Which is the thing generics are made to fix.

The whole point is: are generics good for anything except collections and don't type constraints make generic as specialized, as the use of this type constraint instead of generic type parameter inside the class does?

Body:
Let's first talk about pure parametric polymorphism and get into bounded polymorphism later.

Parametric Polymorphism

What does parametric polymorphism mean? Well, it means that a type, or rather type constructor is parameterized by a type. Since the type is passed in as a parameter, you cannot know in advance what it might be. You cannot make any assumptions based on it. Now, if you don't know what it might be, then what is the use? What can you do with it?

Well, you could store and retrieve it, for example. That's the case you already mentioned: collections. In order to store an item in a list or an array, I need to know nothing about the item. The list or array can be completely oblivious to the type.

But what about the Maybe type? If you are not familiar with it, Maybe is a type which maybe has a value and maybe doesn't. Where would you use it? Well, for example, when getting an item out of a dictionary: the fact that an item might not be in the dictionary is not an exceptional situation, so you really shouldn't throw an exception if the item isn't there. Instead, you return an instance of a subtype of Maybe<T>, which has exactly two subtypes: None and Some<T>. int.Parse is another candidate of something that really should return a Maybe<int> instead of throwing an exception or the whole int.TryParse(out bla) dance.

Now, you might argue that Maybe is kinda-sorta like a list which can only have zero or one elements. And thus kinda-sorta a collection.

Then what about Task<T>? It's a type which promises to return a value at some point in the future, but doesn't necessarily have a value right now.

Or what about Func<T, …>? How would you represent the concept of a function from one type to another type if you cannot abstract over types?

Or, more generally: considering that abstraction and reuse are the two fundamental operations of software engineering, why wouldn't you want to be able to abstract over types?

Bounded Polymorphism

So, let's now talk about bounded polymorphism. Bounded polymorphism is basically where parametric polymorphism and subtype polymorphism meet: instead of a type constructor being completely oblivious about its type parameter, you can bind (or constrain) the type to be a subtype of some specified type.

Let's go back to collections. Take a hashtable. We said above that a list doesn't need to know anything about its elements. Well, a hashtable does: it needs to know that it can hash them. (Note: in C#, all objects are hashable, just like all objects can be compared for equality. That's not true for all languages, though, and is sometimes considered to be design mistake even in C#.)

So, you want to constrain your type parameter for the key type in the hashtable to be an instance of IHashable:

class HashTable<K, V> where K : IHashable
{
  Maybe<V> Get(K key);
  bool Add(K key, V value);
}

Imagine if instead you had this:

class HashTable
{
    object Get(IHashable key);
    bool Add(IHashable key, object value);
}

What would you do with a value you get out of there? You can't do anything with it, you only know it's an object. And if you iterate over it, all you get yielded is a pair of something you know is an IHashable (which doesn't help you much because it only has one property Hash) and something you know is an object (which helps you even less).

Or something based on your example:

class Repository<T> where T : ISerializable
{
    T Get(int id);
    void Save(T obj);
    void Delete(T obj);
}

The item needs to be serializable because it is going to be stored on disk. But what if you have this instead:

class Repository
{
    ISerializable Get(int id);
    void Save(ISerializable obj);
    void Delete(ISerializable obj);
}

With the generic case, if you put a BankAccount in, you get a BankAccount back, with methods and properties like Owner, AccountNumber, Balance, Deposit, Withdraw, etc. Something you can work with. Now, the other case? You put in a BankAccount but you get back a Serializable, which has just one property: AsString. What are you going to do with that?

There are also some neat tricks you can do with bounded polymorphism:

F-bounded polymorphism

F-bounded quantification is basically where the type variable appears again in the constraint. This can be useful in some circumstances. E.g. how do you write an ICloneable interface? How do you write a method where the return type is the type of the implementing class? In a language with a MyType feature, that's easy:

interface ICloneable
{
    public this Clone(); // syntax I invented for a MyType feature
}

In a language with bounded polymorphism, you can do something like this instead:

interface ICloneable<T> where T : ICloneable<T>
{
    public T Clone();
}

class Foo : ICloneable<Foo>
{
    public Foo Clone()
    {
        // …
    }
}

Note that this is not as safe as the MyType version, because there is nothing stopping someone from simply passing the "wrong" class to the type constructor:

class EvilBar : ICloneable<SomethingTotallyUnrelatedToBar>
{
    public SomethingTotallyUnrelatedToBar Clone()
    {
        // …
    }
}

Abstract Type Members

As it turns out, if you have abstract type members and subtyping, you can actually get by completely without parametric polymorphism and still do all the same things. Scala is heading in this direction, being the first major language that started out with generics and then trying to remove them, which is exactly the other way around from e.g. Java and C#.

Basically, in Scala, just like you can have fields and properties and methods as members, you can also have types. And just like fields and properties and methods can be left abstract to be implemented in a subclass later, type members can also be left abstract. Let's go back to collections, a simple List, that would look something like this, if it were supported in C#:

class List
{
    T; // syntax I invented for an abstract type member
    T Get(int index) { /* … */ }
    void Add(T obj) { /* … */ }
}

class IntList : List
{
    T = int;
}
// this is equivalent to saying `List<int>` with generics


问:
What's the most used programming language in high performance computing? And why?
I believe a lot of Fortran is used in HPC, but not sure if that's only for legacy reasons.

Features of modern programming languages like garbage collection or run-time polymorphism are not suitable for HPC since speed matters so not sure where C# or Java or C++ come in.

Any thoughts?

答:
Fortran is most common, primarily due to legacy (people still run old code) and familiarity (most people who do HPC are not familiar with other kinds of languages).

Features of modern programming languages like garbage collection or run-time polymorphism are not suitable for HPC since speed matters so not sure where C# or Java or C++ come in.

That is not true in general. Classical HPC was mostly doing linear algebra with machine-precision numbers. However, modern HPC is increasingly using supercomputers for a wider variety of crunching, like symbolic calculations with arbitrary mathematical expressions instead of machine precision numbers. This places quite different characteristics on the tools you use and it is not uncommon to use programming languages other than Fortran because symbolic computation can be prohibitively difficult without GC and other kinds of optimizing compiler such as OCaml's optimizing pattern match compiler.

For example, read this paper by Fischbacher et al. which says "the authors have strong reason to believe that this may well be the largest symbolic calculation performed so far".


问:
Is it safe to execute the "regedit" command on Windows?
I'm writing a Java application, I need to create a URI Scheme.
I've seen a library creating a URI Scheme using the "regedit" command on Windows.

Is it safe to execute "regedit" for this task? Is there anything I should avoid or do in a application that is using the command?

答: Launching RegEdit may require administrative privileges, (depending on who is attempting to run it,) so if you attempt to do that, either your application will need to always run with elevated privileges, or some of your users will be prompted with a UAC dialog each time you attempt to launch RegEdit on their behalf. That's not very nice.  Why don't you just directly manipulate the registry ?  See: https://stackoverflow.com/a/6163701/773113</p>


问:
Data structure for effects animation?
I'm making a prototype for a game.  I'm working on effects at the moment, but more generally animation.

Currently, I have list where newly spawned effects are added to.  Then on the update section of the game loop, I'd let each effect change their state based on time.  When an effect finishes, I have it trigger an internal flag.  After I update all of the effects, I check the list over again for any finished effects and remove them from the list.

It works.  I figured it can be done a better way, but I'm not sure how.  I mean, it runs through the list twice to update and purge finished effects.  If I use an array, deletion will leave a hole there, and I'd have to track where the holes are, which seems more complicated.  I figure a linked list is best?  Any suggestions?

答:
It's hard to say, given what you've put into your question (no mention of language or performance requirements).

An array will work.  As you noted, you can remove finished effects then add logic to handle the holes.  If it's an array of objects, just setting that element to NULL should suffice.  You can also have a field isFinished inside an object if you prefer.

Depending on your language and performance requirements, you may be able to use something like C#'s List<>.  Java has a similar class.  You can think of it as an array with support for deleting without holes.

There's nothing wrong with a linked list, but I'd be a little concerned about the possibility of premature optimization.

Stick with the simplest code that works, wait until you have a measurable performance problem, then use the scientific method to isolate the code that needs optimizing.

Title: Data structure for effects animation?


问:
Can I remove all-caps and shorten the disclaimer on my License?
I am using the MIT License for a particular piece of code. Now, this license has a big disclaimer in all-caps:

```<code>THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY
OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF...
...
</code>```

I've seen a normally capitalised disclaimer on the zlib license (notice that it is above the license text), and even software with no disclaimer at all (which implies, i take it, that there is indeed a guarantee?), but i'd like some sourced advice by a trusted party. I just haven't found any.

GNU's License notice for other files comes with this disclaimer:

This file is offered as-is,
  without any warranty.

Short and simple.

My question therefore: Are there any trusted sources indicating that a short rather than long, and a normally spelled rather than capitalised disclaimer (or even one or the other) are safely usable in all of the jurisdictions I should be concerned with?

For the purposes of this question, the software is released in the European Union, should it make any difference.

答:
The all-caps disclaimer in the MIT license is more or less a copy-paste from the legal language found in commercial shrink-wrap licenses, where the spelling out of "no warranties" is required to be more legally precise than it needs to be for free software.  Since open-source licenses do exist that do not have this legal verbiage, I assume that the short form is probably OK.

As with all things legal, if you are really concerned about it, you should consult a lawyer that specializes in software licensing law.


问:
Burrows-Wheeler transform backward search: how to find suffix index?
BWT backward search algorithm is pretty straightforward if we only need the multiplicity of a pattern. However I also need to find the suffix indices (i.e. positions in the reference string where a pattern occurs). e.g., given string banana and pattern an, it occurs twice at positions 1 and 3.

I could compute all suffixes and sort them, but that would increase the time complexity to O(nlogn), n being length of the reference string. Is there a way to do this and still keep the O(length of pattern) time complexity?

答:
The algorithm you are looking for is Ukkonen's suffix tree. It runs in O(n).

The algorithm you describe is not O(n log n). It has that number of string comparisons. In the extreme case, where your string being is "verylong_verylong_", comparisons take O(n), bringing your algorithm down to quadratic complexity.


问:
What do Java developers think of Scala?
I've noted that IDE support is nowhere near as good, but the language itself supports functional programming idioms much more cleanly.</p>

答:
Scala is complex. No way around it! Its syntax is extremely flexible and can be customized in numerous ways (above all operators / infix notation) - and the type system has more different features than any other language I know.

So things aren't that straight as e.g. in Haskell: Typeclasses to cover them all.

As Scala tries to put together functional programming, OO, procedural programming and java libraries as well as own ideas, we finally end up with lots of concepts that somehow seem to go "in the same direction":

Implicit values

Implicit functions

Existentials

Wildcards

Traits

Interfaces

Abstract classes

Case classes

Structural types

Generic constraints

View bounds

Anonymous types

Choosing among them seems difficult at first and one might easily wonder if one has found the correct solution to some problem. It's even easily possible to produce hacky stuff by abusing implicits.

But the interesting thing is: Scala works. It's sometimes hard to understand why (especially figuring out through what implicit conversions + inheritance + ... some object has got functionality X), but you don't have to bother about that most of the times.

Write Scala as straightforward as possible and it will work. Don't get confused by everything that is possible and just use what you need. And if you need something, you can be sure that somehow Scala has it ;)

And the better you get, the more you'll be able to customize Scala with operators, implicits, monads, funky syntax ... and finally get something close to a DSL that will perfectly address your problem.

After all, you have always the possibility to just use Scala as a much much better Java with cleaner, easier syntax, type inference and some functional features.

Title: What do Java developers think of Scala?


问:
A condition on an argument used in multiple calls of a method: enforced by caller or by the method?
Let's assume I have an object a of a class A. It has a method that needs an argument in form of another object of a particular type - but the argument should also be in particular state, because the operation performed by the method (let's say it's querying an external service, but it could be something else) requires it.

```<code>class A(object):
    def action(self, argument):

        return do_something(argument)
</code>```

The first solution that comes to my mind is simple: the method should
enforce a condition on the input data. It should test it for required state and then either raise an exception or modify the state:

```<code>class A(object):
    def action(self, argument):
        if argument.state == False:
            raise Exception()

        return do_something(argument)

class A(object):
    def action(self, argument):
        if argument.state == False:
            argument.change_state()

        return do_something(argument)
</code>```

However, the instance we are talking about is only one of many instances of the A. All these instances should perform the same operation on input data: testing it for a particular state and then enforcing it, or just raising an exception. It seems they could use a shared instance of parameter whose required state is already enforced by an external caller, instance of class B:

```<code>class B(object):
    def action(self, argument):
        argument.change_state()
        for a in self.instances_of_A:
            yield a.action(argument)
</code>```

Because I think the operation performed by the method wouldn't be properly encapsulated without enforcing the required state of argument inside the method, I think it should be moved to the former caller. The object a and all other instances of class A would just provide data necessary for performing the operation.

```<code>class B(object):
    def action(self, argument):
        argument.change_state()
        for a in self.instances_of_A:
            yield  do_something(argument, a.data)
</code>```

However, there is another problem: the operation returns a value that could be interpreted in a way related to instance of A to get another piece of data - and now it seems like the operation do_something should be encapsulated in a method of class A.

How should I solve this problem? Should I simply keep the current design and make object a return data that could be used to interpret return code provided by the operation? Perhaps I should use chain of command pattern and modify class A to delegate the operation to other instances of A? What are the other ways I could handle it?

答:
I guess you need to introduce a simple DTO into your scheme. Take your agrument, check if it is in a valid state and put that state into a new DTO object. In your last example, you can do that inside your B::action method.

This way you will no longer need any state checking because this DTO is always in a valid state by definition. A will enforce its contract by accepting only this DTO for an operation.


问:
Is it a good practice to separate lower level code from ReactiveX
Consider I have a Calculator class, it calculates an Integer. On higher parts of the system, say a MVP presenter, I want to work with an ReactiveX Observable that emits the Integer.

I could do the following:

```<code>public class Calculator {

    public Observable<Integer> doSomeVeryComplicatedCalculations() {

        return Observable.just(0);

    }

}
</code>```

I am wondering if it is a good practice to keep the Calculator class free from ReactiveX and use a wrapper like this:

```<code>public class Calculator {

    public Integer doSomeVeryComplicatedCalculations() {

        return 0;

    }

}

public class RxCalculator {

    public Observable<Integer> doSomeVeryComplicatedCalculations() {
        return Observable.create(new Observable.OnSubscribe<Integer>() {
            @Override
            public void call(Subscriber<? super Integer> subscriber) {
                subscriber.onNext(new Calculator().doSomeVeryComplicatedCalculations());
            }
        });
    }

}
</code>```

This way the actual Calculator

a. can be tested without ReactiveX where imho ReactiveX adds some complexity to testing

b. the Calculator class can be used in projects that don't use ReactiveX.

Are there any downsides to this, besides of course that I'll end up with more code / classes?

答:
I am wondering if it is a good practice to keep the Calculator class
  free from ReactiveX and use a wrapper

Yes. You should not depend on your framework, library or tool. Depend on abstractions, not on implementations.

I am PHP programmer and once I was looking for a good http library to use in my project. I chose Guzzle. It's really good. It has tons of features from which I use only 1% ;) I used it in several projects of mine through all the code.

But the next version of Guzzle was released with backwards incompatible changes. They changed a lot (for the better). And I suddenly realized, that I depend on previous Guzzle version through all my code! To switch to a newer version means, that I need to rewrite a good bunch of it.

Now when I'm using some powerful external library, I always create a wrapper, that has only features enough to suit my needs and allows me to quickly swap implementation.


答:
IANAL, but one works with me. So, I asked. The result:

The caps allow you to say 'no way could they have missed the disclaimer, it is hardly fine print!' This is important in a license or EULA that non-lawyers must read and accept.

There is a difference between 'express' and 'implied'. Some areas have laws that allow people to 'imply' a warranty, even though one was not explicitly offered, unless you make certain specifications.

He suggested not making any changes to existing licenses, as that basically creates a whole new (and likely weaker) license. License proliferation is a problem. Bad license proliferation is a bigger problem.

The license is designed to protect you, and given this brave new era of endless litigation, caps and run on sentences that very few people read to begin with are a small price to pay :)

This is one of the biggest reasons why V2/V3 of the (L|A)GPL specifically say that altering the license is prohibited.

People sue, every day .. for damages that common sense should have averted. For instance "How did I know the coffee was hot? I wouldn't have spilled it on my lap if it was labeled as so .."

You really should take care not to weaken a 'shield' that prevents gold diggers from bothering you.

Title: Can I remove all-caps and shorten the disclaimer on my License?

Body:
I am using the MIT License for a particular piece of code. Now, this license has a big disclaimer in all-caps:

```<code>THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY
OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF...
...
</code>```

I've seen a normally capitalised disclaimer on the zlib license (notice that it is above the license text), and even software with no disclaimer at all (which implies, i take it, that there is indeed a guarantee?), but i'd like some sourced advice by a trusted party. I just haven't found any.

GNU's License notice for other files comes with this disclaimer:

This file is offered as-is,
  without any warranty.

Short and simple.

My question therefore: Are there any trusted sources indicating that a short rather than long, and a normally spelled rather than capitalised disclaimer (or even one or the other) are safely usable in all of the jurisdictions I should be concerned with?

For the purposes of this question, the software is released in the European Union, should it make any difference.


问:
What are good ways to measure project size? How do I compare the size of my project to other projects?

Background

I am currently working for a quite large (relative to what I have done before) hobby project. I would like to compare the size of this project to other open-sourced projects but I cannot figure out how I should do that in a good and meaningful way.

Problems with using line count

I usually see project size being measured in line of code.

I do not consider that to be a good way to measure code size because then projects that have code that is styled like this:

```<code>int function(int argument_one, int argument_two) {
    int var1, var2, var3;
    code;
    code;
    if (test(var2, var3))
        code;
    else
        code;
    return var1;
}
</code>```

will appear about 40 % smaller than projects with code that is styled like this:

```<code>int function(int argument_one, int argument_two)
{
    int var1;
    int var2;
    int var3;

    code;
    code;

    if (test(var2, var3))
    {
        code;
    }
    else
    {
        code;
    }

    return var1;
}
</code>```

Other ways

Some other ways I have heard of are:

Character count

Comment count

Word count

Compilation time

But all of these has disadvantages. Comment count would make messy code with lots of comments appear longer. Compilation time is dependent on how fast the computer is and how the code is compiled. Word and character count are also highly dependent on how the code is styled.

Question

I am wondering if there are any more reliable ways to measure project size than the ones listed here.

What are more reliable ways to measure code size? Has there been attempts to come up with a universal way to measure code size? Are there any tools available that measures code size in a more meaningful way than simply counting lines/words/chars?

答:
Cyclomatic complexity algorithms are what you want to look into.

There are a few tools that calculate this info.


问:
Fixing a bug while working on a different part of the code base
This happened at least once to me. I'm working on some part of the code base and find a small bug in a different part, and the bug stops me from completing what I'm currently trying to do. Fixing the bug could be as simple as changing a single statement.

What do you do in that situation?

Fix the bug and commit it together with your current work

Save your current work elsewhere, fix the bug in a separate commit, then continue your work [1]

Continue what you're supposed to do, commit the code (even if it breaks the build fails some tests), then fix the bug (and the build make tests pass) in a separate commit

[1] In practice, this would mean: clone the original repository elsewhere, fix the bug, commit/push the changes, pull the commit to the repository you're working on, merge the changes, and continue your work.

Edit: I changed number three to reflect what I really meant.

答:
I fix the bug and I do separate commits, one for each fix/feature.

Most of the time, the changes are not in the same file, so it's easy to separate the commits. If the changes are in the same file, I use TortoiseHg (a mecurial GUI front-end) to select precisely the diffs I want to commit (I think it's possible to do this on the command line with the Record extension, but it's less convenient).

Some people use the Mercurial Queues to isolate the minor fixes while working on a feature. The minor fixes are stacked up in the MQ, and when the feature is finished and committed, the content of the queue is also committed (one changeset for each entry in the queue).


问:
Optimization: How much time saved is considered worth it?
I was reading up about branch predictions and cache misses, and have decided to read what every programmer should know about memory. But I'm not sure how much low level knowledge do I need to have to write performant code.

One classic example is accessing the memory in the wrong way, accessing column by column when it's row-major would cause a cache miss on every lookup.

I ran a benchmark of 10 000 by 10 000 matrix, and the correct order runs in 97ms while the wrong order runs in 1535ms.

While it's evident that accessing the memory in the right order is much faster, but by how much? In this example, it's only faster by 1.44s. So a program written by a programmer without such memory knowledge is probably only penalized by up to a few seconds.

I have 2 questions.

How much low level knowledge does a competent programmer need to have?

How much time saved through optimization is considered worthwhile? At least a minute shaved? Half a minute? Or any amount of time saved?

Some people think that it's totally not worth it to optimize just to save a few seconds or even milliseconds. But what do you all think?

答:
Its not only a question of how long a piece of string is, but what that string is used for.

Sure, spending a month to optimise a second off your code execution time is probably worthless. You could have found some slower code that was easier to optimise, or add more features. But sometimes you know something is slow and you need to modify it to make it faster and you have to experiment a bit to achieve this - for example a colleague years ago spent several months implementing a caching mechanism to our product (that was far too slow at the time). It added a 10% increase to overall speed. Then we discovered the MS_DTS setup we were using was incredibly inefficient, changed it to DCOM and achieved a 100% speed increase.  What was certain was that our product was far too slow and we all needed to spend a lot of time making it faster in every way.

The other aspect is how much time is saved cumulatively - shaving a fraction of a second off a query might sound useless, but if that query is used repeatedly and often by every user, those fractions are going to add up to a fairly worthwhile server performance improvement.

So its difficult to answer your question without knowing your specific circumstances. You just need to trade off the performance impact against the cost of development.It can be useful to give a "cost to the user" to make this trade off easier to calculate - saving a second on how long it takes the start menu to show might not sound much, but if you have a billion users it might be worth the effort.


问:
Trying to understand on what "user.dir" property actually means?
So basically wen I googled on what the "user.dir" property does I got this link to a similar question on stackexchange: Java “user.dir” property - what exactly it means?

So basically the answer given was : It's the directory where Java was run from, where you started the JVM. Does not have to be within the user's home directory. It can be anywhere where the user has permission to run Java.

Which is okay, but then I found this other link in the android context: Why does System.getProperty(“user.dir”) return “/”
As the documentation says, the user.dir property is the user working directory, which is not necessarily the same as the directory where your apk is placed.

So the first best voted answer in the first link says the directory does not have to be within the users home directory while the other says "it is the user working directory."

Now I am terribly confused and need help on this.

答:
As previous answer says user.dir is "current user directory"
Just look at next examples:

cd /path/to/your/jar

$JAVA_HOME/bin/java -jar myprogram.jar

(user.dir = /path/to/your/jar)

cd $JAVA_HOME/bin

java -jar /path/to/your/jar/myprogram.jar

(user.dir = $JAVA_HOME/bin)

cd ~

$JAVA_HOME/bin/java -jar /path/to/your/jar/myprogram.jar

(user.dir = user home directory)


问:
Ruby: if variable vs if variable.nil?
I'm new to Ruby and I was surprised when I found out that all objects are true apart from nil and false. Even 0 is true.

A nice thing about that property of the language is that you can write:

```<code>if !variable
  # do stuff when variable is nil
end
</code>```

My colleagues, who are more seasoned Ruby developers, insist I should choose that instead of using .nil? like so:

```<code>if variable.nil?
  # do stuff when variable is nil
end
</code>```

However I believe that the latter is a better option for two reasons:
1. I think it's more object oriented, especially in a language like Ruby where everything is an object and message exchange.
2. It is more readable, in my subject opinion, even if it is less compact.

Am I making a "newbie" mistake here?

答:
Idiomatically, unless variable is preferable to if !variable. Negated if statements are often considered a code smell as it's easier to miss the negation when skimming.

The bigger picture here is that doing nil checks like this is also a bit of a code smell. For proper OO, aim to use the null object pattern so that this sort of check is never needed.

Tell objects what to do, don't ask them what they are. This is sometimes known as tell don't ask

Title: Ruby: if variable vs if variable.nil?

ContentLicense: CC BY-SA 4.0


问:
Is there anything that can be done with recursion that can't be done with loops?
There are times where using recursion is better than using a loop, and times where using a loop is better than using recursion. Choosing the "right" one can save resources and/or result in fewer lines of code.

Are there any cases where a task can only be done using recursion, rather than a loop?

答:
It depends on how strictly you define "recursion".

If we strictly require it to involve the call-stack (or whatever mechanism for maintaining program state is used), then we can always replace it with something that doesn't. Indeed, languages that lead naturally to heavy use of recursion tend to have compilers that make heavy use of tail-call optimisation, so what you write is recursive but what you run is iterative.

But lets consider a case where we make a recursive call and use the result of a recursive call for that recursive call.

public static BigInteger Ackermann(BigInteger m, BigInteger n)
{
  if (m == 0)
    return  n+1;
  if (n == 0)
    return Ackermann(m - 1, 1);
  else
    return Ackermann(m - 1, Ackermann(m, n - 1));
}
```

<p>Making the first recursive call iterative is easy:</p>

<pre class="lang-cs prettyprint-override"><code>public static BigInteger Ackermann(BigInteger m, BigInteger n)
{
restart:
  if (m == 0)
    return  n+1;
  if (n == 0)
  {
    m--;
    n = 1;
    goto restart;
  }
  else
    return Ackermann(m - 1, Ackermann(m, n - 1));
}
</code>```

We can then clean-up remove the goto to ward off velociraptors and the shade of Dijkstra:

public static BigInteger Ackermann(BigInteger m, BigInteger n)
{
  while(m != 0)
  {
    if (n == 0)
    {
      m--;
      n = 1;
    }
    else
      return Ackermann(m - 1, Ackermann(m, n - 1));
  }
  return  n+1;
}
```

<p>But to remove the other recursive calls we're going to have to store the values of some calls into a stack:</p>

<pre class="lang-cs prettyprint-override"><code>public static BigInteger Ackermann(BigInteger m, BigInteger n)
{
  Stack<BigInteger> stack = new Stack<BigInteger>();
  stack.Push(m);
  while(stack.Count != 0)
  {
    m = stack.Pop();
    if(m == 0)
      n = n + 1;
    else if(n == 0)
    {
      stack.Push(m - 1);
      n = 1;
    }
    else
    {
      stack.Push(m - 1);
      stack.Push(m);
      --n;
    }
  }
  return n;
}
</code>```

Now, when we consider the source code, we have certainly turned our recursive method into an iterative one.

Considering what this has been compiled to, we have turned code that uses the call stack to implement recursion into code that does not (and in doing so turned code that will throw a stack-overflow exception for even quite small values into code that will merely take an excruciatingly long time to return [see How can I prevent my Ackerman function from overflowing the stack? for some further optimisations that make it actually return for many more possible inputs]).

Considering how recursion is implemented generally, we have turned code that uses the call-stack into code that uses a different stack to hold pending operations. We could therefore argue that it is still recursive, when considered at that low level.

And at that level, there are indeed no other ways around it. So if you do consider that method to be recursive, then there are indeed things we cannot do without it. Generally though we do not label such code recursive. The term recursion is useful because it covers a certain set of approaches and gives us a way to talk about them, and we are no longer using one of them.

Of course, all of this assumes you have a choice. There are both languages that prohibit recursive calls, and languages that lack the looping structures necessary for iterating.

Body:
It depends on how strictly you define "recursion".

If we strictly require it to involve the call-stack (or whatever mechanism for maintaining program state is used), then we can always replace it with something that doesn't. Indeed, languages that lead naturally to heavy use of recursion tend to have compilers that make heavy use of tail-call optimisation, so what you write is recursive but what you run is iterative.

But lets consider a case where we make a recursive call and use the result of a recursive call for that recursive call.

public static BigInteger Ackermann(BigInteger m, BigInteger n)
{
  if (m == 0)
    return  n+1;
  if (n == 0)
    return Ackermann(m - 1, 1);
  else
    return Ackermann(m - 1, Ackermann(m, n - 1));
}

Making the first recursive call iterative is easy:

public static BigInteger Ackermann(BigInteger m, BigInteger n)
{
restart:
  if (m == 0)
    return  n+1;
  if (n == 0)
  {
    m--;
    n = 1;
    goto restart;
  }
  else
    return Ackermann(m - 1, Ackermann(m, n - 1));
}

We can then clean-up remove the goto to ward off velociraptors and the shade of Dijkstra:

public static BigInteger Ackermann(BigInteger m, BigInteger n)
{
  while(m != 0)
  {
    if (n == 0)
    {
      m--;
      n = 1;
    }
    else
      return Ackermann(m - 1, Ackermann(m, n - 1));
  }
  return  n+1;
}

But to remove the other recursive calls we're going to have to store the values of some calls into a stack:

public static BigInteger Ackermann(BigInteger m, BigInteger n)
{
  Stack<BigInteger> stack = new Stack<BigInteger>();
  stack.Push(m);
  while(stack.Count != 0)
  {
    m = stack.Pop();
    if(m == 0)
      n = n + 1;
    else if(n == 0)
    {
      stack.Push(m - 1);
      n = 1;
    }
    else
    {
      stack.Push(m - 1);
      stack.Push(m);
      --n;
    }
  }
  return n;
}

Now, when we consider the source code, we have certainly turned our recursive method into an iterative one.

Considering what this has been compiled to, we have turned code that uses the call stack to implement recursion into code that does not (and in doing so turned code that will throw a stack-overflow exception for even quite small values into code that will merely take an excruciatingly long time to return [see How can I prevent my Ackerman function from overflowing the stack? for some further optimisations that make it actually return for many more possible inputs]).

Considering how recursion is implemented generally, we have turned code that uses the call-stack into code that uses a different stack to hold pending operations. We could therefore argue that it is still recursive, when considered at that low level.

And at that level, there are indeed no other ways around it. So if you do consider that method to be recursive, then there are indeed things we cannot do without it. Generally though we do not label such code recursive. The term recursion is useful because it covers a certain set of approaches and gives us a way to talk about them, and we are no longer using one of them.

Of course, all of this assumes you have a choice. There are both languages that prohibit recursive calls, and languages that lack the looping structures necessary for iterating.


问:
Is there any reason to use "plain old data" classes?
In legacy code I occasionally see classes that are nothing but wrappers for data. something like:

```<code>class Bottle {
   int height;
   int diameter;
   Cap capType;

   getters/setters, maybe a constructor
}
</code>```

My understanding of OO is that classes are structures for data and the methods of operating on that data. This seems to preclude objects of this type. To me they are nothing more than structs and kind of defeat the purpose of OO. I don't think it's necessarily evil, though it may be a code smell.

Is there a case where such objects would be necessary? If this is used often, does it make the design suspect?

答:
As @Anna said, definitely not evil. Sure you can put operations (methods) into classes, but only if you want to. You don't have to.

Permit me a small gripe about the idea that you have to put operations into classes, along with the idea that classes are abstractions.
In practice, this encourages programmers to

Make more classes than they need to (redundant data structure). When a data structure contains more components than minimally necessary, it is un-normalized, and therefore contains inconsistent states. In other words, when it is altered, it needs to be altered in more than one place in order to remain consistent. Failure to perform all coordinated changes makes it inconsistent, and is a bug.

Resolve problem 1 by putting in notification methods, so that if part A is modified, it tries to propagate necessary changes to parts B and C. This is the primary reason why it is recommended to have get-and-set accessor methods. Since this is recommended practice, it appears to excuse problem 1, causing more of problem 1 and more of solution 2. This results not only in bugs due to incompletely implementing the notifications, but to a performance-sapping problem of runaway notifications. These are not infinite computations, merely very long ones.

These concepts are taught as good things, generally by teachers who haven't had to work within million-line monster apps riddled with these issues.

Here's what I try to do:

Keep data as normalized as possible, so that when a change is made to the data, it is done at as few code points as possible, to minimize the likelihood of entering an inconsistent state.

When data must be un-normalized, and redundancy is unavoidable, do not use notifications in an attempt to keep it consistent. Rather, tolerate temporary inconsistency. Resolve inconsistency with periodic sweeps through the data by a process that does only that. This centralizes the responsibility for maintaining consistency, while avoiding the performance and correctness problems that notifications are prone to. This results in code that is much smaller, error-free, and efficient.


问:
Using websockets for server “broadcasting”?
I want to make it possible to edit shared todo lists in real time.

There's already a REST interface, and it's possible to send updates to the server - add items, mark items as done, etc.

For the client to get these updates immediately, I did some research, and it seems that the best approach would be websockets, as they are quick and reliable. Push notifications on the other side can take "a few seconds" and are not reliable. I think I also saw something about "HTTP broadcasting" which did look more suitable for videos and things like that. Can't find it again.

So I was wondering, first, if websockets are really the best fit for this, second, if it's a good practice to use this in combination with REST - that is, I do the "push" from client A to server using a REST call, and then do the "push" from the server to client B using a websocket. Of course client B can also send updates to the server which have to be pushed to A (and other possible participants). So maybe it would be simpler to open websocket connections for both and throw out my REST code. On the other side a list can also have only 1 participant (the current user), in which case a websocket is not necessary, so maybe I could let these users use REST and switch to websockets only when there are more than 1 participants?

Does a mix of REST/websockets make sense for this application? Or should I stick to one or the other?

答:
If you want a complete WebSocket solution (there's no real need for REST unless you already have some REST framework on the server-side), there's an implementation of the shared todo canonical demo ToDoMVC by one of the Kaazing engineers that uses pub/sub with WebSocket.  Its written in Angular and uses a universal messaging API.

http://kaazing.org/demos/todomvc/todo


问:
Should my public webservices use HTTP or HTTPS?
The situation is a bit more complex than the title suggests (but not much).

I'm working on a REST API that will have a few open / publicly available resources and a few with authentication. (The latter is currently BasicAuth, but may in the future become something else.)

Obviously, I'd like to have HTTPS for the authenticated resources. But should I also use it for the open ones?

I can't decide between:

Using HTTP means less overhead and less fiddling with certificates for both server and client

Using HTTPS means a more homogenous setup, plus it hides the content from being read during transport

Thoughts?

答:
Is it a problem if anyone else is able to read the data you're transmitting (sending and receiving)?

Is it a problem if data that you transmit might be altered in route?

If the answer to either question is "yes," then you should be using HTTPS.

Obviously if the data you're sending is trivial and/or available elsewhere, then HTTP is fine. But if the users are sending email addresses, passwords, etc. (even if it's only for your site), then consider HTTPS.


答:
Just use LoC.

Exclude blank lines and comments.  If you're worried about differences in coding style, then you can use a tool like clang-format to try to standardize coding style.

Yeah, LoC has all kinds of limitations as a measure of project size or complexity - but so does anything else you could come up with, and LoC has the advantage of being easy to implement and easy and intuitive to understand. And, for all its limitations, it can at least give a rough comparison between different projects. Quoting Wikipedia:

Many useful comparisons involve only the order of magnitude of lines of code in a project. Using lines of code to compare a 10,000 line project to a 100,000 line project is far more useful than when comparing a 20,000 line project with a 21,000 line project. While it is debatable exactly how to measure lines of code, discrepancies of an order of magnitude can be clear indicators of software complexity or man hours.

Title: What are good ways to measure project size? How do I compare the size of my project to other projects?

Body:
Background

I am currently working for a quite large (relative to what I have done before) hobby project. I would like to compare the size of this project to other open-sourced projects but I cannot figure out how I should do that in a good and meaningful way.

Problems with using line count

I usually see project size being measured in line of code.

I do not consider that to be a good way to measure code size because then projects that have code that is styled like this:

```<code>int function(int argument_one, int argument_two) {
    int var1, var2, var3;
    code;
    code;
    if (test(var2, var3))
        code;
    else
        code;
    return var1;
}
</code>```

will appear about 40 % smaller than projects with code that is styled like this:

```<code>int function(int argument_one, int argument_two)
{
    int var1;
    int var2;
    int var3;

    code;
    code;

    if (test(var2, var3))
    {
        code;
    }
    else
    {
        code;
    }

    return var1;
}
</code>```

Other ways

Some other ways I have heard of are:

Character count

Comment count

Word count

Compilation time

But all of these has disadvantages. Comment count would make messy code with lots of comments appear longer. Compilation time is dependent on how fast the computer is and how the code is compiled. Word and character count are also highly dependent on how the code is styled.

Question

I am wondering if there are any more reliable ways to measure project size than the ones listed here.

What are more reliable ways to measure code size? Has there been attempts to come up with a universal way to measure code size? Are there any tools available that measures code size in a more meaningful way than simply counting lines/words/chars?


答: As a Information Security Analyst, the default answer is to go fully HTTPS (This might even be a good topic for the IS SE page.) The reason is pretty simple, your using HTTPS for you authenticated sources, at this point, you already have the complexity of using TLS, extending it to additional ports from a maintenance point is irrelevant. </p>

Title: Should my public webservices use HTTP or HTTPS?

Body:
The situation is a bit more complex than the title suggests (but not much).

I'm working on a REST API that will have a few open / publicly available resources and a few with authentication. (The latter is currently BasicAuth, but may in the future become something else.)

Obviously, I'd like to have HTTPS for the authenticated resources. But should I also use it for the open ones?

I can't decide between:

Using HTTP means less overhead and less fiddling with certificates for both server and client

Using HTTPS means a more homogenous setup, plus it hides the content from being read during transport

Thoughts?


问:
Does the Factory Pattern violate the Open/Closed Principle?
Why does this ShapeFactory use conditional statements to determine what object to instantiate. Dont we have to modify ShapeFactory if we want to add other classes in the future? Why doesnt this violate the open closed principle?

答:
The example probably uses a conditional statement because it is the simplest. A more complex implementation might use a map or configuration or (if you want to be really fancy) some kind of registry where the classes can register themselves. However there is nothing wrong with using a conditional if the number of classes is small and changes infrequently.

Extending the conditional to add support for a new subclass in the future would indeed strictly speaking be a violation of the open/closed principle. The "correct" solution would be to create a new factory with the same interface. That said, adherence to the O/C principle should always be weighed against other design principles like KISS and YAGNI.

That said, the code displayed is clearly example code which is designed to show the concept of a factory and nothing else. E.g. it is really bad style to return null as the example does, but more elaborate error handling would just obscure the point. Example code is not production quality code, any you shouldn't expect it to be.


问:
how to evaluate own project
I am working on a open source project in pure C, that I have started some time ago, but only recently found time to add some features. I can clearly some weaknesses of my old design, so I am trying to refactor my old code. I have no idea however, how to evaluate properly my new code. Do you know about any techniques or tools for code evaluation? I am pretty good with object oriented design, but for about three years I had no contact with purely structural one. Therefore I don't have enough experience, to be able to discern between good and bad design choices.

答: If you are looking for a simple answer, I would always keep in mind D.R.Y. Don't Repeat Yourself. If you have copy and pasted code from one area to another, you are probably doing it wrong. Cut and paste is fine, copy and paste not so much. Also if your code is hard to unit test then I would be concerned about the design.</p>

OwnerDisplayName: gruszczy

Title: how to evaluate own project

OwnerDisplayName: Clutch


答:
If you think about the Open-Close at class level with this factory you are making other class in your system Open-Close, for example if you have other class that take one Shape and calculate the area (typical example) this class is OpenClose because it can calculate the area for new types of shapes without modification. Then you have another class that draws the shape, another class that take N shapes and return the bigger one and you can think in general that the other classes in your system that deals with shapes are Open-Close (at least about shapes). Looking at the design the factory enables the rest of the system to be Open-Close and off course the factory itself ITS NOT Open-Close.

Off course you can make this factory open-close too, via some kind of dynamic loading and your entire system can be Open-Close (you can add new shapes dropping some jar in the classpath for example). You need to evaluate is this extra complexity is worth depending on the system your are building, not all systems need pluggable features and not all the system need to be completely Open-Close.

Title: Does the Factory Pattern violate the Open/Closed Principle?

Body: Why does this ShapeFactory use conditional statements to determine what object to instantiate. Dont we have to modify ShapeFactory if we want to add other classes in the future? Why doesnt this violate the open closed principle?


问:
Background Threads in Horizontally Scaled Application
I have what I believe is a fairly common situation these days: I have a webapp that scales horizontally across multiple machines in order to serve greater load. This particular application is written in Java.

On this same webapp, I find that I have a need to run a background process in this webapp periodically. However, this process executes requests against another service, and I don't believe it would be safe to have multiple invocations of this process going at once.

It would be easiest to just get a new machine that runs these background processes by itself. However, company policies make it difficult to get new machines, so I'm trying to investigate other options in case this isn't possible. This means I'm trying to figure out how to make just one machine at a time run this background process at once. I've thought about some of the following ways:

Figure out how to make one machine the "leader" and be the only one to execute these periodic background tasks. This is complicated by the fact that I'm running on an AWS auto-scale group, so this leader could be killed at any time, so I'm stuck with needing to do leader election on my own.

Establishing a mutex of some kind that each instance must grab before it executes. I've thought about using an in-memory data grid like Hazelcast for this, but that seems a bit heavyweight to set up and use just for this.

What are some good ways of achieving my goal of running this background process in my webapp and making sure it only runs once?

答:
Can you add another piece of software to your architecture? If so, I would recommend you to use some sort of queue, let's say RabbitMQ, for that matter.

In this scenario, you won't have to worry about managing which process is running at a given moment (or will run next). They stay there waiting for a job requisition to arrive via queue. One of them will "take the order" to start the request to the external service. I see this as an out of box implementation for your idea of a "mutex".

What you have to figure is how to enqueue this "now we need a new request for an external service" trigger.


答:
If your distributed webapp uses a shared database, you can implement your suggested mutext by using a database table row and locking.

But I think the best and sound solution would be to use a dedicated machine and service that runs this background process on it's own dedicated machine. If cost is the issue then you can minimize the cost by only having the machine up and running periodically when the request is going to be made.

Title: Background Threads in Horizontally Scaled Application

Body:
I have what I believe is a fairly common situation these days: I have a webapp that scales horizontally across multiple machines in order to serve greater load. This particular application is written in Java.

On this same webapp, I find that I have a need to run a background process in this webapp periodically. However, this process executes requests against another service, and I don't believe it would be safe to have multiple invocations of this process going at once.

It would be easiest to just get a new machine that runs these background processes by itself. However, company policies make it difficult to get new machines, so I'm trying to investigate other options in case this isn't possible. This means I'm trying to figure out how to make just one machine at a time run this background process at once. I've thought about some of the following ways:

Figure out how to make one machine the "leader" and be the only one to execute these periodic background tasks. This is complicated by the fact that I'm running on an AWS auto-scale group, so this leader could be killed at any time, so I'm stuck with needing to do leader election on my own.

Establishing a mutex of some kind that each instance must grab before it executes. I've thought about using an in-memory data grid like Hazelcast for this, but that seems a bit heavyweight to set up and use just for this.

What are some good ways of achieving my goal of running this background process in my webapp and making sure it only runs once?


问:
Are there any compilers that attempt to fix syntax errors on their own?
I heard a while back that there used to be a compiler that attempted to fix syntax errors by analyzing context and inferring what was intended.

Does such a compiler really exist? Obviously it has little practical value, but would be very interesting to play with and learn from.

答: When I was coding FORTRAN and PL/I back in the late 80s and early 90s on DEC and IBM minicomputer and mainframe systems, I seem to remember the compilers would regularly log out messages like "blah blah error; assuming blah blah and continuing...".  Back then, this was a legacy of the (even earlier, before my time) days of batch processing and punched cards when there was likely an enormous wait between submitting your code to run and getting the results back.  So it made a lot sense for compilers to make an attempt to second-guess the programmer and carry on rather than abort on the first mistake encountered.  Mind you, I don't remember the "corrections" being particularly sophisticated.  When I eventually moved onto interactive Unix workstations (Sun, SGI etc), I did notice the feature seemed to be entirely absent from their C compilers.</p>


问:
Docstring convention for Python __str__, __unicode__, and __repr__ class methods
What is the docstring convention in Python for the following "magic" class methods:

__str__

__unicode__

__repr__

Should I add docstrings for these? If yes, what should they say (for each)?

答: I wouldn't add docstrings; they'll never meaningfully differ from the python stdlib docs relating to them.</p>


问:
Should defects have story points in Scrum?
As far as I know, we use story points to measure the complexity of a story in Scrum.

But what about Defect? Should Defect have story points? If it does, what does it mean by completing these points, given that a Defect doesn't have business value like a story? Should we have something different from story points, for example, defect points?

答:
[...] given that a Defect doesn't have business value like a story?

I disagree with this. As a user, I want my software product to work and behave as intended. A known defect goes against this. Accumulate and ignore enough defects and sooner or later your customer(s) will stop using your product and use someone else's instead.

This is something known as retained revenue1, which includes customer(s) that would leave if something the customer wants/needs is not done. This is often mentioned in terms of features, but it can also include defects. (Can you honestly claim your product has some feature X if said feature is broken? I don't think so.)

Since it is assumed that when a feature or story is accepted as "done" it works as expected, it's perfectly valid to create another story and estimate it in the same way as you normally do, especially if the defect is discovered by the customer(s) after release. If the defect is known prior to release, then perhaps the Product Owner should've rejected the "done" status for the story and moved it back to "In Progress" or a equivalent status, but not call it "done".

Should we have something different from story points, for example,
  defect points?

No. Just treat it like any other story in your team's backlog with a size estimate for its effort/complexity and a priority that's relative to other stories.

Since defects are an example of "Technical Debt", and bugs become more expensive to fix the more their resolution is delayed after being discovered, the team and P.O. should consider giving defects a slightly higher priority. What you use to determine this priority (e.g. visibility, customer annoyance, something else?) should be up to your team.

Just my 2 cents.

1 Agile Estimation and Planning, by M. Cohn

OwnerDisplayName: Hackjustu

OwnerDisplayName: ray


答:
If you are properly linking defects to your user stories (whether directly or indirectly), then you should have backward traceability.  So the story points that are affected by the defect are your reference.
From that, if you have already estimated each story point's complexity/size/effort that can help you estimate the defect's complexity/size/effort.</p>

Title: Should defects have story points in Scrum?

Body:
As far as I know, we use story points to measure the complexity of a story in Scrum.

But what about Defect? Should Defect have story points? If it does, what does it mean by completing these points, given that a Defect doesn't have business value like a story? Should we have something different from story points, for example, defect points?

OwnerDisplayName: Andarta


答: My team put story points on any defect identified after the sprint in which the story was completed.  If the defect is found during the sprint that the story is being developed we consider those acceptance bugs and are part of the original estimate of the story.</p>