问:
How can I get an anonymous user to submit bugs on a private GitHub project?
Our company has a private GitHub repository for the project I'm working on.  After a full summer of work, it looks like we'll be launching this week (wheee!).  However, I want to include a "submit a bug" link in the program that leads to a form somewhere where the user can fill out a form that becomes an issue for us on GitHub.  Googling around hasn't found any solution (or someone who has the same problem).

Is this possible (through some API, perhaps?) or will I have to manually enter the bugs my users report?

答:
I don't think the API is going to help you in this case. Because the project is private no one that is not logged in AND has access to the project will be able to do anything with the project, including creating tickets.

If you use the Github API you'll have to include the username and password to an account that is a collaborator on the project. Probably not a great idea.

Your next option would be to create a public project with a similar name, but without the code. Then you can use that project to track the external customer bugs.


问:
Can one edit a built-in Python module?
I'm currently learning Python and I'm at the point in the book about using the Math library. I looked on the Python website and noticed the library was a bit scarce and am writing some more useful functions. For example, I went ahead and wrote a function to take coefficients and return the roots of the equation. Essentially a quadratic formula function. I'm wondering if it's possible to add this to the python Math library. If it isn't, how do I save it such that I can use that function in other Python programs I write just by calling it?</p>

答:
The math module is a builtin, so short of modifying the Python interpreter itself, I don't think you can modify it.  However, writing a module is definitely something you can do.

If you structure your files like this:

```<code>somefolder
    mymath.py
    myprogram.py
</code>```

...you could simply do import mymath inside myprogram.py, and use any functions or classes inside mymath.py as normal.

So if mymath.py looks like this:

```<code>def quadratic(a, b, c):
    # blah blah blah
</code>```

You could do the below inside myprogram.py

```<code>import mymath

print mymath.quadratic(1, 2, 3)
</code>```

If you want the module you've written available for any program, you could either copy-and-paste it into the folder of any project you're working on, or add it to your PATH.  (For example, you could include mymath.py inside the site-packages folder, which is located at C:\Python27\Lib\site-packages on my computer).  Once you do that, you should be able to do import mymath without ever having to copy-and-paste anything.

As a side-note, numpy has a pretty comprehensive set of math and science related functions that you could check out.  It's pretty much the de-facto standard for numerical computation in Python, afaik.

ContentLicense: CC BY-SA 3.0

Title: Can one edit a built-in Python module?

Body:
The math module is a builtin, so short of modifying the Python interpreter itself, I don't think you can modify it.  However, writing a module is definitely something you can do.

If you structure your files like this:

somefolder
    mymath.py
    myprogram.py

...you could simply do import mymath inside myprogram.py, and use any functions or classes inside mymath.py as normal.

So if mymath.py looks like this:

def quadratic(a, b, c):
    # blah blah blah

You could do the below inside myprogram.py

import mymath

print mymath.quadratic(1, 2, 3)

If you want the module you've written available for any program, you could either copy-and-paste it into the folder of any project you're working on, or add it to your PATH.  (For example, you could include mymath.py inside the site-packages folder, which is located at C:\Python27\Lib\site-packages on my computer).  Once you do that, you should be able to do import mymath without ever having to copy-and-paste anything.

As a side-note, numpy has a pretty comprehensive set of math and science related functions that you could check out.  It's pretty much the de-facto standard for numerical computation in Python, afaik.

ContentLicense: CC BY-SA 4.0


问:
Storing plaintext passwords for detecting fraud
I am well aware of best practices for storing user passwords:

Never store passwords in plaintext

Never store encrypted passwords; always store password hashes

Always salt your password hash to deter brute force attacks

Always use unique salts to deter attacks using rainbow tables.

However, I have recently came upon on a potentially legitimate use case for keeping plaintext (or plaintext-accessible encrypted) user passwords: fraud detection. For example, if we have a system that needs to restrict purchases to 1 (or a small number) per person, we have observed that fraudsters often use the same password over and over, so if we have detected fraudulent purchases on one account, we can use the fact that password matches as a useful signal in a fraud detection system.

But implementing such a system requires breaking all the best practices for password storage.

Question: If it is determined that the fraud-detection ability of being to retrieve passwords is necessary, what are the best practices for storing passwords securely but in a way that is plaintext-accessible?

答:
The only way I'd consider doing something like this is if you put a stand-alone machine in a locked room with only an RS232 connection between it and the web server.  No network card, no wi-fi, no USB thumbdrives allowed.

Perform an unsalted hash on the web server, send only the hash and a user ID over the serial port, and get back a count of the number of users with matching hashes from the locked computer.  Don't cache the result on the webserver!

The locked computer can have a database of all the hashes stored by user ID and can do the comparison to say how many match.

Even then, this is all dependent on the discipline of the company involved.  You don't want to be poking holes in the air gap here.


答:
The Redmine turnkey linux appliance is available free for your own hosting or through the Amazon cloud (just pay and turn it on). Redmine allows for ticket submission through email, so you're users could have your users send in the tickets that way. Redmine also allows for anonymous users to add tickets, if you set up the permissions that way.

Since the appliance is a complete linux box, you can have a cron job or push notification that runs a script and adds the new ticket to the private github repo. The github API also allows for getting issues, so you could have the script keep the redmine box up to date too.

Personally, I'd just use the Redmine appliance by itself and have it monitoring the remote github repo.

Title: How can I get an anonymous user to submit bugs on a private GitHub project?

Body:
Our company has a private GitHub repository for the project I'm working on.  After a full summer of work, it looks like we'll be launching this week (wheee!).  However, I want to include a "submit a bug" link in the program that leads to a form somewhere where the user can fill out a form that becomes an issue for us on GitHub.  Googling around hasn't found any solution (or someone who has the same problem).

Is this possible (through some API, perhaps?) or will I have to manually enter the bugs my users report?


问:
How stable is Common LISP as a language?
I have been reading a bit about Common Lisp and I am considering trying to learn it (I only know very basic concepts) or even using it for some project.

Question: how stable is Common Lisp as a language? What I mean is, regardless of new libraries, are new language features (involving new syntax and semantics) being added to the language? In other words, if I learn Common Lisp now, would I be able to use the same language in 10 years from now, or read code that was written 10, 20 years ago (apart, of course, from having to get familiar with different libraries and API's)?

答:
The first edition of the book Common Lisp The Language, written by the lispers
at CMU (Carnegie-Mellon University)[1] and published in 1984, served as a basis
for ANSI Common Lisp the standard.  The second edition (published in 1990)
reflected the current state of the standardisation process that was still
ongoing.

In 1994, the ANSI Common Lisp standard was finally published.  It differed in
certain ways from the dialects described by the two editions of Common Lisp The
Language but acknowledged the practical importance of both editions by
suggesting that the keywords :cltl1 and :cltl2 be included in the *features*
list, allowing for conditionals to be added to code that must interoperate
between ANSI Common Lisp and these other two dialects.

CLTL1 (as it is known) is ancient history today and most, if not all,
implementations have settled on something somewhere in between ANSI and CLTL2.
However, the ANSI standard suffered from a bigger problem that had nothing to do
with the language per se; it failed to address one or two important practical
aspects of everyday programming and discrepancies arose in the way
implementations addressed these practical needs.  As a result of this (not the
minor language differences between ANSI and CLTL2) lispers talk toady about
portable versus non-portable code.

So, to summarise, the core language (the fixed set of 24 special forms[2] which
every implementation must include if it wants to call itself Common Lisp) is
absolutely rock solid and cast in stone, but practical shortcomings in the ANSI
standard have lead to discrepancies in the way implementations make up for them.

[1] SBCL builds on the original CMU code base, hence the name Steel Bank Common
Lisp.  (Carnegie was a steel magnate and Mellon was a Wall Street financier).

[2] Common Lisp special forms


问:
Javascript, Text Annotations and Ideas
I am very curious to hear input from others on a problem I've been contemplating for some time now.

Essentially I would like to present a user with a text document and allow him/her to make selections of text and annotate it.  Specific to the annotations i aim to achieve the following:

Allow users to make a text selection, annotate it, then save the selection and annotation for reference later

(UI) Support representing overlapped annotations.  For example if the string where: "This is the test sentence for my example test sentence", user1 might have an annotation on "is the test sentence for my example" and user2 might have an annotation on "for my example".

Account for a situations where the document's text changes.  The annotations would to be updated, if possible.

How would you tackle this from a technical perspective?

Some ideas I've had are:

Use javascript ranges and store an annotation as a pair of integers something like: (document_start_char, document_end_char).  Save this pair in the db.

Alternatively, using JS get the text selected and actually save the full text in the db. (not sure how i would then do overlapping annotations)

Represent overlapped annotations by applying a css style to highlight the text then darken the "stack" of annotations where they overlap.  Smallest annotation would always have to be on the top of the "stack".

What are your thoughts or areas of improvement?  How the heck could I support a document's text being updated without breaking all the annotations?

答:
Working on this myself, and using the OKFN Annotator mentioned above. It's non-trivial to do it right, and Annotator does it right:

https://github.com/okfn/annotator

As for the changing text issue: non-trivial also. Smart guy at the New York Times discusses that issue in this blog post:

http://open.blogs.nytimes.com/2011/01/11/emphasis-update-and-source/

Good luck.

Title: Javascript, Text Annotations and Ideas


问:
What are the practical ways to implement the SRP?
Simply what are the practical techniques people use to check if a class violates the single responsibility principle?

I know that a class should have only one reason to change, but that sentence is somewhat lacking a practical way to really implement that.

The only way I found is to use the sentence "The ......... should ......... itself." where the first space is the class name and the later is the method (responsibility) name.

However, sometimes it's hard to figure out if a responsibility really violates the SRP.

Are there more ways to check for the SRP?

Note:

The question is not about what the SRP means, but rather a practical methodology or a series of steps to check and implement the SRP.

UPDATE

I have added a sample class that clearly violates the SRP. It would be great if people could use it as an example to explain how they approach the single responsibility principle.

The example is from here.

答:
In your example, it is not clear SRP is being violated.  Maybe the report should be able to format and print itself, if they are relatively simple:

```<code>class Report {
  void format() {
     text = text.trim();
  }

  void print() {
     new Printer().write(text);
  }
}
</code>```

The methods are so simple it doesn't make sense to have ReportFormatter or ReportPrinter classes.  The only glaring problem in the interface is getReportData because it violates ask don't tell on non-value object.

On the other hand, if the methods are very complicated or there are many ways to format or print a Report then it makes sense to delegate the responsibility (also more testable):

```<code>class Report {
  void format(ReportFormatter formatter) {
     text = formatter.format(text);
  }

  void print(ReportPrinter printer) {
     printer.write(text);
  }
}
</code>```

SRP is a design principle not a philosophical concept and so it is based on the actual code you are working with.  Semantically you can divide or group a class into as many responsibilities as you wish.  However, as a practical principle, SRP should help you find the code you need to modify.  Signs you are violating SRP are:

Classes are so large you waste time scrolling or looking for the right method.

Classes are so small and numerous you waste time jumping between them or finding the correct one.

When you have to make a change it affects so many classes it is hard to keep track.

When you have to make a change it is unclear what classes need to change.

You can fix these through refactoring by improving names, grouping similar  code together, eliminating duplication, using a layered design, and splitting/combining classes as needed.  The best way to learn SRP is to dive into a codebase and refactor away the pain.

Body:
In your example, it is not clear SRP is being violated.  Maybe the report should be able to format and print itself, if they are relatively simple:

class Report {
  void format() {
     text = text.trim();
  }

  void print() {
     new Printer().write(text);
  }
}

The methods are so simple it doesn't make sense to have ReportFormatter or ReportPrinter classes.  The only glaring problem in the interface is getReportData because it violates ask don't tell on non-value object.

On the other hand, if the methods are very complicated or there are many ways to format or print a Report then it makes sense to delegate the responsibility (also more testable):

class Report {
  void format(ReportFormatter formatter) {
     text = formatter.format(text);
  }

  void print(ReportPrinter printer) {
     printer.write(text);
  }
}

SRP is a design principle not a philosophical concept and so it is based on the actual code you are working with.  Semantically you can divide or group a class into as many responsibilities as you wish.  However, as a practical principle, SRP should help you find the code you need to modify.  Signs you are violating SRP are:

Classes are so large you waste time scrolling or looking for the right method.

Classes are so small and numerous you waste time jumping between them or finding the correct one.

When you have to make a change it affects so many classes it is hard to keep track.

When you have to make a change it is unclear what classes need to change.

You can fix these through refactoring by improving names, grouping similar  code together, eliminating duplication, using a layered design, and splitting/combining classes as needed.  The best way to learn SRP is to dive into a codebase and refactor away the pain.


问:
Can Agile and ISO 9001 interact well?
There are few academic papers addressing the relationship between lean software development and the practices covered by ISO 9001. Most articles says that the divergence between these approaches is big, but some also point that these concepts can be complementary and gains are much higher when using both approaches.

Academically it is very beautiful, but in practice is it anyway?

So here's the question: do you work or worked at companies applying both Agile as ISO 9001? What is your perception? What is really good and what is inappropriate?

答:
I am a medical doctor and a freelance ISO Auditor in the USA.
I feel it is not fair to say that the ISO per se is a failure. It depends on how the company looks at it. If you are determined to marry the certificate alone yes they cannot achieve much,but we cannot blame the standard for it. You can achieve a lot if only you have quality processes in place. ISO is not a "documentation demon" as some portray it to be. The idea is that "do what you say and document what you do" I feel ISO can really gel well with the lean methodology of Six Sigma as it need not be limited to manufacturing processes.
As for as Agile is concerned,I see it as a subset of the already existing Iterative type of the SDLC. It is hard to imagine though that there is no importance to documentation. What happens to the lessons learned if you do not document.
I feel wit quality processes and the right documentation,Agile goes well with ISO and I go a step further to suggest that the lean of Six Sigma,ISO 9000 and Agile methodology do interact gainfully and can save you on time money and resources.
Also the CMMi model which is essentially built around the ISO standard can go hand in hand with the trio of ISO,Agile and lean Six Sigma.
Patience is the key word and I bet no standard or methodology can fetch the company profits only on getting certified in the respective decipline. Initially you need that much hard work to implement them and follow them in the right spirit.</p>

Title: Can Agile and ISO 9001 interact well?


问:
Are fluent interfaces more flexible than attributes and why?
In a EF 4.1 Code First tutorial the following code is given:

```<code>public class Department
{
    public int DepartmentId { get; set; }
    [Required]
    public string Name { get; set; }
    public virtual ICollection<Collaborator> Collaborators { get; set; }
}
</code>```

Then it is explained that the fluent interface is more flexible:

Data Annotations are definitely easy to use but it  is preferable to
  use a programmatic approach that provides much more flexibility.

The example of using the fluent interface is then given:

```<code>protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Department>().Property(dp => dp.Name).IsRequired();
    modelBuilder.Entity<Manager>().HasKey(ma => ma.ManagerCode);
    modelBuilder.Entity<Manager>().Property(ma => ma.Name)
        .IsConcurrencyToken(true)
        .IsVariableLength()
        .HasMaxLength(20);
}
</code>```

I can't understand why the fluent interface is supposedly better. Is it really? From my perspective it looks like the data annotations are more clear, and have more of a clean semantic feel to it.

My question is why would a fluent interface be a better option than using attributes, especially in this case?

(Note: I'm quite new to the whole concept of fluent interfaces, so please expect no prior knowledge on this.)

Reference: http://codefirst.codeplex.com/

答:
I don't think that statement should be broadly applied; it is very specific to Code First. In Code First, data annotations include only a subset of the functionality that is available in the fluent API. In other words, there are certain model configurations that can only be done using the fluent API.

For example, here are some of the things that can't be specified using the annotations:

The precision of a DateTime property

The precision and scale of numeric properties

A String or Binary property as fixed-length

A String property as non-unicode

The on-delete behavior of relationships

Advanced mapping strategies

Personally, I tend to use the validation-related data annotations whenever possible since other technologies like MVC can also take advantage of these. For everything else, I prefer the fluent API.


问:
What can be done to programming languages to avoid floating point pitfalls?
The misunderstanding of floating point arithmetic and its short-comings is a major cause of surprise and confusion in programming (consider the number of questions on Stack Overflow pertaining to "numbers not adding correctly"). Considering many programmers have yet to understand its implications, it has the potential to introduce many subtle bugs (especially into financial software). What can programming languages do to avoid its pitfalls for those that are unfamiliar with the concepts, while still offering its speed when accuracy is not critical for those that do understand the concepts?

答:
As other answers have noted, the only real way to avoid floating point pitfalls in financial software is not to use it there.  This may actually be feasible -- if you provide a well-designed library dedicated to financial math.

Functions designed to import floating-point estimates should be clearly labelled as such, and provided with parameters appropriate to that operation, e.g.:

```<code>Finance.importEstimate(float value, Finance roundingStep)
</code>```

The only real way to avoid floating point pitfalls in general is education -- programmers need to read and understand something like What Every Programmer Should Know About Floating-Point Arithmetic.

A few things that might help, though:

I'll second those who ask "why is exact equality testing for floating point even legal?"

Instead, use an isNear() function.

Provide, and encourage use of, floating-point accumulator objects (which add sequences of floating point values more stably than simply adding them all into a regular floating point variable).

ContentLicense: CC BY-SA 2.5

Body:
As other answers have noted, the only real way to avoid floating point pitfalls in financial software is not to use it there.  This may actually be feasible -- if you provide a well-designed library dedicated to financial math.

Functions designed to import floating-point estimates should be clearly labelled as such, and provided with parameters appropriate to that operation, e.g.:

Finance.importEstimate(float value, Finance roundingStep)

The only real way to avoid floating point pitfalls in general is education -- programmers need to read and understand something like What Every Programmer Should Know About Floating-Point Arithmetic.

A few things that might help, though:

I'll second those who ask "why is exact equality testing for floating point even legal?"

Instead, use an isNear() function.

Provide, and encourage use of, floating-point accumulator objects (which add sequences of floating point values more stably than simply adding them all into a regular floating point variable).


问:
Is OOP hard because it is not natural?
One can often hear that OOP naturally corresponds to the way people think about the world. But I would strongly disagree with this statement: We (or at least I) conceptualize the world in terms of relationships between things we encounter, but the focus of OOP is designing individual classes and their hierarchies.

Note that, in everyday life, relationships and actions exist mostly between objects that would have been instances of unrelated classes in OOP. Examples of such relationships are: "my screen is on top of the table"; "I (a human being) am sitting on a chair"; "a car is on the road"; "I am typing on the keyboard"; "the coffee machine boils water", "the text is shown in the terminal window."

We think in terms of bivalent (sometimes trivalent, as, for example in, "I gave you flowers") verbs where the verb is the action (relation) that operates on two objects to produce some result/action. The focus is on action, and the two (or three) [grammatical] objects have equal importance.

Contrast that with OOP where you first have to find one object (noun) and tell it to perform some action on another object. The way of thinking is shifted from actions/verbs operating on nouns to nouns operating on nouns -- it is as if everything is being said in passive or reflexive voice, e.g., "the text is being shown by the terminal window". Or maybe "the text draws itself on the terminal window".

Not only is the focus shifted to nouns, but one of the nouns (let's call it grammatical subject) is given higher "importance" than the other (grammatical object). Thus one must decide whether one will say terminalWindow.show(someText) or someText.show(terminalWindow). But why burden people with such trivial decisions with no operational consequences when one really means show(terminalWindow, someText)? [Consequences are operationally insignificant -- in both cases the text is shown on the terminal window -- but can be very serious in the design of class hierarchies and a "wrong" choice can lead to convoluted and hard to maintain code.]

I would therefore argue that the mainstream way of doing OOP (class-based, single-dispatch) is hard because it IS UNNATURAL and does not correspond to how humans think about the world. Generic methods from CLOS are closer to my way of thinking, but, alas, this is not widespread approach.

Given these problems, how/why did it happen that the currently mainstream way of doing OOP became so popular? And what, if anything, can be done to dethrone it?

答:
I think the OOP and OOP languages have problems too.

If understand it correctly, OOP is about black boxes (objects) which has push buttons on them that can be pushed (methods). Classes are just there to help organize these black boxes.

One problem is when the programmer puts the push buttons on the wrong object. The terminal cannot show text on itself, the text cannot show itself on the terminal. The window manager component of the operating system that can do that. Terminal window and text is just a passive entity. But if we think this way we realize the most entities are passive things and we would have only a very few objects that actually do anything (or simply one: the computer). Indeed when you use C you organize it into modules, these modules represent that few objects.

Another point is that the computer just executes instructions sequentially. Let's assume you have a VCR and a Television object, how would you play video? You probably write something like this:

```<code>connect(television, vcr);
vcr.turnOn();
television.turnOn();
insert(vcr, yourFavoriteCasette);
vcr.play();
while (vcr.isPlaying()) {} // Wait while the VCR is playing the casette.
vcr.eject();
vcr.turnOff();
television.turnOff();
</code>```

This would be this simple, but you would need at least 3 processors (or processes) for that: one plays the role of you, the second is the VCR, the third is the TV. But normally you have only one core (at least not enough for all your objects). In college, lot of my classmates did not understand why the GUI freezes when a push button does an expensive operation.

So I think an object oriented design may describe the world quite well, but it's not the best abstraction for the computer.

Title: Is OOP hard because it is not natural?

Body:
I think the OOP and OOP languages have problems too.

If understand it correctly, OOP is about black boxes (objects) which has push buttons on them that can be pushed (methods). Classes are just there to help organize these black boxes.

One problem is when the programmer puts the push buttons on the wrong object. The terminal cannot show text on itself, the text cannot show itself on the terminal. The window manager component of the operating system that can do that. Terminal window and text is just a passive entity. But if we think this way we realize the most entities are passive things and we would have only a very few objects that actually do anything (or simply one: the computer). Indeed when you use C you organize it into modules, these modules represent that few objects.

Another point is that the computer just executes instructions sequentially. Let's assume you have a VCR and a Television object, how would you play video? You probably write something like this:

connect(television, vcr);
vcr.turnOn();
television.turnOn();
insert(vcr, yourFavoriteCasette);
vcr.play();
while (vcr.isPlaying()) {} // Wait while the VCR is playing the casette.
vcr.eject();
vcr.turnOff();
television.turnOff();

This would be this simple, but you would need at least 3 processors (or processes) for that: one plays the role of you, the second is the VCR, the third is the TV. But normally you have only one core (at least not enough for all your objects). In college, lot of my classmates did not understand why the GUI freezes when a push button does an expensive operation.

So I think an object oriented design may describe the world quite well, but it's not the best abstraction for the computer.


问:
Can someone explain to me C#'s coding convention?
I recently started working with Unity3D and primarily scripting with C#. As I normally program in Java, the differences aren't too great but I still referred to a crash course just  to make sure I am on the right track.

However, my biggest curiosity with C# is that it capitalises the first letter of its method names (eg. Java: getPrime() C#: GetPrime() aka: Pascal Case?). Is there a good reason for this? I understand from the crash course page that I read that apparently it's convention for .Net and I have no way of ever changing it, but I am curious to hear why it was done like this as opposed to the normal (relative?) camel case that, say, Java uses.

Note: I understand that languages have their own coding conventions (Python methods are all lower case which also applies in this question) but I've never really understood why it isn't formalised into a standard.

答: Naming conventions represent arbitrary choices of their publisher. There is nothing in the language itself to prohibit you from naming your methods the way you do in Java: as long as the first character is a letter/underscore, and all other characters are letters, digits, or underscores, C# is not going to complain. However, the class libraries that come with .NET follow a convention that Microsoft has adopted internally. Microsoft also published these guidelines, so that others may choose to adopt them for their own class libraries too. Although it is your choice to follow or to ignore Microsoft's guidelines, familiarization with your code by others may go faster if you follow the same naming guidelines.</p>


答:
Perhaps due to Pascal / Delphi influence. The creator of C# and Delphi was the same person after all (Anders Hejlsberg).

Delphi coding conventions by and large happen to be the same as C#'s in this aspect; see http://www.econos.de/delphi/cs.html#ObjectPascal_Procedures or http://wiki.delphi-jedi.org/index.php?title=Style_Guide#Method_Naming - coincidence?

Title: Can someone explain to me C#'s coding convention?

Body:
I recently started working with Unity3D and primarily scripting with C#. As I normally program in Java, the differences aren't too great but I still referred to a crash course just  to make sure I am on the right track.

However, my biggest curiosity with C# is that it capitalises the first letter of its method names (eg. Java: getPrime() C#: GetPrime() aka: Pascal Case?). Is there a good reason for this? I understand from the crash course page that I read that apparently it's convention for .Net and I have no way of ever changing it, but I am curious to hear why it was done like this as opposed to the normal (relative?) camel case that, say, Java uses.

Note: I understand that languages have their own coding conventions (Python methods are all lower case which also applies in this question) but I've never really understood why it isn't formalised into a standard.


问:
Legitimate use for IRC bots
I recently saw a question on SE about how to do such and such when creating an IRC bot. The only use of IRC bots I was familiar with was message flooding and spamming. I did a Google search for the string I used as my title and was led to an article that was an eye opener as to what all an evil IRC bot could do, but I did not see any explanation of a benevolent (or neutral) use of an IRC bot.

Is there any? If so, what are they used for?

答:
I have an IRC bot which rolls dice for RPGs. It has support for various game systems and types of output. It's useful as it allows someone to (for example) 'roll' 30 6-sided dice, sort them by value, reroll any 6's, and report back the number of 5's or 6's rolled in total (Shadowrun).

Alternately, I also have a chatbot that uses Markov models to generate entertaining text from the channel logs. There's also a variant of this which takes a corpus from specific authors/locations; so that text can be generated in the style of said authors. ShakespeareBot, DylanBot, PalahniukBot; that sort of thing.

My next project is going to be a card-dealing IRC bot. That way the channel I frequent can play poker or similar things. (Or RPGs that use cards as a mechanic, of course)

Title: Legitimate use for IRC bots


答: In addition to the other answers made, having camel case for methods means that they can conflict with names for private members, parameters and method variables that use camel case for their naming. In Java (and C# 1.0) this isn't terribly common since delegate use is awkward and rare. In modern C# it's not exactly common, but it's also not unheard-of.


问:
EE vs Computer Science: Effect on Developers' Approaches, Styles?
Are there any systematic differences between software developers (sw engineers, architect, whatever job title) with an electronics or other engineering background, compared to those who entered the profession through computer science?

By electronics background, I mean an EE degree, or a self-taught electronics tinkerer, other types of engineers and experimental physicists.

I'm wondering if coming into the software-making professions from a strong knowledge of flip flops, tristate buffers, clock edge rise times and so forth, usually leads to a distinct approach to problems, mindsets, or superior skills at certain specialties and lack of skills at others, when compared to the computer science types who are full of concepts like abstract data types, object orientation, database normalization, who speak of "closures" in programming languages - things that make little sense to the soldering iron crowd until they learn enough programming.

The real world, I'm sure, offers a wild range of individual exceptions, but for the most part, can you say there are overall differences?   Would these have hiring implications e.g. (to make up something) "never hire an electron wrangler to do database design"?   Could knowing about any differences help job seekers find something appropriate more effectively?   Or provide enlightenment or some practical advice for those who find themselves misfits in a particular job role?

(Btw, I've never taken any computer science classes; my impression of exactly what they cover is fuzzy.   I'm an electronics/physics/art type, myself.)

答:
If I had to generalize, here's what my experience has been:

Engineers (or just EE's) tend to do better in the "perfection of the small".  Given a small programming task, they think very long and hard about all the edge cases, and are more likely to end up building a piece of software that's very robust.  It's usually driven from a top-down design-it-all-up-front approach, because that's what they're used to in hardware.  It usually involves the use of state machines, because they're used to designing them for hardware, and it fits with the "big design" approach.  On the flip side, they aren't thinking as much about scalability or maintainability.

Your traditional developers are better at managing large complexity, mostly because the training pushes breaking down problems into smaller more manageable bits.  They're taught to avoid the big design, and just separate the concerns, write tests, and make the tests pass.  Typically there are lots of little missed edge cases, just due to complexity & time, but those eventually get covered off.  Developers tend to take advantage of the fact that it's just software and it should be (or is) easy to change.  When EE's work with hardware, they don't have this advantage, and I think it takes time to make the transition.

As I said, that's my generalized experience.  It's not true in every case.


问:
Return magic value, throw exception or return false on failure?
I sometimes end up having to write a method or property for a class library for which it is not exceptional to have no real answer, but a failure. Something cannot be determined, is not available, not found, not currently possible or there is no more data available.

I think there are three possible solutions for such a relatively non-exceptional situation to indicate failure in C# 4:

return a magic value that has no meaning otherwise (such as null and -1);

throw an exception (e.g. KeyNotFoundException);

return false and provide the actual return value in an out parameter, (such as Dictionary<,>.TryGetValue).

So the questions are: in which non-exceptional situation should I throw an exception? And if I should not throw: when is returning a magic value perferred above implementing a Try* method with an out parameter? (To me the out parameter seems dirty, and it is more work to use it properly.)

I'm looking for factual answers, such as answers involving design guidelines (I don't know any about Try* methods), usability (as I ask this for a class library), consistency with the BCL, and readability.

In the .NET Framework Base Class Library, all three methods are used:

return a magic value that has no meaning otherwise:

Collection<T>.IndexOf returns -1,

StreamReader.Read returns -1,

Math.Sqrt returns NaN,

Hashtable.Item returns null;

throw an exception:

Dictionary<,>.Item throws KeyNotFoundException,

Double.Parse throws FormatException; or

return false and provide the actual return value in an out parameter:

Dictionary<,>.TryGetValue,

Double.TryParse.

Note that as Hashtable was created in the time when there were no generics in C#, it uses object and can therefore return null as a magic value. But with generics, exceptions are used in Dictionary<,>, and initially it didn't have TryGetValue. Apparently insights change.

Obviously, the Item-TryGetValue and Parse-TryParse duality is there for a reason, so I assume that throwing exceptions for non-exceptional failures is in C# 4 not done. However, the Try* methods didn't always exist, even when Dictionary<,>.Item existed.

答:
You're trying to communicate to the user of the API what they have to do.  If you throw an exception, there's nothing forcing them to catch it, and only reading the documentation is going to let them know what all the possibilities are.  Personally I find it slow and tedious to dig into the documentation to find all the exceptions that a certain method might throw (even if it's in intellisense, I still have to copy them out manually).

A magic value still requires you to read the documentation, and possibly reference some const table to decode the value.  At least it doesn't have the overhead of an exception for what you call a non-exceptional occurrence.

That is why even though out parameters are sometimes frowned upon, I prefer that method, with the Try... syntax.  It's canonical .NET and C# syntax.  You're communicating to the user of the API that they have to check the return value before using the result.  You can also include a second out parameter with a helpful error message, which again helps with debugging.  That's why I vote for the Try... with out parameter solution.

Another option is to return a special "result" object, though I find this a lot more tedious:

```<code>interface IMyResult
{
    bool Success { get; }
    // Only access this if Success is true
    MyOtherClass Result { get; }
    // Only access this if Success is false
    string ErrorMessage { get; }
}
</code>```

Then your function looks right because it only has input parameters and it only returns one thing.  It's just that the one thing it returns is kind of a tuple.

In fact, if you're into that kind of thing, you can use the new Tuple<> classes that were introduced in .NET 4.  Personally I don't like the fact that the meaning of each field is less explicit because I can't give Item1 and Item2 useful names.

OwnerDisplayName: Virtlink

Body:
You're trying to communicate to the user of the API what they have to do.  If you throw an exception, there's nothing forcing them to catch it, and only reading the documentation is going to let them know what all the possibilities are.  Personally I find it slow and tedious to dig into the documentation to find all the exceptions that a certain method might throw (even if it's in intellisense, I still have to copy them out manually).

A magic value still requires you to read the documentation, and possibly reference some const table to decode the value.  At least it doesn't have the overhead of an exception for what you call a non-exceptional occurrence.

That is why even though out parameters are sometimes frowned upon, I prefer that method, with the Try... syntax.  It's canonical .NET and C# syntax.  You're communicating to the user of the API that they have to check the return value before using the result.  You can also include a second out parameter with a helpful error message, which again helps with debugging.  That's why I vote for the Try... with out parameter solution.

Another option is to return a special "result" object, though I find this a lot more tedious:

interface IMyResult
{
    bool Success { get; }
    // Only access this if Success is true
    MyOtherClass Result { get; }
    // Only access this if Success is false
    string ErrorMessage { get; }
}

Then your function looks right because it only has input parameters and it only returns one thing.  It's just that the one thing it returns is kind of a tuple.

In fact, if you're into that kind of thing, you can use the new Tuple<> classes that were introduced in .NET 4.  Personally I don't like the fact that the meaning of each field is less explicit because I can't give Item1 and Item2 useful names.


答:
I don't think that your examples are really equivalent. There are three distinct groups, each with it's own rationale for its behaviour.

Magic value is a good option when there is an "until" condition such as StreamReader.Read or when there is a simple to use value that will never be a valid answer (-1 for IndexOf).

Throw exception when the semantics of the function is that the caller is sure that it will work. In this case a non-existing key or a bad double format is truly exceptional.

Use an out parameter and return a bool if the semantics is to probe if the operation is possible or not.

The examples you provide are perfectly clear for cases 2 and 3. For the magic values, it can be argued if this is a good design decision or not in all cases.

The NaN returned by Math.Sqrt is a special case - it follows the floating point standard.

Title: Return magic value, throw exception or return false on failure?

Body:
I sometimes end up having to write a method or property for a class library for which it is not exceptional to have no real answer, but a failure. Something cannot be determined, is not available, not found, not currently possible or there is no more data available.

I think there are three possible solutions for such a relatively non-exceptional situation to indicate failure in C# 4:

return a magic value that has no meaning otherwise (such as null and -1);

throw an exception (e.g. KeyNotFoundException);

return false and provide the actual return value in an out parameter, (such as Dictionary<,>.TryGetValue).

So the questions are: in which non-exceptional situation should I throw an exception? And if I should not throw: when is returning a magic value perferred above implementing a Try* method with an out parameter? (To me the out parameter seems dirty, and it is more work to use it properly.)

I'm looking for factual answers, such as answers involving design guidelines (I don't know any about Try* methods), usability (as I ask this for a class library), consistency with the BCL, and readability.

In the .NET Framework Base Class Library, all three methods are used:

return a magic value that has no meaning otherwise:

Collection<T>.IndexOf returns -1,

StreamReader.Read returns -1,

Math.Sqrt returns NaN,

Hashtable.Item returns null;

throw an exception:

Dictionary<,>.Item throws KeyNotFoundException,

Double.Parse throws FormatException; or

return false and provide the actual return value in an out parameter:

Dictionary<,>.TryGetValue,

Double.TryParse.

Note that as Hashtable was created in the time when there were no generics in C#, it uses object and can therefore return null as a magic value. But with generics, exceptions are used in Dictionary<,>, and initially it didn't have TryGetValue. Apparently insights change.

Obviously, the Item-TryGetValue and Parse-TryParse duality is there for a reason, so I assume that throwing exceptions for non-exceptional failures is in C# 4 not done. However, the Try* methods didn't always exist, even when Dictionary<,>.Item existed.

OwnerDisplayName: Anders Abel


答:
I think the Try pattern is the best choice, when code just indicate what happened. I hate out param and like nullable object. I've created following class

```<code>public sealed class Bag<TValue>
{
    public Bag(TValue value, bool hasValue = true)
    {
        HasValue = hasValue;
        Value = value;
    }

    public static Bag<TValue> Empty
    {
        get { return new Bag<TValue>(default(TValue), false); }
    }

    public bool HasValue { get; private set; }
    public TValue Value { get; private set; }
}
</code>```

so I can write following code

```<code>    public static Bag<XElement> GetXElement(this XElement element, string elementName)
    {
        try
        {
            XElement result = element.Element(elementName);
            return result == null
                       ? Bag<XElement>.Empty
                       : new Bag<XElement>(result);
        }
        catch (Exception)
        {
            return Bag<XElement>.Empty;
        }
    }
</code>```

Looks like nullable but not only for value type

Another example

```<code>    public static Bag<string> TryParseString(this XElement element, string attributeName)
    {
        Bag<string> attributeResult = GetString(element, attributeName);
        if (attributeResult.HasValue)
        {
            return new Bag<string>(attributeResult.Value);
        }
        return Bag<string>.Empty;
    }

    private static Bag<string> GetString(XElement element, string attributeName)
    {
        try
        {
            string result = element.GetAttribute(attributeName).Value;
            return new Bag<string>(result);
        }
        catch (Exception)
        {
            return Bag<string>.Empty;
        }
    }
</code>```

Body:
I think the Try pattern is the best choice, when code just indicate what happened. I hate out param and like nullable object. I've created following class

public sealed class Bag<TValue>
{
    public Bag(TValue value, bool hasValue = true)
    {
        HasValue = hasValue;
        Value = value;
    }

    public static Bag<TValue> Empty
    {
        get { return new Bag<TValue>(default(TValue), false); }
    }

    public bool HasValue { get; private set; }
    public TValue Value { get; private set; }
}

so I can write following code

    public static Bag<XElement> GetXElement(this XElement element, string elementName)
    {
        try
        {
            XElement result = element.Element(elementName);
            return result == null
                       ? Bag<XElement>.Empty
                       : new Bag<XElement>(result);
        }
        catch (Exception)
        {
            return Bag<XElement>.Empty;
        }
    }

Looks like nullable but not only for value type

Another example

    public static Bag<string> TryParseString(this XElement element, string attributeName)
    {
        Bag<string> attributeResult = GetString(element, attributeName);
        if (attributeResult.HasValue)
        {
            return new Bag<string>(attributeResult.Value);
        }
        return Bag<string>.Empty;
    }

    private static Bag<string> GetString(XElement element, string attributeName)
    {
        try
        {
            string result = element.GetAttribute(attributeName).Value;
            return new Bag<string>(result);
        }
        catch (Exception)
        {
            return Bag<string>.Empty;
        }
    }

OwnerDisplayName: GSerjo


答:
As your examples already show, each such case must be evaluated separately and there is a considerable spectrum of gray between "exceptional circumstances" and "flow control", especially if your method is intended to be reusable, and might be used in quite different patterns than it was originally designed for.  Do not expect us all here to agree on what "non-exceptional" means, especially if you immediately discuss the possibility of using "exceptions" to implement that.

We might also not agree on what design makes the code easiest to read and maintain, but I will assume that the library designer has a clear personal vision of that and only needs to balance it against the other considerations involved.

Short answer

Follow your gut feelings except when you are designing pretty fast methods and expect a possibility of unforeseen reuse.

Long answer

Each future caller may freely translate between error codes and exceptions as it wishes in both directions; this makes the two design approaches almost equivalent except for performance, debugger-friendliness and some restricted interoperability contexts.  This usually boils down to performance, so let's focus on that.

As a rule of thumb, expect that throwing an exception is 200x slower than a regular return (in reality, there is a significant variance in that).

As another rule of thumb, throwing an exception may often allow much cleaner code compared with the crudest of magic values, because you are not relying on the programmer translating the error code into another error code, as it travels through multiple layers of client code towards a point where there is enough context for handling it in a consistent and adequate way.  (Special case: null tends to fare better here than other magic values because of its tendency to automatically translating itself to a NullReferenceException in case of some, but not all types of defects; usually, but not always, quite close to the source of the defect.)

So what's the lesson?

For a function that's called just a few times during the lifetime of an application (like the app initialization), use anything that gives you cleaner, easier to understand code.  Performance cannot be a concern.

For a throw-away function, use anything that gives you cleaner code.  Then do some profiling (if needed at all) and change exceptions to return codes if they are among the suspected top bottlenecks based on measurements or overall program structure.

For an expensive reusable function, use anything that gives you cleaner code.  If you basically always have to undergo a network roundtrip or parse an on-disk XML file, the overhead of throwing an exception is probably negligible.  It is more important to not lose  details of any failure, not even accidentally, than to return from a "non-exceptional failure" extra fast.

A lean reusable function requires more thought.  By employing exceptions, you are forcing something like a 100 times slow down on callers who will see the exception on half of their (many) calls, if the body of the function executes very fast.  Exceptions are still a design option, but you will have to provide a low overhead alternative for callers who can not afford this.  Let's look at an example.

You list a great example of Dictionary<,>.Item, which, loosely speaking, changed from returning null values to throwing KeyNotFoundException between .NET 1.1 and .NET 2.0 (only if you are willing to consider Hashtable.Item to be its practical non-generic forerunner).  The reason of this "change" is not without interest here.  Performance optimization of value types (no more boxing) made the original magic value (null) a non-option; out parameters would just bring a small part of the performance cost back.  This latter performance consideration is completely negligible in comparison with the overhead of throwing a KeyNotFoundException, but the exception design is still superior here.  Why?

ref/out parameters incur their costs every time, not just in the "failure" case

Anyone who cares can call Contains before any call to the indexer, and this pattern reads completely naturally.  If a developer wants to but forgets to call Contains, no performance issues can creep in; KeyNotFoundException is loud enough to be noticed and fixed.

OwnerDisplayName: Jirka Hanika


问:
What's your favourite quote about programming?
What's your favourite quote about programming?

One quote per answer, and please check for duplicates before posting!

答:
I have always wished for my computer to be as easy to use as my telephone; my wish has come true because I can no longer figure out how to use my telephone

-- Bjarne Stroustrup

LastEditorDisplayName: Roger Pate


问:
can gpl code contain more restrictively licensed code? (CC BY-NC-ND 3.0)
There is a wordpress theme I am modifying to create my own derived work. This original wordpress theme has the GPLv2 licence in it's root directory, so I assume that the entire theme is GPL code.

There is a particular php file which has the following written in its first few lines:

// This code is protected under Creative Commons License: http://creativecommons.org/licenses/by-nc-nd/3.0/

Is that legal for them to make a part of the code under a more restrictive license? The CC license referenced is more restrictive because it prohibits derivative work, but that is exactly what I am doing is making a derivative work.

So here are my two questions:

By having the full GPL (version 2) licence in the root of the theme's directory, is that a legally binding way of saying that the code is licensed under the GPL2?

Is that legal for them to make that file licensed under that particular CC license?

Ultimately, what I care about is this: I want to make sure that what I am doing is technically legal :)

None of the source files actually say that it is under GPL; except the theme does include jQuery and jQuery plugins (under MIT and GPL2) as well as thumb.php which explicitly says it is under GPL2.

答:
From what I understand, what they did is technically not legal, and the GPL license trumps the referenced CC license.

According to http://www.gnu.org/licenses/gpl-howto.html:

Whichever license you plan to use, the process involves adding two elements to each source file of your program: a copyright notice (such as “Copyright 1999 Terry Jones”), and a statement of copying permission, saying that the program is distributed under the terms of the GNU General Public License (or the Lesser GPL).

And they did not do that. However, the inclusion of thumb.php immediately makes the whole theme ("program") under GPL according to http://www.gnu.org/licenses/old-licenses/gpl-2.0-faq.html#MereAggregation:

If either part is covered by the GPL, the whole combination must also be released under the GPL

Therefore, I can safely know that the GPLv2 license trumps anything else for the whole theme.


答:
If the license is compatible then there's no reason why not: several GPL releases (for example, most of the id Software game engines, who you would expect would be particular about getting this right) combine code in this manner.  The owner of the copyright for a GPL work is also allowed to define special exceptions that can allow this for incompatible licenses;
see: http://www.gnu.org/licenses/gpl-faq.html#GPLIncompatibleLibs and http://en.wikipedia.org/wiki/GPL_linking_exception.

IANAL, etc.

Title: can gpl code contain more restrictively licensed code? (CC BY-NC-ND 3.0)

Body:
There is a wordpress theme I am modifying to create my own derived work. This original wordpress theme has the GPLv2 licence in it's root directory, so I assume that the entire theme is GPL code.

There is a particular php file which has the following written in its first few lines:

// This code is protected under Creative Commons License: http://creativecommons.org/licenses/by-nc-nd/3.0/

Is that legal for them to make a part of the code under a more restrictive license? The CC license referenced is more restrictive because it prohibits derivative work, but that is exactly what I am doing is making a derivative work.

So here are my two questions:

By having the full GPL (version 2) licence in the root of the theme's directory, is that a legally binding way of saying that the code is licensed under the GPL2?

Is that legal for them to make that file licensed under that particular CC license?

Ultimately, what I care about is this: I want to make sure that what I am doing is technically legal :)

None of the source files actually say that it is under GPL; except the theme does include jQuery and jQuery plugins (under MIT and GPL2) as well as thumb.php which explicitly says it is under GPL2.


答:
What is the best thing to do in such a relatively non-exceptional situation to indicate failure, and why?

You should not allow failure.

I know, it's hand-wavey and idealistic, but hear me out. When doing design, there are a number of cases where you have the opportunity to favor a version that has no failure modes. Instead of having a 'FindAll' that fails, LINQ uses a where clause that simply returns an empty enumerable. Instead of having an object that needs to be initialized before used, let the constructor initialize the object (or initialize when the not-initialized is detected). The key is removing the failure branch in consumer code. This is the problem, so focus on it.

Another strategy for this is the KeyNotFound sscenario. In almost every codebase I've worked on since 3.0, something like this extension method exists:

```<code>public static class DictionaryExtensions {
    public static V GetValue<K, V>(this IDictionary<K, V> arg, K key, Func<K,V> ifNotFound) {
        if (!arg.ContainsKey(key)) {
            return ifNotFound(key);
        }

        return arg[key];
    }
}
</code>```

There is no real failure mode for this. ConcurrentDictionary has a similar GetOrAdd built in.

All that said, there will always be times where it's simply unavoidable. All three have their place, but I would favor the first option. Despite all that is made of null's danger, it's well known and fits into a lot of the 'item not found' or 'result is not applicable' scenarios that make up the "not exceptional failure" set. Especially when you're making nullable value types, the significance of the 'this might fail' is very explicit in code and hard to forget/screw up.

The second option is good enough when your user does something dumb. Gives you a string with the wrong format, tries to set the date to December 42nd... something that you want things to blow up quickly and spectacularly during testing so that bad code is identified and fixed.

The last option is one I increasingly dislike. Out parameters are awkward, and tend to violate some of the best practices when making methods, like focusing on one thing and not having side effects. Plus, the out param is usually only meaningful during success. That said, they are essential for certain operations that are usually constrained by concurrency concerns, or performance considerations (where you don't want to make a second trip to the DB for example).

If the return value and out param are non-trivial, then Scott Whitlock's suggestion about a result object is preferred (like Regex's Match class).

Body:
What is the best thing to do in such a relatively non-exceptional situation to indicate failure, and why?

You should not allow failure.

I know, it's hand-wavey and idealistic, but hear me out. When doing design, there are a number of cases where you have the opportunity to favor a version that has no failure modes. Instead of having a 'FindAll' that fails, LINQ uses a where clause that simply returns an empty enumerable. Instead of having an object that needs to be initialized before used, let the constructor initialize the object (or initialize when the not-initialized is detected). The key is removing the failure branch in consumer code. This is the problem, so focus on it.

Another strategy for this is the KeyNotFound sscenario. In almost every codebase I've worked on since 3.0, something like this extension method exists:

public static class DictionaryExtensions {
    public static V GetValue<K, V>(this IDictionary<K, V> arg, K key, Func<K,V> ifNotFound) {
        if (!arg.ContainsKey(key)) {
            return ifNotFound(key);
        }

        return arg[key];
    }
}

There is no real failure mode for this. ConcurrentDictionary has a similar GetOrAdd built in.

All that said, there will always be times where it's simply unavoidable. All three have their place, but I would favor the first option. Despite all that is made of null's danger, it's well known and fits into a lot of the 'item not found' or 'result is not applicable' scenarios that make up the "not exceptional failure" set. Especially when you're making nullable value types, the significance of the 'this might fail' is very explicit in code and hard to forget/screw up.

The second option is good enough when your user does something dumb. Gives you a string with the wrong format, tries to set the date to December 42nd... something that you want things to blow up quickly and spectacularly during testing so that bad code is identified and fixed.

The last option is one I increasingly dislike. Out parameters are awkward, and tend to violate some of the best practices when making methods, like focusing on one thing and not having side effects. Plus, the out param is usually only meaningful during success. That said, they are essential for certain operations that are usually constrained by concurrency concerns, or performance considerations (where you don't want to make a second trip to the DB for example).

If the return value and out param are non-trivial, then Scott Whitlock's suggestion about a result object is preferred (like Regex's Match class).


答:
Always prefer to throw an exception. It's got a uniform interface amongst all functions that could fail, and it indicates failure as noisily as possible- a very desirable property.

Note that Parse and TryParse aren't really the same thing apart from failure modes. The fact that TryParse can also return the value is somewhat orthogonal, really. Consider the situation where, for example, you're validating some input. You don't actually care what the value is, as long as it's valid. And there's nothing wrong with offering a kind of IsValidFor(arguments) function. But it can never be the primary mode of operation.


问:
How to properly design classes for a big project?
If we need to represent classes in a class diagram for a big project that is not completely designed yet, and the classes have to be actual tables in a database, how would we predict and design the classes?

Let's say we have a project that is going to have more than 15 tables, do all these tables need to be classes in the class diagram?

How would classes be designed in this kind of situation? The language that is being used is Java and the class diagram has to prepared in UML. I know how to design them, I just don't know if the tables should represent the classes in this case.

答:
It does not seem to be a big project if you have a little more than 15 tables. However, main point is which development approach and design are you planning to have?

Data modeling needs to be done before class designs. While doing your data modeling , you may also continue to work on your Architecture Modeling Technique. There are several alternatives to consider and all that will depend on your project specifications. Tools like ER diagram may help you to design high level, as well as low level class diagrams.

Depending on your application type, you may get some hints on structuring your classes from open source project samples. Let me mention an important point, as your project moves forward you may see need to slightly change the structure or add additional layers depending on requirements and design.

There are some good references to look:

Open Source Software in Java

Open Source Projects at Sun

Well written java open source projects (for learning)?


问:
How to deal with hints/tutorial mode?
Currently I'm  working on an basic application that has a 'tutorial mode'. Initially hints (bubbles with text) will be displayed above various ui elements, explaining how they work. Currently I have a main view which contains a hint object that can be updated (position, text, etc.) and I'm dispatching update events from the various views that need to display a hint. In most cases when the user click a hint, it disappears, but there are a few situations when the user must perform another action(like dragging-dropping an element, clicking another,etc.) to progress.

Phew, that's the background in a nutshell. My main question is:

Should there be dispatching events from various views and handle the hints centrally or should hints only be handled locally within each view ?
What's the recommended approach ?

答:
I'd suggest having hints dealt with in their own class, including body of the hint (so you can change it). To call it, just add one line of code, like:

```<code> if ( hintsOn ) { HintHandeler.display ( ); }
</code>```

The less the call to the hints needs to know, the better. Try to have whatever must be dealt with to be dealt with in the Hints class

To find out where the HintHandeler call came from, make use of: Thread.currentThread().getStackTrace(), and lex it as needed to find out where you came from. Ideally, store that in a variable, then have a massive switch{} statement, if possible (for speed), go down the list of places a call might be made from, and call additional code as necessary.

OwnerDisplayName: George Profenza

Title: How to deal with hints/tutorial mode?

Body:
I'd suggest having hints dealt with in their own class, including body of the hint (so you can change it). To call it, just add one line of code, like:

 if ( hintsOn ) { HintHandeler.display ( ); }

The less the call to the hints needs to know, the better. Try to have whatever must be dealt with to be dealt with in the Hints class

To find out where the HintHandeler call came from, make use of: Thread.currentThread().getStackTrace(), and lex it as needed to find out where you came from. Ideally, store that in a variable, then have a massive switch{} statement, if possible (for speed), go down the list of places a call might be made from, and call additional code as necessary.


答:
"This original wordpress theme has the GPLv2 licence in it's root
  directory, so I assume that the entire theme is GPL code"

Not necessarily, the GPLed code should say so in each source file. There may be other differently;y licensed code in the same directory, themes/icons/tutorials/samples etc might be licensed differently.

The GPLed source code probably has a comment saying "See copying.txt for licence", so you would expect a copying.txt in the directory. The copying.txt doesn't confer any license by being there


问:
Why can't the IT industry deliver large, faultless projects quickly as in other industries?
After watching National Geographic's MegaStructures series, I was surprised how fast large projects are completed. Once the preliminary work (design, specifications, etc.) is done on paper, the realization itself of huge projects takes just a few years or sometimes a few months.

For example, Airbus A380 "formally launched on Dec. 19, 2000", and "in the Early March, 2005", the aircraft was already tested. The same goes for huge oil tankers, skyscrapers, etc.

Comparing this to the delays in the software industry, I can't help wondering why most IT projects are so slow, or more precisely, why they cannot be as fast and faultless, at the same scale, given enough people?

Projects such as the Airbus A380 present both:

Major unforeseen risks: while this is not the first aircraft built, it still pushes the limits of the technology and things which worked well for smaller airliners may not work for the larger one due to physical constraints; in the same way, new technologies are used which were not used before, because for example they were not available in 1969 when the Boeing 747 was certified.

Risks related to human resources and management in general: people quitting in the middle of the project, inability to reach a person because she's on vacation, ordinary human errors, etc.

With those risks, people still achieve projects like those large airliners in a very short period of time, and despite the delivery delays, those projects are still hugely successful and of a high quality.

When it comes to software development, the projects are hardly as large and complicated as an airliner (both technically and in terms of management), and have slightly less unforeseen risks from the real world.

Still, most IT projects are slow and late, and adding more developers to the project is not a solution (going from a team of ten developers to two thousand will sometimes make it possible to deliver the project faster, sometimes not, and sometimes will only harm the project and increase the risk of not finishing it at all).

Those which are still delivered may often contain a lot of bugs, requiring consecutive service packs and regular updates (imagine "installing updates" on every Airbus A380 twice a week to patch the bugs in the original product to prevent the aircraft from crashing).

How can such differences be explained? Is it due exclusively to the fact that the software development industry is too young to be able to manage thousands of people on a single project in order to deliver large scale, nearly faultless products very fast?

答:
Imagine, in the middle of the design of the Airbus A380, someone piped up in a meeting and said, "Heh, could build it as a triplane?" Others joined in saying, "Yeah, yeah. A triplane. More wings are better." The next thee years is spent turning the A380 design into a triplane. At another meeting, someone says, "A triplane? That's old. We want a biplane. Just remove one of the wings."

Or imagine, in the middle of a bridge construction project, someone says, "Heh, we just made a deal with a shipping company. They need the bridge to be another 40 feet higher, because their ships are much taller. Fix it. Thanks."

These are but some of the reasons why software projects, big and small, end in failure at an alarming rate.


问:
Patterns for Handling Changing Property Sets in C++
I have a bunch "Property Sets" (which are simple structs containing POD members). I'd like to modify these property sets (eg: add a new member) at run time so that the definition of the property sets can be externalized and the code itself can be re-used with multiple versions/types of property sets with minimal/no changes.

For example, a property set could look like this:

```<code>struct PropSetA
{
    bool activeFlag;
    int processingCount;
    /* snip few other such fields*/
};
</code>```

But instead of setting its definition in stone at compile time, I'd like to create it dynamically at run time. Something like:

```<code>class PropSet propSetA;
propSetA("activeFlag",true);  //overloading the function call operator
propSetA("processingCount",0);
</code>```

And the code dependent on the property sets (possibly in some other library) will use the data like so:

```<code> bool actvFlag = propSet["activeFlag"];
 if(actvFlag  == true)
 {
   //Do Stuff
 }
</code>```

The current implementation behind all of this is as follows:

```<code>class PropValue
{
 public:
    // Variant like class for holding multiple data-types
    // overloaded Conversion operator. Eg:
    operator bool()
    {
      return (baseType == BOOLEAN) ? this->ToBoolean() : false;
    }
    // And a method to create PropValues various base datatypes
    static FromBool(bool baseValue);
};

class PropSet
{

 public:
  // overloaded[] operator for adding properties
  void operator()(std::string propName, bool propVal)
  {
    propMap.insert(std::make_pair(propName, PropVal::FromBool(propVal)));
  }

 protected:
   // the property map
   std::map<std::string, PropValue> propMap;
};
</code>```

This problem at hand is similar to this question on SO and the current approach (described above) is based on this answer. But as noted over at SO this is more of a hack than a proper solution. The fundamental issues that I have with this approach are as follows:

Extending this for supporting new types will require significant code change. At the bare minimum overloaded operators need to be extended to support the new type.

Supporting complex properties (eg: struct containing struct) is tricky.

Supporting a reference mechanism (needed for an optimization of not duplicating identical property sets) is tricky. This also applies to supporting pointers and multi-dimensional arrays in general.

Are there any known patterns for dealing with this scenario? Essentially, I'm looking for the equivalent of the visitor pattern, but for extending class properties rather than methods.

Edit: Modified problem statement for clarity and added some more code from current implementation.

答:
One suggestion is to make a PropValue a base type and BoolValue, IntValue, DoubleValue, ArrayValue, can be derived classes. Numbers could optionally be grouped into NumberValue and ArrayValue could be subclassed into VectorValue, DictionaryValue, etc.

This could help divide up the problems of defining traits as well as where to allow conversions of types.

I'm not seeing a complete picture of where you are handling dynamic types. It seems as though the consumer already knows or expects a bool in your example. So it is only syntactic sugar make an overloaded conversion rather than to call something like:

```<code>bool b_by_ref;
Error err  = Propset.GetBool("propname",&b_by_ref);
</code>```

If you don't know or care about the type yet, just pass it as a PropValue* and let functions worry about the types internally in that algorithm.

```<code>void FooFunc (PropValue* p)
{
    DWORD id = p->GetTypeID();
    switch(id)
    {
        case INT_VALUE_TYPEID:   FooInt(p);
        case FLOAT_VALUE_TYPEID: FooFloat(p);
         .....
        default: Assert(0);
    }
 }
</code>```

Body:
One suggestion is to make a PropValue a base type and BoolValue, IntValue, DoubleValue, ArrayValue, can be derived classes. Numbers could optionally be grouped into NumberValue and ArrayValue could be subclassed into VectorValue, DictionaryValue, etc.

This could help divide up the problems of defining traits as well as where to allow conversions of types.

I'm not seeing a complete picture of where you are handling dynamic types. It seems as though the consumer already knows or expects a bool in your example. So it is only syntactic sugar make an overloaded conversion rather than to call something like:

bool b_by_ref;
Error err  = Propset.GetBool("propname",&b_by_ref);

If you don't know or care about the type yet, just pass it as a PropValue* and let functions worry about the types internally in that algorithm.

void FooFunc (PropValue* p)
{
    DWORD id = p->GetTypeID();
    switch(id)
    {
        case INT_VALUE_TYPEID:   FooInt(p);
        case FLOAT_VALUE_TYPEID: FooFloat(p);
         .....
        default: Assert(0);
    }
 }


问:
How should a website validate a users mailing address?
This is for a site that relies on shipping items via UPS or FedEx. I know there is software out there that does it (http://en.wikipedia.org/wiki/Coding_Accuracy_Support_System), but if you are trying to build your own solution for a simple website.</p>

答:
Unless you can do it against an API provided by your shipper (UPS/Fedex/etc) or there is an official list (like the Postal Address File) - then don't.

It's annoying having to make up an incorrect address because some dumb software insists that my city needs a county, or that my house must have a number. Even worse if you assume it must be a US address


问:
Should Agile teams deliver new features daily?
My company is in the midst of a transition from waterfall-style development to Agile/Scrum.  Among other things, we're told that the expectation is for us to have new working, testable (by QA) features at the end of each day.

Most of our devs lose around 2 hours a day to meetings and other enterprisey overhead.  This means that in any given 6-hour (at best) period, we have to design, write, unit-test, build, and deploy (with release notes) enough code to produce a complete feature for QA to play with.  I understand that the build/deploy/release notes could be automated with a proper CI setup but we're not there yet.

We also have a large offshore contingent writing our server-side code, and the 12-hour time difference makes this even more difficult.

We attempt to task out stories into narrow, deep vertical slices in order to complete features end-to-end as fast as possible, but most days feel rather frantic and I often catch people taking stupid, fragile shortcuts to ensure QA has their build.  This problem is compounded after a sprint has been in progress for a couple of days, when the inevitable defects start rolling in and have to fit into the same 6-hour window.

Is this a normal pace for Agile teams?  Even if we manage to implement a CI setup, I can't see how we'll be able to sustain this pace and still create quality software.

Edit:  There are several good answers here.  It made me realize that what I was really asking is, should Agile teams deliver new features daily.  I updated the title accordingly.

答:
Short Answer: No. It just simply can not be accomplished daily.

However, agile team supposed to deliver working software pieces or user stories in each sprint. Usually, status meeting are held daily to see the progress and impediments.

In regards to quality software, continuous integration(CI) processes in place will make sure that quality control is applied to small pieces of efforts (check-ins), and done as frequently as configured. It also targets to improve the quality of software, and to reduce the time taken to deliver it, by replacing the traditional practice of applying quality control after completing all development.


答:
If you had working software yesterday, why wouldn't it be working today? If you didn't finish any tasks today, todays build will be the same as yesterday. Daily builds and the pace of development are separate things. Just because you have daily builds that doesn't mean you have new features in every build. </p>

<p>When finally some feature gets finished and checked-in at the main branch, then you should have automated process that builds the software and runs tests. If there is a problem with building or running tests, team is notified and they focus their effort to get it working again. That is how CI works and how it helps you release working software all the time. </p>

Title: Should Agile teams deliver new features daily?

Body:
My company is in the midst of a transition from waterfall-style development to Agile/Scrum.  Among other things, we're told that the expectation is for us to have new working, testable (by QA) features at the end of each day.

Most of our devs lose around 2 hours a day to meetings and other enterprisey overhead.  This means that in any given 6-hour (at best) period, we have to design, write, unit-test, build, and deploy (with release notes) enough code to produce a complete feature for QA to play with.  I understand that the build/deploy/release notes could be automated with a proper CI setup but we're not there yet.

We also have a large offshore contingent writing our server-side code, and the 12-hour time difference makes this even more difficult.

We attempt to task out stories into narrow, deep vertical slices in order to complete features end-to-end as fast as possible, but most days feel rather frantic and I often catch people taking stupid, fragile shortcuts to ensure QA has their build.  This problem is compounded after a sprint has been in progress for a couple of days, when the inevitable defects start rolling in and have to fit into the same 6-hour window.

Is this a normal pace for Agile teams?  Even if we manage to implement a CI setup, I can't see how we'll be able to sustain this pace and still create quality software.

Edit:  There are several good answers here.  It made me realize that what I was really asking is, should Agile teams deliver new features daily.  I updated the title accordingly.

Body:
If you had working software yesterday, why wouldn't it be working today? If you didn't finish any tasks today, todays build will be the same as yesterday. Daily builds and the pace of development are separate things. Just because you have daily builds that doesn't mean you have new features in every build.

When finally some feature gets finished and checked-in at the main branch, then you should have automated process that builds the software and runs tests. If there is a problem with building or running tests, team is notified and they focus their effort to get it working again. That is how CI works and how it helps you release working software all the time.


答:
There are three possibilities:

The author of all the code under the GPL license crafted an exception to permit the code to be combined.

The author of the all the code under the CC license crafted an exception to permit the code to be combined.

Someone with no authority to do combined GPL code with CC code. The distribution is (most likely) unlawful as the GPL does not permit distributing derived works with any portions under more restrictive license.

Unfortunately, you can't really be sure of anything but the licenses on the specific parts of the code, so you should try to comply with all of them. I think that's possible so long as you don't redistribute the code. If you need to redistribute it, you have a problem and should seek real legal advice.


答:
There are many projects out there that deliver daily builds, which thanks to continuous integration, are working software. At least in theory.

It means it's not necessarily containing new features. Maybe few minor bug fixes, or nothing at all.

In theory, if you are unable to provide more work to your QA daily, you must either increase the number of developer or reduce the number of testers. Terrible idea!

Your job is to get things done.

Tell the QA that they will get something to test when it's done. You need to explain to them why.


答:
Stop looking for an exclusively OOP paradigm and try on some JavaScript.

I currently have something of a scheme worked out where my UI objects are operating under an event-driven interface. That is to say, I'll have what looks like a typical public method that when fired results in an internally defined action. But when it's fired, what really happens is that I trigger an event on the object itself and a pre-defined handler inside that object responds. This event and the event object you can attach properties to that gets passed to any other listener can be heard by anything that cares to listen. You can listen directly to the object, or you can listen generally for that event type (events are also triggered on a generic object all objects built by the factory can listen to). So now for instance, I've got a combo box where you select a new item from the dropdown list. The comboBox knows what to do to set its own display value and update the server if it needs to, but I can also have as many other combo boxes as I want listening in to swap out their select lists which are tied to the current value of the first combo box.

If you want, (and I was surprised to discover that I don't usually want - it's a legibility issue when you can't see where the event comes from) you can have complete object decoupling and establish context via a passed event object. Regardless, you're still dodging single-dispatch by being able to register multiple responders.

But I'm not doing this with OOP alone and JS is not even 'properly' OOP by some definitions, which I find hilarious. Proper, for the higher levels of app development in my opinion, is having the power to bend the paradigm to whatever works for your situation and we can emulate classes just fine if we care to. But in this case, I'm mixing aspects of functional (passing handlers around) with OOP.

More importantly, what I have feels pretty powerful. I'm not thinking in terms of one object acting on another. I'm basically deciding what the objects care about, giving them the tools they need to sort things out and just dropping them into a mixer and letting them react to each other.

So I guess what I'm saying is this: it's not a switch statement kind of a problem. It's mix and match. The problem is languages and fads that want you to believe it's one thing uber alles. How can a junior java dev, for instance, truly appreciate OOP when they think they're always doing it properly by default?

Title: Is OOP hard because it is not natural?

Body:
One can often hear that OOP naturally corresponds to the way people think about the world. But I would strongly disagree with this statement: We (or at least I) conceptualize the world in terms of relationships between things we encounter, but the focus of OOP is designing individual classes and their hierarchies.

Note that, in everyday life, relationships and actions exist mostly between objects that would have been instances of unrelated classes in OOP. Examples of such relationships are: "my screen is on top of the table"; "I (a human being) am sitting on a chair"; "a car is on the road"; "I am typing on the keyboard"; "the coffee machine boils water", "the text is shown in the terminal window."

We think in terms of bivalent (sometimes trivalent, as, for example in, "I gave you flowers") verbs where the verb is the action (relation) that operates on two objects to produce some result/action. The focus is on action, and the two (or three) [grammatical] objects have equal importance.

Contrast that with OOP where you first have to find one object (noun) and tell it to perform some action on another object. The way of thinking is shifted from actions/verbs operating on nouns to nouns operating on nouns -- it is as if everything is being said in passive or reflexive voice, e.g., "the text is being shown by the terminal window". Or maybe "the text draws itself on the terminal window".

Not only is the focus shifted to nouns, but one of the nouns (let's call it grammatical subject) is given higher "importance" than the other (grammatical object). Thus one must decide whether one will say terminalWindow.show(someText) or someText.show(terminalWindow). But why burden people with such trivial decisions with no operational consequences when one really means show(terminalWindow, someText)? [Consequences are operationally insignificant -- in both cases the text is shown on the terminal window -- but can be very serious in the design of class hierarchies and a "wrong" choice can lead to convoluted and hard to maintain code.]

I would therefore argue that the mainstream way of doing OOP (class-based, single-dispatch) is hard because it IS UNNATURAL and does not correspond to how humans think about the world. Generic methods from CLOS are closer to my way of thinking, but, alas, this is not widespread approach.

Given these problems, how/why did it happen that the currently mainstream way of doing OOP became so popular? And what, if anything, can be done to dethrone it?


问:
OAuth2 flow - does the server validate with the Auth server?
I've been reading a lot on OAuth2 trying to get my head around it, but I'm still confused about something.

I understand that the client authorises with the OAuth provider (Google for example) and allows the Resource Server to have access to the user's profile data. Then the client can send the access token to the resource server and be given back the resource.

But what does not seem to be covered in any of the documentation is what happens when the client app asks the resource server for a resource and passes it the access token. Everything I have read so far states that the resource server just responds with the requested resource.

But that seems like a huge hole, surely the resource server must somehow validate the access token, otherwise I could just fake up any old request and pass an old, stolen, fake, or randomly generated token and it would just accept it.

Can anyone point me at a simple to follow explanation of OAuth2 because so far the ones I have read feel incomplete.

答: Found it. Buried in the spec. They say the resource server should validate the access token with the auth server but that it's outside the scope of the document. Pity, I would have thought that token validation was an important part.</p>


答:
The crimes that are committed in the name of Agile these days make me sad. Lots of people are having a hard time making this transition.

Agile Manifesto: "We value people and interactions over process and tools.". When the people are clearly hurting, the process is wrong. I don't want to tell you how to do it, but will share how I do it.

In my teams, the important part is to avoid committing to a shared repo code that is broken in ways that will waste the rest of the team's time. In this sense only, I strive to 'deliver working code every day'. Don't break QA. Don't block other developers. Ideally I never check in any bugs. (ha ha).

The implication is not that you have to commit something every day. The implication is that you should only commit good stuff, so that each day you can get a build of all the good stuff that anyone committed. This way the team keeps firing on all cylinders.

In my teams QA is constant. I build commercial products, so the project is never over until the product is obsolete. QA Engineers test the features that are available to test. QA Engineers always have a backlog. There is never enough QA time to test or automate everything we would idealistically want.

If developers need multiple days before merging in changes for a feature or fix, it's fine, encouraged if it helps them get the code right before risking our time. Developers can commit code to their private repo or branch without affecting the team or QA. Developers can run unit tests or regression automation on code built from a developer's repo or private branch. On particularly risky cases a QA Engineer will work with the developer to test before merging, to protect the team from delay.

In this sense, I practice what your managers want. Almost every day for the last 12 years my development teams have had code that works in the shared repository. We're always almost ready to ship. Occasionally we do not achieve this but we don't worry too much about it. Sometimes it is intentional, to accomodate major tools changes or difficult merges.

The Agile Manifesto, to me, sums up the best of the new thinking on development process that emerged in the 1990's. I'm pretty much a true believer in those principles, but the process details can vary. As I see it, the point of Agile is to adapt your process to your product's and clients' needs, not to be a slave to process.


问:
Searching in a repository
I'm very new to source control management and one thing puzzles me: is it possible to search through the whole repository for a string? For example I'm tracking one file, which has 100 commits and I would like to see all the version of the file which contain "xyz" inside.

Is this possible? I'm using various GUI clients and non of them has this..? Yes, they can search trough commit messages but I want to find a version even when the commit message does not contain the string.

To put it differently, which GUI client has such a feature? I don't care about which SCM it uses - git, hg, bazaar, all are fine.

答: There is hg grep which does that (see hg help grep), though I don't know if it's exposed in any GUIs.

Title: Searching in a repository


答:
It actually depends on the size of the project; if the project is a large one there is no feasible way to achieve this.

Daily (or even more often) builds which come out of continuous integration tools, does not mean working software; it barely means compilable code.


答:
Designing your classes to map directly to tables can be seen as an anti-pattern.  There is a natural Object - Relational impedance mismatch that you get when using OO and relational DBs.

Designing your application according to its domain independent of its data storage is often a recommended practice. Domain Driven Design is one such technique you might find useful.

Title: How to properly design classes for a big project?

Body:
If we need to represent classes in a class diagram for a big project that is not completely designed yet, and the classes have to be actual tables in a database, how would we predict and design the classes?

Let's say we have a project that is going to have more than 15 tables, do all these tables need to be classes in the class diagram?

How would classes be designed in this kind of situation? The language that is being used is Java and the class diagram has to prepared in UML. I know how to design them, I just don't know if the tables should represent the classes in this case.


问:
Exclusive use of a Jini server during long-running call
I'm trying to use Jini, in a "Masters/Workers" arrangement, but the Worker jobs may be long running. In addition, each worker needs to have exclusive access to a singleton resource on that machine.

As it stands, if a Worker receives another request while a previous request is running, then the new request is accepted and executed in a second thread.

Are there any best-practices to ensure that a Worker accepts no further jobs until the current job is complete?

Things I've considered:

synchronize the job on the server, with a lock on the singleton resource. This would work, but is far from ideal. A call from a Master would block until the current Worker thread completes, even if other Workers become free in the meantime

unregister the Worker from the registry while the job is running, then re-register when it completes. Might work OK, but something doesn't smell right with this idea...

Of course, I'm quite happy to be told that there are more appropriate technologies than Jini... but I wouldn't want anything too heavyweight, like rolling out EJB containers all over the place.

答:
The "Masters/Workers" pattern you link to is clearly not what you're implementing, because that uses a JavaSpace as an intermediate store for requests and results, thus making your problem disappear.

And indeed that's the standard solution for this kind of scenario: a queue to which "Masters" add requests and from which "Workers" take requests to process.

OwnerDisplayName: Matthew Flint


问:
Why categorization into "Property" and "Methods"
I am looking at the String class in Actionscript 3.0.

It has a property called String.length .
Internally it's a getter function (or method ?) that returns the length of string.

Why can't it be String.getLength() ?

Methods can take in 1, 2 or more values...so their significance can be understood. But what significance does "property" have? As it is, after all, a function only. So, why the categorization into properties? Is it just for adding an overhead botheration to remember that something has been categorized into a property?

In other words, as a programmer, how am I helped when I'am told that String.length is a property of the String class when I can't find any method for the same.

While writing a program, how would I know what is a property and what is a method?

I appreciate having someone shed some light on this.

V.

答:
Short Answer: String.Length is a getter property of the string object. It is a read-only property without a set modifier in the .NET Framework.

As suggested, have a look at this comparison - SO discussion on  Properties vs Methods

Also read from the official documentation of  String.Length