答:
Your friend seems to be facing numerous headwinds based on his anecdote. That is unfortunate, and can be a very hard environment to work in. Despite the difficulty, he was on the correct path of using patterns to make his life easier, and it is a shame that he left that path. The spaghetti code is the ultimate result.

Since there are two different problem areas, technical and interpersonal, I'll address each separately.

Interpersonal

The struggle your friend is having is with rapidly changing requirements, and how that is affecting his ability to write maintainable code. I would first say that requirements changing twice a day, every day for such a long period of time is a bigger problem, and has an unrealistic implicit expectation. The requirements are changing faster than the code can change. We cannot expect the code, or the programmer, to keep up. This rapid pace of change is symptomatic of an incomplete conception of the desired product at a higher level up. This is a problem. If they don't know what they really want, they'll waste a lot of time and money to never get it.

It might be good to set boundaries for changes. Group together changes into sets every two weeks, then freeze them for the two weeks while they are implemented. Build up a new list for the next two week period. I have a feeling some of these changes overlap or contradict (ex, waffling back and forth between two options). When changes come fast and furious, they all have top priority. If you let them accumulate into a list, you can work with them to organize and prioritize what is most important to maximize efforts and productivity. They may see that some of their changes are silly or less important, giving your friend some breathing room.

These problems should not stop you from writing good code, though. Bad code leads to worse problems. It may take time to refactor from one solution to another, but the very fact that it is possible shows the benefits of good coding practices through patterns and principles.

In an environment of frequent changes, technical debt will come due at some point. It is far better to make payments toward it rather than throw in the towel and wait until it becomes too big to overcome. If a pattern is no longer useful, refactor it away, but don't go back to cowboy coding ways.

Technical

Your friend seems to have a good grasp on the basic design patterns. Null object is a good approach to the problem he was facing. In truth, it still is a good approach. Where he seems to have challenges is understanding the principles behind the patterns, the why of what they are. Otherwise, I don't believe he would have abandoned his approach.

(What follows is a set of technical solutions that were not asked for in the original question, but that show how we could adhere to patterns for illustrative purposes.)

The principle behind null object is the idea of encapsulating what varies. We hide what changes so we don't have to deal with it everywhere else. Here, the null object was encapsulating variance in the product.Price instance (I'll call it a Price object, and a null object price will be NullPrice). Price is a domain object, a business concept. Sometimes, in our business logic, we don't yet know the price. This happens. Perfect use case for the null object. Prices have a ToString method that outputs the price, or empty string if it's not known (or, NullPrice#ToString returns an empty string). This is a reasonable behavior. Then requirements change.

We have to output a null to the API view or a different string to the managers' view. How does this affect our business logic? Well, it doesn't. In the above statement, I used the word 'view' twice. This word was probably not spoken explicitly, but we must train ourselves to hear the hidden words in requirements. So why does 'view' matter so much? Because it tells us where the change has to really happen: in our view.

Aside: whether or not we are using an MVC framework is irrelevant here. While MVC has a very specific meaning for 'View', I am using it in the more general (and perhaps more applicable) meaning of a piece of presentation code.

So we really need to fix this in the view. How could we do that? The easiest way to do this would be an if statement. I know the null object was intended to get rid of all the ifs, but we have to be pragmatic. We can check the string to see if it's empty, and switch:

```<code>if(product.Price.ToString("c").Length == 0) { // one way of many
    writer.write("Price unspecified [Change]");
} else {
    writer.write(product.Price.ToString("c"));
}
</code>```

How does this affect encapsulation? The most important part here is that view logic is encapsulated in the view. We can keep our business logic/domain objects completely isolated from changes in the view logic this way. It's ugly, but it works. This is not the only option, though.

We could say that our business logic has changed just a bit in that we want to output default strings if no price is set. We can make a minor tweak to our Price#ToString method (actually create an overloaded method). We can accept a default return value and return that if no price is set:

```<code>class Price {
    ...
    // A new ToString method
    public string ToString(string c, string default) {
        return ToString(c);
    }
    ...
}

class NullPrice {
    ...
    // A new ToString method
    public string ToString(string c, string default) {
        return default;
    }
    ...
}
</code>```

And now our view code becomes:

```<code>writer.write(product.Price.ToString("c", "Price unspecified [Change]"));
</code>```

The conditional is gone. Doing this too much, though, could proliferate special case methods into your domain objects, so this only makes sense if there will only be a few instances of this.

We could instead create an IsSet method on Price that returns a boolean:

```<code>class Price {
    ...
    public bool IsSet() {
        return return true;
    }
    ...
}

class NullPrice {
    ...
    public bool IsSet() {
        return false;
    }
    ...
}
</code>```

View logic:

```<code>if(product.Price.IsSet()) {
    writer.write(product.Price.ToString("c"));
} else {
    writer.write("Price unspecified [Change]");
}
</code>```

We see the return of the conditional in the view, but the case is stronger for business logic telling if the price is set. We can use Price#IsSet elsewhere now that we have it available.

Finally, we can encapsulate the idea of presenting a price entirely in a helper for the view. This would hide the conditional, while preserving the domain object as much as we would like:

```<code>class PriceStringHelper {
    public PriceStringHelper() {}

    public string PriceToString(Price price, string default) {
        if(price.IsSet()) { // or use string length to not change the Price class at all
           return price.ToString("c");
        } else {
            return default;
        }
    }
}
</code>```

View logic:

```<code>writer.write(new PriceStringHelper().PriceToString(product.Price, "Price unspecified [Change]"));
</code>```

There are many more ways to make the changes (we could generalize PriceStringHelper into an object that returns a default if a string is empty), but these are a few quick ones that preserve (for the most part) both the patterns and the principles, as well as the pragmatic aspect of making such a change.

Body:
Your friend seems to be facing numerous headwinds based on his anecdote. That is unfortunate, and can be a very hard environment to work in. Despite the difficulty, he was on the correct path of using patterns to make his life easier, and it is a shame that he left that path. The spaghetti code is the ultimate result.

Since there are two different problem areas, technical and interpersonal, I'll address each separately.

Interpersonal

The struggle your friend is having is with rapidly changing requirements, and how that is affecting his ability to write maintainable code. I would first say that requirements changing twice a day, every day for such a long period of time is a bigger problem, and has an unrealistic implicit expectation. The requirements are changing faster than the code can change. We cannot expect the code, or the programmer, to keep up. This rapid pace of change is symptomatic of an incomplete conception of the desired product at a higher level up. This is a problem. If they don't know what they really want, they'll waste a lot of time and money to never get it.

It might be good to set boundaries for changes. Group together changes into sets every two weeks, then freeze them for the two weeks while they are implemented. Build up a new list for the next two week period. I have a feeling some of these changes overlap or contradict (ex, waffling back and forth between two options). When changes come fast and furious, they all have top priority. If you let them accumulate into a list, you can work with them to organize and prioritize what is most important to maximize efforts and productivity. They may see that some of their changes are silly or less important, giving your friend some breathing room.

These problems should not stop you from writing good code, though. Bad code leads to worse problems. It may take time to refactor from one solution to another, but the very fact that it is possible shows the benefits of good coding practices through patterns and principles.

In an environment of frequent changes, technical debt will come due at some point. It is far better to make payments toward it rather than throw in the towel and wait until it becomes too big to overcome. If a pattern is no longer useful, refactor it away, but don't go back to cowboy coding ways.

Technical

Your friend seems to have a good grasp on the basic design patterns. Null object is a good approach to the problem he was facing. In truth, it still is a good approach. Where he seems to have challenges is understanding the principles behind the patterns, the why of what they are. Otherwise, I don't believe he would have abandoned his approach.

(What follows is a set of technical solutions that were not asked for in the original question, but that show how we could adhere to patterns for illustrative purposes.)

The principle behind null object is the idea of encapsulating what varies. We hide what changes so we don't have to deal with it everywhere else. Here, the null object was encapsulating variance in the product.Price instance (I'll call it a Price object, and a null object price will be NullPrice). Price is a domain object, a business concept. Sometimes, in our business logic, we don't yet know the price. This happens. Perfect use case for the null object. Prices have a ToString method that outputs the price, or empty string if it's not known (or, NullPrice#ToString returns an empty string). This is a reasonable behavior. Then requirements change.

We have to output a null to the API view or a different string to the managers' view. How does this affect our business logic? Well, it doesn't. In the above statement, I used the word 'view' twice. This word was probably not spoken explicitly, but we must train ourselves to hear the hidden words in requirements. So why does 'view' matter so much? Because it tells us where the change has to really happen: in our view.

Aside: whether or not we are using an MVC framework is irrelevant here. While MVC has a very specific meaning for 'View', I am using it in the more general (and perhaps more applicable) meaning of a piece of presentation code.

So we really need to fix this in the view. How could we do that? The easiest way to do this would be an if statement. I know the null object was intended to get rid of all the ifs, but we have to be pragmatic. We can check the string to see if it's empty, and switch:

if(product.Price.ToString("c").Length == 0) { // one way of many
    writer.write("Price unspecified [Change]");
} else {
    writer.write(product.Price.ToString("c"));
}

How does this affect encapsulation? The most important part here is that view logic is encapsulated in the view. We can keep our business logic/domain objects completely isolated from changes in the view logic this way. It's ugly, but it works. This is not the only option, though.

We could say that our business logic has changed just a bit in that we want to output default strings if no price is set. We can make a minor tweak to our Price#ToString method (actually create an overloaded method). We can accept a default return value and return that if no price is set:

class Price {
    ...
    // A new ToString method
    public string ToString(string c, string default) {
        return ToString(c);
    }
    ...
}

class NullPrice {
    ...
    // A new ToString method
    public string ToString(string c, string default) {
        return default;
    }
    ...
}

And now our view code becomes:

writer.write(product.Price.ToString("c", "Price unspecified [Change]"));

The conditional is gone. Doing this too much, though, could proliferate special case methods into your domain objects, so this only makes sense if there will only be a few instances of this.

We could instead create an IsSet method on Price that returns a boolean:

class Price {
    ...
    public bool IsSet() {
        return return true;
    }
    ...
}

class NullPrice {
    ...
    public bool IsSet() {
        return false;
    }
    ...
}

View logic:

if(product.Price.IsSet()) {
    writer.write(product.Price.ToString("c"));
} else {
    writer.write("Price unspecified [Change]");
}

We see the return of the conditional in the view, but the case is stronger for business logic telling if the price is set. We can use Price#IsSet elsewhere now that we have it available.

Finally, we can encapsulate the idea of presenting a price entirely in a helper for the view. This would hide the conditional, while preserving the domain object as much as we would like:

class PriceStringHelper {
    public PriceStringHelper() {}

    public string PriceToString(Price price, string default) {
        if(price.IsSet()) { // or use string length to not change the Price class at all
           return price.ToString("c");
        } else {
            return default;
        }
    }
}

View logic:

writer.write(new PriceStringHelper().PriceToString(product.Price, "Price unspecified [Change]"));

There are many more ways to make the changes (we could generalize PriceStringHelper into an object that returns a default if a string is empty), but these are a few quick ones that preserve (for the most part) both the patterns and the principles, as well as the pragmatic aspect of making such a change.


问:
What payoffs have you seen from taking care of technical debt?
This article on technical debt has some good points, including:

Working on the "technical matters" works best when it is driven by stories. The code base is probably in need of work everywhere, but the payoff will be received only where the code is going to be worked on for user-facing reasons. If no stories are going to pass through some crufty area, working on it is largely wasted.

Therefore, I prefer the approach of taking stories as usual (but probably fewer of them), and following the "boy scout rule" of leaving the campground better than you found it. In other words, wherever the stories lead us, let's write more tests, let's refactor more aggressively.

This approach has at least these advantages:

maintains "best sensible" flow of stories;

provides help from all team talent;

provides for whole team to learn how to keep code clean;

focuses improvement exactly where it is needed;

does not waste improvement that "may" be needed;

I've seen code quality have a very big effect on long-term productivity, so I am a believer that technical debt should be taken care of.  I think the post above makes sense, but I'm not so sure about the last two points.  I'm interested in finding out real experiences of benefits from cleaning technical debt, even if it was not related to user stories.

What positive benefits have you seen from cleaning up your code base and ridding yourself of technical debt? What methods did you use to get the work done?

答:
Regarding the last two points: I understand where it's coming from, as explained in his original post :

Or, is it possible to reassign some developers to get these
    technical matters done, while the rest of the team continues on
    the user-oriented stuff? This may affect team velocity, but so what?

"So what" equals: the product owner
  and other business-side people become
  unhappy. And when Momma's unhappy,
  everyone's unhappy.

Yet, the line between what has to be done and what may be done is pretty vague. User-faced is very broad, and includes performance and occurence of errors. But in quite some cases, the underlying problem of poor performance and high occurence of errors lies deeper in the code. To say it in his words: a story might not go through a crufty area, but that crufty area can hide some nasty things that attacking the story on the cleaned-up path next to it.

Things that do not influence the overall performance are less interesting to clean up, but one should evaluate very carefully the influence of those points. More often than not they have an indirect influence that can be pretty substantial.

ContentLicense: CC BY-SA 2.5


问:
Refactoring previous intern's noodle code with future interns in mind
Background

I've run across this problem as I am currently an intern at a large company's local software division. I have been given the task of extending a project that several previous interns have worked on (not collectively but sequentially). The project is written in C# and is a relatively simple tool (codebase of about 10,000 lines)

The problem

The first intern started writing the tool using pretty much only lists and ignoring the fact that setting up data structures (such as objects) makes the tool much more extensible and readable. The interns that came afterward did not bother to change this and instead built upon the tool in the same manner. This led to a couple of massive methods ( +700 lines), lots of global variables (most variables were global), and just very bad organization.

My Approach

I spent countless hours in the debugger understanding the logic of the code and have (for the most part) a very good outlook on it. I have written the required data structures and am organizing as well as rewriting "black box" portions of the code in order to make it possible to add a new feature without spending +2 weeks trying to figure out what is going on. I am doing this not just for my own sanity but for the intern that will come after me. I am constantly trying to focus on readability and simplicity while avoiding solutions that are short, effective, but slightly esoteric to another intern. I am following general OOP design and trying to avoid pitfalls that come from blindly believing a certain method is the best method without researching it and understanding why and how its applied. I am leaning heavily to a top-down approach in terms of design and how the execution flow will be laid out as this seems to be easier for others to quickly understand and internalize, but am open to suggestions for alternative approaches or methodologies.

The Question

How would I go about balancing my wish to write good code and writing code is understandable to a relatively untrained intern (the assumption is that they are pursuing a computer science degree but are still in school) while having a good outlook for the future in terms of extendability?

Any help is greatly appreciated

答:
Your question has two major concerns: should I write good code, even if the next person may not understand it? and, how to I make sure that my efforts are not wasted if a less experienced person takes over after me?

As to the first, you should always write the best code you can. We know that code written with design patterns and principles is flexible, maintainable, and extensible. Even new programmers can generally see this, even if they don't understand how to do it themselves. Tests also provide tremendous benefit, and can fill a documentation role as well. You cannot let expectations of who will come after you prevent you from writing good code; if anything, it should encourage you to write good code.

With regards to preserving all the work you've put in, most developers, even new ones, can generally understand what is going on in a piece of well-written code (at least on the surface), but some developers, especially new developers in school, have no idea why a piece of code is the way it is. This is what you have to communicate.

I would recommend writing a document to communicate how and why you got the code to where it is. I would briefly discuss how you use version control for the project, as some curricula do not involve any version control, and provide resources on where to learn about your VCS (for example, hginit.com and "Mercurial: The Definitive Guide for Mercurial, similar resources exists for other VCSes). You should talk about design patterns, especially which are the ones they'll see often. Once again, some curricula don't talk about design patterns. Once again, provide resources to learn more.

Also talk about the code, and your experience with it. Talk about conquering the 700 line method, how you did it, why you did it, and how it made everyone's life easier. I would write this less formally, and in a narrative tone to keep it interesting and personable. This will help the next person to see what progress you've made, see how you work, and build a personal bond. All developers can commiserate over experiences working with bad code.

I would leave out any specific details, like how to access your repositories or log into your servers, or confidential business information. The reason I would do this is so that they could send this out to an intern before they start, and they could keep it after they leave, as an informative resource. You should supply the other information in a separate document that they get once they actually start the internship. I would aim for a length between 5 and 10 pages, enough room for you to tell your stories while short enough to be read casually.

Programmers who come after will likely do the same thing you did (as you saw before where the list lived forever), if they can understand how and why to do it. If you build a good base, and clearly show the way, the next person is pretty likely to go with the flow.

ContentLicense: CC BY-SA 3.0


问:
Why does C have no competitors in low level stuff?
As far as I know, C is by far the most widely used language for low level stuff such as systems programming and embedded. Sometimes assembly is used, but that's when you really need to be close to the hardware.

My question is why doesn't C have any competitors in low level development? It might be my ignorance, but I'm pretty sure that C is the obvious (or possibly only) choice for low level programming.

This is as opposed to high level development, where there are many competing programming languages to choose from.

How can you explain this?

答:
1) ..C is by far the most widely used language for low level.. why?

It is so widely used because of its age. According to Wikipedia - C (programming language) it is 42 years old. It means 42*number_of_programmers man-years of work done. As the C is included in basic programming courses at any serious programming school the number of programmers that can speak C worldwide is very huge and the amount of now available C code is very very huge.

2) ..why doesn't C have any competitors in low level development?..

your claim "doesn't have any competitors" is not true so it does not have any why answer available.

VHDL (start at http://en.wikipedia.org/wiki/Vhdl) is low level language much more efficient for low level stuff. e.g. for expressing the parallelism that can be compiled directly into hardware circuit design or flashed into and "interpreted" with very high speed and efficiency on Field-programmable gate array (FPGA) hardware chips.

This language is not so wide spread as it is not so old, not usually taught at general purpose programming courses, requires special (though cheap) processors to run on. It is more demanding for programmer's discipline and it is not a language for writing a "hello world" applications that just flashes with few LEDs connected to the COM port or to print some fancy ASCII art tables.

VHDL is serious very strong C competitor for low level development. It is not "just another assembler". It is a paradigm shift

3)

In the category of "least common denominator" languages that might replace C something that would be able to efficiently express/compile into MMIX (pronounced em-mix) is a 64-bit RISC architecture designed by Donald Knuth might becom an competitor.

But!

Who nowadays invests the time and effort into inventing new efficient language with tools etc. writing a compiler for it etc. Who needs such an tremendous effort today? What problems would it solve? Even programmers want to raise children, want to have lives. To make such new language widespread it is not solvable as one-man-show-spare-time-hobby-project anymore. Just compare the code bases of various compilers/IDEs with something you know, something you write yourself - and you'll see another answer to the why


问:
How to model more than one 'last name'?
In Spanish-speaking countries we use more than one last name, like:

First name ↘                           ↙ Last name

                  Pedro Arturo Rodríguez Loyola

          Middle name ↗                               ↖ (?)

I'm trying to model data for patient name. In our country it's important, so I can't neglect the second last name, but I would like to build an application that can makes sense to other developers, especially from English-speaking countries.

I created a similar question on English.SE, it has some insights about why it's important to persist both values.

答:
There are three types of personal names: Polynyms (names with multiple components), Mononyms (names with only one component, ex "Cher") and Pictonyms (names represented by pictures, ex The Artist).

A person can have multiple names, playing roles, for example Legal Name, and Preferred Name.

A polynym has several components, of which given name and surname should be required. There are a few kinds of surnames:

Regular surnames (Jones)

Double-barrelled surnames ("Vaughn Williams" or "Louis-Dreyfus")

True Compound surnames { givenName:"Juan Pablo" surname:"Fernández de Calderón", secondarySurname:"García-Iglesias" }

3 is important because he would be expected to be addressed as Mr. Fernández de Calderón, not Mr. Fernández de Calderón García-Iglesias.

So basically, have a mandatory surname field, and a nullable secondarySurname field.

Title: How to model more than one 'last name'?


问:
What would you think about a new Java persistence tool, that's not really an ORM?

Persistence in Java

Over the past years, I have gathered experience in the field of persistence abstraction in Java, using concepts such as EJB 2.0, Hibernate, JPA and home-grown ones. They seemed to me to have a steep learning curve and lots of complexity. In addition, as a big fan of SQL, I also thought that many abstraction models provide too much abstraction over SQL, creating concepts such as "criteria", "predicates", "restrictions" that are very good concepts, but not SQL.

The general idea of persistence abstraction in Java seems to be based on the Object-relational model, where RDBMS are somehow matched with the OO world. The ORM-debate has always been an emotional one, as there does not seem to exist a single solution that suits everyone - if such a solution can even exist.

jOOQ

My personal preference of how to avoid ORM-related problems is to stick to the relational world. Now the choice of data model paradigm should not be the topic of discussion as it is a personal preference, or a matter of what data model best suits a concrete problem. The discussion I would like to start is around my very own persistence tool called jOOQ. I designed jOOQ to provide most of the advantages modern persistence tools have:

A Domain Specific Language based on SQL

Source code generation mapping the underlying database schema to Java

Support for many RDBMS

Adding some features that few modern persistence tools have (correct me if I'm wrong):

Support for complex SQL - unions, nested selects, self-joins, aliasing, case clauses, arithmetic expressions

Support for non-standard SQL - stored procedures, UDT's, ENUMS, native functions, analytic functions

Please consider the documentation page for more details: http://www.jooq.org/learn.php. You will see that a very similar approach is implemented in Linq for C#, although Linq is not exclusively designed for SQL.

The Question

Now, having said that I'm a big fan of SQL, I wonder whether other developers will share my enthusiasm for jOOQ (or Linq). Is this kind of approach to persistence abstraction a viable one? What are the advantages / disadvantages you might see? How could I improve jOOQ, and what's missing in your opinion? Where did I go wrong, conceptually or practically?

Critical but constructive answers appreciated

I understand that the debate is an emotional one. There are many great tools out there that do similar things already. What I am interested in is critical but constructive feedback, based on your own experience or articles you may have read.

答:
"There are a lot of magic bullets out there, and no shortage of naive developers."

No offense, it appears that you don't entirely understand what's been done in this space already and therefore are reinventing some wheels - experience would tell us all that the wheels you invent, while neat and fun, aren't likely to be nearly as good or useful as the nicely refined wheels already available.


答:
How do you model the various components of someone's name?  You Don't.  Instead of modeling separate fields for all the components of someone's legal name, plus their preferred salutation, appelation, informal name, username, nick-name, and handle, only model what you care about.

Odds are your system only really cares about at most four "names" for someone:

A Display Name which allows them to know that they are logged in to the system.

An Informal Name by which you would address them on a phone call.

A Formal Name with which you would refer to them on correspondence.

A Sort Name which expresses #2 in a way that it would be ordered in a list.

Many systems would simply use someone's formal name for #1 and #2, leaving the only names you care about as "a string representing the user's name" and "a string representing how the former should be sorted."

From a data modeling perspective, define only those values that you would actually need.  How best to optimize the storage of these values is an implementation detail -- one that you will only cause headaches for if you over-optimize.  (Sure, you "could" just store a first name and last name, but what would you do for someone who only has a single name?)

Title: How to model more than one 'last name'?

Body:
In Spanish-speaking countries we use more than one last name, like:

First name ↘                           ↙ Last name

                  Pedro Arturo Rodríguez Loyola

          Middle name ↗                               ↖ (?)

I'm trying to model data for patient name. In our country it's important, so I can't neglect the second last name, but I would like to build an application that can makes sense to other developers, especially from English-speaking countries.

I created a similar question on English.SE, it has some insights about why it's important to persist both values.


问:
Static vs. non-static? (with non-OOP functions)
Although this question has come up before, mine is different because it is not supposed to cover anything OOP but only plain (ANSI) C.

Especially in open-source software, I usually encounter a plethora of functions (please don't call them methods since we're not in OOP) with the static keyword preceding the data type.

But what effect does this actually have with plain C? In my own projects, I've never had an occasion where the static keyword was actually needed. (Although a so-called expert programmer would probably have given me the advice, "This function should be declared static" and I would probably have replied in my own sarcastic way: "Uh-huh. Well, it works as-is, after all". :)).

From reading the OSS code, I assumed it might just generate less overhead when compiling the project. However, CPU have advanced in performance so much that I've wondered many times why there is such an ongoing interest to declare functions static even though it might need some benchmark tool to measure the differences in execution speed.

答:
When applied to a function definition, the static keyword prevents the function name from being exported to the linker; code in other translation units (files) cannot call that function by name.

To abuse some terminology, you're making the function definition "private" to that source file.

For example, assume I have a file like

```<code>static int a_helper_function( /* some arguments here */ )
{
  ...
}

int public_function( /* some arguments here */ )
{
  ...
  if ( a_helper_function( /* arguments */ ))
    /* do something interesting */
  ...
}
</code>```

When I build my project, only functions defined within that same source file can call a_helper_function directly; it's not visible to code in other translation units.

This isn't a performance issue so much as a maintenance and design issue.  It reduces namespace collisions (you could have multiple versions of a_helper_function with different signatures in different files), and it allows you to encapsulate some operations within each file.

Now, all this does is prevent the function name from being exported to the linker; other translation units can still call this function, just not by name.  I could have another function in that same file that returns a pointer to a_helper_function:

```<code>int (*get_helper(/* args for get_helper */))(/* args for a_helper_function */)
{
  return a_helper_function;
}
</code>```

The get_helper function returns a pointer to a_helper_function, so a function in another translation unit could use that function pointer to call a_helper_function.

Body:
When applied to a function definition, the static keyword prevents the function name from being exported to the linker; code in other translation units (files) cannot call that function by name.

To abuse some terminology, you're making the function definition "private" to that source file.

For example, assume I have a file like

static int a_helper_function( /* some arguments here */ )
{
  ...
}

int public_function( /* some arguments here */ )
{
  ...
  if ( a_helper_function( /* arguments */ ))
    /* do something interesting */
  ...
}

When I build my project, only functions defined within that same source file can call a_helper_function directly; it's not visible to code in other translation units.

This isn't a performance issue so much as a maintenance and design issue.  It reduces namespace collisions (you could have multiple versions of a_helper_function with different signatures in different files), and it allows you to encapsulate some operations within each file.

Now, all this does is prevent the function name from being exported to the linker; other translation units can still call this function, just not by name.  I could have another function in that same file that returns a pointer to a_helper_function:

int (*get_helper(/* args for get_helper */))(/* args for a_helper_function */)
{
  return a_helper_function;
}

The get_helper function returns a pointer to a_helper_function, so a function in another translation unit could use that function pointer to call a_helper_function.


问:
How are OOP "objects" and "classes" organized in memory in terms of assembly language?
How are objects organized in memory?

For instance, I know that a function is a piece of code in memory, that expects parameters via the stack and/or the registers and handles it's own stack frame.

But objects are a much more complicated structure. How are they organized?
Does each object have "links" to methods and passes address to itself to that method?

It would be great to see a good explanation of this topic.

UPD. I made the question more exact, and I'm mainly interested in statically typing languages.

答:
This is answer in the sense of the proverb "if you give a man a fish you feed him for a day, while if you teach him to fish you feed him for life" as your question is very broad

1. research open information sources

Google for "assembly object oriented programming" lists pretty many different relevant resources.

e.g. Object Oriented Programming in Assembly, Ethan J. Eldridge, December 15, 2011 came as 3rd link and looks good

2. learn from existing hand-written code

You can see how it works by studying source codes written with some popular assembly languages with OOP explicitly declared e.g.

http://en.wikipedia.org/wiki/High_Level_Assembly

http://en.wikipedia.org/wiki/Fasm

http://en.wikipedia.org/wiki/Netwide_Assembler

3. learn from code patterns generated by compilers

You can see how it works by studying intermediate assembly language files produced by OOP compilers of your choice. Both C++ and FreePascal compilers can be configured so that you can see what the transcription of the high level OOP code into the assembly language code looks like

4. solve the puzzle with your common sense

Now it is quite too late as you already know the hints from other answers. But before the internet was so easy to search and before there were sites where you can get your answer without any effort within several hours for free from some volunteer who learned it the hard way, the only working method available for free to anyone was

Ask yourself: "how would I implement it?"

Very often after several days of the background-thinking process running in your mind and after throwing away several paper draft designs you would find that the solution you came up with is very similar to the solution other programmers came up with and already implemented

Now is my answer opinion based, does not directly answer OP's question and senior high-rep users can freely downvote me


答:
Well,
the question is what you define as embedded...

Is a Raspberry Pi still an embedded system?
If so, then there is competition...
You can install Node.JS on it and run JavaScript on it, is it performant? A little bit?
Do you care about every circle? (For 10 users (not really)(

So let's say, we only have 33Mhz
Do you care about the circles? Yes
Likely you could write an Rust - or an Go -Code.
But it would give you some cycles tradeoff.. (Security Checks, garbage collection (etc))

Should we care about the GHz or MHz Cycles all the time? Yes and No :)

Title: Why does C have no competitors in low level stuff?

Body:
As far as I know, C is by far the most widely used language for low level stuff such as systems programming and embedded. Sometimes assembly is used, but that's when you really need to be close to the hardware.

My question is why doesn't C have any competitors in low level development? It might be my ignorance, but I'm pretty sure that C is the obvious (or possibly only) choice for low level programming.

This is as opposed to high level development, where there are many competing programming languages to choose from.

How can you explain this?


问:
What's the easiest way to comply with open source licenses?
I'm really confused by all the open source licensing details like "I wrote a web application, which should run on a computer not owned by me. My software uses the library/language xxx. Is this considered a software redistribution of xxx?".

Looking at the first four pieces of used software reveals four different licenses (MIT, BSD, Apache, Apache/Eclipse dual). It looks like all of them require about the same, i.e., list them and link to their license.

So I thought I could simplify my life by simply voluntarily listing all the software used. The list is not that long and it'd call it fair. But there are obstacles like copyrighted names, trademarks and such stuff. I've tried to google for an example, but found nothing but the EPSON list (which is for a piece of hardware).

Does anyone know an example of software list for a web application? I'm especially curious what's the best solution for Java (run on a computer not owned by me).

答:
The only real "easy" ways to comply with "all" open source licenses is to never distribute your code, or make it accessible by the public.  Absent that, there is no technique that will allow you to ensure compliance with all of the various OSS requirements without understanding them.

Hoverer, you may be overestimating the amount of work it would be to read, understand, and comply with the few licenses that actually affect your project. Just because your software uses another program does not mean that you are deriving from that program, and thus would need to follow its rules.  Your fancy web-app could be written in php, on a Linux 0S, and be designed with an assumption of MySQL and Mozilla Firefox, and yet you wouldn't necessarily be covered by the copyleft rules of any of those projects.  (unless you shipped a pre-made server or something.)


答:
If I understand your tool correctly, it maps Objects directly to a conceptual SQL framework rather than mapping Objects that implement some mapping to SQL functionality (ORM), almost like a ORM-- abstraction for greater geeky control so that you can use more SQL features ORM's usually wouldn't give you?

Not sure what problem you're trying to solve. Since your tool requires in-depth knowledge of SQL, wouldn't people just use, well, SQL? Is it the glue-code you're trying to get rid of? Better validation of the SQL queries through API modelling instead of simple strings?

I have to admit that your JOOQ examples look like LISP versions of the SQL. Not that that is a bad thing :) and I do see some of the advanced stuff being interesting, but the advantages you list slowly disappear as you become increasingly advanced (more config, less abstract, more ingrained in the inner sanctum of the specific SQL engine, etc.)

One suggestion I'd like to see that I do miss in most ORMs is a framework that can deal with Objects in a non-relational way, translating Object interactions into whatever the backend might be (SQL, NoSQL, Topic Maps, RDF, etc.) which requires caching of the Model used rather than specifics of SQL interactions, dialects, and relational thinking.

IMHO, of course. :)

Title: What would you think about a new Java persistence tool, that's not really an ORM?

Body:
Persistence in Java

Over the past years, I have gathered experience in the field of persistence abstraction in Java, using concepts such as EJB 2.0, Hibernate, JPA and home-grown ones. They seemed to me to have a steep learning curve and lots of complexity. In addition, as a big fan of SQL, I also thought that many abstraction models provide too much abstraction over SQL, creating concepts such as "criteria", "predicates", "restrictions" that are very good concepts, but not SQL.

The general idea of persistence abstraction in Java seems to be based on the Object-relational model, where RDBMS are somehow matched with the OO world. The ORM-debate has always been an emotional one, as there does not seem to exist a single solution that suits everyone - if such a solution can even exist.

jOOQ

My personal preference of how to avoid ORM-related problems is to stick to the relational world. Now the choice of data model paradigm should not be the topic of discussion as it is a personal preference, or a matter of what data model best suits a concrete problem. The discussion I would like to start is around my very own persistence tool called jOOQ. I designed jOOQ to provide most of the advantages modern persistence tools have:

A Domain Specific Language based on SQL

Source code generation mapping the underlying database schema to Java

Support for many RDBMS

Adding some features that few modern persistence tools have (correct me if I'm wrong):

Support for complex SQL - unions, nested selects, self-joins, aliasing, case clauses, arithmetic expressions

Support for non-standard SQL - stored procedures, UDT's, ENUMS, native functions, analytic functions

Please consider the documentation page for more details: http://www.jooq.org/learn.php. You will see that a very similar approach is implemented in Linq for C#, although Linq is not exclusively designed for SQL.

The Question

Now, having said that I'm a big fan of SQL, I wonder whether other developers will share my enthusiasm for jOOQ (or Linq). Is this kind of approach to persistence abstraction a viable one? What are the advantages / disadvantages you might see? How could I improve jOOQ, and what's missing in your opinion? Where did I go wrong, conceptually or practically?

Critical but constructive answers appreciated

I understand that the debate is an emotional one. There are many great tools out there that do similar things already. What I am interested in is critical but constructive feedback, based on your own experience or articles you may have read.


问:
Starting all over again?
Have you ever been developing something and just came to a point where you think that this is rubbish, the design is bad and although I will lose time it will be better to just start all over again?

What should you consider before making this step? I know it can be drastic in some cases, is it best to just totally ignore what you did before, or take some of the best bits from it? Some real life examples would be great.

答:
Throwing everything away is usually a bad idea. Rewriting parts of the system may be a good idea. Refactoring is often a good idea.

The way I see it, the question is not whether the code is good or not. Code you wrote more than a week ago is always a terrible mess because you have since learned something new which you wish you had used.

The question is whether the tech debt you've accumulated is making it hard to get work done. If your system is hard to run or changes are harder than they should be,  that means you probably need to fix something. But unless things are difficult across the board, don't rewrite everything. Just rewrite the parts that are causing you pain.

Title: Starting all over again?


问:
Best patterns for variable-scope disposables
I have Client which uses a disposable Connection for talking to a remote service. A Connection is somewhat expensive to set up and needs to be Dispose()d properly.

I want to allow multiple methods in Client to share a connection, like this:

```<code>using (client._connection = client.Connect())
{
  client.SyncTime();
  client.UpdateUsers();
  client.SomeOtherOperation();
}
</code>```

But I don't want to insist on Client's consumers managing connections. They should be allowed to call individual single Client methods without being aware or concerned with Connections.

Here is the pattern I'm using at the moment. It makes SRP cry. Any suggestions on how I can do this better, or should I be doing this at all?

```<code>public class Client
{
  Connection _connection;

  public void SyncTime()
  {
    bool wasConnected = _connection == null;
    try
    {
      if (!wasConnected)
        _connection = Connect();

      _connection.ActuallyDoSomeWork();
      ...

    }
    finally
    {
      if (!wasConnected)
        _connection.Dispose()
    }
  }
}
</code>```

答:
The first thing you need to do is explicitly separate out the connection lifecycles in your two scenarios. Trying to juggle the two will only lead to confusion. To that end, I would completely remove the _connection member variable.

Here's what I propose:

Use a "context object" to manage your state. Your Connect method already returns a Connection, so that can serve as your context object for now. Make all your functional API methods SyncTime, UpdateUsers, etc. always take in this context object and act accordingly.

So your implementation becomes:

```<code>public class Client
{
    public void SyncTime(Connection connection)
    {
        if (connection == ONE_TIME_CONNECTION)
        {
            using (Connection localConnection = client.Connect())
            {
                SyncTimeInternal(localConnection);
            }
        }
        else
        {
            SyncTimeInternal(connection);
        }
    }

    private void SyncTimeInternal(Connection connection)
    {
        DoSomeWork();
        connection.DoSomeMoreWork();
        EvenMoreWork();
    }

    public static final Connection ONE_TIME_CONNECTION = null;
}
</code>```

Then your consumer code becomes:

```<code>using (Connection connection = client.Connect())
{
  client.SyncTime(connection);
  client.UpdateUsers(connection);
  client.SomeOtherOperation(connection);
}
</code>```

or just:

```<code>client.SyncTime(Client.ONE_TIME_CONNECTION);
</code>```

Notice the use of the constant to abstract away a null value. This makes it easier to change the internals in the future.

Of course, you can extend this pattern to create an explicit ClientContext object containing the connection as well as other state information.

Body:
The first thing you need to do is explicitly separate out the connection lifecycles in your two scenarios. Trying to juggle the two will only lead to confusion. To that end, I would completely remove the _connection member variable.

Here's what I propose:

Use a "context object" to manage your state. Your Connect method already returns a Connection, so that can serve as your context object for now. Make all your functional API methods SyncTime, UpdateUsers, etc. always take in this context object and act accordingly.

So your implementation becomes:

public class Client
{
    public void SyncTime(Connection connection)
    {
        if (connection == ONE_TIME_CONNECTION)
        {
            using (Connection localConnection = client.Connect())
            {
                SyncTimeInternal(localConnection);
            }
        }
        else
        {
            SyncTimeInternal(connection);
        }
    }

    private void SyncTimeInternal(Connection connection)
    {
        DoSomeWork();
        connection.DoSomeMoreWork();
        EvenMoreWork();
    }

    public static final Connection ONE_TIME_CONNECTION = null;
}

Then your consumer code becomes:

using (Connection connection = client.Connect())
{
  client.SyncTime(connection);
  client.UpdateUsers(connection);
  client.SomeOtherOperation(connection);
}

or just:

client.SyncTime(Client.ONE_TIME_CONNECTION);

Notice the use of the constant to abstract away a null value. This makes it easier to change the internals in the future.

Of course, you can extend this pattern to create an explicit ClientContext object containing the connection as well as other state information.


问:
Should we avoid using design patterns in constantly changing projects?
A friend of mine is working for a small company on a project every developer would hate: he's pressured to release as quickly as possible, he's the only one who seem to care about technical debt, the customer has no technical background, etc.

He told me a story which made me think about the appropriateness of design patterns in projects like this one. Here's the story.

We had to display products at different places on the website. For example, content managers could view the products, but also the end users or the partners through the API.

Sometimes, information was missing from the products: for example, a bunch of them didn't have any price when the product was just created, but the price wasn't specified yet. Some didn't have a description (the description being a complex object with modification histories, localized content, etc.). Some were lacking shipment information.

Inspired by my recent readings about design patterns, I thought this was an excellent opportunity to use the magical Null Object pattern. So I did it, and everything was smooth and clean. One just had to call product.Price.ToString("c") to display the price, or product.Description.Current to show the description; no conditional stuff required. Until, one day, the stakeholder asked to display it differently in the API, by having a null in JSON. And also differently for content managers by showing "Price unspecified [Change]". And I had to murder my beloved Null Object pattern, because there was no need for it any longer.

In the same way, I had to remove a few abstract factories and a few builders, I ended up replacing my beautiful Facade pattern by direct and ugly calls, because the underlying interfaces changed twice per day for three months, and even the Singleton left me when the requirements told that the concerned object had to be different depending on the context.

More than three weeks of work consisted of adding design patterns, then tearing them apart one month later, and my code finally became spaghetti enough to be impossible to maintain by anyone, including myself. Wouldn't it be better to never use those patterns in the first place?

Indeed, I had to work myself on those types of projects where the requirements are changing constantly, and are dictated by persons who don't really have in mind the cohesion or the coherence of the product. In this context, it doesn't matter how agile you are, you'll come with an elegant solution to a problem, and when you finally implement it, you learn that the requirements changed so drastically, that your elegant solution doesn't fit any longer.

What would be the solution in this case?

Not using any design patterns, stop thinking, and write code directly?

It would be interesting to do an experience where a team is writing code directly, while another one is thinking twice before typing, taking the risk of having to throw away the original design a few days later: who knows, maybe both teams would have the same technical debt. In the absence of such data, I would only assert that it doesn't feel right to type code without prior thinking when working on a 20 man-month project.

Keep the design pattern which doesn't make sense any longer, and try to add more patterns for the newly created situation?

This doesn't seem right neither. Patterns are used to simplify the understanding of the code; put too much patterns, and the code will become a mess.

Start thinking of a new design which encompasses the new requirements, then slowly refactor the old design into the new one?

As a theoretician and the one who favors Agile, I'm totally into it. In practice, when you know that you'll have to get back to the whiteboard every week and redo the large part of the previous design and that the customer just doesn't have enough funds to pay you for that, nor enough time to wait, this probably won't work.

So, any suggestions?

答:
Let's pause for a moment and look at the fundamental issue here - Architecting a system where the architecture model is too coupled to low-level features in the system, causing the architecture to break frequently in the development process.

I think we have to remember that the use of architecture and design patterns related to it have to be laid on a appropriate level, and that the analysis of what is the right level is not trivial. On one hand, you might easily keep the architecture your system on a too high level with only very basic constraints like "MVC" or the like, which can lead to missed opportunities as in clear guidelines and code leverage, and where spaghetti code can easily flourish in all that free space.

On the other hand, you might just as well over-architect your system, as in setting the constraints on a to detailed level, where you assume you can rely on constraints that in reality is more volatile then you expect, constantly breaking your constraints and forcing you to constantly remodel and rebuild, until you start to despair.

Changes in requirements for a system will always be there, to a lesser or greater extent. And the potential benefits of using architecture and design patterns will always be there, so there is not really a question of using using design patterns or not, but on what level you should use them.

This requires you not only to understand the current requirements of the proposed system, but also to identity what aspects of it can be seen as stable core properties of the system, and what properties might be likely to change during the course of the development.

If you find that you constantly have to fight with unorganized spaghetti code, you are probably not doing enough architecture, or on a to high level. If you find that your architecture frequently breaks, you are probably doing too detailed architecture.

The use of architecture and design patterns is not something you can just "coat" a system in, like if you would paint a desk. They are techniques that should be applied thoughtfully, on a level where the constraints you need to rely on have a high possibility of being stable, and where these techniques actually are worth the trouble of modelling the architecture and implementing the actual constraints/architecture/patterns as code.

Relevant to the issue of a too detailed architecture, you can as well put just to much effort in architecture where it is not giving much value. See risk driven architecture for reference, I like this book - Just enough Software Architecture, maybe you will too.

Edit

Clarified my answer since I realized I often expressed myself as "too much architecture", where I really meant "too detailed architecture", which is not exactly the same. Too detailed architecture can probably often be seen as "too much" architecture, but even if you keep the architecture on a good level and create the most beautiful system mankind has ever seen, this might still be too much effort on architecture if the priorities are on features and time to market.


问:
Javascript function should call python logic in django web development without additional triiger
I have been trying to solve this problem for sometime now. This is regarding django web development.

I have an HTML page which has a Javascript function to upload an image file from the users local computer. After that file has been uploaded on to the HTML template, I want to use the uploaded image file for further processing. I am calling my python logic from views.py  for processing the image before rendering the processed information on to another HTML page.

My problem is that I want my upload function() to call my python logic.(There should be no additional trigger to call the python logic. i.e somefunction() within the upload function() which can directly call my python logic without having to use any button click or anything else.)

Can I somehow call the Python logic from javascript function (the one which uploads the image)? or should I save the uploaded file to my local computer and use its path to process the image information?

I googled and found that both of these are challenging tasks. There is no direct method to do it since one is client side scripting while the other is server side. Also, javascript does not have input output facilities (for writing/saving the uploaded image to local disk that too without a trigger).

What should be done in such a case? Should I write my upload function also in python then?(I don't want that to happen). Please help. Thanks in advance :)

答:
If you want to call server-side logic from the client, you will have to make an HTTP (or other) request -- this can not be avoided. From what I understand as I read your question, an AJAX request may be what you're looking for.

See: https://www.w3schools.com/xml/ajax_intro.asp

If you're using jQuery: http://api.jquery.com/jquery.ajax/


问:
Unit testing statically loaded data
Scenario: I have a configuration file containing some structured data that is loaded in at runtime and is not modified by the application, but is referenced in many places.  There are functions that retrieve specific data from the configuration file (after it's been loaded into memory).

I'd like to write unit tests that ensure that data has not been changed inadvertently by a developer, is this good practice or overkill?

E.g. Assert(GetDataForKey("SomeKey") == "MyValue")

答:
No overkill.

Configuration file values are intended to be edited by administrators, but ...

Configuration files that live in source control probably are part of a deployed default configuration. As such, they should only be changed with changing the default configuration in mind, however ...

Developers need to be able to edit them as well, to help isolate bugs or implement new features.

What you want to prevent are unintentional changes to the configuration files.

I would therefore take the same approach to these configuration files, as I would to literals that are part of an application's API.

I advocate having unit tests on all literals used in an API. All these literals are of course coded as constants, so typo's are not necessarily a concern. The tests are there to catch unintended edits of the literal values of these constants. The tests - by design - do not use these constants. The thinking being that if you edit only the literal value of the constant, or only the literal value in the test it probably was unintended and you need the notification of a test failing. While if you edited both literal values, you probably intended the change and the test can pass.

Title: Unit testing statically loaded data


问:
Asynchronous Web Language
I'm searching for a suitable way to make web requests to databases and display results in real-time. The data will be used in an interface for staff, so there cannot be any blocking or lag as time is a key factor.

So far, I've been using PHP for the backend of the system. However now that I've come to the interface, I'm slightly stuck.

I've used java (android) asynchronously before, and ideally am after a similar method of processing calls. From what I've read there is no current way of using php truly asynchronously.

What is a good web language to use for this purpose? or what are my available options?

答:
As commented, you probably don't mean strong real-time computing!

Assuming you mean HTML5 you could use Ajax techniques (then Jquery could help) to periodically (e.g. every 10 seconds) query some web server (that web server could itself query some database) from inside the browser.

HTTP itself is synchronous: each HTTP request gets one answer.

There is also webservices and websockets

Several languages and frameworks support all this quite well: not only PHP but also Opa or Ocaml with Ocsigen, or HOP. You could also code in C, C++ or in Java with some good HTTP server library like libonion (of course some Javascript code is needed on the browser side)

Your question is too broad to get a more precise answer. It seems that you need to learn more about web technologies. w3schools is not perfect, but has several tutorials and you could find many others (e.g. some HTML-5 tutorial...)

Title: Asynchronous Web Language


答:
Configuration files in source control are pretty much equivalent to constants in a programming language.

And the distinctive thing about constants, at least in most programming languages, is that if you treat them as the unit under test, they literally cannot have any internal bugs.

For example:

```<code>final static double PI = 4.2;
</code>```

has no locally detectable bugs. It just has a lot of 'potential integration issues'...

You can write a test for it as:

```<code>assertThat(PI, is(closeTo(4.2, epsilon));
</code>```

and that not only won't find the problem, but will fail when somone fixes it.

If you work on a code base in this style, then every change you make will fail a test. Which is more or less equivalent to not having any tests; it's practically like having two copies of the source code in git and requiring them to be the same to 'prevent unintentional modifications'.

Either you have to read and review the code, or test at a larger level. For example noting that circles using PI are wonky.

In your case, this would mean testing that:

the default behavior is correct

changing the config value changes the behavior

Title: Unit testing statically loaded data

Body:
Scenario: I have a configuration file containing some structured data that is loaded in at runtime and is not modified by the application, but is referenced in many places.  There are functions that retrieve specific data from the configuration file (after it's been loaded into memory).

I'd like to write unit tests that ensure that data has not been changed inadvertently by a developer, is this good practice or overkill?

E.g. Assert(GetDataForKey("SomeKey") == "MyValue")

Body:
Configuration files in source control are pretty much equivalent to constants in a programming language.

And the distinctive thing about constants, at least in most programming languages, is that if you treat them as the unit under test, they literally cannot have any internal bugs.

For example:

final static double PI = 4.2;

has no locally detectable bugs. It just has a lot of 'potential integration issues'...

You can write a test for it as:

assertThat(PI, is(closeTo(4.2, epsilon));

and that not only won't find the problem, but will fail when somone fixes it.

If you work on a code base in this style, then every change you make will fail a test. Which is more or less equivalent to not having any tests; it's practically like having two copies of the source code in git and requiring them to be the same to 'prevent unintentional modifications'.

Either you have to read and review the code, or test at a larger level. For example noting that circles using PI are wonky.

In your case, this would mean testing that:

the default behavior is correct

changing the config value changes the behavior


答:
One experience I had was when I was managing a Site Performance team at my previous employer.  Every night, for a period of an hour to two hours, the website my team was monitoring would dip below acceptable performance thresholds due to a bot scraping information from the site rapidly.  The measures the team took to address this consisted of logging into a manual admin system and blocking the IP addresses which were causing the troubles.  Needless to say, this cost one member of the team hours of sleep nearly every night.  I noticed what was occurring and took the on-call BlackBerry myself for several days to see how bad it was and give my team some rest.  </p>

<p>After a few days,  I simply went to the business owner of the team and let them know that if we did not implement an automated blocking system such that bots would have a much more difficult time affecting the performance of the site, we would likely lose some if not all of the team members due to fatigue and burnout.  They agreed, and we implemented a system which allowed us to get sleep at night.  The business owner understood that the cost of a few days or a week of development was minimal compared to the cost of hiring/training new engineers. </p>

Title: What payoffs have you seen from taking care of technical debt?

Body:
This article on technical debt has some good points, including:

Working on the "technical matters" works best when it is driven by stories. The code base is probably in need of work everywhere, but the payoff will be received only where the code is going to be worked on for user-facing reasons. If no stories are going to pass through some crufty area, working on it is largely wasted.

Therefore, I prefer the approach of taking stories as usual (but probably fewer of them), and following the "boy scout rule" of leaving the campground better than you found it. In other words, wherever the stories lead us, let's write more tests, let's refactor more aggressively.

This approach has at least these advantages:

maintains "best sensible" flow of stories;

provides help from all team talent;

provides for whole team to learn how to keep code clean;

focuses improvement exactly where it is needed;

does not waste improvement that "may" be needed;

I've seen code quality have a very big effect on long-term productivity, so I am a believer that technical debt should be taken care of.  I think the post above makes sense, but I'm not so sure about the last two points.  I'm interested in finding out real experiences of benefits from cleaning technical debt, even if it was not related to user stories.

What positive benefits have you seen from cleaning up your code base and ridding yourself of technical debt? What methods did you use to get the work done?

Body:
One experience I had was when I was managing a Site Performance team at my previous employer.  Every night, for a period of an hour to two hours, the website my team was monitoring would dip below acceptable performance thresholds due to a bot scraping information from the site rapidly.  The measures the team took to address this consisted of logging into a manual admin system and blocking the IP addresses which were causing the troubles.  Needless to say, this cost one member of the team hours of sleep nearly every night.  I noticed what was occurring and took the on-call BlackBerry myself for several days to see how bad it was and give my team some rest.

After a few days,  I simply went to the business owner of the team and let them know that if we did not implement an automated blocking system such that bots would have a much more difficult time affecting the performance of the site, we would likely lose some if not all of the team members due to fatigue and burnout.  They agreed, and we implemented a system which allowed us to get sleep at night.  The business owner understood that the cost of a few days or a week of development was minimal compared to the cost of hiring/training new engineers.


问:
Test Driven Development for Complex Games
I'm coding a game in my spare time, but I am mostly still a beginner when it comes to programming.  I'm sorry if this question is off topic or if it ends up not being helpful to anyone else, but hopefully it will be.

I've spent a lot of time reading books about the design of code, as well as different methodologies and approaches to coding.  In the course of this research I keep running into the concept of Test Driven Development.  The people who espouse this idea usually seem very passionate about it.  I do believe that it can help the speed and efficiency of writing software.  Time is a very precious resource so I would rather learn to do things the best way rather than muddle through without trying to expand my knowledge of the programming craft.

Anyway, possibly because I am a beginner, I cannot imagine how to apply test driven development to games.  I've found a couple of articles on the subject but they were not very helpful.  Most of the examples of unit tests that I have seen are very simple boilerplate examples, or examples from software that is not at all like a game.

In my own coding, I try to approach it with a similar mindset to test driven development, although I'm sure it does not actually qualify as TDD.  I write the minimum amount of code to try to implement whatever feature I am adding to the game, and then I immediately test the game to see if it works.  If things don't happen as I intended, I immediately make changes to get it closer to what I want.  If it is not working or broken, and if I cannot find the bugs by reading the code, I step through the methods in the debugger until I find the unexpected behavior, and then I remove it.  What I am trying to say is that I am constantly testing the game, pretty much after each and every incremental change.  Testing drives my development.  The "unit test" is in my head, because for example I know what the unit in my game is supposed to be doing, so I test to make sure that it is doing it, and if not, I try to fix it right away.

On to my actual question. How can one write unit tests for a complex game?  By complex, I mean with many emergent aspects of gameplay, such that the meat of the gameplay emerges from the interaction between the many different elements inside the game combined with the player's choices.  For example, a roguelike rpg with a procedural world.  What kind of unit tests would one write for a game like that?  How could one apply test driven development to such a game?

答: Unit tests don't test gameplay. There's no programmatic criteria to see if a game is fun, or a level is the right difficulty. Unit tests will test that your roguelike mapgen actually produces a level with a stairs up and a stairs down. It will test that your encumberance rules are setup that your character actually moves slower when weighted. It will make sure your character can't wear 50 hats. It will make sure that the mechanics are all implemented correctly in relative isolation.


问:
I have a legacy project that I'm working on, how should I improve its structure?
I have a slightly old PHP project I'm working on for a client (I think it was started around 5 years ago), it makes extensive use of the outmoded mysql_query function, which is concerning not only because it's now deprecated but because it could also open security holes.

The project doesn't seem to have much of a structure either, I think the original developer had some kind of method when working on it, but there's no documentation and I'm not able to get in contact with him regarding said project.

As I've been going through I've been switching the database queries to use PDO, and trying to clean things up a little, but it's quite a big project (a few hundred php files) and I don't want to spend too much time restructuring things at it detracts from the time I've got allotted to this each month.

What should I do? Would a rewrite be a good idea? Or should I simply try and re-mold the current project into something a little nicer?

答:
Unless you are introducing an existing framework into the code and 90% of the original code will be taken over by the framework, doing a big rewrite will almost certainly cost more time than incrementally refactoring the code.

If the original code is essentially good (well documented & structured), but just not according to today's best practices, then you won't gain much by restructuring it and you might as well keep the original structure also for the new features (consistency across a codebase is far more important for maintainability than following the latest best practices).

If the original code is not really all that good, but you don't have the time/resources to fix it all at once, then you could tackle each month a small portion that irritates you the most or that hinders you in implementing some new features.


问:
Am I doing TDD wrong when multiple tests can fail for the same reason?
Assume a method with the following declaration

```<code>public IList<Location> GetLocations() { ... }
</code>```

I write (at least) the following tests

Check to see if the method returns an empty collection if no locations are found.

Check to see if the method returns the correct number of locations.

Check to see if the data in the locations the method return is correct.

However, all the tests above will fail if the method returns null. I feel like a single error should only result in one unit test failure, but at the same time I do not see how to avoid it  in a scenario like this. Is this just the way it works; sometimes multiple tests will fail for the same reason?

答:
Your assumption is wrong,

I feel like a single error should only result in one unit test
  failure

every unit-test test only one aspect of the method so:

Check to see if the method returns an empty collection if no locations are found.

Check to see if the method returns the correct number of locations.

Check to see if the data in the locations the method return is correct.

in every above test if the method return null, test fail is the auspicable response

sometimes multiple tests will fail for the same reason?

The only acceptable answer should be Yes


问:
Is recursion an instance of being "too clever" when programming?
I've read several books and learned through experience that optimizing code to the point where it is inscrutable, or coming up with an extremely fast but extremely complex solution to a problem is not desirable when working in teams, or even when you're working by yourself and have to understand your clever solution some time later.

My question is, should recursion be treated in the same manner?  Does the average programmer understand recursion easily and thus one should use it with impunity, or does the average programmer not understand recursion very well and one should stay away from it for the sake of overall team productivity?

I know there are simple answers of, "Any programmer who doesn't understand recursion isn't worth a grain of salt, so don't worry about them" but I was wondering if you all had some real world experience you would like to share that would illuminate the issue more than the opinion I just mentioned.

答:
Some problems are naturally recursive. Coming up with an iterative solution in these cases can actually be more clunky and complex than recursive ones. A good example is any algorithm which needs to traverse a hierarchical tree structure, which is a not-uncommon task in programming.

TL;DR version: No.


问:
Lists & Collections in MVVM - which approach to take?
I'm currently working on a Silverlight app using Caliburn.Micro.

At present, we have Views (eg: PeopleView) and View Models (eg: PeopleViewModel) that equate to 'pages' of the application.

PeopleView might contain a ListBox ("People") which is bound to an ObservableCollection of Person objects, and has an ItemTemplate assigned to denote how each Person object should be displayed.

However, one of my colleagues has begun to implement a list in another way, where each Person is a View Model (ie: PersonViewModel) and has an associated PersonView to determine how that PersonViewModel should be displayed in the ListBox.

The latter seems more MVVM (or at least has more mention of V and VM!) but I'm not sure whether there's a particularly large advantage to doing one over the other.

Are both of these ways valid? Is either better than the other?

答:
If person is in your model, then it seems to violate the separation created by only exposing view model to the view.

My general rule is the ability to create the viewmodel and view without a model.  If this can not be accomplished I make changes.

Exposing the Model to the view is perfectly valid, but it is more of a MVC pattern.


问:
Solution for multiple versions of one Software
I'm sorry if the title is a little hard to get.

I've never built an entire big software my self, just some small apps in my free time, i was more familiar with the do-what-my-boss-told-me things. And our approach is a little amateur, obsolete also (Foxpro 8.0 and MS SQL 2000).

Now i've started to work at another company and been assigned to build a software in C#.Net, but the problem is i'm not sure with the program's architecture

My problem is, we're building a software. But we have variety of clients, and for example, we have a CalculateCostOfProduct funtion, and it might be different for each client.

Says for party A, the function is :

```<code>function CalculateCostOfProduct()
return 5;
</code>```

for party B :

```<code>function CalculateCostOfProduct()
return 10;
</code>```

...

And there should be extra modules for specific needs also ! So there will be customized versions from the original standard. How should i manage this ?

But we can't build different exe for different client!

So please give me some ideas, or solutions that might solve this problem.

答:
For solving these types of problems is why polymorphism and dependency injection exist.

Following your example, you can have a CostCalculator interface or abstract class and two implementations: ClientACostCalculator and ClientBCostCalculator. With this half of the problem is solved, now we need to use dependency injection to solve the other half.

Suppose you use these classes from a process in your system, call the process "MyCalculationProcess", then you need to inject the correct CostCalculatorn depending on your client. You can use a dependency injection framework (there are a lot for .net) and inject the clientA o clientB implementation depending in some configuration or environment variable. Or you can implement this very easily yourself, for example:

```<code>class MyCalculationProcessFactory {

   public MyCalculationProcess createProcess(Config config) {

        if (config.isClient("A"))
            return new MyCalculationProcess(new ClientACostCalculator());

        if (config.isClient("B"))
            return new MyCalculationProcess(new ClientBCostCalculator());

   }

}
</code>```

Its not the best way to implement this and its more java than c# but i hope that you can get the idea behind.

Also, if you have not only this CostCalculator, you have more things like that depending on a client better than the previous "simple factory" you can use a AbstractFactory pattern.

Body:
For solving these types of problems is why polymorphism and dependency injection exist.

Following your example, you can have a CostCalculator interface or abstract class and two implementations: ClientACostCalculator and ClientBCostCalculator. With this half of the problem is solved, now we need to use dependency injection to solve the other half.

Suppose you use these classes from a process in your system, call the process "MyCalculationProcess", then you need to inject the correct CostCalculatorn depending on your client. You can use a dependency injection framework (there are a lot for .net) and inject the clientA o clientB implementation depending in some configuration or environment variable. Or you can implement this very easily yourself, for example:

class MyCalculationProcessFactory {

   public MyCalculationProcess createProcess(Config config) {

        if (config.isClient("A"))
            return new MyCalculationProcess(new ClientACostCalculator());

        if (config.isClient("B"))
            return new MyCalculationProcess(new ClientBCostCalculator());

   }

}

Its not the best way to implement this and its more java than c# but i hope that you can get the idea behind.

Also, if you have not only this CostCalculator, you have more things like that depending on a client better than the previous "simple factory" you can use a AbstractFactory pattern.


问:
Why don't Python and Ruby make a distinction between declaring and assigning a value to variables?
Two of the most popular dynamically typed scripting languages, Python and Ruby, do not make a distinction in syntax between the declaration of a variable and assignation of a value to it.

That is in both languages, declaring a variable n and assigning a value to it would look like so:

```<code>n = 10
</code>```

And assigning a new value to the variable later on would look just the same.

This creates two major problems:

A typo in a variable's name when changing it's value would create a new variable and cause bugs.

It makes the intentions of the code less clear. Hard to know where a variable is first declared and used, might make the code more confusing.

What I don't understand is why these languages don't have a var keyword to use on declaration, to make a distinction between a declaration and an assignment. This doesn't make the language any less dynamically typed, and I see no drawbacks.

What is the advantage of not having to explicitly define a variable?

答:
As a user rather (than designer) of Python there are three reasons I'm happy with this decisions:

Chiefly, it reads better. Of course I have to consciously decide to introduce a new variable when writing, but code is read far more often than it is written. A lot of code is simple in the sense that control flow and nesting has no influence on the meaning and existence of variables. When I read

```<code>it = Snark()
message = "A letter, not signed"
if random.random() > 0.5:
    hunt(it)
    message += " (by the Knave)"
return [it, message]
</code>```

then I usually don't really care which (if any) mention of a name first introduces it, I just care that it's there and what happens to it.

Note that a significant body of pseudo code uses the same convention (no declaration, implicit introduction via assignment), and Python is often described as executable pseudo code, only half-jokingly. Four extra characters for every local variable does, to my spoiled eyes, feel like significant clutter in the context of Python, especially when it doesn't feel like it adds any value (see below); this would be lessened by a := operator as in Go.

Second, I have yet to encounter a typo bug (due to this specific feature) that didn't also show itself in another clear manner. Maybe I'll change my mind in a few more years when I've encountered some bugs of this kind, but so far it's way, way down on my list of things that cause bugs. There's a fair number of questions about UnboundLocalError and it's a bit tricky to explain to beginners, but the frequency and popularity of those questions, compared to other gotchas (mutable default parameters, reference semantics, class vs. instance variables) indicates it's a rare problem.

Finally, the intent thing... sorry but I can't really understand this one. When reading and writing Python, it's always perfectly clear: What you assign to is intended as a local, unless loudly and explicitly declared otherwise. No question about it. Moreover, since (at least in Python) a variable is either local for the entire function or not at all, you can't have tricky code that uses a local variable in one branch and a global one in another. You see a name being assigned to? You instantly know it was always local from the beginning. Well, unless the code is broken in a very special way (and will throw the dreaded UnboundLocalError at run time, when entering those cases).

Body:
As a user rather (than designer) of Python there are three reasons I'm happy with this decisions:

Chiefly, it reads better. Of course I have to consciously decide to introduce a new variable when writing, but code is read far more often than it is written. A lot of code is simple in the sense that control flow and nesting has no influence on the meaning and existence of variables. When I read

it = Snark()
message = "A letter, not signed"
if random.random() > 0.5:
    hunt(it)
    message += " (by the Knave)"
return [it, message]

then I usually don't really care which (if any) mention of a name first introduces it, I just care that it's there and what happens to it.

Note that a significant body of pseudo code uses the same convention (no declaration, implicit introduction via assignment), and Python is often described as executable pseudo code, only half-jokingly. Four extra characters for every local variable does, to my spoiled eyes, feel like significant clutter in the context of Python, especially when it doesn't feel like it adds any value (see below); this would be lessened by a := operator as in Go.

Second, I have yet to encounter a typo bug (due to this specific feature) that didn't also show itself in another clear manner. Maybe I'll change my mind in a few more years when I've encountered some bugs of this kind, but so far it's way, way down on my list of things that cause bugs. There's a fair number of questions about UnboundLocalError and it's a bit tricky to explain to beginners, but the frequency and popularity of those questions, compared to other gotchas (mutable default parameters, reference semantics, class vs. instance variables) indicates it's a rare problem.

Finally, the intent thing... sorry but I can't really understand this one. When reading and writing Python, it's always perfectly clear: What you assign to is intended as a local, unless loudly and explicitly declared otherwise. No question about it. Moreover, since (at least in Python) a variable is either local for the entire function or not at all, you can't have tricky code that uses a local variable in one branch and a global one in another. You see a name being assigned to? You instantly know it was always local from the beginning. Well, unless the code is broken in a very special way (and will throw the dreaded UnboundLocalError at run time, when entering those cases).


答:
I would have to recommend the advice of Martin Fowler on this one.

When you find you have to add a feature to a program, and the program's code is not structured in a convenient way to add the feature, first refactor the program to make it easy to add the feature, then add the feature.

In other words, refactor as needed when you need to make a change. This keeps you from getting entangled in a massive refactoring for the sake of refactoring, while providing a justification to refactor when you need to refactor.

Title: I have a legacy project that I'm working on, how should I improve its structure?

Body:
I have a slightly old PHP project I'm working on for a client (I think it was started around 5 years ago), it makes extensive use of the outmoded mysql_query function, which is concerning not only because it's now deprecated but because it could also open security holes.

The project doesn't seem to have much of a structure either, I think the original developer had some kind of method when working on it, but there's no documentation and I'm not able to get in contact with him regarding said project.

As I've been going through I've been switching the database queries to use PDO, and trying to clean things up a little, but it's quite a big project (a few hundred php files) and I don't want to spend too much time restructuring things at it detracts from the time I've got allotted to this each month.

What should I do? Would a rewrite be a good idea? Or should I simply try and re-mold the current project into something a little nicer?


答:
I would say use recursion where it's appropriate, but always seek out ways to avoid explicit recursion.

For example, if you find the need to manually traverse a tree structure, then yes, you should be using recursion. If someone's dumb enough to not understand a recursive tree traversal, they're going to make neither head nor tail of the iterative version.

But a better option is to use an iterator that abstracts the recursion away to the point where all you see is "I perform this operation on everything in the tree".

Title: Is recursion an instance of being "too clever" when programming?

Body:
I've read several books and learned through experience that optimizing code to the point where it is inscrutable, or coming up with an extremely fast but extremely complex solution to a problem is not desirable when working in teams, or even when you're working by yourself and have to understand your clever solution some time later.

My question is, should recursion be treated in the same manner?  Does the average programmer understand recursion easily and thus one should use it with impunity, or does the average programmer not understand recursion very well and one should stay away from it for the sake of overall team productivity?

I know there are simple answers of, "Any programmer who doesn't understand recursion isn't worth a grain of salt, so don't worry about them" but I was wondering if you all had some real world experience you would like to share that would illuminate the issue more than the opinion I just mentioned.


问:
Android Icons Square
I created an action bar icon for an Android app I'm working on and it seems to downscale my icon.
The thing is, it isn't a square icon. The width is greater than the height.

Do I really HAVE to provide square icons or is there a workaround for this?
I don't really want to ditch my icons just because of this...

答:
An applications logo is typically wider than it's icon and resizes as necessary to fit the height of the action bar. I believe this is what you're looking for.

By default, the system uses your application icon in the action bar, as specified by the icon attribute in the  or  element. However, if you also specify the logo attribute, then the action bar uses the logo image instead of the icon.

Source: http://developer.android.com/guide/topics/ui/actionbar.html#Adding

setDisplayUseLogoEnabled() Enables the use of an alternative image (a "logo") in the Action Bar, instead of the default application icon. A logo is often a wider, more detailed image that represents the application. When this is enabled, the system uses the logo image defined for the application (or the individual activity) in the manifest file, with the android:logo attribute. The logo will be resized as necessary to fit the height of the Action Bar. (Best practice is to design the logo at the same size as your application icon.)

Source: http://developer.android.com/guide/topics/ui/actionbar.html#Style

To replace the icon with a logo, specify your application logo in the manifest file with the android:logo attribute, then call setDisplayUseLogoEnabled(true) in your activity.

Source: http://developer.android.com/sdk/android-3.0.html#api

Also see https://stackoverflow.com/questions/6735649/android-icon-vs-logo

In the case of the Action Items instead of the activity icons, it's a fairly simple work around and involves using Action Views rather than Action Items.

An action view is a widget that appears in the action bar as a substitute for an action button. An action view provides fast access to rich actions without changing activities or fragments, and without replacing the action bar.

Source: http://developer.android.com/guide/topics/ui/actionbar.html#ActionView

To do what you're asking all you need to do is add an ImageButton to your action bar as an Action View.

Title: Android Icons Square


问:
Is it a bad practice to give two very different files with the same general purpose the same name?
Is it a bad practice to give two very different files with the same general purpose the same name, separating them into different directories?

```<code><script src="client_scripts/app/player_stats/generator.js"></script>
<script src="client_scripts/app/coach_settings/generator.js"></script>
</code>```

I'd like to keep my file names short, and both of the files have the same general purpose without being identical. I'm not sure whether or not this would be considered a bad practice in a professional programming environment. I'd like to know what the best practice is in this situation.

Alternatively, at the expense of the name's short length, I could use:

```<code><script src="client_scripts/app/player_stats/player_stats_generator.js"></script>
<script src="client_scripts/app/coach_settings/coach_settings_generator.js"></script>
</code>```

答:
Always use descriptive names over short names unless it's something like a mathematical constant or loop variable where conventions of the language in question favor short names. For instance, if you call a variable "pi" and have it be some appropriately precise value of pi, then the name is good and gets the point across. On the other hand, if you have a generator that generates terms of the Taylor series for Pi and adds them together to approximate pi, you want to call it something like "taylorPiGenerator or similar.

Good names now save refactor time later or even worse massive errors later.

The books Clean Code and Code Complete go into considerable detail as the whys and wherefores of good naming but they are by no means the only sources.


问:
Potentially justifiable use case for const_cast or bad design?
I'm designing a data structure in C++, and I want to expose an interface to the user to traverse the structure in some order. Instead of creating several different types of enumerators, I want to keep it simple and provide a single enumerator, while maintaining const-correctness.

My design is summarised as follows:

```<code>class DataStructureNode; // The basic building block of the structure

class DataStructureEnumerator
{
public:

    friend class DataStructure;

    DataStructureEnumerator GetNext() { ... }
    DataStructureEnumerator GetPrevious() { ... }

private:

    const DataStructureNode* m_Node;
    ...
};

class DataStructure
{
public:

    DataStructureEnumerator GetEnumerator() { ... }

    DataStructureNode* GetNodeFromEnumerator(const DataStructureEnumerator& e)
    {
        // Let's assume this function also ensures the node belongs to this structure
        return const_cast<DataStructureEnumerator&>(e).m_Node; // <--- Ooo! const_cast!
    }

    const DataStructureNode* GetNodeFromEnumerator(const DataStructureEnumerator& e) const
    {
        // Let's assume this function also ensures the node belongs to this structure
        return e.m_Node;
    }
};
</code>```

This design has the benefit that there is only one type of enumerator that handles both mutable and immutable structures.

Of course, the alternative (and the conventional) design in C++ is to have two (or more) enumerator classes, such as DataStructureEnumerator and DataStructureConstEnumerator. The conventional design comes with added code-bloat, more templates, and an uglier interface (in my opinion!), but it's the norm in C++ communities.

I'm interested in hearing opinions of the community on this design. Are there any potential pitfalls that I'm missing with my design?

答:
It's probably simpler and more straightforward to just use a single template class that's compatible with iterator conventions:

```<code>template <typename T> DataIterator {
  public:
    T &operator* () const {
      return *m_node;
    }

  DataIterator &operator++ () {
    // get next node...
    return *this;
  }

  DataIterator &operator-- () {
    // get previous node...
    return *this;
  }

private:
  T *m_node;
}
</code>```

This can then be used for either const or non-const versions of the type:

```<code>typedef DataIterator<Data> iterator;
typedef DataIterator<Data const> const_iterator;
</code>```

This is, from what I've seen, the generally accepted way to handle "enumerators" in C++, and it's how all of the STL's containers expose their contents. Your code seems to be betraying the idea of Separation of Concerns, also, by having the DataStructure class be responsible for extracting a node from an enumerator.

Body:
It's probably simpler and more straightforward to just use a single template class that's compatible with iterator conventions:

template <typename T> DataIterator {
  public:
    T &operator* () const {
      return *m_node;
    }

  DataIterator &operator++ () {
    // get next node...
    return *this;
  }

  DataIterator &operator-- () {
    // get previous node...
    return *this;
  }

private:
  T *m_node;
}

This can then be used for either const or non-const versions of the type:

typedef DataIterator<Data> iterator;
typedef DataIterator<Data const> const_iterator;

This is, from what I've seen, the generally accepted way to handle "enumerators" in C++, and it's how all of the STL's containers expose their contents. Your code seems to be betraying the idea of Separation of Concerns, also, by having the DataStructure class be responsible for extracting a node from an enumerator.