问:
Difference between Signal/Slot and DataBusPattern
I'm just trying to figure out what makes the Signal/Slot (Pattern?). Wikipedia tells me not so much and calls it an implementation of the ObserverPattern* while I would think it has much more resemblance to the DataBusPattern**.

Can someone explain in an abstract way what Signal/Slot is? Do the participants in Signal/Slot need to know each other (as in ObserverPattern) or not (as in DataBusPattern) and what are the key differences?

I tried to figure it out reading the QT docs, but there is to much C++ magic.

*) http://c2.com/cgi/wiki?ObserverPattern

**) http://c2.com/cgi/wiki?DataBusPattern

答:
The connection information between a signal and a slot is completely held between the connected sender and receiver objects.  See here for more information.  A connect operation is always given between two concrete instances, and the programmer must know about both of them.  One is doing the publishing, one is doing the subscribing.  You can connect many signals to one slot, and many slots to one signal, but each connection is made individually.

In a data bus pattern, you don't make individual connections.  You just broadcast your events onto the bus, and every receiver on the bus receives every single event.  They can choose not to do anything with certain events, but they can't choose not to receive them at all.


问:
How should I handle logger failures?
In several of our company's applications, we use a custom logger. It's fairly robust, though we may replace it with something like NLog in the future. One of the logger's tasks is to log any exceptions encountered in the application.

One concern I've always had is that the exception handling within the logger allows for a silent failure. That is, if the log isn't written for a given exception (due to an error in the logger), how should I handle it and (somehow) log the exception in the logger itself?

Let's say the WriteLog function throws an exception. Should I try to call the function some number of times or until the exception isn't thrown? Should I try to write the thrown exception with the logger (which would likely just result in exceptions all the way down. . .)? I have been lucky enough to not encounter this situation except when we were first implementing the custom logger. On the other hand, I have no way of knowing at the moment if the logger has failed to log application exceptions (due to its own exceptions).

I have tried searching online and on some SE sites, but it's been fruitless so far since all the posts deal with errors in a logger (but not potential exceptions and how to log them) or with exceptions outside the logger.

答:
When you encounter exceptions within the logger itself, you shouldn't use the logger to log its own exceptions. The reason for that is that:

You may be stuck in an infinite loop. Imagine that within your logger, you have a conditional branch which wasn't tested (and generates an exception). Imagine that once the condition is met, any further reported exception is handled by the same branch. This means that from the moment the branch is executed, you're in an infinite loop.

You may be stuck in a temporary loop, generating thousands of exceptions per second. Imagine you're reporting exceptions to a remote server. An issue with the server causes another exception, which causes another one, and so on, until the connection is back.

What you should do instead is to fallback to a safer way to log the exceptions. For example, if your logger sends the exceptions to a remote server, send the exceptions within the logger to syslog instead. If your logger records exceptions in Windows Events and this action fails, store the failure exception in a simple text file.

Once you have that, the next question is how do you know that those exceptions occurred: if you have dozens of applications running on thousands of servers, you can't possibly SSH each of them on regular basis to check whether they were logging something locally.

One way is to have a cron job which checks for those “exceptional logs” and pushes them to the location where other exceptions are stored (eventually using your logger, but beware of infinite or temporary loops!).

ContentLicense: CC BY-SA 3.0

Title: How should I handle logger failures?


问:
Replacing Throwing Exceptions with Notification in Validations
Martin Fowler recommends replacing exceptions with notifications when dealing with validations.  Essentially, instead of throwing an exception, you append error messages to a Notification object that gets returned.  This allows you to keep exceptions to "exceptional" circumstances, and return all the validation information, not just the first one checked.

The idea makes all sense.  However, how do you apply this idea in cases where a method does some user input validation but also returns an object?

答:
By adding some metadata to your object, either by inheriting from an abstract class that contains that data, writing a composite object, or something similar.

In ASP.NET MVC 1, this would have been done by attaching a partial class to your entity (In the C# language, classes having the same name with the modifier partial in front of them are merely treated like one big single class).

So, for example:

public partial class Dinner {

    public bool IsValid {
        get { return (GetRuleViolations().Count() == 0); }
    }

    // Return a list of errors that we can iterate over with `foreach`
    public IEnumerable<RuleViolation> GetRuleViolations() {

        // Validation rules go here; see below for an example.

        yield break;
    }

    partial void OnValidate(ChangeAction action) {
        if (!IsValid)
            throw new ApplicationException("Rule violations prevent saving");
    }
}
```

<p>A Rule Violation is just an immutable object containing an Error Message and a Property Name:</p>

<pre class="lang-cs prettyprint-override"><code>public class RuleViolation {

    public string ErrorMessage { get; private set; }
    public string PropertyName { get; private set; }

    public RuleViolation(string errorMessage, string propertyName) {
        ErrorMessage = errorMessage;
        PropertyName = propertyName;
    }
}
</code>```

You would then check for errors like this:

public IEnumerable<RuleViolation> GetRuleViolations() {

    if (String.IsNullOrEmpty(Title))
        yield return new RuleViolation("Title required","Title");

    if (String.IsNullOrEmpty(Description))
        yield return new RuleViolation("Description required","Description");

    if (String.IsNullOrEmpty(HostedBy))
        yield return new RuleViolation("HostedBy required", "HostedBy");

    if (String.IsNullOrEmpty(Address))
        yield return new RuleViolation("Address required", "Address");

    if (String.IsNullOrEmpty(Country))
        yield return new RuleViolation("Country required", "Country");

    if (String.IsNullOrEmpty(ContactPhone))
        yield return new RuleViolation("Phone# required", "ContactPhone");

    if (!PhoneValidator.IsValidNumber(ContactPhone, Country))
        yield return new RuleViolation("Phone# does not match country", "ContactPhone");

    yield break;
}
```

<p>This arrangement allows you to pass the errors back to a view so that they can be displayed to the user, like so  (This is a controller method; it accepts a form POST from a user web form):</p>

<pre class="lang-cs prettyprint-override"><code>[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, FormCollection formValues) {

    Dinner dinner = dinnerRepository.GetDinner(id);

    try {

        // Map form fields to dinner object
        UpdateModel(dinner);

        // Validation occurs here.  Throws exception if validation fails
        dinnerRepository.Save();

        return RedirectToAction("Details", new { id=dinner.DinnerID });
    }
    catch {

        // Add each rule violation to the View, so that errors can be displayed.
        foreach (var issue in dinner.GetRuleViolations()) {
            ModelState.AddModelError(issue.PropertyName, issue.ErrorMessage);
        }

        // Display form with validation errors.
        return View(dinner);
    }
}
</code>```

Note that the exception is there only to trigger the validation handling process; there isn't an exception for every possible validation error.  Instead, the validation rules are encoded in the GetRuleViolations() method, and they are all handled at once.

Of course, nowadays, the process has become a bit more refined.  In the newer versions of ASP.NET MVC, attributes are used to encode the validation rules.  But the principle is still the same: you don't use exceptions to encode individual validation rules.  Notice the validation metadata that is encoded in the attributes of the code below (the attributes are those lines of code that are surrounded by brackets):

public class Movie
{
    public int ID { get; set; }

    [StringLength(60, MinimumLength = 3)]
    public string Title { get; set; }

    [Display(Name = "Release Date")]
    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
    public DateTime ReleaseDate { get; set; }

    [RegularExpression(@"^[A-Z]+[a-zA-Z''-'\s]*$")]
    [Required]
    [StringLength(30)]
    public string Genre { get; set; }

    [Range(1, 100)]
    [DataType(DataType.Currency)]
    public decimal Price { get; set; }

    [RegularExpression(@"^[A-Z]+[a-zA-Z''-'\s]*$")]
    [StringLength(5)]
    public string Rating { get; set; }
}
```

Body:
By adding some metadata to your object, either by inheriting from an abstract class that contains that data, writing a composite object, or something similar.

In ASP.NET MVC 1, this would have been done by attaching a partial class to your entity (In the C# language, classes having the same name with the modifier partial in front of them are merely treated like one big single class).

So, for example:

public partial class Dinner {

    public bool IsValid {
        get { return (GetRuleViolations().Count() == 0); }
    }

    // Return a list of errors that we can iterate over with `foreach`
    public IEnumerable<RuleViolation> GetRuleViolations() {

        // Validation rules go here; see below for an example.

        yield break;
    }

    partial void OnValidate(ChangeAction action) {
        if (!IsValid)
            throw new ApplicationException("Rule violations prevent saving");
    }
}

A Rule Violation is just an immutable object containing an Error Message and a Property Name:

public class RuleViolation {

    public string ErrorMessage { get; private set; }
    public string PropertyName { get; private set; }

    public RuleViolation(string errorMessage, string propertyName) {
        ErrorMessage = errorMessage;
        PropertyName = propertyName;
    }
}

You would then check for errors like this:

public IEnumerable<RuleViolation> GetRuleViolations() {

    if (String.IsNullOrEmpty(Title))
        yield return new RuleViolation("Title required","Title");

    if (String.IsNullOrEmpty(Description))
        yield return new RuleViolation("Description required","Description");

    if (String.IsNullOrEmpty(HostedBy))
        yield return new RuleViolation("HostedBy required", "HostedBy");

    if (String.IsNullOrEmpty(Address))
        yield return new RuleViolation("Address required", "Address");

    if (String.IsNullOrEmpty(Country))
        yield return new RuleViolation("Country required", "Country");

    if (String.IsNullOrEmpty(ContactPhone))
        yield return new RuleViolation("Phone# required", "ContactPhone");

    if (!PhoneValidator.IsValidNumber(ContactPhone, Country))
        yield return new RuleViolation("Phone# does not match country", "ContactPhone");

    yield break;
}

This arrangement allows you to pass the errors back to a view so that they can be displayed to the user, like so  (This is a controller method; it accepts a form POST from a user web form):

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, FormCollection formValues) {

    Dinner dinner = dinnerRepository.GetDinner(id);

    try {

        // Map form fields to dinner object
        UpdateModel(dinner);

        // Validation occurs here.  Throws exception if validation fails
        dinnerRepository.Save();

        return RedirectToAction("Details", new { id=dinner.DinnerID });
    }
    catch {

        // Add each rule violation to the View, so that errors can be displayed.
        foreach (var issue in dinner.GetRuleViolations()) {
            ModelState.AddModelError(issue.PropertyName, issue.ErrorMessage);
        }

        // Display form with validation errors.
        return View(dinner);
    }
}

Note that the exception is there only to trigger the validation handling process; there isn't an exception for every possible validation error.  Instead, the validation rules are encoded in the GetRuleViolations() method, and they are all handled at once.

Of course, nowadays, the process has become a bit more refined.  In the newer versions of ASP.NET MVC, attributes are used to encode the validation rules.  But the principle is still the same: you don't use exceptions to encode individual validation rules.  Notice the validation metadata that is encoded in the attributes of the code below (the attributes are those lines of code that are surrounded by brackets):

public class Movie
{
    public int ID { get; set; }

    [StringLength(60, MinimumLength = 3)]
    public string Title { get; set; }

    [Display(Name = "Release Date")]
    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
    public DateTime ReleaseDate { get; set; }

    [RegularExpression(@"^[A-Z]+[a-zA-Z''-'\s]*$")]
    [Required]
    [StringLength(30)]
    public string Genre { get; set; }

    [Range(1, 100)]
    [DataType(DataType.Currency)]
    public decimal Price { get; set; }

    [RegularExpression(@"^[A-Z]+[a-zA-Z''-'\s]*$")]
    [StringLength(5)]
    public string Rating { get; set; }
}


答:
If logging is critical to your application, then one should stop the application if logging fails.

If not critical, then being somewhat defensive one could have a secondary component to handle logging failures that logs/alerts to a secondary source.  But even that is not fool proof and you will have to consider what happens if the secondary logger fails while it is monitoring the primary logger.

A good strategy is logging to a local file and if that fails, maybe logging that failure to the event log, generating an email alert, saving to a database, etc.  With the logging frameworks that are available this should be foolproof unless the machine runs out of disk space or some other rare condition.

Ideally your better off failing silently as that will make the application less complex.

More importantly, to handle logging failures one should be monitoring the logs from a 3rd party.  Over time you should be able to discern how many events a healthly application is logging.  If it starts logging low or no events, then through monitoring you can see the problem occurring and potentially alert through that 3rd party mechanism.

Title: How should I handle logger failures?

Body:
In several of our company's applications, we use a custom logger. It's fairly robust, though we may replace it with something like NLog in the future. One of the logger's tasks is to log any exceptions encountered in the application.

One concern I've always had is that the exception handling within the logger allows for a silent failure. That is, if the log isn't written for a given exception (due to an error in the logger), how should I handle it and (somehow) log the exception in the logger itself?

Let's say the WriteLog function throws an exception. Should I try to call the function some number of times or until the exception isn't thrown? Should I try to write the thrown exception with the logger (which would likely just result in exceptions all the way down. . .)? I have been lucky enough to not encounter this situation except when we were first implementing the custom logger. On the other hand, I have no way of knowing at the moment if the logger has failed to log application exceptions (due to its own exceptions).

I have tried searching online and on some SE sites, but it's been fruitless so far since all the posts deal with errors in a logger (but not potential exceptions and how to log them) or with exceptions outside the logger.


问:
Searching algorithm used in switch statement
What is the searching algorithm used in switch statement in C language?

If the cases are not in order still it searches proper case which means it is not a binary search algorithm, can anybody explain?

答: Generally, switch statements are implemented as Jump Tables. There is no searching involved.</p>


问:
What parts of your coding standard contribute to quality code?
In response to This Question, I ask:   What are the best parts of your coding standard?

What are the best practices that help with code quality, reliability, maintainability, readability, etc.

Please include the language, the item from the standard, and the reason it improves your code.

答:
C#: Differing naming styles for different types of names.

For example:

```<code>public class ClassNamesArePascalCase{
    public int FieldsArePascalCase;
    private int _privateFieldsAreUnderscoredCamelCase
    public const int CONSTANTS_ARE_CAPITAL = 3;

    public void MethodNamesArePascalCase( string parametersAreCamel ){
        int localVariablesAreCamel;
    }
}
</code>```

It doesn't matter so much which standards you use for which name types, as long as it's consistent among that type (eg, all constants are capital), consistent within the project, and different from eachother.  The benefit here is that I can tell at a glance that _someVar is a private field without having to look it up.

ContentLicense: CC BY-SA 2.5

Body:
C#: Differing naming styles for different types of names.

For example:

public class ClassNamesArePascalCase{
    public int FieldsArePascalCase;
    private int _privateFieldsAreUnderscoredCamelCase
    public const int CONSTANTS_ARE_CAPITAL = 3;

    public void MethodNamesArePascalCase( string parametersAreCamel ){
        int localVariablesAreCamel;
    }
}

It doesn't matter so much which standards you use for which name types, as long as it's consistent among that type (eg, all constants are capital), consistent within the project, and different from eachother.  The benefit here is that I can tell at a glance that _someVar is a private field without having to look it up.


答:
Several options:

the naive method would be an if else cascade (slow)

the compiler can sort the cases behind the scene and then do a binary search (good for disjoint cases)

a jump table; only good for sequential cases but very fast.

For string-based switches there is the option of the prefix Trie, a sorted table that can be binary searched or the strings are hashed and used for the cases of a switch against the hash of the input string with a double check in each case.

Title: Searching algorithm used in switch statement

Body:
What is the searching algorithm used in switch statement in C language?

If the cases are not in order still it searches proper case which means it is not a binary search algorithm, can anybody explain?


问:
CSS: When to use which selector
I've been learning HTML5/CSS3 for a month now, and I've built my first demo website. At first I was using a lot of the element selectors like: >, ,, + in combination with the type names for selecting nested tags.

Now I've moved more to the id and class selectors and use the >, ,, + less often for selecting nested tags.

Is using id and class selectors a better approach for selecting tags which are (deeply) nested? Are there any downsides to this approach? Or is it just a matter of style?

答:
I think it's a little bit of personal preference, however I typically choose to use class names over anything else so that if I decide to add/remove a layer of nesting than I won't break my selector.

So while I might put a class on a "toolbar" div, I might not decorate a contained ul or individual items. I would select the container based on class, then know that what's underneath that are toolbar buttons.

As with most things related to CSS, trial and error wins the day - best of luck to you!

Title: CSS: When to use which selector


答:
This is not only a matter of style. It is a matter of performance and maintainability. Anecdotally, some selectors are difficult to implement efficiently for browsers. For example, the general sibling selector A ~ B or the descendant selector A B. And of course the universal selector *. Unless actually needed, these should be avoided. The thing that is really fast is using class names or IDs. The comma A, B  is not considered a selector.

When you start out with CSS, you might be tempted to write something like ul.#steps > li.item-without-bullet. That is not good for various reasons:

Do not use IDs in selectors, because any ID can only be used once in a document. This prevents you from re-using the styling.

Avoid element names in selectors. HTML is meant to be used as semantic markup that highlights what each element means. This should be kept mostly separate from the styling. You will still want to style elements directly (e.g. using a different font only for headings, or setting the line height for paragraphs). That is OK, and I wouldn't use classes for that (yuck), but you shouldn't refer to the element names when styling something special such as a nav bar, or an image carousel, or a pull quote, or ….

Avoid ID and class names that focus too much on what text effect they provide (you might as well use inline style attributes), and instead use class names as custom elements or element modifiers, as a way to add your own semantics. A class such as red-text is not as “semantic” as error--fatal.

Avoid the descendant selector A B  and the child selector A > B. You can usually encode the necessary information through your class names, e.g. steps  and steps__step. You can trust that whoever is applying the classes to the HTML structure will respect proper nesting, given sufficiently self-documenting class names.

Seriously consider a strict naming scheme such as BEM (Block Element Modifier). Yes, it's incredible overkill, but using the BEM naming scheme can help you to properly structure your CSS. It exclusively uses class names, and does not generally use selectors.

Title: CSS: When to use which selector

Body:
I've been learning HTML5/CSS3 for a month now, and I've built my first demo website. At first I was using a lot of the element selectors like: >, ,, + in combination with the type names for selecting nested tags.

Now I've moved more to the id and class selectors and use the >, ,, + less often for selecting nested tags.

Is using id and class selectors a better approach for selecting tags which are (deeply) nested? Are there any downsides to this approach? Or is it just a matter of style?


问:
Saving an object via a method of its own or via another class?
If I want to save and retrieve an object, should I create another class to handle it, or would it better to do that in the class itself? Or maybe mixing both?

Which is recommended according to OOD paradigm?

For example

```<code>Class Student
{
    public string Name {set; get;}
    ....
    public bool Save()
    {
        SqlConnection con = ...
        // Save the class in the db
    }
    public bool Retrieve()
    {
         // search the db for the student and fill the attributes
    }
    public List<Student> RetrieveAllStudents()
    {
         // this is such a method I have most problem with it
         // that an object returns an array of objects of its own class!
    }
}
</code>```

Versus. (I know the following is recommended, however it seems to me a bit against the cohesion of Student class)

```<code>Class Student { /* */ }
Class DB {
  public bool AddStudent(Student s)
  {

  }
  public Student RetrieveStudent(Criteria)
  {
  }
  public List<Student> RetrieveAllStudents()
  {
  }
}
</code>```

How about mixing them?

```<code>   Class Student
    {
        public string Name {set; get;}
        ....
        public bool Save()
        {
            /// do some business logic!
            db.AddStudent(this);
        }
        public bool Retrieve()
        {
             // build the criteria
             db.RetrieveStudent(criteria);
             // fill the attributes
        }
    }
</code>```

答:
Define a method on that class that serializes the object, and returns a sequence of bytes that you can put in a database or file or whatever

Have a constructor for that object that takes such a sequence of bytes as input

About the RetrieveAllStudents() method, your feeling is right, it is indeed probably misplaced, because you might have multiple distinct lists of students. Why not simply keep the list(s) outside of the Student class ?


问:
Is a developer-driven product a good thing?
I work in a company where the CEO manages the product team, who mockup features and drop in the lap of developers to then implement said features. There is some iteration of course, developer's opinions are respected. But I wonder how effective this process is.

Jason Calacanis just wrote :

The Zuckerberg Doctrine: Developers
  design products with significantly
  improved speed and functionality
  compared to product managers and
  designers, outweighing potential
  mistakes and drawbacks.

...

Then it really hit me:
  Developer-driven startups always
  produce product faster.

This stands to reason: our
  nontechnical people are having
  discussions and debates while
  Zuckerberg is coding his next feature.
  This is why no one has been able to
  keep up with Facebook!

While MySpacers debated how to iterate
  on their product, Facebook simply
  tried stuff.

Does this actually work better in practice ?

答:
Short answer: sometimes.

Long Answer:
Customer-drive development works if you know who your customers are and they know what they want.

Developer-driven development has merit for people that don't realise they will find it useful yet. In other words, sometimes customers can't always know what they want. New Requirements can come from an existing experience of how an existing product is deficient. There weren't any customers for Facebook, Zuckerberg created a product, an answer before the question. Now established, Facebook is influenced by its customers, but before it was created and during creation, it was a developer-driven idea.

Customer driven development is ideal for established, perhaps mature product making money or new iterations of the product in the same market, where ignoring the customer's wishes would be highly detrimental to future income streams.

Developer-driven development is a sideline, prototyping activity, falling within the Google 20% arena, whereby their developers spend 20% of their working time on own projects.


答:
Each type of css selector has its place. The progression of usage you describe is natural because it mirrors the progression of design from general to specific. There are several selector types to help us fulfill our design goals (I've given two examples of each in parenthesis):

element selectors (p, div) to establish overall styling

state selectors (:hover, :checked) to provide feedback on user interaction

class selectors (.nav, .span5) to further style groups of similar elements

id selectors (#container, #result) to customize unique elements

attribute selectors ([target=_blank], [lang|=en]) to vary style with attribute values

position selectors (::after, ::first-line) for finer control

relation selectors (A B, A > B) are not as efficient, but can be useful

Title: CSS: When to use which selector


问:
Scrum and backlogged issues
I run a development team that recently started using Jira and we began using agile scrum. I'm curious about a certain aspect of backlogged issues.

So far I have been marking new issues as unassigned until the issues are actually assigned to anyone. Most of the time this process is done during the sprint planning meeting.

A different team leader began assigning my name to the unassigned issues and changed the setting to the default assignee is myself rather than "unassigned". Does this sound logical?

答:
A different team leader began assigning my name to the unassigned issues and changed the setting to the default assignee is myself rather than "unassigned". Does this sound logical?

What happens when the task is not in the project backlog - are you removing your name?

It isn't the end of the world to put your name there as a default if you remove it when it becomes defined/moved to the sprint.  Just an annoyance. Your name there effectively will mean "unassigned."

Regardless you definitely don't want to actually assign tasks to developers directly as the lead or you will result in blockage/bogging your team down.

So, basically:

If it's only a temporary thing (IE until it's defined or put into the current sprint) then it doesn't matter other than it creates extra overhead as you have to remove your name when it's moved from the product backlog.

If you have had problems with people starting tasks in your backlog prior because they are "unassigned" then address this - don't assign yourself story to get around this, deal with how people are picking up unassigned tasks.

If you are actually working on user stories yourself then you definitely don't want to have your name there because you will not have a good way to ever see who has started tasks if they get moved back into the backlog.

Title: Scrum and backlogged issues


答:
I think how you manage your Jira is really up to you and your team. We use a different issue tracking system to Jira that has the ability to create "virtual accounts". Our last lead developer used to like all issues assigned to him which he would then dish out.

When I took over temporarily I created a virtual account called "Up For Grabs" and moved all un-assigned work to this account. I did this because I didn't want people thinking that work was being done because it was assigned to someone (me) when it was not. So I moved anything that was not being worked on to this account. Since our new team leader has joined us and we have adopted scrum, we have kept the Up For Grabs account and used that as our default assignee. We find this works best because no one in our team assigns work out, instead we pick up tasks ourselves from the current sprint.  This also means no one has anything else attached to them other than what they're currently working on.

However if you have multiple teams it could potentially get confusing. I'm not very familiar with Jira but perhaps having something you can assign it to that is called something like "Team X - Up For Grabs" or something akin to a virtual user (not attached to any team member individually). This would mean your other team leaders don't get confused with unassigned work, but you also don't have a swamped account with loads of assigned work.

Title: Scrum and backlogged issues

Body:
I run a development team that recently started using Jira and we began using agile scrum. I'm curious about a certain aspect of backlogged issues.

So far I have been marking new issues as unassigned until the issues are actually assigned to anyone. Most of the time this process is done during the sprint planning meeting.

A different team leader began assigning my name to the unassigned issues and changed the setting to the default assignee is myself rather than "unassigned". Does this sound logical?


答:
I've always seen the practice that once an issue is assigned, that person takes ownership follows it through to completion (unless there's a reason to pass it off).

Assigning every issue to a default person who then routes it to someone else seems like unnecessary handling of each issue. All that interaction will really add up over time.

Title: Scrum and backlogged issues


答:
To design a good product, you need a lot of knowledge about the problem domain. A general-public product like facebook can be driven by developers, because it solves a problem developers have, too: How to connect and stay in touch with friends etc.
The same is even more true for products aimed at software developers: Developers know what an IDE should do and how.

But for many other problem domains, developers often just don't know enough. Even with a general insight and some experience, they will often tend to implement cool features or features that are easy to implement, but do not add much value for the customer and make the product more complex. These are cases where products should be driven by domain experts.

Title: Is a developer-driven product a good thing?

Body:
I work in a company where the CEO manages the product team, who mockup features and drop in the lap of developers to then implement said features. There is some iteration of course, developer's opinions are respected. But I wonder how effective this process is.

Jason Calacanis just wrote :

The Zuckerberg Doctrine: Developers
  design products with significantly
  improved speed and functionality
  compared to product managers and
  designers, outweighing potential
  mistakes and drawbacks.

...

Then it really hit me:
  Developer-driven startups always
  produce product faster.

This stands to reason: our
  nontechnical people are having
  discussions and debates while
  Zuckerberg is coding his next feature.
  This is why no one has been able to
  keep up with Facebook!

While MySpacers debated how to iterate
  on their product, Facebook simply
  tried stuff.

Does this actually work better in practice ?


答:
If it's a very simple app where the object is more or less tied to the datastore and visa-versa (i.e. can be thought of as a property of the datastore), then having a .save() method for that class might make sense.

But I think that would be pretty exceptional.

Rather, it's usually better to let the class manage its data and its functionality (like a good OO citizen), and externalize the persistence mechanism to another class, or set of classes.

The other option is to use a persistence framework that defines persistence declaratively (like with annotations), but that's still externalizing the persistence.

Title: Saving an object via a method of its own or via another class?

Body:
If I want to save and retrieve an object, should I create another class to handle it, or would it better to do that in the class itself? Or maybe mixing both?

Which is recommended according to OOD paradigm?

For example

```<code>Class Student
{
    public string Name {set; get;}
    ....
    public bool Save()
    {
        SqlConnection con = ...
        // Save the class in the db
    }
    public bool Retrieve()
    {
         // search the db for the student and fill the attributes
    }
    public List<Student> RetrieveAllStudents()
    {
         // this is such a method I have most problem with it
         // that an object returns an array of objects of its own class!
    }
}
</code>```

Versus. (I know the following is recommended, however it seems to me a bit against the cohesion of Student class)

```<code>Class Student { /* */ }
Class DB {
  public bool AddStudent(Student s)
  {

  }
  public Student RetrieveStudent(Criteria)
  {
  }
  public List<Student> RetrieveAllStudents()
  {
  }
}
</code>```

How about mixing them?

```<code>   Class Student
    {
        public string Name {set; get;}
        ....
        public bool Save()
        {
            /// do some business logic!
            db.AddStudent(this);
        }
        public bool Retrieve()
        {
             // build the criteria
             db.RetrieveStudent(criteria);
             // fill the attributes
        }
    }
</code>```


问:
Permutting a list of numbers in order to get a list which satisfies given condition
Here is algorithmic problem I'm trying to solve:

Given a list [x_1,x_2,...,x_n] return a permutation of elements of the list [y_1,y_2,...,y_n] (where for each i we have y_i = x_j for only one j) which maximises the sum from k=1 to k=n-1 of |y_k-y_(k+1)|.

So to make it simpler - we get a list of integers and we need to "shuffle" these numbers in such a way, that we get a list where where we take sum of all |y_m-y_n| such that y_m and y_n are next to each other, we get a maximum possible number of all permutations of the elements in list.

I think this can be solved in O(n*log n), I thought of sorting the list and returning a list where first element is maximum element,  next element is minimum, next is maximum of those left, etc... But this leads to nowhere, I cannot prove that it's correct, so probably it isn't. So, any tips how to tackle this problem?

答:
Believe it or not, this problem is solvable in time O(n).

First, let m be the median of the array.  For a pair (x, y) that are next to each other, define the contribution of x from that pair to be:

```<code>def contribution (x, y, m):
    if m < x:
        if x < y:
            return 0
        elif y < m:
            return x - m
        else:
            return x - y
    else:
        if y < x:
            return 0
        elif m < y:
            return m - x
        else:
            return y - x
</code>```

This definition is kind of complex, but note that contribution(x, y, m) + contribution(y, x, m) == |x - y|. And the sum you are looking for is the sum of all of the contributions of all elements to both pairs.

The way to maximize the contribution of an element is to have it with elements on the other side of the median next to it on each side.  What elements don't matter, just on the other side of the median.  And the elements on the edge only do half their contribution, so it is clear that you want the two elements that are closest to the median on the ends.  So this tells us exactly what the permutation that we want is.  We want the two elements on the ends to be as close to the median as possible, while alternating above/below.

Now that we understand this, we can use http://en.wikipedia.org/wiki/Quickselect to find the median in O(n) time.  Partitioning the array, and identifying the two elements to put on the end can then be done in O(n) time.  And then interleaving it is also O(n) for a O(n) algorithm.

Body:
Believe it or not, this problem is solvable in time O(n).

First, let m be the median of the array.  For a pair (x, y) that are next to each other, define the contribution of x from that pair to be:

def contribution (x, y, m):
    if m < x:
        if x < y:
            return 0
        elif y < m:
            return x - m
        else:
            return x - y
    else:
        if y < x:
            return 0
        elif m < y:
            return m - x
        else:
            return y - x

This definition is kind of complex, but note that contribution(x, y, m) + contribution(y, x, m) == |x - y|. And the sum you are looking for is the sum of all of the contributions of all elements to both pairs.

The way to maximize the contribution of an element is to have it with elements on the other side of the median next to it on each side.  What elements don't matter, just on the other side of the median.  And the elements on the edge only do half their contribution, so it is clear that you want the two elements that are closest to the median on the ends.  So this tells us exactly what the permutation that we want is.  We want the two elements on the ends to be as close to the median as possible, while alternating above/below.

Now that we understand this, we can use http://en.wikipedia.org/wiki/Quickselect to find the median in O(n) time.  Partitioning the array, and identifying the two elements to put on the end can then be done in O(n) time.  And then interleaving it is also O(n) for a O(n) algorithm.


问:
What is a relation between Dependency Injection, single instance, and singletons?
I read So Singletons are bad, then what? which was a great explanation of dependency injection as the solution for inversion of control. The asker assumed singleton and single instance were synonyms, and as others pointed out singleton is a more restrictive example of single instance.

My question is, why did the responder go from single instance to talking about dependency injection? He states:

A cache does not need to be a singleton. It may need to be a single instance if you want to avoid fetching the same data for multiple cache instances; but that does not mean you actually have to expose everything to everyone.

With DI, you have one interface, in this case "Cache". However, you have multiple instances. Instances of VideoPage + instances of MyAccountPage + etc. VideoPage implements IMediaCache which extends Cache. The DI is that the dependent class that makes use of this caching abstraction does so by using the Cache interface as a type in a parameter list (parameter list of constructor if using constructor injection, etc.)

So there are multiple instances (x VideoPages, y MyAccountPages, etc.) The Cache is the "single" thing in this design pattern, but it's not an instance since you can't instantiate an interface.

"Single instance" and "Dependency Injection" to me are separate ideas, so that response confused me.

I also don't know why people saying dependency injection is an alternative to singletons. A singleton forces one instance even if I try to instantiate again.  As for dependency injection, again, what is my "single instance"? The Cache isn't, as I explained earlier. And there are multiple instances of classes ultimately implementing the Cache interface.

答:
Because dependency injection container can and is used for lifetime management. Basically, singleton's main purpose is to maintain lifetime of exactly one instance : it is created once at startup (or first use) and is destroyed when application ends. But if you put both lifetime management and behavior itself in single class (eg. singleton), you break single responsibility principle.

On the other hand, if you have a single top container and use it to manage lifetime of that one instance, based on interface. You can tell you DI container to handle that one implementation of interface as a singleton. So it returns same instance every time it is requested. There are also different lifetimes : per-thread, per-(web)request, etc..

If you use DI instead of static field, then design around this single instance becomes much cleaner. It will also make it easier to change your mind later on, if you realize that what you first thought was a singleton actually isn't.


问:
Is it possible to quickly change an array declared on the stack to one declared on the heap
I have about 5000 lines of code which manipulates a large array in C++. The problem is that when I try to make the array even larger i.e. A[10000][10000], the gcc compiler throws me a segmentation fault error.

I believe the solution is to change the array to a dynamic array. Is it possible to do this by only changing the declaration of the array variable? Or would I have to change how the memory is accessed?

For example,

I have:

```<code>int A[10000][10000];    //rest of the code
</code>```

Can I change this directly to:

```<code>int** A = new int*[size of input];      //rest of the code
</code>```

while leaving the rest of the code intact?

Thanks

答:
Your suggestion isn't quite right.

```<code>int A[x][y];
</code>```

(where 'x' and 'y' are expressions that can be evaluated to a constant at compile time) declares a single block of memory that is xysizeof(int) bytes long, and A[i][j] is translated to  a reference to the I*y+jth value in the block. On the other hand,

int ** A = new int *[x];

allocates an array of x pointers to int arrays of unknown size, and does not initialize those pointers to point to anything specific. There are two consequences to this:

Before you can use the array you'll also need to allocate a block for each row and store that in the top level array of pointers, and

while you don't need to change the syntax you're using to access the array (A[i][j] will still work), be aware that the code the compiler generates has to load a pointer from the top level array and then preform arithmetic on that to find the location of the element, which is less efficient.

You should also, as mentioned in the comments, make sure you delete everything you create. Be aware that deleting arrays in c++ requires you to use "delete []" rather than the ordinary delete.

As you're working in c++, I would recommend that you consider using the STL "array<>" type if you know the size of your arrays at compile time:

```<code>unique_ptr<array<array<int,y>,x> > pA(new array <array <int, y>, x> >);
auto &A = *pA;
</code>```

should allow you to use the same syntax as you're used to, allocate all the memory in a single block on the heap so using it is as efficient as your original code, and take care of deleting it automatically when it hours out of scope.

Body:
Your suggestion isn't quite right.

int A[x][y];

(where 'x' and 'y' are expressions that can be evaluated to a constant at compile time) declares a single block of memory that is xysizeof(int) bytes long, and A[i][j] is translated to  a reference to the I*y+jth value in the block. On the other hand,

int ** A = new int *[x];

allocates an array of x pointers to int arrays of unknown size, and does not initialize those pointers to point to anything specific. There are two consequences to this:

Before you can use the array you'll also need to allocate a block for each row and store that in the top level array of pointers, and

while you don't need to change the syntax you're using to access the array (A[i][j] will still work), be aware that the code the compiler generates has to load a pointer from the top level array and then preform arithmetic on that to find the location of the element, which is less efficient.

You should also, as mentioned in the comments, make sure you delete everything you create. Be aware that deleting arrays in c++ requires you to use "delete []" rather than the ordinary delete.

As you're working in c++, I would recommend that you consider using the STL "array<>" type if you know the size of your arrays at compile time:

unique_ptr<array<array<int,y>,x> > pA(new array <array <int, y>, x> >);
auto &A = *pA;

should allow you to use the same syntax as you're used to, allocate all the memory in a single block on the heap so using it is as efficient as your original code, and take care of deleting it automatically when it hours out of scope.


问:
Should make concrete factories in the same count of families of objects or according to stages in my problem?
I am programming a game. In this game I have 3 stages. In the first stage, there is a static goal and a static shooter in the game. In the second stage, the goal will move. And in the third one both are moving.

I want to use abstract factory to create objects of same family.

I want to know which of the following designs is right:

With 2 factories:

With 3 factories:

I just don't know whether I should make concrete factories in the same count of families at the right hand or according to my problem?

For example, in the scenario, I have two families of objects (Products). First family is Gun and the second is Goal. But I have 3 stages that I have explained above. Is it right to have 2 factories because of the count of families of products or to have 3 families according to the stages?

答:
To be honest, I'd probably take a different approach entirely. I'd build 4 factories, one for each object type. I'd then create a new Level class that contains one instance of a GunFactory and one of a GoalFactory, and I would create 3 instances of Level (probably stored in a List) each having the appropriate combination of factory.

There are two reasons for this, one theoretical and one practical. On a theoretical level, it is not at all clear that the responsibilities "create a gun" and "create a goal" are part of the same responsibility, so the Single Responsibility Pattern states that we should avoid having a single object that doesboth. The Level object on the other hand does have one clear responsibility: "hold together all of the information and behavior necessary to initialize a level of the game".

The second, more practical aspect, is that this lets you add new levels more easily than either of your original suggestions. Say you want to add a fourth level that uses a different combination of gun and goal again; in your first design you would have to change your existing initialization code to pick a different set of factories, in the second you'd have to create a new subclass of your abstract factory class, whereas with my suggestion you'd just add a new Level instance to the list, a single line change. (This could also be phrased theoretically as "the design is more compliant with the open/closed principle when levels need to be added", but I prefer the practical emphasis here).


问:
Is it ok to access private members while doing same class comparison?
I am writing a class which basically is a wrapper around a dictionary with some extra functionality. This dictionary is stored as protected member _store. Now I am writing a __eq__ method to compare objects of my class. The criterion is, if the underlying dictionaries are equal, the objects are equal, therefore the easiest approach would be:

```<code>def __eq__(self, other):
    return self._store == other._store
</code>```

But this entails accessing the protected members of a third object. Although this third object belongs to the same class as self. Can we consider this breaking encapsulation??

The other option is to do an item comparison between the two objects, which leads to a slightly less efficient and longer code (keys set comparison and check that the key-value pairs of one object equal the ones of the other object).

答:
You tagged this with object-oriented, so the answer is: no. The fact that objects only know about their own private implementation / representation and not about that of other objects even of the same type is the defining characteristic of object-oriented data abstraction as opposed to Abstract Data Types, where instances of an ADT do know about the private implementation of other instances of the same type.

If you are familiar with Java, then there is a simple way to think about this: class == ADT, interface == object.

This is beautifully explained in On Understanding Data Abstraction, Revisited by William R. Cook.

Note that there's nothing wrong with ADTs per se, but a) as the name implies they rely on types (in the type-theoretic sense of the word, by which they mean static types), which Python doesn't have, and b) you specifically tagged the question with object-oriented.

Note also that it is not quite easy to define what "two ADT instances of the same type" means in Python, since, after all, classes aren't types, ducks are.


答:
Since you tagged this with python, I'll give you the Python perspective on this.

In Python, this is entirely normal. Attributes are not private, they are merely marked as 'internal', by convention, by using a leading underscore. So _store is something that is 'internal' to the class, just as the implementation of __eq__ is an internal matter.

You are not breaking encapsulation here; you are merely providing a correct implementation of a hook method. Accessing other._store here is no different from accessing self._store in that respect. That's because Python is a pragmatic language, it is not a purist OO language (you can use functional and procedural paradigms whenever you feel that fits the problem space better, for example).

Note that you may want to return the NotImplemented singleton object for comparisons that your class doesn't support:

```<code>def __eq__(self, other):
    if not isinstance(other, MyClass):  # or not hasattr(other, '_store') perhaps
        return NotImplemented
    return self._store == other._store
</code>```

Python would then delegate the test to the other object; if it doesn't implement the __eq__ method or returns NotImplemented as well, then Python falls back to an identity test (self is other).

You'll find this pattern (using internal attributes in comparison hook methods) throughout the Python standard library. For example, all comparison methods for the decimal.Decimal() class delegate to the Decimal._cmp() method, and the implementation for that method is based almost exclusively on using internal attributes and methods (_is_special, _isinfinity(), _sign, _exp and _int), accessed both on self and other.

Some more examples:

fractions.Fraction.__eq__()

sets.Set.__eq__() (a precursor to the built-in set type, now deprecated)

Title: Is it ok to access private members while doing same class comparison?

Body:
I am writing a class which basically is a wrapper around a dictionary with some extra functionality. This dictionary is stored as protected member _store. Now I am writing a __eq__ method to compare objects of my class. The criterion is, if the underlying dictionaries are equal, the objects are equal, therefore the easiest approach would be:

```<code>def __eq__(self, other):
    return self._store == other._store
</code>```

But this entails accessing the protected members of a third object. Although this third object belongs to the same class as self. Can we consider this breaking encapsulation??

The other option is to do an item comparison between the two objects, which leads to a slightly less efficient and longer code (keys set comparison and check that the key-value pairs of one object equal the ones of the other object).

Body:
Since you tagged this with python, I'll give you the Python perspective on this.

In Python, this is entirely normal. Attributes are not private, they are merely marked as 'internal', by convention, by using a leading underscore. So _store is something that is 'internal' to the class, just as the implementation of __eq__ is an internal matter.

You are not breaking encapsulation here; you are merely providing a correct implementation of a hook method. Accessing other._store here is no different from accessing self._store in that respect. That's because Python is a pragmatic language, it is not a purist OO language (you can use functional and procedural paradigms whenever you feel that fits the problem space better, for example).

Note that you may want to return the NotImplemented singleton object for comparisons that your class doesn't support:

def __eq__(self, other):
    if not isinstance(other, MyClass):  # or not hasattr(other, '_store') perhaps
        return NotImplemented
    return self._store == other._store

Python would then delegate the test to the other object; if it doesn't implement the __eq__ method or returns NotImplemented as well, then Python falls back to an identity test (self is other).

You'll find this pattern (using internal attributes in comparison hook methods) throughout the Python standard library. For example, all comparison methods for the decimal.Decimal() class delegate to the Decimal._cmp() method, and the implementation for that method is based almost exclusively on using internal attributes and methods (_is_special, _isinfinity(), _sign, _exp and _int), accessed both on self and other.

Some more examples:

fractions.Fraction.__eq__()

sets.Set.__eq__() (a precursor to the built-in set type, now deprecated)


问:
Are there defined standards for argument sequence?
Say I have a function taking three arguments:

a symbol (an alias for a class, method or function name)

a mirror/reflection of a specific object

a mirror/reflection of a class in general

is there a how-to (e.g. for certain languages or libraries) to sort things in function calls to keep an API consistent?

答:
That pretty much depends on your API / environment.

A few rules and guidelines that I know of:

In general: POLA - Principle of Least Astonishment (first brought to Computer Science by Mike Colishaw in his book the Rexx Programming Language), also known as Rule of Least Surprise - try to think from an API user's perspective, how is it easy to remember? How is it natural to read? Avoid astonishment / surprise.

Place cohesive arguments together. Example: In arraycopy(src, srcOffset, dst, dstOffest, length), src and srcOffset are very cohesive, so they stay together. length is also cohesive to src, but it is equally cohesive to dst, which makes the cohesion less specific, therefore it comes last.

Place the primary object first, i.e. the object that would be a this reference in an OO language. In other words: Place the object "to which the operation is told" first.

Place the destination before the source (C and similar languages).

Place the source / input before the destination / output (Java and similar languages).

Place those arguments that are more likely to vary between similar function calls more to the right, those arguments that are more likely to stay the same more to the left.

Place the parameters with more generic meaning more to the left, the ones with more specific meaning more to the right. For example: (directory, file) is usually more logical than (file, directory) - unless directory is a destination. Or class, object usually is more logical than object, class - unless object is of this nature.

Try to make the calls read (almost) like well-written prose.

And a few hints:

Be consistent within your API.

Make it easy for users which already know similar APIs, i.e. look around. If you develop a Qt extension, look how the Qt API itself feels. If you develop a Java API, look how the SUN / Oracle Java API looks and feels.

A few more examples:

If a function takes an array, an offset into that array, and a length, the sequence should be (array, offset, length) because that's how you think: First what, then the details, and the details in the sequence in which they matter. The contract is probably about iteration which we expect to start at offset and run until length is reached.

In your case it depends on the nature of the symbol, the object and the class. If I assume that object is a member of class, and symbol is a member of object, I would probably expect the sequence to be (class, object, symbol).


问:
Why public access level method get overridden in java?
This question is raised with a clarification required to decide when to declare a method protected or public during class design of a package.

My point is, if one needs to override a method of a SuperClass then make that method access level as package private or protected in SuperClass but do not give access level public, and then SubClass inherit SuperClass to override that method.

if public access level method is also overridden in SubClass then public access level method has also become an implementation dependent method in every new SubClass designed, which breaks concept of abstraction. Because user using public level access method addNotify(), should know that it's implementation is different in  awt.Component/ awt.Checkbox/awt.Button class, which means hiding of implementation details not ensured here. In addition, abstract class is supposed to be discovered and designed to have only common implementations of its concrete subclass methods, But it is pretty strange to see that abstract class Component{} breaks this definition.

With the access level given to this method public void addNotify() {}, Without knowing the meaning or significance of this method, I would like to ask,

Does it become difficult to decide the access level of a method during class design to be either public or protected?

Because I would like to say that at design time any method will be public in SuperClass only when below 2 reasons are satisfied:

1) There must not be a need to override this method in SubClass in/out of package, if one tries to override SuperClass.

2) Based on the signature of any public level method it must be safe after making a decision that this method can be publicly available so that means this method should not be implementation dependent in any new SubClass  in/out of package. signature in the sense that, i made my below DList class available to perform sequential update of DList in O(n) time, so no SubClass must override prevNode() method of DList class. This is risky!!! Because prev/next pointers can be manipulated here with bad coding. LSK principle will become safe.

```<code>   package DList;/* DList.java */
   public class DList {
    ......
      public DListNode prevNode(DListNode node) { /* check this signature*/
        if(node.prev != this.sentinel){
            return node.prev;
        }else{
            return null;
        }
      }
    .......
    }
    /* DListNode.java */
    package List;
    public class DListNode {
       public Object item; /* check this */
       protected DListNode prev;
       protected DListNode next;

      DListNode(Object i, DListNode p, DListNode n) {/* check this signature*/
        this.item = i;
        this.prev = p;
        this.next = n;
      }
    }
</code>```

So,

With the experience of java code written, it looks easy for me to decide the one of the two possible access levels of all the classes/interface design within a package.

it looks easy to decide while introducing signature of new methods,
whether a method should have access level private
whether a method should have access level package private

If i understand the below question, It would become easy to decide when a method be protected or public.
1) Why java allows to override public access level methods? Because it is difficult for me to decide when to make my method protected, despite i know that public is more visible than protected among packages. One has to foresee the cost/consequence of introducing a new inheritance relation before giving protected access level to the method of your current design of class.

2) Can i know the proper resource to learn when a method can be protected?

Note: I am a Java beginner who currently understands abstraction/encapsulation/inheritance/polymorphism and about to learn "package and access specifiers"

答:
The answer to your last question is that it will come to you with experience. But basically, you don't start by adding new methods and then wondering which keyword to use. You start by thinking about what responsibilities the class will have, what promises it will make to the classes around it. Each class handles certain details so that other classes don't have to worry about them, and you can think of it like a bunch of contracts. The access modifiers are the tools you use to state (and to some extent enforce) those contracts.

The answer to your other question is that public, protected, and private are about accessibility, not override-ability. The Java keyword that controls whether something can be overridden in a subclass is final. So if you want a member to be accessible but not  overridable, declare it public final. There is no way to do the opposite (overridable in a subclass but not accessible from a subclass) because it doesn't make sense to override something you can't see.


答:
if public access level method is also overridden in SubClass then public access level method has also become an implementation dependent method in every new SubClass designed, which breaks Encapsulation. Because user using public level access method addNotify(), should know that it's implementation is different in  awt.Component/ awt.Checkbox/awt.Button class, which means hiding of implementation details not ensured here.

The parts in bold should not be true for the majority of cases. In fact, if you must know the subtype of an object before using it, it's a sign that your abstractions are not good enough in hiding implementation details (leaky). This is further expanded by the Liskov Substitution Principle (LSP), which says that you should be able to write your code around the use of a superclass/interface, and have its behavior unchanged if and when any object of a subclass is given to you.

So to answer your questions:

Java allows you to override public methods because there is nothing wrong in doing that at all. Because some people may misuse a tool, doesn't  mean the tool is bad. Follow the LSP and try to keep your abstractions closed enough, and you won't need to worry about extending public behavior of an object in the future.

Given that you have already defined all the public methods, and is simply choosing whether to keep the internal methods private or protected, then you could use the following rule: Leave everything private, until the need for subclassing/overriding exists, then turn it into protected. This is a good guideline especially since we cannot foresee the future, and a very considerable amount of time can be wasted on trying to make everything extensible only to find that there were only few cases where it was useful. If you want to read about the best guidelines for allowing future extensibility, you can read materials around applications of Open-Closed Principle (OCP) - beware though, it is one of the hardest SOLID principles to apply, unless you can see the future (or have enough experience to make very reliable guesses).

Overall, I recommend that you read up on the SOLID principles, with especial focus on LSP and OCP, because they fit with your current problems. Also, I'd recommend reading about Composition vs. Inheritance, since sometimes its better not to extend classes at all, but to compose them of other exchangeable objects instead.

Title: Why public access level method get overridden in java?

Body:
This question is raised with a clarification required to decide when to declare a method protected or public during class design of a package.

My point is, if one needs to override a method of a SuperClass then make that method access level as package private or protected in SuperClass but do not give access level public, and then SubClass inherit SuperClass to override that method.

if public access level method is also overridden in SubClass then public access level method has also become an implementation dependent method in every new SubClass designed, which breaks concept of abstraction. Because user using public level access method addNotify(), should know that it's implementation is different in  awt.Component/ awt.Checkbox/awt.Button class, which means hiding of implementation details not ensured here. In addition, abstract class is supposed to be discovered and designed to have only common implementations of its concrete subclass methods, But it is pretty strange to see that abstract class Component{} breaks this definition.

With the access level given to this method public void addNotify() {}, Without knowing the meaning or significance of this method, I would like to ask,

Does it become difficult to decide the access level of a method during class design to be either public or protected?

Because I would like to say that at design time any method will be public in SuperClass only when below 2 reasons are satisfied:

1) There must not be a need to override this method in SubClass in/out of package, if one tries to override SuperClass.

2) Based on the signature of any public level method it must be safe after making a decision that this method can be publicly available so that means this method should not be implementation dependent in any new SubClass  in/out of package. signature in the sense that, i made my below DList class available to perform sequential update of DList in O(n) time, so no SubClass must override prevNode() method of DList class. This is risky!!! Because prev/next pointers can be manipulated here with bad coding. LSK principle will become safe.

```<code>   package DList;/* DList.java */
   public class DList {
    ......
      public DListNode prevNode(DListNode node) { /* check this signature*/
        if(node.prev != this.sentinel){
            return node.prev;
        }else{
            return null;
        }
      }
    .......
    }
    /* DListNode.java */
    package List;
    public class DListNode {
       public Object item; /* check this */
       protected DListNode prev;
       protected DListNode next;

      DListNode(Object i, DListNode p, DListNode n) {/* check this signature*/
        this.item = i;
        this.prev = p;
        this.next = n;
      }
    }
</code>```

So,

With the experience of java code written, it looks easy for me to decide the one of the two possible access levels of all the classes/interface design within a package.

it looks easy to decide while introducing signature of new methods,
whether a method should have access level private
whether a method should have access level package private

If i understand the below question, It would become easy to decide when a method be protected or public.
1) Why java allows to override public access level methods? Because it is difficult for me to decide when to make my method protected, despite i know that public is more visible than protected among packages. One has to foresee the cost/consequence of introducing a new inheritance relation before giving protected access level to the method of your current design of class.

2) Can i know the proper resource to learn when a method can be protected?

Note: I am a Java beginner who currently understands abstraction/encapsulation/inheritance/polymorphism and about to learn "package and access specifiers"


问:
Metric by which to hold developers accountable
I asked a question on lines of code per hour and got torn a new one.  So my matured follow-up question is this:

If not lines of code, then what is a good metric by which to measure (by the hour/day/unit-of-time) the effectiveness of remote programmers?

答:
Use a methodology, whereby the written documentation marries up to the code written. Start the week deciding on what needs to be done, get an agreement, then wait till the end of the week to see if its been done or not. Keep tasks small and measurable as in how many days. I don't think you need to measure the programmers work per say, but the agreement on what is to be delivered and when is a must for control.

Second part to this solution would be peer-to-peer code reviews which is backed up by some sort of Versioning system that makes who did what and when traceable. If the consensus  is that the code is good then your onto a winner, if bad, then find out why and how it could be improved.

Time and motion studies are a no no as far as I am concerned, some code such as Regexes or some really hard logic can take days to develop but may only form a couple of lines of code. The only true measurement is deliverables on time, on an agreed time.


问:
Separation of construction and initialization
I'm confused by this post by Mark Seeman.

And his comment on IInitializable below:

The problem with an Initialize method is the same as with Property
  Injection (A.K.A. Setter Injection): it creates a temporal coupling
  between the Initialize method and all other members of the class.
  Unless you truly can invoke any other member of the class without
  first invoking the Initialize method, such API design is deceitful and
  will lead to run-time exceptions. It also becomes much harder to
  ensure that the object is always in a consistent state.

The same time he writes:

This issue is similar to the issue of invoking virtual members from
  the constructor. Conceptually, an injected dependency is equivalent to
  a virtual member.

I thinks this statement is true only if admit that constructed != initialized.

What we get now:

Dependencies are injected in constructor but it is not recommended to use them.

Initialize phase brings complexity and should be avoided.

Isn't it contradictory?

Imagine class needs to set its state using the provided dependencies. Loading saved setting for example.

Init is bad, constructor is bad, so where to perform this operation?

And another point:

Are not methods like Connection.Open() just another name for Initialize?

Question:

So can anyone describe a good initialization pattern in the context of Dependency Injection that addresses the concerns Mark Seeman brings up?

答:
For flexibility, DO NOT do initialisation in constructors.

For simplicity, i.e. if you can afford it and are sure it will not cause you headaches later, DO initialisation in constructors (RAII). Then you can make the usual safe RAII assumptions about (monolithic?) deallocations.

All programming relies on correct ordering of events. There is nothing "deceitful" about placing on the programmer expectations to perform certain operations before certain other operations (in this case, constructing -> initialising all members -> using the object). Seeman's idea of "deceit" is patently absurd.

I tend to favour felxibility (the former) these days as I've been burnt too many times by winding up needing the flexiblity that individual injection / initialisations of members brings. (by the by, I favour C over C++ for the same reason: flexibility.). Constructor injection is RAII. RAII admits (in its very name) to being a conflation of concerns. As a result, objects cannot go into a pool to be reconfigured / reused, they instead need to be reconstructed which means extra runtime allocations. There is a lack of any real control over instruction ordering (dynamic DI concern). And of course there are the long, ugly parameter lists.


问:
Is it misleading to label code as a particular design pattern if it only loosely fits the definition?
Background:

I have a rough, but working understanding of ~15 design patterns. It's been my experience using design patterns in my own projects that the resulting implementations usually end up as some variant of a pattern and don't always fit the canonical textbook examples.

Case:

I find it useful to leave tag-like comments that hint at an underlying archetype, e.g., in the following Javadoc class description, the "[Singleton]" label is used merely to describe that there's only one of these objects used at any given time. This class may or may not be set up to "restrict the instantiation of a class to one object" --Wikipedia.

```<code>/**
 * [Singleton]
 * The manager of all jewels, which are stored here in collections.
 */
public class JewelManager implements IDestroyable
{
</code>```

Context:

I'm working on a team with several other developers, but I need to assume there may be other devs working on the project with whom I will never have the opportunity to speak.

Question:

Is it misleading to label classes or methods as a particular design pattern (Strategy, Mediator, etc.) if they only loosely fit that definition?

答:
Is it misleading to label classes or methods as a particular design pattern (Strategy, Mediator, etc.) if they only loosely fit that definition?

It depends.

If you have a singleton and it does not prevent instantiation, then it would be misleading to label it a singleton, since it's not a singleton. It's a global variable. Doing otherwise leads your fellow developers to make (reasonable) assumptions, which will be wrong, which will lead to subtle, catastrophic errors.

If you have say... a factory that returns new random objects rather than new objects based on the input to the factory. It's probably okay to call that a factory. Your fellow programmers shouldn't know (or care) about its implementation details. And that new implementation, while not a factory per se, does not break the implied contract of a factory: "you give me X and I will give you a new Y".


问:
What's the purpose of keeping a changelog if everyone uses their VCS properly?
Every VCS that I've seen includes a means (and sometimes requires you) to make a log of what a particular commit does.  If this history is being properly kept, what is the purpose of manually keeping the same history in a regular file?

Note that I'm not positing the changelog is useless, I just don't see a use for it myself.  Are there other tools that use the changelog?

答:
Basically, you're completely right. All the information should be in the VCS as well, and as commenters said, changelogs are often generated out of VCS information.

However, prepared changelogs come with some remarkable advantages:

A changelog does not require to connect to the VCS, maybe install the proper VSC client before, scrolling through tons of commits, and such hassle. Instead, it quickly provides the required information in a neatly formatted document without much overhead.

The audience reading the changelog may be developers, but often they're not. Or if they are developers, they lack the necessary inside knowledge to interpret raw VCS data correctly. So even if changelogs are to be generated from VCS data, the raw data may be still be cleaned up, consolidated or reformatted to make some points clearer to the audience. This becomes more important, the more the user audience differs (with regard to technical interna) from the product developers/contributors.


问:
How to represent a multiple choice attribute in UML class diagram?
I'm modelling a Filter class that stores the options for filtering a search. Some of the attributes are multiple choice.

For example, if you are filtering hotel rooms you have a Price attribute that can take these three values: Best, Average, High. You can choose many values at the same time. In an UI would be represented as a group of checkboxes.

Can this be represented in a UML class diagram?

答:
(1)

(2)

(3)

?

See also: uml-diagrams.org: Class and Object Diagrams Overview

As @robert-harvey pointed out, your requirement to select many values at the same time is strange as you can see from the model


问:
Interface inherits from interface without specifying new member
Is it some kind of bad design to have something like this:

```<code>public interface IFooStream
{
    long Length { get; }
    long Position {get; set;}
    //...
}

public interface IReadableFooStream<T> : IFooStream
{
    int Read(T[] buffer, int offset, int count);
}

public interface IByteStream : IReadableFooStream<byte>
{
}

public interface IFloatStream : IReadableFooStream<float>
{
}
</code>```

How would you solve something like this? I definitely must have the IByteStream and the IFloatStream interface.

答:
I definitely must have the IByteStream and the IFloatStream interface.

Without a compelling reason, I definitely say you don't. Do you make a ByteList or a FloatList? No, you leave List be and let people parameterize it.

This sort of aliasing can occasionally be useful, but more often it is a code smell that your interface/class is too abstract (or doing too many things). You're allowing things to be parameterized to the n-th degree, and that is usually not needed.

How would you solve something like this?

In my experience, an IFooStream isn't useful by itself. I would make a read stream, a write stream, and a combination maaaaybe with a base interface if/when I find I actually need it. Assuming of course that the .NET streams are somehow incapable of supplying the interface I need to do the work...


问:
Include internal defects into the release notes?
When delivering a product, Release notes clearly contain known issues found by customer in the previous build.
But should we include defects that we, as a supplier, found during our testing, those unresolved and hence present in the build?
I mean, it makes sense to me but I would love to know what more experienced people think about that problem.</p>

答:
Yes.

Otherwise, your customers may find those bugs themselves, and give you bug reports for things you've already fixed.  This wastes everybody's time.

In addition, bugs may be causing your customers problems that they are unaware of.  Getting notice of these issues may induce them to upgrade more quickly, reducing the scope of the issue.  (Imagine for instance that you are shipping a library, and that library is being used in a commerce application.  Suppose the defect in your library has a snowball effect that causes tax to be collected improperly for a particular state, but your customer has not noticed yet.  This may change their decision from "Upgrade at next release" to "OMFG we need a hotfix!")


问:
What is meant by “redundant, but not duplicative” in the Steelman language requirements?
The Steelman language requirements have this:

The language shall require some redundant, but not duplicative, specifications in programs.

I think I can see the underlying idea (that re-stating things may lead to fewer errors given the limitations of human cognition), but I would like a more detailed explanation.

What do they mean by “redundant” and by “duplicative”?

答:
In this context "redundant" means that program's behavior is described multiple times. But "not duplicative" means that each of the of the specific types behaviors is different.

For example, automated testing. The code is "redundant", because the behavior is described twice : once in code and once in form of automated test. But it is not duplicative, because both cases use completely different way to express what they do.

At least that's how I understand it.


问:
Are version numbers needed
We build a system which works as software as a service. Now I am wondering if it is needed to give the version number to the clients. For example Facebook doesn't give a version number neither does Google. My question is basically would one include version numbers in an application where the client cannot change the version themselves?

Update 1

Just a quick update, yes we do offer an API and the API will be versioned in a similar way like Atlassian does api/ and then api/v2/ and so on.

The version number is just about the website the customer sees, not about developers.

Internally we use Jira for project management and there we also use the Jira releases feature. So internally we do have version numbers. Just not for the customers at the moment.

答:
You might want to have internal version numbers of your application to better manage your internal development processes. However, these numbers are of little use for the user.

The usual purpose of version numbers is to tell the user if their application is up-to-date or not. When this is not within their control, it can at least be useful for support personnel to verify that they received the latest version. But when you have a software-as-a-service where all users share the same deployment, there is little reason to communicate the version number to them.

An exception could be when you aren't the only one who offers the service. When you only licensed the software or are licensing it yourself so others also offer the same software as a service, it could be useful to communicate the version number to the end-user so they can compare which provider offers which version and also be aware of the version used by their provider in case there are relevant differences in usage.

Title: Are version numbers needed


问:
Should I use .ToString() when concatenating string and integer variables in C#?
```<code>int a = 1;
int b = 2;
int sum = a + b;
string expression = "Expression: " + a + " + " + b + " = " + sum;
Console.WriteLine(expression); //displays Expression 1 + 2 = 3
</code>```

Should I use:

```<code>string expression = "Expression: " + a + " + " + b + " = " + sum;
</code>```

or

```<code>string expression = "Expression: " + a.ToString() + " + " + b.ToString() + " = " + result.ToString();
</code>```

Is it recommended to use ToString() when concatenating string and int?

答:
ToString usage

No, you shouldn't use ToString here.

String concatenation automatically transforms non-strings into strings, which means that your two variants are nearly¹ identical:

When one or both operands are of type string, the predefined addition operators concatenate the string representation of the operands.

Source: C# Language Specification: Addition operator, MSDN.

On the other hand, the first one (without ToString):

Is shorter to write,

Is shorter to read,

Is easier to maintain and:

shows exactly the intention of the author: to concatenate strings.

So prefer the first one.

Under the hood

What is also interesting is to see what happens under the hood. One of the ways to see it is to watch the IL code within LINQPad. This program:

```<code>void Main()
{
    var a = 3;
    var b = " Hello";
    var c = a + b;
    Console.WriteLine(c);
}
</code>```

is translated to the following IL:

```<code>IL_0001:  ldc.i4.3
IL_0002:  stloc.0     // a
IL_0003:  ldstr       " Hello"
IL_0008:  stloc.1     // b
IL_0009:  ldloc.0     // a
IL_000A:  box         System.Int32
IL_000F:  ldloc.1     // b
IL_0010:  call        System.String.Concat
IL_0015:  stloc.2     // c
IL_0016:  ldloc.2     // c
IL_0017:  call        System.Console.WriteLine
</code>```

See that System.String.Concat? That means that the original code can be written also like that, which translates into exactly same IL:

```<code>void Main()
{
    var a = 3;
    var b = " Hello";
    var c = string.Concat(a, b); // This is the line which was changed.
    Console.WriteLine(c);
}
</code>```

When you read the documentation of string.Concat(object[]), you may learn that:

The method concatenates each object in args by calling the parameterless ToString method of that object; it does not add any delimiters.

This means that ToString is redundant. Also:

String.Empty is used in place of any null object in the array.

Which handles nicely the case where some of the operands are null (see the footnote 1).

While in the last example, concatenation was translated into string.Concat, one should also highlight compiler optimizations:

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

is translated into:

```<code>ldstr       "Hello World"
stloc.0
</code>```

On the other hand:

```<code>var a = string.Concat("Hello ", "World");
</code>```

is translated into:

```<code>ldstr       "Hello "
ldstr       "World"
call        System.String.Concat
stloc.0
</code>```

Other alternatives

There are of course other ways to concatenate string representations of objects in C#.

StringBuilder is used when you need to do a lot of concatenation operations and helps reducing the number of intermediary strings created. Deciding whether you should use a StringBuilder or an ordinary concatenation may not be easy. Use a profiler or search for relevant answers on Stack Overflow.

Using StringBuilder has a major drawback of making the code difficult to read and maintain. For simple cases as the one in your question, StringBuilder is not only harmful to the readability of the code, but also useless in terms of performance.

string.Join should be used when you need to add delimiters.

Obviously, never use string.Join with an empty delimiter to concatenate strings.

string.Format can be used when string templating is preferred to string concatenation. One of the cases where you may prefer that is when the message may be localized, as suggested in the answer by kunthet.

Using string.Format has several drawbacks which makes it unsuited for simple cases like yours:

With simple "{0}" placeholders, it is often unclear which parameter goes where. It is frequent to mistakenly reverse the parameters or to forget one. Luckily, C# 6 finally introduces string interpolation which solves this problem.

Runtime performance may degrade. Of course, don't assume string.Format is always slower. If performance matters, measure two approaches and determine which one is faster based on your actual results instead of assumptions.

The code is slightly longer to write, longer to read and harder to maintain, although this is extremely minor and shouldn't bother you too much.

¹ The difference appears when one of the objects is null. Without ToString, a null is replaced by an empty string. With ToString, a NullReferenceException is thrown.

Body:
ToString usage

No, you shouldn't use ToString here.

String concatenation automatically transforms non-strings into strings, which means that your two variants are nearly¹ identical:

When one or both operands are of type string, the predefined addition operators concatenate the string representation of the operands.

Source: C# Language Specification: Addition operator, MSDN.

On the other hand, the first one (without ToString):

Is shorter to write,

Is shorter to read,

Is easier to maintain and:

shows exactly the intention of the author: to concatenate strings.

So prefer the first one.

Under the hood

What is also interesting is to see what happens under the hood. One of the ways to see it is to watch the IL code within LINQPad. This program:

void Main()
{
    var a = 3;
    var b = " Hello";
    var c = a + b;
    Console.WriteLine(c);
}

is translated to the following IL:

IL_0001:  ldc.i4.3
IL_0002:  stloc.0     // a
IL_0003:  ldstr       " Hello"
IL_0008:  stloc.1     // b
IL_0009:  ldloc.0     // a
IL_000A:  box         System.Int32
IL_000F:  ldloc.1     // b
IL_0010:  call        System.String.Concat
IL_0015:  stloc.2     // c
IL_0016:  ldloc.2     // c
IL_0017:  call        System.Console.WriteLine

See that System.String.Concat? That means that the original code can be written also like that, which translates into exactly same IL:

void Main()
{
    var a = 3;
    var b = " Hello";
    var c = string.Concat(a, b); // This is the line which was changed.
    Console.WriteLine(c);
}

When you read the documentation of string.Concat(object[]), you may learn that:

The method concatenates each object in args by calling the parameterless ToString method of that object; it does not add any delimiters.

This means that ToString is redundant. Also:

String.Empty is used in place of any null object in the array.

Which handles nicely the case where some of the operands are null (see the footnote 1).

While in the last example, concatenation was translated into string.Concat, one should also highlight compiler optimizations:

var a = "Hello " + "World";

is translated into:

ldstr       "Hello World"
stloc.0

On the other hand:

var a = string.Concat("Hello ", "World");

is translated into:

ldstr       "Hello "
ldstr       "World"
call        System.String.Concat
stloc.0

Other alternatives

There are of course other ways to concatenate string representations of objects in C#.

StringBuilder is used when you need to do a lot of concatenation operations and helps reducing the number of intermediary strings created. Deciding whether you should use a StringBuilder or an ordinary concatenation may not be easy. Use a profiler or search for relevant answers on Stack Overflow.

Using StringBuilder has a major drawback of making the code difficult to read and maintain. For simple cases as the one in your question, StringBuilder is not only harmful to the readability of the code, but also useless in terms of performance.

string.Join should be used when you need to add delimiters.

Obviously, never use string.Join with an empty delimiter to concatenate strings.

string.Format can be used when string templating is preferred to string concatenation. One of the cases where you may prefer that is when the message may be localized, as suggested in the answer by kunthet.

Using string.Format has several drawbacks which makes it unsuited for simple cases like yours:

With simple "{0}" placeholders, it is often unclear which parameter goes where. It is frequent to mistakenly reverse the parameters or to forget one. Luckily, C# 6 finally introduces string interpolation which solves this problem.

Runtime performance may degrade. Of course, don't assume string.Format is always slower. If performance matters, measure two approaches and determine which one is faster based on your actual results instead of assumptions.

The code is slightly longer to write, longer to read and harder to maintain, although this is extremely minor and shouldn't bother you too much.

¹ The difference appears when one of the objects is null. Without ToString, a null is replaced by an empty string. With ToString, a NullReferenceException is thrown.

ContentLicense: CC BY-SA 4.0


答:
Instead, you should use string formatter. It's easier to format your number into string representation or localization. e.g.:

```<code>string expression = string.Format("Expression: {0} + {1} = {2}", a, b, sum);
</code>```

More info on MSDN.

However, string formatter is less readable (and maybe also performance) than string concatenation.

Title: Should I use .ToString() when concatenating string and integer variables in C#?

Body:
```<code>int a = 1;
int b = 2;
int sum = a + b;
string expression = "Expression: " + a + " + " + b + " = " + sum;
Console.WriteLine(expression); //displays Expression 1 + 2 = 3
</code>```

Should I use:

```<code>string expression = "Expression: " + a + " + " + b + " = " + sum;
</code>```

or

```<code>string expression = "Expression: " + a.ToString() + " + " + b.ToString() + " = " + result.ToString();
</code>```

Is it recommended to use ToString() when concatenating string and int?

Body:
Instead, you should use string formatter. It's easier to format your number into string representation or localization. e.g.:

string expression = string.Format("Expression: {0} + {1} = {2}", a, b, sum);

More info on MSDN.

However, string formatter is less readable (and maybe also performance) than string concatenation.


答:
User facing code does not need version numbers.

But if you are writing code that is consumed by external developers, then you absolutely should offer version numbers, and ALSO maintain multiple versions on your site.  With a clear deprecation policy.  Doing that will give you the freedom to make potentially backwards incompatible changes to your API, and then lets people who depend on you to upgrade when it is more convenient for them.  And doing so is not as hard as you might think in the days of AWS since you just maintain servers running an old version and launch new ones using the new one.  Release to the old when you need to, and then decommission them when you are done.

Yes, I know that Facebook is not good about doing this.  But they are also infamous for releasing code that unexpectedly breaks people using their APIs.  And I know quite a few developers who dearly wish that they had any alternative to Facebook.  Facebook successfully locks developers in because they have the users.  But you don't have that.  If you make developers feel that way about using your service, they will leave.

Title: Are version numbers needed

Body:
We build a system which works as software as a service. Now I am wondering if it is needed to give the version number to the clients. For example Facebook doesn't give a version number neither does Google. My question is basically would one include version numbers in an application where the client cannot change the version themselves?

Update 1

Just a quick update, yes we do offer an API and the API will be versioned in a similar way like Atlassian does api/ and then api/v2/ and so on.

The version number is just about the website the customer sees, not about developers.

Internally we use Jira for project management and there we also use the Jira releases feature. So internally we do have version numbers. Just not for the customers at the moment.


答:
There are two possible consumers of version numbers.  Your internal processes and people using your service.

With internal processes, version numbers help you identify when something was fixed and what has changed since them.  By saying "we fixed this in version 1.2.3" you know where that was done and if you are now experiencing the same bug, you've got a regression.  By being able to identify when it was fixed or implemented (with a version number) you can now narrow down what you need to do to fix it.

Consumers of the service can also use version numbers. Not all consumers need to know version numbers, but it is something that can help them.  By saying "these bugs were fixed in version 1.2.3 which was deployed on some date" you, as the consumer know that bugs that you may have reported are fixed.  Furthermore, when reporting bugs you have the opportunity to say "this was fixed in 1.2.3 but now in 1.2.5 it is broken again."  This is possibly valuable information for reporting bugs.

Many times, software as a service also has an API for interfacing to it.  This API should be also versioned.  You can see this with the Stack Exchange API and Google's data APIs.  An API is very much like a library which is hosted on another server.  Just as libraries are versioned, so are APIs.

The purpose of a version number in these cases is to allow more efficient communication of the information about what software something was reported in, fixed in, and currently running.  That there is only one instance of the 'currently running' doesn't lessen the usefulness of the first two points.  It is useful for internal and external alike.

Consider also that unless you are offering an API, semantic versioning is not necessarily as useful.  I've worked in situations where the build number from the continuous integration server was sufficiently useful for a version number - "production is running build 123, we fixed that in build 145 which is currently being tested in the QA environment.  The current build is 155."

Title: Are version numbers needed


答:
In general, you should include information about known defects in release notes to inform your users. You can see many software vendors have public bug trackers, so it obviously is a common practice.

Reasons to have a list of known issues:

Issue may never be fixed, because newer major version of software is going to be released. That newer version may be incompatible with previous one, so some users may stuck with older version for some time (may be forever).

You can save the time of your customers, because they're no longer have to discover and examine defects themselves, probably writing bug reports.

You can reduce your customer's irritation caused by encountering defects by providing a description of defects and a way to avoid/mitigate them.

You make yourself a good reputation: you care about your product and your users.

As for citations from books on management or standards, I've never seen one.

Important exceptions:

Defects that imply some security risks. You should not give any information about vulnerabilities to potential attackers. Instead, you should fix such security-related defects ASAP.

Defects that may significantly hurt your reputation. That may be bugs which don't cause any serious problems, but just make you look stupid.

Title: Include internal defects into the release notes?

Body:
When delivering a product, Release notes clearly contain known issues found by customer in the previous build.
But should we include defects that we, as a supplier, found during our testing, those unresolved and hence present in the build?
I mean, it makes sense to me but I would love to know what more experienced people think about that problem.</p>