问:
How far should we rename code and data when end users nomenclatures change?
A long time ago we added a feature where our users could "Accept" an image after it was added to a workflow queue. Turns out, we used the wrong term, and users actually "Approve" the image.

Changing Accept to Approve on our interface is easy, just replace one word. But we programmed all layers with the word "accept", from the CSS class name to the database values.

The CSS class that turns the button green: ".accepted";

The model method that verifies and binds the class attribute on the DOM node: "isAccepted";

JavaScript status attribute: Array with "unreviewed", "accepted" and "published";

Mysql status column: ENUM with "unreviewed", "accepted" and "published";

Test names;

It's trivial (specially when you have tests) to replace most occurrences of accept to approve. A little bit harder is to migrate the data, specially since it needs to be synchronized with deployment.

This specific case is simple, but I've faced similar, yet more complex cases, during my career. When a file is also renamed and deployment happens on dozens of servers, or when proxy caching, memcached and mysql are involved.

Leaving "accepted" on every other layer except the interface is a bad idea, since new programmers joining the team might not learn the historical reasons it led to this decision, and while accept -> approve are close words in terms of meaning, if it was renamed to "queued for managerial next status meeting", it certainly wouldn't make any sense. And it feels if we compromise here and there, in a few iterations the user interface concepts will have no bearings to the system internals, and I certainly do not want to work on a system where half of the output has no connection to its innards.

So, do you always rename everything when needed? If this happened to you, and you decided that the trade-off was not worth, did it come back to bite you? Is code comment or developer documentation enough to avoid this issue?

答:
For me, it is definitely best to change everything related to the item in question.

It is a form of code degradation, and while 1 item not being changed might not be a big deal, it sets the tone for the code base.

It could also lead to confusion in the future and make it harder for new devs to understand the code base/domain.


答:
You may want to look into Localization (l10n) options.  While it may not seem as drastic as going from English to Spanish, you're dealing with a different term for the same concept. If this seems to happen commonly, then using l10n can allow you to quickly change what is displayed in the user interface while not having to change the term used in code.

With that in place, just use the terms in your code that are the most widely understood. Choose names from the domain as developers know it and might expect it.

ContentLicense: CC BY-SA 3.0

Title: How far should we rename code and data when end users nomenclatures change?

Body:
A long time ago we added a feature where our users could "Accept" an image after it was added to a workflow queue. Turns out, we used the wrong term, and users actually "Approve" the image.

Changing Accept to Approve on our interface is easy, just replace one word. But we programmed all layers with the word "accept", from the CSS class name to the database values.

The CSS class that turns the button green: ".accepted";

The model method that verifies and binds the class attribute on the DOM node: "isAccepted";

JavaScript status attribute: Array with "unreviewed", "accepted" and "published";

Mysql status column: ENUM with "unreviewed", "accepted" and "published";

Test names;

It's trivial (specially when you have tests) to replace most occurrences of accept to approve. A little bit harder is to migrate the data, specially since it needs to be synchronized with deployment.

This specific case is simple, but I've faced similar, yet more complex cases, during my career. When a file is also renamed and deployment happens on dozens of servers, or when proxy caching, memcached and mysql are involved.

Leaving "accepted" on every other layer except the interface is a bad idea, since new programmers joining the team might not learn the historical reasons it led to this decision, and while accept -> approve are close words in terms of meaning, if it was renamed to "queued for managerial next status meeting", it certainly wouldn't make any sense. And it feels if we compromise here and there, in a few iterations the user interface concepts will have no bearings to the system internals, and I certainly do not want to work on a system where half of the output has no connection to its innards.

So, do you always rename everything when needed? If this happened to you, and you decided that the trade-off was not worth, did it come back to bite you? Is code comment or developer documentation enough to avoid this issue?


答:
From the question content and tags I'll assumer you're using ubiquitous language.

In my experience UL is great but, as you mentioned, can lead to additional maintenance tasks as the language evolves.  This, in itself, isn't a bad thing.  Sure, it's inconvenient, but it's also expected.

What I've typically done (and seen done) is either:

1-shot upfront refactoring:  Refactor all layers of the application to adopt the updated language; or

log technical debt:  You can change user-facing code right away, and then log technical debt tasks to bring the rest of the application layers in line with the updated language.  This typically results in a handful of boring (but manageable) tasks.  (Perfect for 5pm!)

I think the key thing here is that what you're describing is technical debt and should be recognized as such.

I've had managers who've argued that we shouldn't be wasting time on such trivial tasks that don't add any visible functionality.  This is when the debt analogy really comes in handy.  It boils down to this:

The team chose to do DDD with Ubiquitous Language.  Straying from this approach by leaving the code in an inconsistent state adds confusion and removes many of the benefits that DDD and UL provide.  In manager terms, it adds cost to the project.  The code becomes more difficult (expensive) to manage, and more confusing for new developers (expensive).


问:
What is considered best practice for printing usage / help (--help)?
When writing tools for the CLI of UNIX, how should I make the program print out help and/or usage?

I usually use fprintf(stderr, "help text here");, but there are several issues with that.

First, I'm not sure, whether I should use stderr. Is that OK, or should I use stdout?

As you can imagine, the help text is quite long, depending on how many options the tool has. Now, I usually, just put several "strings like that\n" in the second parameter. This however, fills my source code with fifty or more lines of help text. It is not easy manageable at all. What should I do instead?

When a tool is not written in C or a C-like language, I tend to use here-docs where possible (most prominently with Perl). I can't use that in C, but is there something like that, that I could use?

I was considering putting it in a headerfile.h inside a #define HELP "help text here", I've never seen it in the wild, don't know whether I should actually use that.

Ideally, I could put the text in an external file, and include it. Using #include for that seems wrong, though. What should I do then?

The idea is, to have a help text, that is easily manageable. Having it inside the source code isn't really convenient.

答:
If I use C or prefer not to depend on Boost libraries, then I stick with GNU getopt. Otherwise I prefer Boost Program Options which prints help automatically.

I also consider guessing the right option one of the best practices when it comes to options handling. I learned it from Git and now use the same in my projects. It basically uses Damerau–Levenshtein distance to print best matches if user enters some unknown command line option.

I wrote a little article about this that you can use as an example.

Hope it helps :)


问:
How to categorise information in end-user documentation?
One of the greatest piece of documentation I ever read is the TeXbook by Donald Knuth—the manual of the TeX typesetting system, and I used it in my first analysis.

As far as I can tell, the type of information conveyed by documentation falls in three categories: recipe,  reference and expert knowledge that I describe hereafter.

Which categories am I missing?

Recipe

A recipe answers a question like “how do I solve that problem with this software?” and binds the problem world with software features.  Chapters 3, 7 and 8 in the TeXbook answer questions like “How do I run TeX?” or “How do I type text?” and provide the user with recipes.  Other software packages often contain installation or backup procedures that fall in this category.

Reference

A reference documents all the needed details on some piece of software.  It is useful for the user knowing that “this feature is useful to solve that problem” and wanting to know if it can parametrise “this feature” to solve a close problem.  It is also useful for troubleshooting the software when it gives unexpected results.  Chapter 14 “How TeX Breaks Paragraphs into Lines” in the TeXbook is an example of a reference text.  UNIX manual pages almost always belong to this category.

Expert knowledge

Expert knowledge pertaining to the problem solved by the software also belong to the software documentation.  Reasons for this are at least:

Users are not experts in the area where the software is useful.

Experts use varying terminology and methodologies to describe or solve problems.

For 1. mathematicians reading the TeXbook also learn the basics of design and layout: they get aware that there is a structured knowledge in this area and learn the names of the basic concepts involved, so that they can phrase out problems and get help.  For 2. it is useful to “fix the notation” in the software documentation and this is best done by providing some high-level or background information.

Hence expert knowledge contained in the user documentation binds the conceptual organisation of the problem as it is known to the software designers to the conceptual organisation of the problem as it is known to the software users.

答:
Some of this varies if you are documenting software or hardware, but possibilities:

Tutorial (not quite similar to what you call Recipe, depends on the situation).  But at least a brief "Hello World" type of thing, and perhaps more.  Some people learn best from examples.  Others just turn right to the reference

Installation / turning the darn thing on

Uninstallation / turning the darn thing off

Interacting with other "standards".  How does this gizmo work with Spring, XML, USB, Roku, LTE, CloudServices, etc.  Is there an Eclipse plugin?

Dangers / Warnings / Requirements / Gotchas.  Don't use underwater, it works but certain options are disabled in Windows RT, requires Java 6 or higher, it doesn't work with IE6, we haven't tested it on Android 2.2 and earlier, etc.

FAQ, plus a link to any on-line help

Legal Notices (if required, hopefully you can avoid these)  Parts are licensed from the FooBar Corporation, parts are GNU, Not for use in Diagnostics, etc...

Glossary (I stole this from @Marco's comment)


问:
How to store Status for Reservation table
I have a reservation table (a user fills out a form to request a reservation).

It has two parts that need to be confirmed. isReservationAccepted (decline,accept,waiting) and hasReservationBeenSent (sent, declined, waiting)

Not sure how to structure my table, thinking about making a lookup table for each column, or maybe just creating them as int, and having 1 = accepted/sent, 2 = declined, 3 = waiting.

not sure if there is a better way (probably)

答:
Why not create a property table for each property (like propReservationStatus and propReservationSendStatus) that holds the statuses:

```
Id Description
---------------
 1 Decline
 2 Accept
 3 Waiting
```

and so on and then define a column ReservationStatusId in your table as a foreign key to the property table?

This scenario has some advantages:

translations of the status independant from id

better maintenance/extensibility (after six months would you still know what 1/2/3 is?)

complies with database normalization rules, for example if you need the same values somewhere else

Yes, you will need two tables: one for the SentStatus and one for the AcceptedStatus.
I would suggest following fields (pseudo sql types):

```<code>Id tinyint PK NN AI
Description string NN
IsDeleted char/bool default value 0 /* you can dynamically hide/show values without changing the property table */
SortOrder int /* this way you can change the order without changing the property table */
</code>```

In the table Reservation create two columns ReservationSentStatusId and ReservationAcceptStatusId of type tinyint and make them both foreign keys to the corresponding table. This has the advantage that you will be not able to add a non-existing value like (in this case) 5.

An option would be to create a view so that you can easily change the order resp. the visibility of the property items and use this view when showing the options to the user instead of mapping values to texts:

```<code>/* pseudo sql */
create view viewPropertyReservationSentStatus
begin
 select
    Id, Description
 from propertyReservationSentStatus
 where IsDeleted = 0
 order by SortOrder ascending
end
</code>```

The view can be used to fill binding sources to show/set the values in a program/webpage (if for example you are using .net/asp.net).

Body:
Why not create a property table for each property (like propReservationStatus and propReservationSendStatus) that holds the statuses:

Id Description
---------------
 1 Decline
 2 Accept
 3 Waiting

and so on and then define a column ReservationStatusId in your table as a foreign key to the property table?

This scenario has some advantages:

translations of the status independant from id

better maintenance/extensibility (after six months would you still know what 1/2/3 is?)

complies with database normalization rules, for example if you need the same values somewhere else

Yes, you will need two tables: one for the SentStatus and one for the AcceptedStatus.
I would suggest following fields (pseudo sql types):

Id tinyint PK NN AI
Description string NN
IsDeleted char/bool default value 0 /* you can dynamically hide/show values without changing the property table */
SortOrder int /* this way you can change the order without changing the property table */

In the table Reservation create two columns ReservationSentStatusId and ReservationAcceptStatusId of type tinyint and make them both foreign keys to the corresponding table. This has the advantage that you will be not able to add a non-existing value like (in this case) 5.

An option would be to create a view so that you can easily change the order resp. the visibility of the property items and use this view when showing the options to the user instead of mapping values to texts:

/* pseudo sql */
create view viewPropertyReservationSentStatus
begin
 select
    Id, Description
 from propertyReservationSentStatus
 where IsDeleted = 0
 order by SortOrder ascending
end

The view can be used to fill binding sources to show/set the values in a program/webpage (if for example you are using .net/asp.net).


问:
"Enterprise" version of GPL'd code?
I know that there are a number of discussions about the GPL on this site but I just ran in to an interesting case of apparent misuse that I (surprisingly) haven’t seen discussed anywhere.

The CFEngine configuration management program is apparently distributed under the GPL (it even appears to be an FSF project) but the original author also distributes an “Enterprise edition” which is blatantly non-free. This appears to be an obvious violation of the GPL.

The official response to this question (from the CFEngine FAQ) is:

As copyright holders we are free to license CFEngine under any terms we choose. The files that belong to both the community edition and enterprise editions are consequently licensed under both sets of terms. The licensee of the Enterprise edition is therefore free to choose the terms that are deemed most desirable.

Which, as I understand the issue, is just not true. As copyright holders they are of course free to change the license (for future releases), but distributing code with both licenses is contradictory at best and illegal at worst.

Am I missing something here or does this seem wildly hypocritical?

答:
Dual licensed models work under the theory that, if you want to write a closed-source application, you can earn that right by paying money for a commercial version.  Otherwise, you can get the software for free, so long as you abide by the terms of the GPL (which is, at least in theory, designed to promote open-source software as truly "free as in speech").

Basically, they're using the GPL as a lever to induce folks to get the pay version.  If they licensed it as MIT or BSD to the open-source community, there would be no incentive to pay for it in a commercial context.

The Free Software Foundation discusses this issue in detail here: http://www.fsf.org/blogs/rms/selling-exceptions:

A copyleft license permits embedding in a larger program only if the
  whole combined program is released under that license; this is how it
  ensures extended versions will also be free. Thus, users that want to
  make the combined program proprietary need special permission. Only
  the copyright holder can grant that, and selling exceptions is one
  style of doing so. Someone else, who received the code under the GNU
  GPL or another copyleft license, cannot grant an exception.

Viewed from a different perspective, the GPL is a way that a commercial software company can provide their software and source code for free to the public while still retaining the ability to make money, without which their software would be completely closed and proprietary.

Not everyone is sympathetic with this view, of course.  See Milking the Gnu for an alternative viewpoint.

Title: "Enterprise" version of GPL'd code?


问:
Is a senior programmers advice about always using books a good idea?
I am a junior developer and have only been in the industry for 5 years. At my current company there is a senior let's call him Infestus. Occasionally I am being given opportunity to shine and do something completely brand new from scratch.

One of the most recent examples was that I had to make a singleton in the multithreaded application. I have decided to use this method. As soon as Infestus saw it, he quickly proceeded to call me stupid and told me to use this approach. Upon asking him why he just brushed it off as this is better and that's how this and this book about Java says it is better.

And it is a common pattern: whenever I get a chance to do something new, I quickly get shot down by Infestus and the only reasoning why his method is better is because those books were written by famous programmers. He is always trying to give me books to read so that I may "learn" which ways to program.

I have only been programming for money for 5 years, but is it always a good idea to just blindly follow the book on best ways for solving a problem, or should I try experimenting every now and then? The constant barrage of complaints from the Infestus is starting to cause me to never try anything new and follow examples in books.

EDIT: I am utterly lost. Yes I know that following anything blindly is a bad idea. But this godlike programmer Infestus who seems to know a lot, tells me that the only way to program properly is by reading books and following everything down to a T. All the rules he imposes are the ones written in books, so I am just wondering if books are the only correct way.

EDIT2: Infestus is not my boss. He is just one of senior developers in charge of reviewing the code. And most of his comments after reviews consist of book names where such and such method is wrong.

答:
Did he really call you stupid, or did he just disparage the code?  Calling anything stupid is tactless, but that doesn't invalidate the suggestion.  I think Infestus has made a valuable suggestion, and in the future you should consider his suggestions seriously.  He seems to do a lot of reading, and at least in this case his opinion is well-informed.  Synchronization is both expensive and tricky.  His recommended implementation is more efficient and simpler than yours, and is guaranteed to work.

He is always trying to give me books to read so that I may "learn" which ways to program.

That is kind of him.  He is actively trying to help you, but you seem to be letting your ego get in the way.  Do not take criticism of your code personally.  Code is cheap to produce and easy to change.  If someone shows you a simpler way of doing something, thank them.

And yes, reading will make you a much better programmer.  All the experts I have known read extensively.  If you are not reading much, then you are mediocre at best, and in another five years you may find that you are no longer marketable.


答: I think that Tutorial as a category is worthy of distinction from the categories listed. A tutorial is not a recipe as you have described it because it is not necessarily a "how". It could be a combination of "how", "why" and "what" used to facilitate understanding of other items. A recipe is just "how" and stands alone whereas a tutorial is teaching an element that may be entirely abstract and only of any use in combination with other items. In fact one might even consider a Recipe as a subcategory of Tutorial.

Title: How to categorise information in end-user documentation?

Body:
One of the greatest piece of documentation I ever read is the TeXbook by Donald Knuth—the manual of the TeX typesetting system, and I used it in my first analysis.

As far as I can tell, the type of information conveyed by documentation falls in three categories: recipe,  reference and expert knowledge that I describe hereafter.

Which categories am I missing?

Recipe

A recipe answers a question like “how do I solve that problem with this software?” and binds the problem world with software features.  Chapters 3, 7 and 8 in the TeXbook answer questions like “How do I run TeX?” or “How do I type text?” and provide the user with recipes.  Other software packages often contain installation or backup procedures that fall in this category.

Reference

A reference documents all the needed details on some piece of software.  It is useful for the user knowing that “this feature is useful to solve that problem” and wanting to know if it can parametrise “this feature” to solve a close problem.  It is also useful for troubleshooting the software when it gives unexpected results.  Chapter 14 “How TeX Breaks Paragraphs into Lines” in the TeXbook is an example of a reference text.  UNIX manual pages almost always belong to this category.

Expert knowledge

Expert knowledge pertaining to the problem solved by the software also belong to the software documentation.  Reasons for this are at least:

Users are not experts in the area where the software is useful.

Experts use varying terminology and methodologies to describe or solve problems.

For 1. mathematicians reading the TeXbook also learn the basics of design and layout: they get aware that there is a structured knowledge in this area and learn the names of the basic concepts involved, so that they can phrase out problems and get help.  For 2. it is useful to “fix the notation” in the software documentation and this is best done by providing some high-level or background information.

Hence expert knowledge contained in the user documentation binds the conceptual organisation of the problem as it is known to the software designers to the conceptual organisation of the problem as it is known to the software users.


答:
I think you've done a very good job summarizing most types of documentation into those three categories. I would like to add two more:

Beginner Knowledge/Bootstrapping

You could classify this under Recipes, but I think it's different enough to deserve its own category. A recipe already assumes a basic knowledge of the system. Writing a recipe for food already assumes a basic knowledge of the cooking domain: You should already know what a tsp is (if you're using that strange system of measurements. :) ), how to use an oven, microwave, etc.

For someone who has never cooked or made food in their life, you'd want a gentle introduction to the entire system, showing them what they can do, and giving them little tidbits of coolness along the way to keep them interested.

The same applies to documentation. A beginner will quickly throw away a recipe book, because they don't have enough domain knowledge to even appreciate the recipes. Therefore, they need some beginner knowledge, or bootstrapping. Here's some points about this documentation format:

Very basic, making sure to explain every possible unfamiliar term. This can be frustrating to some users, but is essential in order to educate anyone looking at the documetentation

Lots of small examples to keep the user interested. These aren't recipes, per se, but they are little things to keep the beginner interested, knowing that this product does cool stuff

Lots of links to other places in the documentation (Recipes, Expert Knowledge, etc.) where they can learn more about some of the concepts being discussed

Short enough to be easily digested. No one wants to read a 300-page introductory novel

Marketing

You could argue that this isn't really "documentation", but it often gets included in documentation. These are descriptions of "why our product is so awesome that you should use it". It's a long-winded description of how the product beats the competition. This is less prevalent in open-source software, but you see it all the time in commercial software.


答: I think you should add an "Indexing" category. That describes the mechanism to pull all of the other information together via tags and hyperlinks so that it can be accessed in a context-sensitive manner from the application and from an index within the application. If the information isn't easily found the users are going to go to Google and skip the documentation.


问:
Entity Framework and distributed Systems
I need some help or maybe only a hint for the right direction.

I've got a system that is sperated into two applications.
An existing VB.NET desktop client using Entity Framework 5 with code first approach and a asp.net Web Api client in C# that will be refactored right yet. It should be possible to deliver OData.
The system and the datamodel is still involving and so migrations will happen in undefined intervalls.

So I'm now struggling how to manage my database access on the web api system. So my favourd approch would be us Entity Framework on both systems but I'm running into trouble while creating new migrations. Two solutions I've thought about:

Shared Data Access dll

The first idea was to separate the data access layer to a seperate project an reference from each of the systems. The context would be the same as long as the dll is up to date in each system. This way both soulutions would be able to make a migration.
The main problem ist that it is much more complicate to update a web api system than it is with the client Click Once Update Solution and not every migration is important for the web api. This would couse more update trouble and out of sync libraries

Database First on Web Api

The second idea was just to use the database first approch an on web api side. But it seems that all annotations will be lost by each model update.

Other solutions with stored procedures have been discarded because of missing OData support and maintainability.

Does anyone run into same conflicts or has any advices how such a problem can be solved!

答: So I think you pretty much called this out on your own. You're going to have duplicated code if each side has it's own EF mappings. This doesn't buy you much at all and puts you at risk for becoming out of date. While creating a shared assembly that houses all the EF mappings/code would allow you manage everything in one place. The fact you're using EF here is kinda of immaterial. This is the perfect example of a shared assembly between projects. This is a common pattern. </p>

OwnerDisplayName: Dirk Beckmann


答: Best to go for the shared DLL strategy. You can manage the Web API updates through use of a versioning strategy for the API to ensure backward compatibility with the clients.</p>

Title: Entity Framework and distributed Systems

Body:
I need some help or maybe only a hint for the right direction.

I've got a system that is sperated into two applications.
An existing VB.NET desktop client using Entity Framework 5 with code first approach and a asp.net Web Api client in C# that will be refactored right yet. It should be possible to deliver OData.
The system and the datamodel is still involving and so migrations will happen in undefined intervalls.

So I'm now struggling how to manage my database access on the web api system. So my favourd approch would be us Entity Framework on both systems but I'm running into trouble while creating new migrations. Two solutions I've thought about:

Shared Data Access dll

The first idea was to separate the data access layer to a seperate project an reference from each of the systems. The context would be the same as long as the dll is up to date in each system. This way both soulutions would be able to make a migration.
The main problem ist that it is much more complicate to update a web api system than it is with the client Click Once Update Solution and not every migration is important for the web api. This would couse more update trouble and out of sync libraries

Database First on Web Api

The second idea was just to use the database first approch an on web api side. But it seems that all annotations will be lost by each model update.

Other solutions with stored procedures have been discarded because of missing OData support and maintainability.

Does anyone run into same conflicts or has any advices how such a problem can be solved!


问:
Is it possible to be good at both programming and graphic design?
The stereotypical view of a programmer can't do graphics very well, from what I've read and seen. However, I love programming (preferably OOP, PHP, C++, Objective-C) and can't deny the fact I have a unique taste in web design and others have said I am doing well at it (CSS). I thought to myself "Hey, wait, I'm a programmer - how can I design well?". Question is: is it possible to be good at programming and designing? Does anyone here feel the same?

For the record: actual images I have created have been called programmer art several times before by friends

答:
User Experience Design could be considered the combination of both.

Yes, there are people who can do it. There are many who practice only one discipline due to time constraints or personal preference but can cross over easily.

ContentLicense: CC BY-SA 2.5


问:
Is this a correct implementation of an Immutable class in Java?
```<code>public final class ImmutableClass {

    private StringBuffer name;

    public ImmutableClass(StringBuffer name) {
        this.name=name;
    }
    public StringBuffer getName() {
        return name;
    }
}
</code>```

Points that I have considered:

Make the class final so that it cannot be extended

Do not provide public mutator methods

Keep the instance variables private

Are the above mentioned considerations sufficient?

答:
Consider:

```<code>ImmutableClass a = new ImmutableClass(new StringBuffer("hello"));
a.getName().append(" world");
System.out.println(a.getName()); // prints "hello world"
</code>```

The above allows the caller to mutate the value of name. Or:

```<code>StringBuffer b = new StringBuffer("hello");
ImmutableClass a = new ImmutableClass(b);
System.out.println(a.getName()); // prints "hello"
b.append(" world");
System.out.println(a.getName()); // prints "hello world"
</code>```

The above is similar, and shows that a change to something else can affect the apparent value of a.

With the ability to do the above, your class cannot be considered "immutable" by any definition. However, if you were to replace StringBuffer with String, then your class would be immutable (because in Java, String is immutable).

Body:
Consider:

ImmutableClass a = new ImmutableClass(new StringBuffer("hello"));
a.getName().append(" world");
System.out.println(a.getName()); // prints "hello world"

The above allows the caller to mutate the value of name. Or:

StringBuffer b = new StringBuffer("hello");
ImmutableClass a = new ImmutableClass(b);
System.out.println(a.getName()); // prints "hello"
b.append(" world");
System.out.println(a.getName()); // prints "hello world"

The above is similar, and shows that a change to something else can affect the apparent value of a.

With the ability to do the above, your class cannot be considered "immutable" by any definition. However, if you were to replace StringBuffer with String, then your class would be immutable (because in Java, String is immutable).


答:
The copyright owner has the right to distribute his software as he chooses, to whom he chooses, or indeed not at all if he desires. The only rule is "no take-backs". You can't change your mind about what has already been distributed.

In this case, he chooses to allow use and re-distribution under the terms and restrictions of the GPL.  But for some users, GPL is not too restrictive. Therefore, under certain conditions, alternate licensing terms are also allowed. He can do this because he owns 100% of the copyright. While you are bound by the GPL if you choose those terms, he isn't bound by anything. He doesn't need to follow any license, because he's the copyright owner.

Let's make a more concrete example out of this:

Say I write a book which I give away for free: you can get a free print directly from me, or you can photocopy one from a friend. But I impose a restriction such that if you photocopy it from a friend, any marks you make on your photocopied version must also be made on the original you photocopied from. Why? Because that's the rule. My book, my rules. If you don't like the rules, write your own book.

Now say a distributer would like to print copies of my book. He's allowed to make copies already, but the restriction about making marks would be a real mess for him to keep track of. He doesn't want to do it. So I create an additional license. I say: if you want to make copies of the book but not keep track of markings, then you can pay me $1 for every copy you print, and agree to distribute your copies in paperback only; no hard cover prints.

In this example, both license apply. You get to pick which terms you want to follow.  In this case, I gave you two options. Nothing wrong with that.

Title: "Enterprise" version of GPL'd code?

Body:
I know that there are a number of discussions about the GPL on this site but I just ran in to an interesting case of apparent misuse that I (surprisingly) haven’t seen discussed anywhere.

The CFEngine configuration management program is apparently distributed under the GPL (it even appears to be an FSF project) but the original author also distributes an “Enterprise edition” which is blatantly non-free. This appears to be an obvious violation of the GPL.

The official response to this question (from the CFEngine FAQ) is:

As copyright holders we are free to license CFEngine under any terms we choose. The files that belong to both the community edition and enterprise editions are consequently licensed under both sets of terms. The licensee of the Enterprise edition is therefore free to choose the terms that are deemed most desirable.

Which, as I understand the issue, is just not true. As copyright holders they are of course free to change the license (for future releases), but distributing code with both licenses is contradictory at best and illegal at worst.

Am I missing something here or does this seem wildly hypocritical?


答:
A copyright license is permission from the copyright owner that allows you to legally use something that is copyrighted.  It lets you out of legal trouble.  The copyright owner couldn't possibly be in legal trouble for violating their own copyright, so even if it were a violation of the GPL, it wouldn't matter, because the author of the code isn't relying on the GPL for rights to their own code.

Offering you permission to use their code under the GPL doesn't (and shouldn't) stop them from offering you permission to use their code under other conditions.  Doing this sort of thing is common enough that it has a name: dual licensing.

The owners of the copyright can license their code to anyone they want under any conditions they like.  Whether you (or the FSF) like their choice is not relevant.

Just because someone uses a license written by Richard Stallman (the GPL) doesn't mean they have to share his views, so there is no hypocrisy.

Title: "Enterprise" version of GPL'd code?


问:
Parallel Class/Interface Hierarchy with the Facade Design Pattern?
About a third of my code is wrapped inside a Facade class. Note that this isn't a "God" class, but actually represents a single thing (called a Line). Naturally, it delegates responsibilities to the subsystem behind it.

What ends up happening is that two of the subsystem classes (Output and Timeline) have all of their methods duplicated in the Line class, which effectively makes Line both an Output and a Timeline. It seems to make sense to make Output and Timeline interfaces, so that the Line class can implement them both. At the same time, I'm worried about creating parallel class and interface structures.

You see, there are different types of lines AudioLine, VideoLine, which all use the same type of Timeline, but different types of Output (AudioOutput and VideoOutput, respectively). So that would mean that I'd have to create an AudioOutputInterface and VideoOutputInterface as well. So not only would I have to have parallel class hierarchy, but there would be a parallel interface hierarchy as well.

Is there any solution to this design flaw?

Here's an image of the basic structure (minus the Timeline class, though know that each Line has-a Timeline):

NOTE: I just realized that the word 'line' in Timeline might make is sound like is does a similar function as the Line class. They don't, just to clarify.

答:
I really agree with both of the other answers.  The primary problem here is that Line has multiple responsibilities.  You are falling into the fallacy of believing that classes correspond to a "thing", when really a class should correspond to a "responsibility".

That being said, it is certainly possible for a class to have the single responsibility of "providing a single facade delegating to several other classes to simplify client code".  It sounds like that might be what you are describing; it depends whether Line has any behavior of it's own, besides delegation.  I don't usually do this, because I don't find it cumbersome to have client code talk to several objects, but that may be chalked up to personal preference.

It seems to make sense to make Output and Timeline interfaces, so that
  the Line class can implement them both. At the same time, I'm worried
  about creating parallel class and interface structures.

What motivates you to do that?  Is there some need for that change, or is it just that you think it would be "more right"?  If the latter, I would just leave your code as is.  Working code is king.


答:
I would research the merits of each approach and come to your own judgement. If you think your approach is better, discuss it with Infestus until one of you convinces the other. If you can't reach an agreement, you could either ask for a second opinion or just accept Infestus's approach, depending on how strongly you feel about it.

In the case of singletons, one argument you could make against the enum approach is that enums can't extend classes. I often write code like this:

```<code>public class DateSerializer extends AbstractSerializer<Date> {
  public static final DateSerializer SINGLETON = new DateSerializer();

  private DateSerializer() {}

  public byte[] serialize(Date date) { ... }
}
</code>```

This can't be done with enums. Since the enum approach doesn't work in all cases, you could argue that for the sake of consistency, it should be avoided even when there's no need for an extends clause.

Some other arguments that could be made against using enums:

it's a hack - it's using enums for something they weren't intended for

it's confusing to readers who haven't seen it before

Title: Is a senior programmers advice about always using books a good idea?

Body:
I am a junior developer and have only been in the industry for 5 years. At my current company there is a senior let's call him Infestus. Occasionally I am being given opportunity to shine and do something completely brand new from scratch.

One of the most recent examples was that I had to make a singleton in the multithreaded application. I have decided to use this method. As soon as Infestus saw it, he quickly proceeded to call me stupid and told me to use this approach. Upon asking him why he just brushed it off as this is better and that's how this and this book about Java says it is better.

And it is a common pattern: whenever I get a chance to do something new, I quickly get shot down by Infestus and the only reasoning why his method is better is because those books were written by famous programmers. He is always trying to give me books to read so that I may "learn" which ways to program.

I have only been programming for money for 5 years, but is it always a good idea to just blindly follow the book on best ways for solving a problem, or should I try experimenting every now and then? The constant barrage of complaints from the Infestus is starting to cause me to never try anything new and follow examples in books.

EDIT: I am utterly lost. Yes I know that following anything blindly is a bad idea. But this godlike programmer Infestus who seems to know a lot, tells me that the only way to program properly is by reading books and following everything down to a T. All the rules he imposes are the ones written in books, so I am just wondering if books are the only correct way.

EDIT2: Infestus is not my boss. He is just one of senior developers in charge of reviewing the code. And most of his comments after reviews consist of book names where such and such method is wrong.

Body:
I would research the merits of each approach and come to your own judgement. If you think your approach is better, discuss it with Infestus until one of you convinces the other. If you can't reach an agreement, you could either ask for a second opinion or just accept Infestus's approach, depending on how strongly you feel about it.

In the case of singletons, one argument you could make against the enum approach is that enums can't extend classes. I often write code like this:

public class DateSerializer extends AbstractSerializer<Date> {
  public static final DateSerializer SINGLETON = new DateSerializer();

  private DateSerializer() {}

  public byte[] serialize(Date date) { ... }
}

This can't be done with enums. Since the enum approach doesn't work in all cases, you could argue that for the sake of consistency, it should be avoided even when there's no need for an extends clause.

Some other arguments that could be made against using enums:

it's a hack - it's using enums for something they weren't intended for

it's confusing to readers who haven't seen it before


问:
Looking to create a custom, graphical editor for a data model using HTML5 and SVG
I need to create a graphical editor for our data model that works in an HTML5 compliant browser. I am looking for a proper library/framework to build on. The model is stored as xml, but that should be largely irrelevant for the front-end technology.

To be more concrete, I am looking to build a kind of diagram editor to create boxes and lines. Each box will have a set of editable properties and a set of relationships to other boxes represented as lines of various kinds (think UML class diagram, but a bit more complex). It must be possible to edit each box's properties through the editor. I require a kind of toolbar from which users can select new boxes to create. Lastly, I would like an automated layout engine, but the user should be able to override through drag and drop.

Eclipse GEF is a good example of the kind of framework that I am looking for. It provides a tool palette, layout managers, drag and drop support, and an MVC architecture. However, I need this to work in a browser, not as a Java-based RCP app.

There are plenty of excellent JS libraries out there for displaying data (like d3 and jqplot). And I have started prototyping in d3. It is a powerful and flexible library, but also low-level. It seems to me that I would need to implement my own toolbar and drag-and-drop capabilities for example.  This is something that Eclipse GEF provides out of the box.

Do I need to implement all this functionality myself or does there exist a library or framework that is more appropriate for my goal?

答:
In a commercial context, yFiles for HTML should be pretty much exactly what you are looking for:

It's a client side Javascript library that uses HTML5 browser technologies like SVG,CSS3 and Canvas, as well as modern Ecmascript features for displaying and editing graph-like structures. It does not depend on any active server components.

It comes with built-in editing capabilities that can be customized to a very high-degree. E.g. if you aren't happy with the default gestures for creating, connecting, or moving elements, if you need a different gesture for zooming or panning the viewport, all of this can be customized. Also it comes with specific support for touch devices and touch gestures.

You can attach any number and kind of data to the elements and optionally display that data in the visualization. The visualization of the diagram elements (nodes, edges, labels, ports, but also the graphical adorners like resize handles, marquee rectangles, etc.) can be fully customized. Adding new elements is easy because at its core, plain SVG is used, so you can leverage existing graphics and third party designer tools to create interactive CSS styled and animated SVG items.

Regarding the storage: Of course the model can be modified and accessed via a Javascript API and at its core the model is Javascript objects. But there are convenience classes and samples on how to populate the graph from XML, JSON data, or angular-observed collections.

Regarding automatic layout capabilities: At the time of writing to my best knowledge the automatic layout algorithms of the library are by far the most elaborate and complete implementations available as native Javascript implementations. This live online demo shows some of the algorithms and some of the configuration options in action. The algorithms support advanced concepts like port-constraints, edge grouping, hierarchical node grouping, integrated labeling, positioning constraints, and many more. The developer's guide gives and introduction to the various available layout algorithms and concepts.

There are demos available that show how to customize the drag and drop gesture and integrate the widget with other Javascript UI frameworks. The library does not come with a toolbar implementation or implementations of other widgets. Instead you can and should consider using a widget toolkit like Dojo, ExtJS, jquery-UI, etc. in order to add widgets like toolbars, context menus, property panels, etc.

In a non-commercial context, finding a library that will do all of this for you, is a lot more difficult. D3 is strong in displaying data quickly and easily, but does not offer out-of-the box strong interaction or layout capabilities. The JsPlumb Toolkit provides nice editing capabilities, but also does not offer layout capabilities. Acceptable layout capabilities are offered by the open-source GraphViz engine. Although it's a C library, there are ways to port that library to make it run as a black-box in Javascript using Javascript source code cross-compilation. This will give you a command-line like interface inside the browser for the algorithms, which is not very convenient, but depending on your requirements may be enough.

Disclaimer: I work for the company that creates the yFiles library, however on SE I do not represent my employer. My posts, thoughts, and comments are my own.


问:
What is the real responsibility of a class?
I keep wondering if it is legitimate to use verbs that are based on nouns in OOP.

I came across this brilliant article, though I still disagree with the point it makes.

To explain the problem a bit more, the article states that there shouldn't be, for instance, a FileWriter class, but since writing is an action it should be a method of the class File. You'll get to realize that it's often language dependent since a Ruby programmer would likely be against the use of a FileWriter class (Ruby uses method File.open to access a file), whereas a Java programmer wouldn't.

My personal (and yes, very humble) point of view is that doing so would break the Single Responsibility principle. When I programmed in PHP (because PHP is obviously the best language for OOP, right?), I would often use this kind of framework:

```<code><?php

// This is just an example that I just made on the fly, may contain errors

class User extends Record {

    protected $name;

    public function __construct($name) {
        $this->name = $name;
    }

}

class UserDataHandler extends DataHandler /* knows the pdo object */ {

    public function find($id) {
         $query = $this->db->prepare('SELECT ' . $this->getFields . ' FROM users WHERE id = :id');
         $query->bindParam(':id', $id, PDO::PARAM_INT);
         $query->setFetchMode( PDO::FETCH_CLASS, 'user');
         $query->execute();
         return $query->fetch( PDO::FETCH_CLASS );
    }

}

?>
</code>```

It is my understanding that the suffix DataHandler doesn't add anything relevant; but the point is that the single responsibility principle dictates us that an object used as a model containing data (may it be called a Record) shouldn't also have the responsibility of doing SQL queries and DataBase access. This somehow invalidates the ActionRecord pattern used for instance by Ruby on Rails.

I came across this C# code (yay, fourth object language used in this post) just the other day:

```<code>byte[] bytes = Encoding.Default.GetBytes(myString);
myString = Encoding.UTF8.GetString(bytes);
</code>```

And I gotta say that it doesn't make much sense to me that an Encoding or Charset class actually encodes strings. It should merely be a representation of what an encoding really is.

Thus, I would tend to think that:

It is not a File class responsibility to open, read or save files.

It is not a Xml class responsibility to serialize itself.

It is not a User class responsibility to query a database.

etc.

However, if we extrapolate these ideas, why would Object have a toString class? It's not a Car's or a Dog's responsibility to convert itself to a string, now is it?

I understand that from a pragmatic point of view, getting rid of the toString method for the beauty of following a strict SOLID form, that makes code more maintainable by making it useless, is not an acceptable option.

I also understand that there may not be an exact answer (which would more be an essay than a serious answer) to this, or that it may be opinion-based. Nevertheless I would still like to know if my approach actually follows what the single-responsibility principle really is.

What's a class's responsibility?

答:
An instance of a class is a closure. That's it. If you think that way all well designed software you look at will look right, and all poorly thought out software will not. Let me expand.

If you want to write something to write to a file, think of all the things you need to specify (to the OS):
filename, access method (read, write, append), the string you want to write.

So you construct a File object with the filename (and access method). The File object is now closed over the filename (in this case it will probably have taken it in as a readonly/const value).
The File instance is now ready to take calls to the "write" method defined in the class. This just takes a string argument, but in the body of the write method, the implementation, there is also access to the filename (or file handle that was created from it).

An instance of File class therefore boxes up some data into some kind of composite blob so that later use of that instance is simpler. When you have a File object, you don't need to worry about what the filename is, you are only concerned about what string you put as argument into the write call. To reiterate - the File object encapsulates all that you don't need to know about where the string you want to write is actually going.

Most problems that you want to solve are layered in this way - things created up front, things created at the start of each iteration of some kind of process loop, then different things declared in the two halves of an if else, then things created at the start of some kind of sub loop, then things declared as some part of algorithm within that loop etc. As you add more and more function calls to the stack, you are doing ever finer-grained code, but each time you'll have boxed up the data in the layers lower in the stack into some kind of nice abstraction which makes it easy to access.
See what you are doing is using "OO" as a kind of closure management framework for a functional programming approach.

The shortcut solution to some problems involves mutable state of objects, which is not so functional - you're manipulating the closures from the outside. You're making some of the things in your class "global", at least to the scope above. Every time you write a setter - try to avoid those. I'd argue this is where you got the responsibility of your class, or the other classes in which it operates, wrong. But don't worry too much - it's pragmatic sometimes to stir in a bit of mutable state to solve certain kinds of problems quickly, without too much cognitive load, and actually get anything done.

So in summary, to answer to your question - what is the real responsibility of a class? It's to present kind of a platform, based on some underlying data, to achieve a more detailed kind of operation. It's to encapsulate half the data involved in an operation that changes less frequently than the other half of the data (Think currying...). E.g. filename vs string to write.

Often these encapsulations looks superficially like real world object/an object in the problem domain but don't be fooled. When you create a Car class, it's not actually a car, it's a collection of data that forms a platform on which to achieve certain kinds of things you might consider wanting to do on a car. Forming a string representation (toString) is one of those things - spitting out all that internal data. Remember that sometimes a Car class might not be the right class even if the problem domain is all about cars.  In contrast to Kingdom of nouns, it's the operations, the verbs that a class should be based around.


答:
I heavily rely on books as a source of knowledge - these are excellent foundations and I think Infestus is right in that you should be consuming significant quantities of books in your spare time as they really accelerate your skills.  Books are not the only source of information though that I think you should be consuming - attend your local user group, get the relevant technology newsletters delivered to your inbox, read blogs.

I disagree however with the assertion that because it is written a certain way in a book, that it is the way it must be done.  Yes books provide great advice, and they are written by experts, and peer reviewed by experts, but having been involved in a comparitively simple book I can tell you it typically takes at least two years start to finish to write, edit and release a book.  The pace of change in technology is rapid and the advice of two years ago may no longer be correct advice for today.  Generic principals often stand the test of time, but optimising a specific activity can be invalidated with a new bit of hardware or a new software release.

The suggestion of asking Infestus to go through suggestions with you is an excellent one - go away, read everything, and come back with a bunch of a thoughtful questions you've already tried to answer/solve for yourself along with your supporting evidence for your method.

There were questions about whether after 5 years why you were still a junior.  For me, the key measure of whether someone is a junior is not years of experience but how much they require spoon feeding.  I expect a mid-level developer to be relatively self-sufficient, a thoughtful consumer of knowledge sources who can act upon it and extend it to their situation.  They should also be at the stage where they can start teaching juniors because they have a firm understanding of their topic so that they can explain things clearly. The other core competency is confidence - if you've done the work, read the stuff, and produced something decent, don't be afraid to stand up for it in a court of debate as a junior requires validation, a developer requests consensus.


问:
Should I write an interface API before an implementation?
I've been delving into more "organized" programming recently and I've been learning that I should be programming to an interface, not an implementation. With that in mind, would it be better to "sketch" out a project in interfaces before writing the implementation for it where possible?

And if this is the case, in the case of using 3rd party libraries (ie Lidgren), should I be wrapping those in interfaces as well and resolve them through IOC containers, or is it OK to expose them to the interfaces?

答:
Unfortunately, you'll find this often boils down to personal preference.

What you've described so far, though, seems good.  In fact, if you wanted to (and I recommend it) you could use the following approach:

Write your application skeleton as Interfaces, abstract classes (stubbed), and classes (also stubbed)

Write your tests against those interfaces and stubs (they will fail for now)

Write your implementations (your tests will start passing as you finish your implementation)

You're focusing on trying to write more "organized" code.  Following TDD will help you with this.

Some extra points:

IoC containers are convenient.  Use them and DI as much as you can.

Do wrap 3rd party libraries.  This will loosen the coupling between your code (code you control) and 3rd party code (code you don't control)


答:
Yes, you should code against interfaces rather than known implementations, and yes, you should construct interfaces first rather than having them emerge from your own code.

The reasons for both recommendations are largely the same: computer programming is largely about human factors. Many find this surprising, but consider: there are a near-infinite number of different ways to solve the same computing problem that work equally well. Nearly all of them are completely impossible to make sense of for anyone who didn't write them (or in fact to the author a short time later).

It follows that good software engineering is largely about how to achieve the desired effect (correct computation with reasonable efficiency) in a way that allows the source code to be worked with later on. Interfaces and APIs are a crucial part of that discipline: they allow you to think about a problem at one level of description at a time. This is far easier than thinking about business consistency rules and about linked list implementations at the same time, and therefore imposing such a separation of concerns forcibly is better than allowing the client programmer to use your code any way he likes.

This is hard to believe for many cowboy programmers, who are convinced that they understand everything they write, are much better than average thinkers, and can handle all the complexity that gives "lesser" programmers trouble. Not being aware of one's own cognitive limits is an extremely common phenomenon - this is why best practices in code organization are so hugely important (and so often ignored).

To repeat, interfaces and API barriers are largely good, even when you only cooperate with yourself. As for external libraries, if they bring a well-thought-out API with them, I see no problem in using it as it is as long as you don't anticipate having to swap out that library for another one. Otherwise, a wrapper or anti-corruption layer can be a very good idea.

Title: Should I write an interface API before an implementation?

Body:
I've been delving into more "organized" programming recently and I've been learning that I should be programming to an interface, not an implementation. With that in mind, would it be better to "sketch" out a project in interfaces before writing the implementation for it where possible?

And if this is the case, in the case of using 3rd party libraries (ie Lidgren), should I be wrapping those in interfaces as well and resolve them through IOC containers, or is it OK to expose them to the interfaces?


问:
Should we always write Defensive null check in code?
Are there any scenarios where we should not write defensive checks for null?

Should we write defensive code or check for NULL every time we have passed a parameter or received a value back from a method?

Will this put an extra burden on the compiler?

答:
The ideal way to deal with null pointers is to forbid them by contract if a method cannot handle them. It depends on the language how well this is supported:

In Java, you can use the javax.validation.constraints.NotNull annotation (or similar ones provided by IDEs like IntelliJ and Eclipse) on any method parameter that is not allowed to be null. Unfortunately, this is not very portable.

In C#, you can use code contracts: Contract.Requires( x != null );

In C++, you can use references instead of pointers (but as soon as you're using smart pointers, you're out of luck)

In Ada, you can use a not null access type.

Some newer languages like Rust forbid null pointers by design.

I'd generally go for the contract approach rather than checking for null at runtime if possible. It enables earlier error discovery. Usually, contract-based null checking also generates a run-time check in addition to the compiler trying to deduce whether a parameter of a method call can violate the contract at compile-time.

Arguing that you trust the caller of your library is a bad idea, because you never know if the library will be re-used in another environment. Trust in callers will always harm code reusability.


问:
How can I automate production deployments without experiencing extreme anxiety?
At our shop we use SVN for source control and CruiseControl for CI on handling automatic builds and deployments to our development, test, and integration environments.

This all works smoothly however due to hardware and resource constraints our integration environment is not a 2 server load balanced environment like our production environment.  While everything else is equal that would be the only difference between our integration and production environments (although a big one!)

Theoretically the difference is a slightly different configuration of our app servers and the deploy script merely would have to drop the build artifacts into two servers instead of just the one, but why am I so nervous to automate our production deployments?!

I am generally not a control freak but I always feel the insatiable need to deploy production to production manually.  I have heard from colleagues that this is generally a Really BAD Thing™ but they failed to make a case against it.

I know that when I do it manually I can SEE that I am physically copying the correct files, I am physically shutting down the app servers and ensuring they closed successfully, I am physically starting the servers back up and then physically inspecting the logs to make sure it started up okay and the deployment was successful.  It gives me a peace of mind.

What are arguments against this OR arguments for automatic scripted production deployment?

答:
Simplify. Your change process should be rsync files, run SQL script, nothing more.

Automate.

Test.

The reason to automate is to obtain something that is test-able, repeatable, and that you can trust to work correctly in every expected situation.

You still need to have a back out plan, as for any change in any context, and it should be automated as well.

You will still want to observe the process as it happens if the environment is really sensitive, but never do it manually as it just can't be reproduced.


答:
As you appropriately depict this, tracking end-user nomenclature
changes in every part of the source is quite an investment.  It is
however definitely worth it, especially for a long living product
developed by a complete infrastructure (with hotline, testers, etc.)

Tracking end-user nomenclature in source is an investment is because
there are so many component types where it appears and there is no
magic wand working simultaneously on all these components.  Maybe
developing such a magic wand, component after component, is an
interesting investment that you can dilute over the lifetime of the
project.

I worked on a 30-year old codebase where the drift between end-user
nomenclature and internal nomenclature grew especially large.  Here
are a few drawbacks of this situation, which all add to the overhead
of everybody's work:

In the absence of an adequate policy, new development tends to use the
current end-user nomenclature.  Thus, the same concept may have two
or more names in different components.  Since the components
interact together, this results in several synonymous names
existing simulatenously in some local parts of the code.

When the hotline/help desk is called, they write down a user story using
end-user nomenclature.  The developer in charge of fixing the
problem must translate the end-user nomenclature to match the
source nomenclature. Of course it is not archived, and of course it
is a mess. (See 1.)

When the programmer debugs the code, she wants to set breakpoints
in relevant functions.  It is hard to find the appropriate
functions if the end-user nomenclature and the source nomenclature
do not agree.  It might even be hard or impossible to be confident
that a listing of the relevant functions is even complete. (See 1.)

In absence of an adequate policy, maintainance of source using an
obsolete nomenclature will from time to time put this obsolete
nomenclature in front of the users again. This produces poor
impression and causes overhead.

I already tracked down two days long the very place where some data is
read off the database and injected in some component of this codebase.
Because whether I nor anybody at the company I worked was able to
figure a name leading to this place I finally dismissed and decided to
find another solution to that problem.

While costing more than[1] two days of maintenance without yielding
anything (no knowledge, no fix, nothing) is probably as bad as it can
get, discrepancies between user-nomenclature and source nomemclature
add overhead to many routine task in the maintainance of a software.

It is important to remark that the overhead cost grows with the company
producing the software, in a large organisation, a problem report will
not arrive on your desk before it has been considered by several
colleagues and the fix might be subject to test.

[1] Because of more than one developer being involved.


答:
Rather than slavishly just programming to interfaces, why not look into Test Driven Development/Design (TDD)?

Many people think of TDD as a testing practice, but actually it's a design approach where you let tests expose how your code will be used via tests (initially via unit tests, but can also be via integration tests).

Programming to interfaces is an important weapon in your toolset, but like most things, it's not always the appropriate solution/technique/practice, as it's not always needed. You should program to interfaces where you need to.

Using TDD will force you to explore where such interfaces are important and where it, frankly, doesn't matter. And at the end of it you should have a pretty good set of unit tests across your code base.

As for using 3rd party libraries I would highly recommend wrapping them in your own abstractions where appropriate; and not let clients of your API "know" about them.

Good Luck!

[edit: saw megaflight's answer - completely agree]


问:
Python interview questions
I am going to interview within two weeks for an internship that would involve Python programming.

Can anyone suggest what possible areas should I polish? I am looking for commonly asked stuff in interviews for Python openings. Apart from the fact that I have already been doing the language for over a year now, I fail to perceive what they can ask me.

Like for a C or C++ interview, there are lots of questions ranging from reversing of strings to building linked lists, but for a Python interview, I am clueless.

Personal experiences and/ or suggestions are welcomed.

答:
I have no such experiences, but here are some guesses:

(Im)mutability

First class functions/classes

Closures

That's some stuff that python programmer should know, otherwise you may as well hire C programmer for the position.

OwnerDisplayName: Andy

Title: Python interview questions


问:
Is a 'God' ViewModel desired in WPF
My application has user controls within user controls. Please see a screen shot of one of the most beautiful applications of all time (UC = user control):

All the properties live in the MainWindow code behind, there are none in my UserControls. To bind to my properties I use

```<code>DataContext="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorLevel=1,AncestorType=Window}}"
</code>```

This works fine but, it does mean all binding properties are in my MainWindow code behind (or the MainWindow ViewModel).

Is this desired in a MVVM (or should I say WPF) approach, in that all the children share the same ViewModel?

答:
Unless overwritten, child controls will inherit the DataContext (except for children of an ItemsControl).

If you aren't explicitly setting the DataContext on all your controls you should be fine (but your coupling is high... ie, your usercontrol now assumes it will only be used in one specific configuration)

If you are explicitly setting the DataContext, then this becomes a problem of Dependency Injection.  If a grand-grand-grandchild usercontrols requires data from the topmost viewmodel, then that data should probably be passed to the closest level viewmodel.  Think about it.  This data is a clearly a dependency of the ViewModel bound to the UserControl.

Title: Is a 'God' ViewModel desired in WPF


问:
Keep indentation level low
I hear a lot that you should not write functions larger than one screen size, that you should extract things into functions if you call things very often and all these coding guidelines. One of them is also keep your indentation level low. Some people told me even I should max indent 4 times.

But in every day programming it keeps happening that I need O(n^2) or O(n^3) loops with some flow control, which creates out of nowhere 7 or 8 layers of indentation...

Are there any good ways to avoid that? One problem is, if you try to avoid complex if/else statement nesting I tend to do this in one row which can look very terrible and be unreadable and not very easy to maintain.

答:
As you have already noticed, bunching up control logic to reduce indentation is totally counter-productive. The problem is not actually with levels of indentation, or number of lines. Those things are just indicators of the actual problem: doing too much in one piece of code.

The solution is to refactor nested, complicated loops into separate methods so that both the calling and the called method can be understood as doing one sensible thing. If your loops need too many local variables to be easily separable, a method object can be useful which encapsulates those variables with a large local scope into the class scope of a new special-purpose mini-class.

The same applies to complicated controller logic: if the condition of continuing or stopping a loop contains many complicated expressions, then refactor it into a boolean method with a sensible name. The object is to make the top-level logic to be obviously correct provided that the ancillary functions are correct, and the helper functions so small that they can be verified easily by themselves.

Title: Keep indentation level low


答:
The idea behind these guidelines is that, when you find yourself in a situation such as yours, that there is most likely (not always, mind you, but still more often than you think) something wrong with your algorithm, and you should step back and rethink it.

I actually don’t think that refactoring will help you much, if it’s indeed an O(n²) or O(n³) algorithm – it might even worsen legibility (for people with wide enough terminals…) and reduce speed. (Of course, if you can improve the situation by refactoring without losing anything, by all means do so!) Really, step back, maybe let a coworker or someone else look at your code and algorithm and give advice… and if nothing else helps, ignore the guideline for that one function – with a detailed comment on top, of course.

Title: Keep indentation level low

Body:
I hear a lot that you should not write functions larger than one screen size, that you should extract things into functions if you call things very often and all these coding guidelines. One of them is also keep your indentation level low. Some people told me even I should max indent 4 times.

But in every day programming it keeps happening that I need O(n^2) or O(n^3) loops with some flow control, which creates out of nowhere 7 or 8 layers of indentation...

Are there any good ways to avoid that? One problem is, if you try to avoid complex if/else statement nesting I tend to do this in one row which can look very terrible and be unreadable and not very easy to maintain.


问:
Technical reason of why you need to use Class::static_method() instead of Class->static_method() in PHP
I'd like to know if there's a technical reason of why PHP's designers decided to invoke a static method using Class::static_method() instead of Class->static_method() (like any other method).
Does the syntax change reflect any technical requirement?

I'm asking this because the syntax for every single other language I know to invoke a method is always the same, despite it being static or not.

答: Invocation of instance methods is not Class->method() but $object->method(). Additionally, semantics of the -> operator is that it passes the instance of the class (vulgo: object) to the method in a hidden parameter; class methods differ from instance methods in that they, at best, have access to class attributes.


问:
How deterministic are SessionIDs from SHA'd GUIDs?
Assume I'm using the following code to generate pseudo-random sessionID's:

```<code>sessionID = SHA-512(GENERATE-GUID())
</code>```

The GUIDs are pretty deterministic, i.e. I see lots of GUIDs with a lot of the same hexadecimals.

My simple question is: How deterministic are my resulting sessionID's?

The algorithms for SHA are supposed to create very different hashes even if a small number of bits are different due to its cascading effect, so how easily could you "guess" (within reasonable time) another sessionID from the resulting hashes?

答:
They are completely random (an UUID consists of 16 octets, some bits of which are fixed and some fully random), so they are nōndeterministic – and not guaranteed to be unique (especially if your random source is flawed).

A better way to generate unique session IDs (which is what I assume you want/need) is to use a counter (such as the PostgreSQL PRIMARY KEY SERIAL of the session table you use) and hash that with a per-installation-of-your-app secret. (Remember to protect your cookies with a MAC, e.g. a HMAC, and to use a different(!) secret for that.)

Also: UUIDs are 16 bytes, which is 128 bit, so there’s no point in hashing them into something longer than 128 bit.

Clarification: I mean something like this:

```<code>$handle = db_query_params('INSERT INTO session (remote_ip, begin, …) VALUES ($1, $2, …)',
    array($remote_ip, now(), …));
$seqnumber = db_insertid($handle);  /* find out which SERIAL PostgreSQL assigned to the session */
$session_id = sha512($somesecret . $seqnumber);
</code>```

Body:
They are completely random (an UUID consists of 16 octets, some bits of which are fixed and some fully random), so they are nōndeterministic – and not guaranteed to be unique (especially if your random source is flawed).

A better way to generate unique session IDs (which is what I assume you want/need) is to use a counter (such as the PostgreSQL PRIMARY KEY SERIAL of the session table you use) and hash that with a per-installation-of-your-app secret. (Remember to protect your cookies with a MAC, e.g. a HMAC, and to use a different(!) secret for that.)

Also: UUIDs are 16 bytes, which is 128 bit, so there’s no point in hashing them into something longer than 128 bit.

Clarification: I mean something like this:

$handle = db_query_params('INSERT INTO session (remote_ip, begin, …) VALUES ($1, $2, …)',
    array($remote_ip, now(), …));
$seqnumber = db_insertid($handle);  /* find out which SERIAL PostgreSQL assigned to the session */
$session_id = sha512($somesecret . $seqnumber);


问:
Using a web framework as python GUI
If I built some useful piece of python code to e.g. scrape a website or to calculate something big, at some point I might want to add a GUI to my project. For this I could use Tk, Qt, Pygame or any python graphic/GUI framework.

Now I also want this tool to be usable by clients without the need for a python installation. Of course I could use something like py2Exe or py2Dmg. But wouldn't it be cooler to use a python-based web framework for this? Something like Django or Pyramid.

What would be the drawbacks of doing this? Can I just use the framework to execute my code on a server and only return the result? Or will this get tricky when there are multiple users?

答:
Making a web UI will make it easier to extend, and update. But it will be another layer of complexity for you to deal with.

I recommend looking at the lightweight http://webpy.org/

```<code>    urls = (
        '/hello', 'hello'
    )
    app = web.application(urls, globals())

    class hello:
        def POST(self, name):
            #call your script here
</code>```

You can call this with POST localhost/hello

Benefits:

Portability: no installers, can access from anywhere.

Extensibility: easyer to modify the UI (if you know HTML/CSS) and easier to re-deploy your application.

drawbacks:

Complexity: you will need to understand HTML, CSS request/response etc, set up a webserver or shared hosting,

Security: don't make it public.

Title: Using a web framework as python GUI

Body:
Making a web UI will make it easier to extend, and update. But it will be another layer of complexity for you to deal with.

I recommend looking at the lightweight http://webpy.org/

    urls = (
        '/hello', 'hello'
    )
    app = web.application(urls, globals())

    class hello:
        def POST(self, name):
            #call your script here

You can call this with POST localhost/hello

Benefits:

Portability: no installers, can access from anywhere.

Extensibility: easyer to modify the UI (if you know HTML/CSS) and easier to re-deploy your application.

drawbacks:

Complexity: you will need to understand HTML, CSS request/response etc, set up a webserver or shared hosting,

Security: don't make it public.


答:
How can I automate production deployments without experiencing extreme anxiety?

The extreme anxiety you would experience when automating production deployments is, most probably, based on two beliefs:

One day or the other, some deployment step will fail and you or another human is able to recover rapidly from the failure while an automated script could overlook it.

An overlooked failure in production has dramatic consequences.

There is little one can do about 2., besides avoiding failures, so let us focus on 1.

A cheap solution slightly improving on the existant would be to use a semi-automatic deployment procedure, waiting for validation at the end of each step of the installation.  With a semi-automatic solution you would enjoy benefits of a full automatic solution, like consistency and reproductibility, while you will still get a chance to monitor progresses and recover from errors as you are currently used to.

The semi-automated script and its biotope (regression tests etc.) could also serve as vehicle for the knowledge you are gathering about failures that happen in the installation procedure and ways to recover from them.

Body:
At our shop we use SVN for source control and CruiseControl for CI on handling automatic builds and deployments to our development, test, and integration environments.

This all works smoothly however due to hardware and resource constraints our integration environment is not a 2 server load balanced environment like our production environment.  While everything else is equal that would be the only difference between our integration and production environments (although a big one!)

Theoretically the difference is a slightly different configuration of our app servers and the deploy script merely would have to drop the build artifacts into two servers instead of just the one, but why am I so nervous to automate our production deployments?!

I am generally not a control freak but I always feel the insatiable need to deploy production to production manually.  I have heard from colleagues that this is generally a Really BAD Thing™ but they failed to make a case against it.

I know that when I do it manually I can SEE that I am physically copying the correct files, I am physically shutting down the app servers and ensuring they closed successfully, I am physically starting the servers back up and then physically inspecting the logs to make sure it started up okay and the deployment was successful.  It gives me a peace of mind.

What are arguments against this OR arguments for automatic scripted production deployment?


答:
Are there any good ways to avoid that? One problem is, if you try to avoid complex if/else statement nesting I tend to do this in one row which can look very terrible and be unreadable and not very easy to maintain.

Use local functions to embody the bodies of these conditionals. By doing this you cut a line between the workflow (supervisor) and the tranformations (performers), which improves clarity.

At a first glance, adding local functions makes reading harder because it breaks the reading flow of the program, but actually, it improves clarity because it separates the workflow from the transformations.

Title: Keep indentation level low


问:
"Enterprise" version of GPL'd code?
I know that there are a number of discussions about the GPL on this site but I just ran in to an interesting case of apparent misuse that I (surprisingly) haven’t seen discussed anywhere.

The CFEngine configuration management program is apparently distributed under the GPL (it even appears to be an FSF project) but the original author also distributes an “Enterprise edition” which is blatantly non-free. This appears to be an obvious violation of the GPL.

The official response to this question (from the CFEngine FAQ) is:

As copyright holders we are free to license CFEngine under any terms we choose. The files that belong to both the community edition and enterprise editions are consequently licensed under both sets of terms. The licensee of the Enterprise edition is therefore free to choose the terms that are deemed most desirable.

Which, as I understand the issue, is just not true. As copyright holders they are of course free to change the license (for future releases), but distributing code with both licenses is contradictory at best and illegal at worst.

Am I missing something here or does this seem wildly hypocritical?

答:
Part of the issue is how that code is used. If contributed code were GPL only, it could not be extended by the non GPL enterprise edition. (This is what is meant when people say the GPL is viral.) The author of the code owns the copyright, as mentioned, and can do what she wants and offer it under whatever license or licenses she wants, but she couldn't use GPL only contributed code from someone else in code she distributed with an enterprise license and also enterprise licensed users could not use any GPL only code in any custom code if it is in combination with the enterprise licensed code.

The people who manage the repository set the rules about contributions, and these rules about community contributions work for them. If it is GPL you are allowed to fork the code and say that your repository will require only GPL licensing.

Title: "Enterprise" version of GPL'd code?


问:
Is a senior programmers advice about always using books a good idea?
I am a junior developer and have only been in the industry for 5 years. At my current company there is a senior let's call him Infestus. Occasionally I am being given opportunity to shine and do something completely brand new from scratch.

One of the most recent examples was that I had to make a singleton in the multithreaded application. I have decided to use this method. As soon as Infestus saw it, he quickly proceeded to call me stupid and told me to use this approach. Upon asking him why he just brushed it off as this is better and that's how this and this book about Java says it is better.

And it is a common pattern: whenever I get a chance to do something new, I quickly get shot down by Infestus and the only reasoning why his method is better is because those books were written by famous programmers. He is always trying to give me books to read so that I may "learn" which ways to program.

I have only been programming for money for 5 years, but is it always a good idea to just blindly follow the book on best ways for solving a problem, or should I try experimenting every now and then? The constant barrage of complaints from the Infestus is starting to cause me to never try anything new and follow examples in books.

EDIT: I am utterly lost. Yes I know that following anything blindly is a bad idea. But this godlike programmer Infestus who seems to know a lot, tells me that the only way to program properly is by reading books and following everything down to a T. All the rules he imposes are the ones written in books, so I am just wondering if books are the only correct way.

EDIT2: Infestus is not my boss. He is just one of senior developers in charge of reviewing the code. And most of his comments after reviews consist of book names where such and such method is wrong.

答:
Reading books and blog posts is very helpful in programming. There are some books, which all developers should read.

However books are not the only source to learn different programming concepts and technologies. Nowadays on-demand video based training is getting very popular. You can check Pluralsight, which provides high quality training to professionals.

In fact, if you read only books that is not going to help either. Besides reading there are other thing that we need to do as well. You can find more details here.


答: I would suggest you use an implementation of session id, that is known to be secure. Also there's RFC about UUID/GUID http://www.ietf.org/rfc/rfc4122.txt where you can learn that there are different versions of GUIDs. I suggest you switch to cryptographycaly secure random numbers. </p>

Title: How deterministic are SessionIDs from SHA'd GUIDs?

Body:
Assume I'm using the following code to generate pseudo-random sessionID's:

```<code>sessionID = SHA-512(GENERATE-GUID())
</code>```

The GUIDs are pretty deterministic, i.e. I see lots of GUIDs with a lot of the same hexadecimals.

My simple question is: How deterministic are my resulting sessionID's?

The algorithms for SHA are supposed to create very different hashes even if a small number of bits are different due to its cascading effect, so how easily could you "guess" (within reasonable time) another sessionID from the resulting hashes?


问:
Greek philosophers, stone tablets and dumb slaves problem
This is one of the questions that I came across while preparing for a programming interview.

Design a system for Greek philosophers to exchange messages using stone tablets carried by dumb slaves.

Well, the guys who had this question have suggested to use analogy of a TCP/IP protocol to describe the communication and some suggested packet data communication to explain the design.

Here is what I think of it going by the clues:

The Greek philosophers would act as 'machines' that are trying to
communicate.

The dumb slaves would be the message carrier which is the 'network' in our analogy.

Stone tablets would be messages carried like the 'data packets'.

May be the slaves would reach philosophers by asking for the route from some random guys that will lead them to the philosopher's place just like the packets arrive at a destination using routers in the network.

And the message could be split in to multiple tablets and so, a message could be eventually carried by more than one slave who might take different paths and arrive in any order. There shall be a way to arrange the message in the correct order on their arrival at the receiver's end. (sequence number in the tablets?)

The system should also be able to handle missing tablets and in which case should the sender philosopher try and send the entire message again after a timeout?

EDIT:

I would like to ask the following questions:

Am I thinking on the correct lines?

Are there any important things that I am missing in the things that I have listed above?

This question to design a system looks vague to me. How would someone depict such a system in an interview ? Using diagrams to show interactions between entities?

Am I handling the missing tablets issue correctly (Mentioned as point 6. above)?

答:
I think that the "stone tablet" restriction quite contradicts what you are trying to solve with your #5. It seems the interviewers do not want the payload data to be split up.

Also, from what you describe, there seems to be no concept of "time" in that network (ancient Greece, dumb slaves), so your #6 somewhat misses the point, IMHO. The key question may be: "how does a sender-philosopher conclude that his message has arrived at the receiver-philosophers place?" This leads to a (philosophical) discussion about acknowledge::retry/reack::reretry etc.
Keep in mind that the slaves may be so dumb that they themselves can't report successful delivery...


问:
HMVC and Database Connections
Whilst I have good experience with OOP, I'm fairly new to the concept of (H)MVC. I understand the basic concept of modular design that comes with HMVC, it's the great attraction of it. But one thing that has been bugging me, and will hopefully help me understand HMVC better is how do you handle the database connection?

I would assume that you would have a module, lets call it Database, that would initiate the connection. Now at the start of my script I would have something along the lines of:

```<code>$dbConn = new Database();
</code>```

That would initiate the connection to the database. However, when I want to run a query I need to run something along the lines of:

```<code>$query = "my query string";
$result = $dbConn->query($query);
</code>```

So I need to access the query function of the database object. Now as far as I can tell in HMVC I shouldn't directly access $dbConn from within a model of another module. But almost every module will need to access $dbConn.

From my understanding this means that in the controller of all other modules, any time I need to run a query I would have to create a new instance of the Database module, passing in an array of arguments, telling Database which method to run and what arguments that method needs.

But then what if I need to make a call to the database half way through a method in a module's model? Quite often I will need to update a table, or select some data based on an if statement. Surely I shouldn't be moving that logic to the controller?

So that means I need to be able to access another module from within a model, which seems to break the rules of HMVC. So how do I implement a database module as this is confusing me?

答:
It's pretty much impossible to be truly 100% modular, there will always be certain dependencies. The best thing you can do is try to organize it in a way that makes sense to your particular project.

That said, it isn't forbidden to make Models from module A to communicate with models from module B.

Title: HMVC and Database Connections


问:
Multi regex matching -- what to do to optimize it?
I have multiple regexes matching an input in greedy-first mode. All regexes are already compiled and I don't see what I can do more to speed-up things. I mean using tools coming with .Net framework.

Since I don't do any replace, or capturing, I wonder if it makes sense to built my own regex matching -- in result I would execute matching only once (per multi-regex) instead of multi matching (per each single regex).

Am I thinking too far? Is there other way to speed it up?

答:
All regexes are already compiled and I don't see what I can do more to
  speed-up things.

Do you reuse Regex objects? Compiling will not speed things up if you don't; quite the contrary.

See https://stackoverflow.com/a/7707369/168719 for reference.

Is the pattern complex? Sometimes regular expressions are too heavy weight for the job. If the matching is not that sophisticated, it would certainly be faster to implement it "manually", with a loop and some hand-made logic etc.


答:
most regex engines use a backtracking mechanism that may slow down on bad inputs (called catastrophic backtracking). I don't know if C# does but my guess is that it does. Read this article if you want to know more

one way to fix it is tuning your regexes to avoid the backtracking pitfall

another is to use a regex engine that builds a DFA and doesn't need to backtrack (not possible when you use backrefs but you aren't doing that) or build your own DFA

Title: Multi regex matching -- what to do to optimize it?

Body:
I have multiple regexes matching an input in greedy-first mode. All regexes are already compiled and I don't see what I can do more to speed-up things. I mean using tools coming with .Net framework.

Since I don't do any replace, or capturing, I wonder if it makes sense to built my own regex matching -- in result I would execute matching only once (per multi-regex) instead of multi matching (per each single regex).

Am I thinking too far? Is there other way to speed it up?


问:
Game development design patterns and architectures?
Some friends and me wish to develop a 2D game just for the experience of learning this paradigm. We are all software engineers with experience in business apps, but we are unsure if the typical design patterns and architectures (MVC, 3-layer, etc) apply as well, and we are totally unknown about the techniques that are typically used in Game development (Scenegraphs, key bindings implementation, event management, sound/texture banks...)

We plan on developing with C# and XNA/Monogame, and I would be grateful if someone could point out any useful bibliography that could be helpful for us to plan an architecture and deal with any day-by-day game development issues.

Thank you

答:
Start from the ground up.  Game development is amazingly fun but quite a different beast from web development.  XNA is a good starting point if you are comfortable with C# but I have to suggest starting from the beginning.

Try to create Pong or Tetris first.  If you are not used to game loops, logic, rendering pipelines, collision detection, input handling, etc. it can get rather overwhelming.  You have the advantage of experience so these should be relatively easy projects, and IMHO, important first steps.


答:
IMHO, there are 2 aspects here, which you should deal with separately:

The fact that the guy is being a jerk, calling you names and such simply because he can (he's senior, you're not, if either of you complains about the other one, he'll get the benefit of the doubt) is simply bully-like behavior, and just bad.

Try not to stoop to his level with this. Don't try to bully him back or "tell on him" to the boss or anything. Do your best to ignore this aspect of his behavior, keeping in mind that it becomes too extreme (i.e. if it affects your productivity and such) you should do something about it.

The fact that he's telling you that your code is bad (and how to do it proper). Honestly from what you describe, ignoring the guy's tone, this aspect of his behavior is not that bad. You learn things a lot faster and get to see them in the proper context when you have someone more experienced correcting you and telling you not only what you did wrong, but also how to do it right (as compared to just learning them all by yourself from personal trial/error experiments and the like).

Many a time I've had someone correct what I initially thought was "my perfect code" and just got upset that the guy was telling me what to do only to later realize that he was right all along, my version was bad, his was good, and thank God he saw that! :) So I've learned to tone down my initial impulses of "hey, u no tell me what to do, mista!" and instead, each time someone corrects me I first really, objectively, re-check my code, then check his, and make sure he's not really right and it's me who's doing the blunder. If it was my fault, I thank him from the help, and make sure I really understand how his solution works (rather than just copy/pasting it in).

And hey, sometimes I do find that the offered correction was in fact worse than what I initially did, at which point I try talking all this out with the other guy. Honestly, I've noticed that nothing gains the others' respect for you faster than when they see that you can accept being corrected when you've made a mistake, but at the same time, are not afraid to say you're the one who's right when you think it's so, given that you can immediately prove that you base your affirmation on some actual research, and not just ego.

On this point, I think you should really try and talk to the guy about what he proposes, and what you propose and so forth. Show him what you think, how you got to a particular solution, and why you think it's better than his (when you honestly and objectively think it is). Or, if you find out that his proposition is better than yours, tell him so, express your appreciation for the help. This may rebuild some burned bridges.