答:
It's not "common sense" not to store credentials in source control. That really depends on your situation. It's a perfectly acceptable practice if the developers would already have access to production resources, or if the accounts are read-only and there's no privacy issue, or if the credentials are encrypted in some way.

If you're going as far as building your own deployment pipeline, then you would usually use a configuration management tool, which will handle all of the storage, encryption, users/privileges, etc. There are open-source tools like ESCAPE which provide this in a REST API, and other commercial tools (and possibly some other open-source tools) that provide similar functionality.

Some teams go with full-blown release management software like those from Atlassian, Red Gate, Thoughtworks, Serena, DevOpsGuys, Octopus, Cachet, etc. I'm not going to recommend a specific one because it depends entirely on your business structure and technology stack. But suffice it to say that most if not all of them will integrate configuration management into the process, and allow you to define "environments" and configurations to go with those environments; when you deploy a specific component to a specific environment, it takes the configuration files and replaces/transforms them with the correct settings for that environment.

Basically it depends on your budget and time. If I had low time/low budget, I'd keep storing them in source control; encrypt them if necessary. If I had lots of time but still a low budget, I'd build a deployment pipeline using an off-the-shelf configuration management tool. And if I had plenty of money to throw around then I'd just invest in one of the commercial release management tools; they really do save a lot of time and it's easier for a paranoid IT infrastructure team to trust a well-known commercial tool than it is for them to trust something you hacked together in a few days.

Title: Strategy for storing passwords/credentials in the context of continuous delivery

Body:
It is common sense not to store passwords/credentials into SCM.

I would like to know then what would be a good strategy for storing passwords/credentials in the context of continuous delivery.

Where and how do I store credentials?

How do I retrieve and use those credentials/passwords?


问:
Arrays' subscripts priority
I was reading a lecture on arrays for Fortran 90
and I came across this sentence :
'Fortran always stores by columns - the first subscript
varies more rapidly than the second, and so on.'

What does the author mean to say ?

答:
These are really two separate points, so let's address them separately:

"Fortran always stores by column.": This means that a(i,j) denotes the element of the 2D array a corresponding to column i, row j.

"The first index varies more rapidly than the second, and so on.": For this to make sense, it helps to think about arrays being stored on a one-dimensional medium, regardless of their dimension. For a 2D array with m rows and n columns, we would store the first element of the second column immediately next to the last element of the first column, etc. This is equivalent to 'stacking' the columns. The distance in this 1D structure between a(i,j) and a(i,j+1) is one, but the distance between a(i,j) and a(i+1,j) is m, the length of one column. The amount of distance being traversed when adding one to the column index is higher, so this index 'varies more rapidly'.

ContentLicense: CC BY-SA 3.0

Title: Arrays' subscripts priority


问:
Relevance of HTML5: Is now the time?
It seems like most of the jobs I'm receiving, and most of the Internet, is still using standard HTML (HTML 4, let's say) + CSS + JS. Does anyone have any vision on where HTML5 is as a standard, particularly regarding acceptance and diffusion? It's easy to find information about inconsistencies between implementations of HTML5 and so forth. What I want to know about is relevance of HTML5.

答:
ONLY if you are prepared to deal with inconsistencies across the browsers. And then add a flash backup anyway for IE.

I agree with @Pierre 303 - wait a year.

That said, if you are building something new, you build with html5 in mind by adding the bits here and there which are standardized.

Background:

We were one of those clients spoken of, asking for an ipad compatible interface even though most of our users are on IE7/8. Thing is, the agency said it'd be a two week project but it turned into two months as they ironed out all the inconsistencies. In the end the interface works and looks great, but the agency isn't signing up for html5 projects anymore.

p.s.
I disagree a little with @Ben. If our agency had told us in the beginning that it would take 2 months instead of 2 weeks, we would have said no. Educate your clients! (but of course accept their money if they stupidly insist.)

ContentLicense: CC BY-SA 2.5

Title: Relevance of HTML5: Is now the time?


问:
Multiple Same Object Instantiation
What exactly happens in Java when you instantiate the same object multiple times?

For example:

```<code>Test test = new Test();
</code>```

then later on I will call it again, Test test = new Test(); again or inside a loop. Will the previous instantiation be disposed?

答:
1: Some wording: We don't instantiate objects at all, we instantiate classes, and the product of a class instantiation is an object (also called an instance). Of course we can instantiate a class as many times as required to create a new and different object with each instantiation.

2: Whatever, you cannot have the code you suggest:

```<code>Test test = new Test();
Test test = new Test();
</code>```

neither you can have this:

```<code>for (i=0; i<3; i++) {
    Test test = new Test();
    Test test = new Test();
}
</code>```

None will compile, because the part Test test is the declaration of variable test (of type Test), and no language, including Java, allows to declare twice the same variable in the same scope.

However you may assign multiple times the same variable (as the name implies), with different objects, like this:

```<code>Test test = new Test();
test = new Test();
</code>```

The first line declares test and assign it an object newly created. The second line assign to test another object, also newly created.

Also note that shortcuts are allowed in Java:

```<code>for (i=0; i<3; i++) {
    Test test = new Test();
}
</code>```

This loop will not declare test 3 times. It is understood as assigning three new different objects in sequence to the variable test which will be declared only once. (compare with the previous loop).

3: What happens to the variable test, and to the two objects of type Test?

The variable test is first assigned the reference of an object, then of another object. A variable retains only the last reference assigned.

The first object of type Test is not assigned to test anymore. If no other variable has been assigned its reference, then this object cannot be accessed in any way by the program, and thus is useless. It is made eligible to garbage collection by the system. At some point in time the system (the JVM) will run its garbage collector which will clear it from memory.

The second object will live as long as at least one variable references it, then the garbage collector will also take care of it and bring it to the Unreferenced Objects Cemetery. That's the true life of Java objects :-(

Title: Multiple Same Object Instantiation

Body:
1: Some wording: We don't instantiate objects at all, we instantiate classes, and the product of a class instantiation is an object (also called an instance). Of course we can instantiate a class as many times as required to create a new and different object with each instantiation.

2: Whatever, you cannot have the code you suggest:

Test test = new Test();
Test test = new Test();

neither you can have this:

for (i=0; i<3; i++) {
    Test test = new Test();
    Test test = new Test();
}

None will compile, because the part Test test is the declaration of variable test (of type Test), and no language, including Java, allows to declare twice the same variable in the same scope.

However you may assign multiple times the same variable (as the name implies), with different objects, like this:

Test test = new Test();
test = new Test();

The first line declares test and assign it an object newly created. The second line assign to test another object, also newly created.

Also note that shortcuts are allowed in Java:

for (i=0; i<3; i++) {
    Test test = new Test();
}

This loop will not declare test 3 times. It is understood as assigning three new different objects in sequence to the variable test which will be declared only once. (compare with the previous loop).

3: What happens to the variable test, and to the two objects of type Test?

The variable test is first assigned the reference of an object, then of another object. A variable retains only the last reference assigned.

The first object of type Test is not assigned to test anymore. If no other variable has been assigned its reference, then this object cannot be accessed in any way by the program, and thus is useless. It is made eligible to garbage collection by the system. At some point in time the system (the JVM) will run its garbage collector which will clear it from memory.

The second object will live as long as at least one variable references it, then the garbage collector will also take care of it and bring it to the Unreferenced Objects Cemetery. That's the true life of Java objects :-(


问:
Minified version of JavaScript library under LGPL used on a site without copyright notice
On this site hackfind.com the autor put minified version of my library without any copyright notice. Is this violation of the LGPL. Note that using on a site is not a copy.</p>

答:
From my reading of http://www.gnu.org/copyleft/lesser.html and the commentary provided in How can I legally use LGPL javascript in a commercial web site?

Yes.

That the code is minified in no way absolves the person using it from noting that the license of the code is LGPL and linking to the license.

Furthermore, if there are any changes based upon your library, it is necessary to release the source code in a form that is neither minified nor obfuscated.


答:
First of all, you have not included the legal text that is expected of a file that is released under the LGPL license. From a legal standpoint, that makes it unclear if the LGPL really applies to your library. I would recommend that you follow the guidelines from FSF on how to apply the (L)GPL to your code.

With that out of the way, it is also a legal gray area if using a client-side JavaScript library on your site distributes that library. You can certainly interpret it that way, because the client's browser downloads the JavaScript and executes it on the client's machine.

But even if it doesn't count as distribution, it is not good manners to rip out a copyright notice and you can certainly ask the maintainer of hackfind.com to use (a local copy of) the minified version of your library that you provide already.

Title: Minified version of JavaScript library under LGPL used on a site without copyright notice

Body: On this site hackfind.com the autor put minified version of my library without any copyright notice. Is this violation of the LGPL. Note that using on a site is not a copy.</p>


问:
What process will you use to clarify functional requirements and to gather non-functional requirements?
I am confused with what's the different between clarify and gather. I know using interview, observe or questionnaire can to elicit the requirement we want, but how to clarify the functional requirement? </p>

答:
Gathering requirements means just that: collecting them.

Clarifying requirements means making sure that those requirements are clear and unambiguous.  You need clear and unambiguous requirements so that there is no dispute with the customer over whether or not something that was asked for has been provided.

One way to clarify requirements is to write acceptance tests.  Acceptance tests are tests that, if they pass, indicate that the requirement has been fulfilled.

```<code>// Acceptance Test
public void GetRandomNumber_ShouldReturn4()
{
    var result = GetRandomNumber();
    Assert.IsEqual(result, 4);
}

// Implementation
public int GetRandomNumber()
{
    return 4;  // Chosen by fair dice roll.  Guaranteed to be random.
}
</code>```

If you're having difficulty with things like scope creep, inaccurate time estimates and disputes over completion of requirements, one way to refine those things is to write a Software Design Specification, including the classes and interfaces it would take to fulfill the requirements.  This can be combined with the Ubiquitous Language of DDD to get a clear understanding of the scope of a project (from both the developers' and customer's perspective), and what it takes to declare success on each requirement.

Further Reading

Clarifying Requirements

Body:
Gathering requirements means just that: collecting them.

Clarifying requirements means making sure that those requirements are clear and unambiguous.  You need clear and unambiguous requirements so that there is no dispute with the customer over whether or not something that was asked for has been provided.

One way to clarify requirements is to write acceptance tests.  Acceptance tests are tests that, if they pass, indicate that the requirement has been fulfilled.

// Acceptance Test
public void GetRandomNumber_ShouldReturn4()
{
    var result = GetRandomNumber();
    Assert.IsEqual(result, 4);
}

// Implementation
public int GetRandomNumber()
{
    return 4;  // Chosen by fair dice roll.  Guaranteed to be random.
}

If you're having difficulty with things like scope creep, inaccurate time estimates and disputes over completion of requirements, one way to refine those things is to write a Software Design Specification, including the classes and interfaces it would take to fulfill the requirements.  This can be combined with the Ubiquitous Language of DDD to get a clear understanding of the scope of a project (from both the developers' and customer's perspective), and what it takes to declare success on each requirement.

Further Reading

Clarifying Requirements


问:
What hat should a programmer not wear?
In my experience, software developers tend to wear multiple hats and fill multiple roles with different responsibilities.  From not only coding, but sometimes also writing SQL, designing the user-interface, designing the database, graphics manipulation, to even QA testing.

If the primary role is to write software/code, what roles should the developer not take on?  Are there any?

The intention of this question is not because a developer is incapable of filling another role-- but having the additional role actually works against the primary role, or should really be a dedicated role of someone who does not primarily program.

答:
Tech Support

So much of my day is wasted by taking tech-support calls...

Some popular ones are:

"My account is locked out" or "I forgot my password"

"My [phone|keyboard|mouse|computer] doesn't work"

"My computer is slow, can you check it out for anything unusual?"

"Why does X happen when I click this button? It should be doing Y"

"I keep getting these popups...." or "I think I have a virus"

"This person is no longer here, can you disable all their stuff?"

"We have a new employee, can you set them up with login, security card, phone ext, email, etc?"

Title: What hat should a programmer not wear?


问:
What is the difference between use case, user requirements and user stories?
I'm wondering what the difference is, and at what stage these different terms are used within the Agile/Scrum methodology?

use case, user requirements and user stories

Am I right in thinking they start off in the requirement elicitation stage as use cases then become the user requirements, which are pretty much the same as the user stories used in the products backlog?

Trying to write a university report and haven't been able to find anything defining all of these terms in the same place, which has made it difficult to understand the differences.

Are some of these terms even required within an Agile approach?

答:
In simple words: user stories are not use cases, and user requirements are more fine-grained document of requirements that are usually approved (or pre-approved) by client.

The user stories don’t provide the details the team needs to do their work. The Scrum process enables this detail to emerge organically, mainly by removing the need to write use cases.

Also there’s consensus that use cases and user stories are not interchangeable:

Alistair Cockburn: A user story is to a use case as a gazelle is to a gazebo

ExtremeProgramming.org: User stories serve the same purpose as use cases but are not the same.

Mike Cohn: User stories aren’t use cases

You may also thing about user stories as - a short description of something that your customer will do when they come to your website or use your application/software,  focused on the value or result they get from doing this thing. They are written from the point of view of a person using your website or application, and written in the language that your customers would use.

Meanwhile,  use cases are more a description of a set of interactions between a system and and one or more actors (where ‘actor’ can be people, or other systems: for example, both online shoppers and PayPal can be actors). They are usually created as documents

References:

 User Story And Use Case Comparison

Linkedin discussion: What is a difference between Use Cases and User Stories in agile development?


答:
Use Case - Formal specification of interaction between actor(s) and a system that realize one single functional requirement of this system (part of UML).

User Story - Informal description of a function of a system (Agile term).

User Requirement - Formal description of what user expects from the system usually gathered/formulated on very early stage of the development process by an architect in close cooperation with the client. There are two main types of requirements:

Functional - requirements that are translated to use cases or user stories and then implemented in business logic of the application.

Non-functional - requirements that (in most cases) should be ensured by the architecture of the system. It's very important that all non-functional requirements are formulated in measurable way, so they can be tested.

It makes less sense to compare User Requirements to User Stories or Use Cases, because requirements serve very different purpose. Use Cases and User Stories describe details of a function in the system, while User Requirements state functions and non-functional properties of the system (unambiguously but without any detail).

Title: What is the difference between use case, user requirements and user stories?

Body:
I'm wondering what the difference is, and at what stage these different terms are used within the Agile/Scrum methodology?

use case, user requirements and user stories

Am I right in thinking they start off in the requirement elicitation stage as use cases then become the user requirements, which are pretty much the same as the user stories used in the products backlog?

Trying to write a university report and haven't been able to find anything defining all of these terms in the same place, which has made it difficult to understand the differences.

Are some of these terms even required within an Agile approach?

ContentLicense: CC BY-SA 4.0


问:
Dealing with a large pull request
I'm currently working on a project with a team that's using a git workflow. It's fairly simple: master should be in a deployable state and branches are used to create features and hotfixes. Whenever we have a feature or bugfix completed and tested then we move that over to master as soon as we can. The idea is that branches should be as small as possible to make it easier to merge them back into master. We have a policy that any code pushed to master branch should be in a deployable state and pass the tests.

We have got a situation where one of the developers has done a lot of work (a few months worth) on a single branch and this branch hasn't been merged back into the master yet. There's now a few separate features and a bunch of commits on this branch. Essentially, this branch really should have been merged back in a few times already but so far hasn't been. Most of the code is in a good state with unit tests that could be merged back into master but the most recent changes should certainly not be as they are not completed and aren't tested.

What is the best way to deal with such a situation where one branch is really far away from the others? What ways can we avoid branches getting a very large number of commits away from master in the future?

答:
If you have a commit that you know this and all previous commits is well tested and should be merged, then simply branch-out from this last good commit and merge the new branch with master.

If you have some commits that you would like to merge, but they are interspersed with other commits that are not production-ready, then I see 2 possibilities:

Create new branch, and cherry pick good commits, merge with master.

Try to rebase unwanted commits to the top (maybe on new branch just to be safe).

As for prevention methods, try to define some funny team rules like "One that does not merge with master within a week will order pizza for a month".

Title: Dealing with a large pull request


问:
What are the perks and drawbacks of using html templates versus building the html in-code
As far as I can see there are two ways of building a html page: "inside" the language (I'll call it building for lack of a better name) or outside the language (using templates). Let me explain a bit what I
mean by this before I jump to the questions.

Building

One way is to build the html page "inside" the language you are using,
using preferably in-language constructs (not just by concatenating strings),
and converting these constructs to html in one last step.

A really good example of this is Clojure's hiccup library, which uses the
Clojure maps and vectors to represent the html. This allows one to use the full
power of the language one's working in to manipulate these structures.

Templating

The second way is to write the html separately from the main program
and use some kind of template DSL to insert logic into the templates.
The hamlet package for Haskell is an example of this.

Now my question is: what are other advantages and disadvantages of both approaches?

I'd love to get more acquainted with these concepts so pointers
to articles etc. are more than welcome. Also please inform me if there
is another approach I didn't think of.

Summary of answers so far

Pro templating

It's easier to separate the view from the rest of the code. The code will be easier to maintain and you avoid mixing business logic with the rest of your code.

This approach generally is much more accessible to people with less technical skills.

Con templating

(none so far)

Pro building

Functional languages, make it easy to write declarative code natively so a template language is not required.

You can get all the power and flexibility of your programming language, and still get the benefits of a declarative syntax.

Con building

Designers/clients are bad at your preferred logic language.

It still boils down to hard-coding the page into codem just that it
is not separate template code.

Has more power, that could be used inappropriately. You have to take extra care

to separate view code and business logic.

In ideal cases it is faster though.

答:
If you are working with a team, it is very helpful to use a template and breakout the html from the code. By separating the two, different people can work simultaneously without interfering. </p>

<p>It is also nice for working with contractors or employees with different skills.  We OEM our product to customers and this allows more freedom for customization. </p>

Body:
If you are working with a team, it is very helpful to use a template and breakout the html from the code. By separating the two, different people can work simultaneously without interfering.

It is also nice for working with contractors or employees with different skills.  We OEM our product to customers and this allows more freedom for customization.


问:
Implementing objects with several equivalent representations
I am wondering if there are patterns, references or useful resources about how to implement objects that may have several equivalent representations. For example:

Suppose I want to implement a Rectangle, and I will instantiate it using its length and width:

```<code>class Rectangle:
    def __init__(self, length, width):
        self.length = length
        self.width = width
</code>```

and suppose now I also want to have the possibility to instantiate the Rectangle using its diagonal and area. My main concern is that I don't want to store redundant information in the object (in this case, these four properties), only the bare minimum possible to define it.

Suppose too I might want to retrieve one set of properties having created the Rectangle using another:

```<code>r = Rectangle(length=3, width=4)
assert r.diagonal == 5
</code>```

This is what I've tried so far:

```<code>class Rectangle:
    def __init__(self, **kwargs):
        params = set(kwargs.keys())
        if params == set(['length', 'width']):
            self._length = kwargs['length']
            self._width = kwargs['width']
        elif params == set(['area', 'diagonal']):
            self._area = kwargs['area']
            self._diagonal = kwargs['diagonal']
        else:
            raise ValueError('Invalid input arguments')

    @property
    def length(self):
        if hasattr(self, '_length'):
            return self._length
        elif hasattr(self, '_area') and hasattr(self, '_diagonal'):
            length, width = ad2lw(self._area, self._diagonal)
            #r = Rectangle(length=length, width=width)
            #return r._length
            return length
        else:
            raise NotImplementedError('No converter available')

    # Same with other three properties

def ad2lw(area, diagonal):
    # Obscure math
    return l, w
</code>```

Is this any known pattern or is there a standard way to do it?

答:
The whole idea is that you have object defined in one way, eg. using width and length and you can calculate other parameters, eg. diagonal and area from them.

First your constructor/init only accepts length and width, but the class could also have static createFromDiagonal method, that accept diagonal and area, calculates the width and length, creates the instance using those parameters and returns this instance.

The second thing is accessing the values. You can easily access length and width, because those are what defines the object. And for diagonal and area you can use Properties, which will calculate the required value from length and width while access from outside will look like normal field.


问:
Fighting technical debt as the "lowest developer"?
Let's say you work for a company and what you do is develop software for them. You have no idea of the big picture or maybe slight. What you do have are tasks assigned to you via issue tracking system. You're given tasks, you make them work the way the task describes them, you send them back. Like adding 2 integers:

```<code>function add(a,b){return a + b;}
</code>```

But later, as the project goes forward, you notice that as add becomes more complex, you realize that it should have needed some form of architecture, more than just a function that adds parameters and returns a value. However, you didn't know that. In the first place, all they needed was that simple add. You didn't expect add to become so complex.

The project progresses with more features, which you didn't expect to have in the first place. And in the end, you keep piling up hacks and layer upon layer of functions to avoid breaking/rewriting the existing code.

How do you deal with these situations? How do you fight technical debt as "the lowest developer"?

Clarification:

You're the "implementer", the lowest in the hierarchy.

You see the problem, but have no say with the matter.

I'm not quantifying technical debt or looking for tools.

Regarding the third "duplicate"

Refactoring & Rewrite - You are locked to your tasks. You are not paid to do extra.

Architecture Overview - You know the overall system, but no idea of the architecture.

Code Freeze - Not your call. You're not management.

Modularization - No idea of architecture. Modules change as requirements change.

Automated Tests - None exists.

答:
You're a professional. Your employer hired you to be professional. So, treat your concerns the same way you'd want professionals you hire to treat their professional opinions. In particular, you expect other professionals to make necessary optimizations and corrections along the way, provided those optimizations don't unexpectedly increase the cost.

For instance, suppose you take your car to a mechanic to have a lamp replaced. The mechanic notices four things:

The wire leading to the lamp is frayed and dangerous. But, it can be trimmed without notably increasing the cost. You'd expect him to take a few minutes to trim the wire, possibly without even noting it.

A bolt is loose. It's totally unrelated, he just happened to see it. It's 20 seconds of his time to grab the necessary driver and tighten it; so, you'd expect him to do it.

The chassis for the lamp is cracked, which will cause the lamp to rattle. It's expensive to replace. And it's not essential. So, he calls you to ask about it -- if you say "no", he puts a written recommendation on your visit summary.

There's a fair amount of brake fluid under the car. He should, and may even be required as a professional, to prevent you from using the car until you allow someone to fix the leak.

Each of these scenarios, and I'm sure others, have parallels in software development -- especially if you consider yourself a professional of any level. As a professional, with very very few exceptions, your job is to reach the end-goal of improving the product in a particular way according to your professional understanding.

If the fix is trivial, whether unrelated or not, make the fix.

If the fix is non-trivial and unnecessary, make a formal recommendation using whatever formal communication/issue-tracking mechanism you've agreed on.

If a case can be made that the fix is necessary to accomplish the primary task, but will unexpectedly increase cost, communicate the scope change.

If the identified problem poses a serious threat to the success of the project, make that clear. Formally. If there are ethical concerns with allowing the problem to go unfixed (like in health, emergency, or transportation systems), insist on addressing the problem before the product ships (notify the media or authorities if ethically necessary).


问:
Why do projects opt to stay on an older version of the .NET Framework?
Why do projects opt to stay on an older framework version of the .NET Framework?

For example, staying on .NET Framework version 3.5 which was released in 2007 instead of upgrading to the latest 4.5.1 version?

Jon Skeet's Noda Time also targets .NET 3.5. Why?

答:
Providing support for an older OS is one reason (see Crono's answer). The other reason is to "save money". Quoted because it only saves money on the short run.

It depends on the type of project of course, but for business applications, which usually survive a significant number of years, there's a good chance an upgrade will be required at some point, for whatever reason: support for newer platforms, new features, better performance...So either you postpone the upgrade until you have no other choice, or you continually upgrade as part of the normal development routine.

Small, quick, cheap steps, or big, slow, expensive steps. It's exactly the same problem as with refactoring. Actually I guess you could even say a framework/library upgrade is a kind of refactoring.

Side note: There's a discussion in the comments of JeffO's answer about the car analogy. Since my rep is too low to comment, I'm leaving this note here. Software does not get old as a car does if it's left untouched, yes, but it does get old if it's worked on. Code is added. It gets bloated. Just as a car, if you don't continually replace parts of it, something breaks. In the case of a car, you can still replace the part that's broken, if it's available. With old software, finding and fixing the issue gets so expensive with time you eventually have to give up.


答:
It is a good idea to break the representation from the data in any case. It is not made clear explicitly from your question if this is what you want, but my guess is that it is what you're pointing to.

I'm not familiar with the precise implementations you've mentioned, but generally speaking it can de handled as follows:

If you roll your own, then you have more control over how you deal with your input. In the Clojure examples it is shown that does some pre-formatting for you, but judging by the examples it still boils down to hard-coding the page into code, with some flexible fields for easier and more consistent response management. It is still something that requires some skill. In ideal cases it is faster though. The downside is that it's much more tempting to sneak in code that should be separated from your representation, fading the distinction between the two.

If you use a true templating engine, the page becomes data that's interpreted before being shown. It's something that can be stored as data, and which is independent of the rest of your design, save for the code hooks that you've defined in the data. These hooks need to correspond with code that you've made available. This approach generally is much more accessible to people with less technical skills, as long as they know how to interface with your code. (see it as learning how to use a new version of HTML vs learning how to program in some functional language)
Because this approach takes more interpretation, it can be slower.

I generally favour the latter approach, as it forces you to make a much cleaner separation between code and representation. This forces you to carefully consider what you're doing. I think it leads to better design overall.

Title: What are the perks and drawbacks of using html templates versus building the html in-code

Body:
As far as I can see there are two ways of building a html page: "inside" the language (I'll call it building for lack of a better name) or outside the language (using templates). Let me explain a bit what I
mean by this before I jump to the questions.

Building

One way is to build the html page "inside" the language you are using,
using preferably in-language constructs (not just by concatenating strings),
and converting these constructs to html in one last step.

A really good example of this is Clojure's hiccup library, which uses the
Clojure maps and vectors to represent the html. This allows one to use the full
power of the language one's working in to manipulate these structures.

Templating

The second way is to write the html separately from the main program
and use some kind of template DSL to insert logic into the templates.
The hamlet package for Haskell is an example of this.

Now my question is: what are other advantages and disadvantages of both approaches?

I'd love to get more acquainted with these concepts so pointers
to articles etc. are more than welcome. Also please inform me if there
is another approach I didn't think of.

Summary of answers so far

Pro templating

It's easier to separate the view from the rest of the code. The code will be easier to maintain and you avoid mixing business logic with the rest of your code.

This approach generally is much more accessible to people with less technical skills.

Con templating

(none so far)

Pro building

Functional languages, make it easy to write declarative code natively so a template language is not required.

You can get all the power and flexibility of your programming language, and still get the benefits of a declarative syntax.

Con building

Designers/clients are bad at your preferred logic language.

It still boils down to hard-coding the page into codem just that it
is not separate template code.

Has more power, that could be used inappropriately. You have to take extra care

to separate view code and business logic.

In ideal cases it is faster though.


问:
What is the difference between writing test cases for BDD and TDD?
I have been learning writing test cases for BDD (Behavior Driven Development) using specflow. If I write comprehensive tests with BDD, is it necessary to write TDD (Test Driven Development) test separately? Is it necessary to write test cases for both TDD and BDD separately, or are they effectively the same thing?

It seems to me that both are same, the only difference being that BDD test cases can be understood by non developers and testers.

答:
In my experience the biggest problem with TDD is the "T".  It causes the lay-person (managers, testers, non-TDD devs) to equate it in their minds with the traditional post-development "Testing" phase of a waterfall style. That is something that anyone can get their head around.

The problem that many struggle with is that TDD is for developers, not testers. Done right TDD is not primarily a test strategy or an acceptance test tool, but a technique that drives good software design from the ground up - small, loosely coupled classes, clear, well defined interfaces, and continually cleaned code through on-going refactoring.  Refactoring that is performed routinely, frequently, and from a position of confidence.

That you happen to end up with a comprehensive test suite that can form part of your CI / build process is a bonus, not the goal.

BDD compliments this by bridging the gap between business requirements and higher-level acceptance tests. It is the satisfying of the BDD suite that scopes out the development process and which determines when the product as a whole has been adequately delivered.


问:
MVC in a desktop application - can the View ever hold a reference to the Model?
(I'm specifying this is a desktop application so people wouldn't refer specifically to web implementations of MVC).

The title says it all pretty much.

In an MVC structure - can the View ever hold a reference to the Model? Or should the Controller be used as a 'middleman' for communication between the View and Model - always - and in both directions?

If the answer is "no, it can't" - why?

答:
The pattern you describe is what I know as MVP, Model View Presenter. This is an alternative to the MVC in that the Presenter contains the logic for updating the UI code without the View requesting the data from the Model.

The traditional MVC pattern does indeed allow for the View to know of the Model.

When to favor one over the other? Purists will argue that MVP is a much cleaner separation of both interface and responsibility. The argument goes that it's much easier to blur the line between querying the Model for any necessary data and being lazy and performing complex or even business operations in the View. Very ugly indeed.

Spoken as a pragmatic programmer, I did once create an Actionscript application where the view communicated indirectly with the Model via events. There was a certain class of ViewEvent or ModelEvent that only the View could receive or emit. This allowed me to get updates from the model without an explicit reference.


问:
What's the difference of an object being final and an object being immutable in java?
```<code>final String str = "do not change me";
str = "why not?"; //it will result in compile time error saying that final fields can not be re-assigned once created i.e. the reference cannot be changed

String str1 = "hello world";
    System.out.println(str1.replaceAll("h", "q"));
    str1 = str1.replaceAll("h", "q");
    System.out.println(str1);  //An immutable object on the other hand means that, there is no way for you to change the object or its contents other than changing the reference.
</code>```

Is the above understanding of definition of a final object and immutable object correct?

答:
Objects can be immutable and references to them can be final; but the reverse is mostly technical confusion. A "final object" is really a final reference to an object, while an "immutable reference" (or "immutable field" or "immutable variable") is rarely mentioned because it is not how they are considered. A reference is effectively an address, and therefore like a primitive number or boolean. A variable or field can contain the integer 10. If you increment that integer, are you "mutating" that 10, or are you really assigning a different integer? On the bit level, you are changing the contents of a single memory location, but at the semantic language level it is the latter, since everywhere else that uses 10 is unchanged.

A final field or variable must be assigned exactly once, and the compiler will enforce this. An immutable object does not change once it has completed construction, but there is no real enforcement. Note that even if you define an object that has only final fields, that does not automatically make the object immutable. If a final field is an object reference, that nested object must be immutable. There is also no way at the language level to make an array immutable; a final reference to an array means you cannot change which array or its length, but you can change its contents. The language cannot enforce making such an object immutable. So in many cases, an object is immutable only because you intend it to be (and if there's a bug in your code, maybe it isn't).

String objects are like that: they have a final array of characters, and are immutable only because the methods that might change something return other instances instead. Methods like substring can actually share the original character array and simply "see" a different section of that array.


问:
How to document a file format specification
For a project, I need to work with varying types of files from some old games and related software--configuration files, saves, resource archives, and so on. The bulk of these aren't yet documented, nor do tools exist to work with them, so I must reverse-engineer the formats and build my own libraries to handle them.

Although I don't suppose there's great demand for most of it, I intend to publish the results of my efforts. Are there any accepted standards for documenting file formats? Looking around, there are several styles in use: some, like the .ZIP File Format Specification, are very wordy; others, like those on XentaxWiki, are much more terse--I find some of them difficult to read; the one I personally like best is this description of the PlayStation 2 Memory Card File System, which includes both detailed descriptive text and several 'memory maps' with offsets and such--it also most closely matches my use case. It will vary a little for different formats, but it seems there should be some general principles that I should try to follow.

Edit: I seem not to have explained very well what I want to do. Let me construct an example.

I may have some old piece of software which stores its configuration in a 'binary' file--a series of bitfields, integers, strings, and whatnot all glued together and understood by the program, but not human-readable. I decipher this. I wish to document exactly what is the format of this file, in a human-readable way, as a specification for implementing a library to parse and modify this file. Additionally, I'd like this to be easily understood by other people.

There are several ways such a document might be written. The PKZIP example above is very wordy and mostly describes the file format in free text. The PS2 example gives tables of value types, offsets, and sizes, with extensive comments on what they all mean. Many others, like those on XentaxWiki, only list the variable types and sizes, with little or no commentary.

I ask whether there is any standard, akin to a coding style guide, which provides guidance on how to write this kind of documentation. If not, is there any well-known excellent example that I should emulate? If not, can anyone at least summarize some useful advice?

答:
A binary file is just a sequence of bits arranged into logical units according to certain rules. These rules are usually called grammar. Grammar can be classified into four types (the Chomsky hierarchy), and for context-free grammars you should use Extended Backus-Naur Form as pointed out by Matt Fenwick in his comment. The interpretation (or semantics) of the sequence stored in the file can be described verbally or with well-annotated sample programs serializing and deserializing the information.

To know more about documenting binary file formats, suggest reading up on e.g. ASN.1 standard.


问:
Are there flavours of OOP where some or all of the SOLID principles are antithetical to clean code?
I recently had a discussion with a friend of mine about OOP in video game development.

I was explaining the architecture of one of my games which, to my friend's surprise, contained many small classes and several abstraction layers.  I argued that this was the result of me focusing on giving everything a Single Responsibility and also to loosen the coupling between components.

His concern was that the large number of classes would translate to a maintenance nightmare.  My view was that it would have the exact opposite effect.  We proceeded to discuss this for what seemed like centuries, eventually agreeing to disagree, saying that perhaps there were cases where SOLID principles and proper OOP didn't actually mix well.

Even the Wikipedia entry on SOLID principles states that they're guidelines that help to writing maintainable code and that they are part of an overall strategy of agile and adaptive programming.

So, my question is:

Are there cases in OOP where some or all of the SOLID principles do not lend themselves to clean code?

I can imagine right away that the Liskov Substitution Principle could possibly conflict with another flavour of safe inheritance.  That is to say, if someone devised another useful pattern implemented through inheritance, it is quite possible the LSP might be in direct conflict with it.

Are there others?  Perhaps certain types of projects or certain target platforms work better with a less SOLID approach?

Edit:

I'd just like to specify that I'm not asking how to improve my code ;)  The only reason I mentioned a project in this question was to give a little context.  My question is about OOP and design principles in general.

If you're curious about my project, see this.

Edit 2:

I imagined this question would be answered in one of 3 ways:

Yes, there exist OOP design principles which partially conflict with SOLID

Yes, there exist OOP design principles which completely conflict with SOLID

No, SOLID is the bee's knees and OOP will forever be better with it.  But, as with everything, it's not a panacea.  Drink responsibly.

Options 1 and 2 would have likely generated long and interesting answers.  Option 3, on the other hand, would be a short, uninteresting, but overall reassuring, answer.

We seem to be converging onto option 3.

答:
I think I have an unusual perspective in that I've worked in both finance and games.

Many of the programmers I met in games were terrible at Software Engineering - but they had no need for practices like SOLID. Traditionally, they put their game in a box - then they're done.

In finance, I've found developers can be really sloppy and undisciplined because they don't need the performance that you do in games.

Both the above statements are of course over-generalizations, but actually, in both cases clean code is critical. For optimization clear and easy to understand code is essential. For maintainability's sake, you want the same thing.

That is not to say that SOLID is not without criticism. They're called principles and yet they're supposed to be followed like guidelines? So when exactly should I follow them? When should I break the rules?

You could probably look at two pieces of code and say which one complies best with SOLID. But in isolation, there is no objective way to transform code to be SOLID. It is definitely to the interpretation of the developer.

It is a non sequitur to say that, "a large number of classes may lead to a maintenance nightmare". However, if SRP is not correctly interpreted you could easily end up with this problem.

I've seen code with many layers of pretty much no responsibility. Classes that do nothing apart from pass state from one class to the other. The classic problem of too many layers of indirection.

SRP if abused can end up with a lack of cohesion in your code. You can tell this when you try to add a feature. If you always have to change several places at the same time then your code lacks cohesion.

Open-Closed is not without its critics. For example, see Jon Skeet's review of the Open Closed principle. I won't reproduce his arguments here.

Your argument about LSP seems rather hypothetical and I don't really understand what you mean by another form of safe inheritance?

ISP seems to somewhat duplicate SRP. Surely they must be interpreted the same as you can never anticipate what all clients of your interface will do. Today's cohesive interface is tomorrow's ISP violator. The only illogical conclusion is to have no more than one member per interface.

DIP can lead to unusable code. I've seen classes with massive numbers of parameters in the name of DIP. These classes would have ordinarily "newed" up their composite parts, but I the name of test-ability we must never use the new keyword again.

SOLID on its own is not enough for you to write clean code. I've seen Robert C. Martin's book, "Clean Code: A Handbook of Agile Software Craftsmanship". The biggest problem with it is that it's easy to read this book and interpret it as rules. If you do that, you're missing the point. It contains a large list of smells, heuristics and principles - many more than just the five from SOLID. All of these 'principles' arent really principles but guidelines. Uncle Bob descibes them himself as "cubby holes" for concepts. They're a balancing act; following any guideline blindly will cause problems.


问:
What are the advantages of recursion compared to iteration?
I'm trying to understand when is preferred to use recursion rather than iteration.

Actually I've encountered recursion only in Javascript but never in Python. I imagine that recursion should be used in determinate contexts or languages but I don't understand when I should use it and which advantages it gives me.

I would like to see some examples of advantageous usage of recursion, as opposed to iteration.

答:
Before deciding, lets look at the similarities and differences.

Iteration is suited to problems where there are a fixed number of partial results. An example is to sum the elements of an array; we only need one partial result - the sum calculated so far.

Implementation: In iteration we have a loop. Think of it as having 4 parts:

A decision to continue or stop, based on some "controlling" data, evaluated as a logical condition.

A body, where the work is done. Sometimes, the body is combined with the next part.

A way of changing the "controlling" data. Often by changing a counter.

A way of invoking the construct (in this case, the loop) again. In c-style languages this is provided by the for, while, or do syntax.

Recursion is suited to problems where we don't know how many partial results there will be. An example is where we are summing the elements of a binary tree (that does not have links to the parent nodes) - we need to keep the sum calculated so far and be able to ascend the tree. Ascending the tree (going to the node's parent) is naturally done in a recursive solution; we just return to the previous call. The call stack is keeping our partial results for us.

Implementation: In recursion we have a function (sometimes several). They have the same 4 parts:

A decision to continue or stop, based on some "controlling" data, evaluated as a logical condition. The controlling data is usually passed to the function as parameter(s).

A body, where the work is done. Sometimes, the body is combined with the next part.

A way of changing the "controlling" data. Sometimes by changing a counter, often by changing which node of a data structure is "current".

A way of invoking the construct (in this case, the function) again - that means call the function (and remember to pass the changed "controlling" data).

So, they are very similar. One feature of recursion has been omitted though: a function can return a value. This means a partial result can be returned to the caller. This is a key part of many recursive solutions.

Reasons for choosing

Language style and support. If you are working in a functional programming language (such as a Lisp dialect, Haskell, Erlang, Scala, etc), recursion is the natural way to go. If your language does not support recursion well, you can be forced to produce an iterative solution. In some problems, this can involve building and managing your own stack of partial results.

Problem or solution structure. Some problems or solutions naturally fit into a in iterative or recursive implementation. The array summing example is a natural fit for an iterative solution. But problems where our solution is like "find a part of the problem I can solve, solve it, and do the same thing again" are a natural fit for a recursive solution.

Performance or space constraints. Recursive solutions can consume more space and processor time than iterative solutions. Compilers, optimizers, and smart programming can help, but there are still cases where we must coerce a naturally recursive solution to be iterative. Until we know we have a problem, we are better following the natural, easy to read solution.


问:
My UML class diagram is too complicated, what should I do?
Classes have 10-20 links with one another and you can't see anything in that mess of a diagram

Unfortunately we finished coding already and if we change the class diagram we have to redo the whole thing

答:
If you have reversed engineered code into a class diagram and your class diagram is too complex, that probably indicates a very complex design. There's really two approaches - rethink your design and implementation or reduce what you are showing on your model.

You could produce alternate views of the software, using multiple class diagrams to show pieces of the system instead of the entire system. You can also consider removing some information that may not be useful depending on the intent. As an example, showing all private members may not add value, so they could be removed from the diagram to reduce the apparent complexity. You can also consider other diagram types to better document your system - the class diagram is one of 14 diagrams in UML 2.2.

However, if your design is overly complex, then the best course of action would be to slowly refactor your project into something that has a simpler design. This does take time and effort, though, in both redesigning, carrying out the refactoring, and then updating and executing tests to ensure that everything continues to work. It's also something that shouldn't be combined with adding new functionality, so it could slow down development. However, having a cleaner design and implementation would allow others to more quickly understand and begin working on the system in the future.

Without a more complete understanding of your requirements and design (which is likely to be beyond the scope of a question/answer format), there's no way to say if your design is overly complex or not. Some systems truly are complex in nature and just require different methods of capturing the design clearly, while others should have their design reevaluated and maintained as appropriate for the project.


答:
The practice. Whether you choose recursion or iteration should depend on the nature of the problem you are trying to solve.

Iteration and recursion are two techniques for dealing with collections of objects. Which one you use depends the nature of the collection. Iteration suits flat collections such as arrays and hash maps; recursion suits nested collections like tree data structures. Note that a collection can be physical, such as tree data structure, or it can be virtual, such as the set of all 4x4 magic squares.

To put it another way, if solving a problem can be done by solving a set of sub-problems of the same kind, then recursion is recommended. If the problem can be solved directly, without breaking it down into nested sub-problems, then iteration is called for.

Sometimes a problem can be solved either way. Here, your choice will depend on professional judgement: How complex is each solution? How difficult (and thus, how defect-prone) is it to code? How efficient is the algorithm? Which of these factors matter more? Say you want to write code to sort the elements of an array. Here are two choices for algorithms:

Linear insertion sort is a simple iterative solution: an outer loop walks through the array visiting each element to be put in
place; an inner loop slides that element to the correct place in the
(growing) sorted section of the list.

Quicksort works recursively: it re-arranges the elements of the list to partition them into two sub-lists, the first with all the
elements smaller than a "pivot" value and the second with all
elements larger than the pivot (this is a linear process); then it
calls itself once on each of the two sub-lists to sort them in place.

The linear insertion sort is simple to program and to validate, but has terrible performance for large arrays. Quicksort requires more care to program, but performs well on large arrays.

The theory. Recursion is a more general, and more conceptually powerful, technique than iteration. The theory behind recursion is a little deeper, which means that it takes more effort to "prove" that a recursive algorithm is correct, versus an iterative one. But because of that generality, there are problems that have straight-forward recursive solutions but have no simple iterative solutions.

Think of iteration as a utility knife and recursion as a sword. The sword is more versatile but requires more skill and effort to wield. If you have a Gordian-knot of a problem to solve, the sword is the only thing that will do. But for most problems that you are likely to encounter, the utility knife will get the job done, and get it done faster and easier.

The reality. In many years of working in the so-called real world (i.e., not in academia), I have seen two or three instances of code that recurses, whereas I have probably seen half a gazillion instances of code that iterates.

Title: What are the advantages of recursion compared to iteration?

Body:
I'm trying to understand when is preferred to use recursion rather than iteration.

Actually I've encountered recursion only in Javascript but never in Python. I imagine that recursion should be used in determinate contexts or languages but I don't understand when I should use it and which advantages it gives me.

I would like to see some examples of advantageous usage of recursion, as opposed to iteration.


问:
Dealing with co-workers who do not have a consistent coding style?
What do you when you're working with someone who tends to write stylistically bad code? The code I'm talking about is usually technically correct, reasonably structured, and may even be algorithmically elegant, but it just looks ugly. We've got:

Mixture of different naming conventions and titles (underscore_style and camelCase and UpperCamel and CAPS all applied more or less at random to different variables in the same function)

Bizarre and inconsistent spacing, e.g. Functioncall  (arg1 ,arg2,arg3 );

Lots of misspelled words in comments and variable names

We have a good code review system where I work, so we do get to look over and fix the worst stuff. However, it feels really petty to send a code review that consists of 50 lines of "Add a space here. Spell 'itarator' correctly. Change this capitalization. etc."

How would you encourage this person to be more careful and consistent with these kinds of details?

答:
The code I'm talking about is usually technically correct, reasonably structured, and may even be algorithmically elegant...

Be happy that you got all of that.  Most programmers will maybe give you the first thing on that list.  I think that variable naming and spacing is the least important thing to worry about.


答:
In my experience:-

Large classes are exponentially more difficult to maintain as they get larger.

Small classes are easier to maintain and the difficulty of maintaining a collection of small classes increases arithmetically to the number of classes.

Sometimes large classes are unavoidable a big problem sometimes needs a big class, but, they are much more difficult to read and understand. For well named smaller classes just the name can be enough for comprehension you do not even need to look at the code unless there is a very specific problem with the class.

Title: Are there flavours of OOP where some or all of the SOLID principles are antithetical to clean code?

Body:
I recently had a discussion with a friend of mine about OOP in video game development.

I was explaining the architecture of one of my games which, to my friend's surprise, contained many small classes and several abstraction layers.  I argued that this was the result of me focusing on giving everything a Single Responsibility and also to loosen the coupling between components.

His concern was that the large number of classes would translate to a maintenance nightmare.  My view was that it would have the exact opposite effect.  We proceeded to discuss this for what seemed like centuries, eventually agreeing to disagree, saying that perhaps there were cases where SOLID principles and proper OOP didn't actually mix well.

Even the Wikipedia entry on SOLID principles states that they're guidelines that help to writing maintainable code and that they are part of an overall strategy of agile and adaptive programming.

So, my question is:

Are there cases in OOP where some or all of the SOLID principles do not lend themselves to clean code?

I can imagine right away that the Liskov Substitution Principle could possibly conflict with another flavour of safe inheritance.  That is to say, if someone devised another useful pattern implemented through inheritance, it is quite possible the LSP might be in direct conflict with it.

Are there others?  Perhaps certain types of projects or certain target platforms work better with a less SOLID approach?

Edit:

I'd just like to specify that I'm not asking how to improve my code ;)  The only reason I mentioned a project in this question was to give a little context.  My question is about OOP and design principles in general.

If you're curious about my project, see this.

Edit 2:

I imagined this question would be answered in one of 3 ways:

Yes, there exist OOP design principles which partially conflict with SOLID

Yes, there exist OOP design principles which completely conflict with SOLID

No, SOLID is the bee's knees and OOP will forever be better with it.  But, as with everything, it's not a panacea.  Drink responsibly.

Options 1 and 2 would have likely generated long and interesting answers.  Option 3, on the other hand, would be a short, uninteresting, but overall reassuring, answer.

We seem to be converging onto option 3.


问:
Is there a download limit to ios apps?
With reference to iOS 7.
I couldn't find any Apple documents with regards to this.

Are we able to download any size of documents and manage them ourselves (within our app say < 100MB)?

Example, we roll out new content every month. Thus after downloading contents for this month, we should remove last month's content to save space. Content doesn't have to be backed up and will be stored in Caches folder.

答:
There aren't any download or storage limits for your app (other than available space on the device, of course); if there were, they'd be mentioned in the iOS Data Storage Guidelines. However, you do need to consider how your data files will work with iCloud -- in particular, you should decide whether it's okay for the device to discard your downloaded data when storage gets low.

If it's okay to remove your files, store them in the caches directory. If it's not okay, then you can store them in the documents directory and set the attributes on your files to exclude them from iCloud backup. Also, be sure to store user data separate from the downloaded data so that the user data can be backed up.

With so much data to download, you should consider using the new NSURLSession network API so that you can download data in a background session. This avoids the need to keep the app running while the data is being downloaded.

Title: Is there a download limit to ios apps?


问:
Should I label class diagram variables as private or public?
In my program, I have several class variables whose access specifier is known as private package.

The default accessor specifier in Java is known as private package where it is accessible within the package which the class belongs to.

For the UML class diagram , should I label these variables as public or private? I can't decide because of this concept of private package.

答:
If the tool you use for drawing the UML diagrams doesn't provide the (language specific) access specifier that you need, you can still draw a useful class diagram.

The easiest way is just to leave out all the access specifiers. This doesn't mean that everything is now public, but rather that the diagram doesn't tell you if the members are public, private, package private or something else.

If you do want to show access specifiers, you also could label the package private members as protected members. While technically incorrect, protected access is the closest in meaning to package private access and is usually used only very little, so you could just add a note to your diagram that the protected access specifier should be read as package private.


问:
What is the path to JavaScript mastery?
I know how we start with JavaScript, we cut-and-paste a snippit to gain a little client-side functionality or validation.

But if you follow this path in trying to implement rich interactive behavior, it doesn't take long before you realize that you are creating a Big Ball Of Mud.

So what is the path towards expertise in programming the interaction layer?  What books, tutorials, exercises, and processes contribute towards the ability to program robust, maintainable JavaScript?

We all know that practice is important in any endeavor, but I'm looking for a path similar to the answer here: https://stackoverflow.com/questions/2573135/

答:
A lot of the techniques which make a programmer an expert in a given language can be applied here, though javascript has a couple pearls which allow it to be used to extraordinary effect.  Perhaps one of the biggest hurdles that I've had to surpass using javascript was to undo my "C" programming mentality, which is to say, a thousand tiny functions cramped into a single js file.

Some general advice is to abstract whenever you can, and try to form classes whenever you can to organize general behavior.  Create new js files for any functionality which can be used to good effect in your other js files (within reason) and avoid global variables if at all possible.  I would highly recommend you learn jQuery if you haven't already.  It's a tool I've grown to love and now I wouldn't do without. It's an extremely flexible extension of javascript which lets you simplify your code tremendously which is good for simplicity and being able to code quickly and efficiently as well.  jQuery comes with a large plugin library which allows you to do many things which couldn't be more impressive if you did it in flash.  Check out jQuery UI for an entire theme system for your site, allowing you to effectively modify the entire layout of your site without doing much at all.  Comes included with a lot of animation effects and handy controls commonly used on web sites (date picker, button, progress bar, etc.), most of which can be activated using a single line of javascript.

Hope that helps!

Title: What is the path to JavaScript mastery?


问:
Can I change operator precedence and associativity in C++?
As the title says, I find it useful to be able to overload operators.  Is it possible to also change the way the operators are parsed by specifying the precedence and associativity of overridden operators?</p>

答:
After reading some of the answers I think that, yes, it's time for me to look for down-votes.

Does << represent bit shift with std::ostream ?

Does + represent an arithmetic addition with std::string?

Does * represent dereference in boost::spirit?

Despite this well established fact, there are still people claiming that overloading operator makes the code unreadable, and hence you should not ... blah blah ... and them must not ... blah blah ... and allowing to change precedence.

I find these arguments simply incoherent.

Operators are what makes entity to form expression that together defines an algebra.
If an entity is not numeric, there is no need (I mean mathematical need) that such an algebra has to follow the same rule of natural numbers.

One of the reason that overloaded operators makes code hard to read is just because they are constrained to stay into the int semantic rules, even for things that do not have integer semantics and hence don't need that same syntax.

The answer to the question is:

NO: you cannot change precedence because the language specification doesn't allow it. Full stop.

And if you want to know why, you have to look at what the language is for.

C++ is already an complex language to parse and to translate.
 By admitting "flex operators" (or even the definition of arbitrary infix-functions, like **, <>,  <->, etc) the expression parser cannot anymore be deployed aside of types, and that was argued by language designer as a "feature with negative tradeoff" (it cost more to be deployed that the advantage it will ever give in real world). It's just "echonomy", not "morality".

All the "moral" aspect (don't do it because it hurts me) have nothing to do with the language and the operator abuse (I can even abuse of for and use it instead of if, but the problem is me , not the for keyword. bashing it makes no sense as makes no sense to bash variable precedence even without knowing a proper use of it, for the simple reason that there cannot be a use - no matter if bad or good - being such a thing prohibited at the origin.) and are just related to language marketing.

C++ operator overloading was introduced to let scientists define private algebraic types. It is normal for them to ask more flexibility in defining and using symbols.

The Java language was defined to standardize coding around OOP. And since not all programmers wannabees are also scientific researchers, Java removed a number of features that can make the language deviate from the OOP paradigm it was philosophically designed around. And to motivate that to newbies, a dogmatic religion claiming "operator considered harmful", "global variables considered harmful" and so on was formalized ad deployed across schools.

And the bash against certain coding practices perfectly common in maths and science began just from there.

It is very simple to teach "no because is bad and makes you go to hell" instead to provide and compare rational ideas. And the result - 20 years later - is that if you do it, you really go to hell because all that religion believers (that nowadays are a huge amount of people) will make your life impossible.

And since Java became the first language newbies are exposed (and C++ eventually a second one) and its paradigms taught as dogmas to students, when those students become programmers they end up applying those "dogmas" to anything by an innate "extension".

After all no-one can give a rational reason abut his favorite football team. it just happen to be when you start follow it. There are no "technical reasons". Just passion (dogmas) and the stress to change (OOP methods forced even outside OOP context)

The reason you cannot change precedence is simply that the world retains that changing that dogma will cause too much stress to too much believers. But rationally speaking, there is no reason you can believe differently and makes you define a language with more freedom in usage.


问:
Practices for domain models in Javascript (with frameworks)
This is a question I've to-and-fro'd with for a while, and searched for and found nothing on: what're the accepted practices surrounding duplicating domain models in Javascript for a web application, when using a framework like Backbone or Knockout?

Given a web application of a non-trivial size with a set of domain models on the server side, should we duplicate these models in the web application (see the example at the bottom)? Or should we use the dynamic nature to load these models from the server?

To my mind, the arguments for duplicating the models are in easing validation of fields, ensuring that fields that expected to be present are in fact present etc. My approach is to treat the client-side code like an almost separate application, doing trivial things itself and only relying on the server for data and complex operations (which require data the client-side doesn't have). I think treating the client-side code like this is akin to separation between entities from an ORM and the models used with the view in the UI layer: they may have the same fields and relate to the same domain concept, but they're distinct things.

On the other hand, it seems to me that duplicating these models on the server side is a clear violation of DRY and likely to lead to differing results on the client- and server-side (where one piece gets updated but the other doesn't). To avoid this violation of DRY we can simply use Javascripts dynamism to get the field names and data from the server as and when they're neeed.

So: are there any accepted guidelines around when (and when not) to repeat yourself in these situations? Or this a purely subjective thing, based on the project and developer(s)?

Example

Server-side model

```<code>class M
{
    int A
    DateTime B
    int C
    int D = (A*C)
    double SomeComplexCalculation = ServiceLayer.Call();
}
</code>```

Client-side model

```<code>function M(){
    this.A = ko.observable();
    this.B = ko.observable();
    this.C = ko.observable();
    this.D = function() { return A() * C(); }
    this.SomeComplexCalculation = ko.observalbe();
    return this;
}l
M.GetComplexValue = function(){
    this.SomeComplexCalculation(Ajax.CallBackToServer());
};
</code>```

I realise this question is quite similar to this one, but I think this is more about almost wholly untying the web application from the server, where that question is about doing this only in the case of complex calculation.

答:
Your actual question is kinda more general so it's hard to answer, but your form validation example is a little bit more specific, so I will try to stick with that one.

As you said you should always be DRY, as much as possible. That's a good thing to keep in mind as a developer. However you should distinguish between the things that they are similar and you should avoid repeating them with the things that they does similar things, but they have different Purposes.

Let's get to your form validation example. The purpose of your validation code on the server is to make sure that you have the user's email address for example to put into the database. So as it's a must for your registration process to have the email address of the user, you're checking that during the registration process.

But what is the purpose of your client-side JavaScript code? Yes, it does the validation on the email input field, but the whole idea is: To check if the user has already entered their email address, if not show them an alert BEFORE sending it to the server! So the purpose of your client-side form validation is to stop sending useless data to the server and show an error message after a few seconds to resend the application form again. Why? because it's annoying for users. Now do you think you should keep your form validation function only on the server? No, because they have different purposes.

The purpose of the form validation on the client-side is not I can't trust users, let's check it out, but it's more of a UX thing where you're trying to avoid communicate with server just to get the validation error message; However the purpose of the form validation on the server-side is that I can't trust the users, let's see what they're asking me to do, and a User can be an API request as well -- without any human-user on the client-side.

If you look at it like this, your form validation example would be totally fine, without making you feel WET.

Regarding your actual question, don't try to keep everything on the server or everything on the client; It really depends to the task. Let say if I need to parse a big-big CSV file for the user and I have only a hundred users on the website and I know that I have mobile users, then I can parse that file on the server and then output a proper easy-to-digest markup to the client. However if I have millions of users, then I'd try to parse the file on their machines -- using their web-browsers to use their processing power to avoid burning out our server. So the the parsing functionality could be either on the server or client, whatever makes more sense.

However if you're not sure where to keep your things, then I'd say keep them on the server and then serve the results to the users -- avoid duplicated code on both server and client.


问:
Do we do white box testing on methods or on an overall program?
I am very confused about white box testing.

A simplified version of the example: the entire system consists of three methods - methodA(), methodB(), methodC().

The program starts from methodA(), and methodB() requires input from methodA() and methodC() requires input from methodB().

Do we create 3 white box tests, one for each method, or do we create one white box test for the entire system?

答:
I'm assuming you are writing automated tests using an xUnit framework of some kind. If that is the case, the ideal situation is usually where each function is tested individually. This gives you several advantages:

defect localization - when something goes wrong you know exactly where in the code it happened.

more control over test input. You can test your code for adverse input more easily if you can control the exact input each function is tested for.

If you're in a position to choose, a good rule of thumb is to prefer a higher level of granularity for unit tests


问:
Ensure that each class has only one responsibility, why?
According to Microsoft documentation, the Wikipedia SOLID principe article, or most IT architects we must ensure that each class has only one responsibility. I would like to know why, because if everybody seems to agree with this rule nobody seems to agree about the reasons of this rule.

Some cite better maintenance, some say it provides easy testing or makes the class more robust, or security. What is correct and what does it actually mean? Why does it make maintenance better, testing easier or the code more robust?

答:
Is easy to create code to fix a particular problem. Is more complicated to create code that fixes that problem while allowing later changes to be made safely. SOLID provides a set of practices that makes the code better.

As to which one is correct: All three of them. They are all benefits of using single responsibility and the reason that you should use it.

As to what they mean:

Better maintenance means that is easier to change and doesn't change as often. Because there is less code, and that code is focused on something specific, if you need to change something that is not related to the class, the class doesn't need to be changed. Furthermore, when you need to change the class, as long as you don't need to change the public interface, you only need to worry about that class and nothing else.

Easy testing means fewer tests, less setup. There are not as many moving parts on the class, so the number of possible failures on the class is smaller, and therefore fewer cases that you need to test. There will be fewer private field/members to set up.

Because of the two above you get a class that changes less and fails less, and therefore is more robust.

Do try to create code for a while following the principle, and revisit that code later on to do some changes. You will see the massive advantage that it provides.

You do the same to each class, and end up with more classes, all complying with SRP. It makes the structure more complex from the point of view of connections, but the simplicity of each class justifies it.


答:
Especially with such important principle as Single Responsibility, I would personally expect that there are many reasons why people adopt this principle.

Some of those reasons might be:

Maintenance - SRP ensures that changing responsibility in one class doesn't affect other responsibilities, making maintenance simpler. That is because if each class has only one responsibility, the changes done to one responsibility are isolated from other responsibilities.

Testing - If a class has one responsibility, it makes it much easier to figure out how to test this responsibility. If a class has multiple responsibilities, you have to make sure you are testing the correct one and that the test is not affected by other responsibilities the class has.

Also note that SRP comes with a bundle of SOLID principles. Abiding by SRP and ignoring the rest is just as bad as not doing SRP in the first place. So you should not evaluate SRP by itself, but in the context of all the SOLID principles.

Title: Ensure that each class has only one responsibility, why?

Body:
According to Microsoft documentation, the Wikipedia SOLID principe article, or most IT architects we must ensure that each class has only one responsibility. I would like to know why, because if everybody seems to agree with this rule nobody seems to agree about the reasons of this rule.

Some cite better maintenance, some say it provides easy testing or makes the class more robust, or security. What is correct and what does it actually mean? Why does it make maintenance better, testing easier or the code more robust?


问:
What do we call the process of changing hard-coded codes into soft-coded codes?
Is there a specific term to call the process of modifying hard-coded codes into soft-coded codes? I have to report what I am doing to the Project manager, shall I just put "modifying hard-coded codes into soft-coded codes"?

Example of "hard-coded codes"

```<code>int random(){
return 42;
}
</code>```

Example of "soft-coded codes"

```<code>int random(){
return Random.nextInt();
}
</code>```

hard coded codes might fulfill requirements for a set of inputs, but it is not flexible.

EDIT: Accepted as Code Refactoring.

答:
It depends on whenever you are changing behavior of the program as a whole. If you are changing a behavior then it is either "Bug Fixing" or "Adding a new feature". In your example, random always returning 42 could be considered bug so replacing it with Random.nextInt() is fixing this bug. On the other hand, if you are replacing hard-coded values with values that are supplied from the outside. For example replacing hard-coded  values with values read from config file is adding new feature of being able to configure the software from the outside.

On the other side, if you are not changing behavior of the program and just cleaning up the code, then that is called Refactoring. And it is generally done to increase quality of code without changing what the program does.


问:
What can slow a developer down?
What things tend to slow a developer down?

Please try to refrain from posting answers that:

are slow now but useful in the feature. (TDD, Refactoring, ...)

list a distraction.

答:
Avoid everything that gets you out of "the zone". That means your email inbox, your twitter popup application, your corporate chat, etc.

Having a quiet working condition means avoiding that desktop noise too.

Title: What can slow a developer down?


问:
How to avoid excessive method overloading?
We have quite a lot of places in the source code of our application , where one class has many methods with same names and different parameters. Those methods always have all the parameters of a 'previous' method plus one more.

It's a result of long evolution (legacy code) and this thinking (I believe):

"There is a method M that does thing A. I need to do A + B. OK, I know ... I will add a new parameter to M, create a new method for that, move code from M to the new method with one more parameter, do the A + B over there and call the new method from M with a default value of the new parameter."

Here is an example (in Java-like-language):

```<code>class DocumentHome {

  (...)

  public Document createDocument(String name) {
    // just calls another method with default value of its parameter
    return createDocument(name, -1);
  }

  public Document createDocument(String name, int minPagesCount) {
    // just calls another method with default value of its parameter
    return createDocument(name, minPagesCount, false);
  }

  public Document createDocument(String name, int minPagesCount, boolean firstPageBlank) {
    // just calls another method with default value of its parameter
    return createDocument(name, minPagesCount, false, "");
  }

  public Document createDocument(String name, int minPagesCount, boolean firstPageBlank, String title) {
    // here the real work gets done
    (...)
  }

  (...)
}
</code>```

I feel like this is wrong. Not only that we can't keep adding new parameters like this forever, but the code hard to extend/change because of all the dependencies between methods.

Here are few ways how to do this better:

Introduce a parameter object:

```<code>class DocumentCreationParams {

  String name;
  int minPagesCount;
  boolean firstPageBlank;
  String title;

  (...)
}

class DokumentHome {

  public Document createDocument(DocumentCreationParams p) {
    // here the real work gets done
    (...)
  }
}
</code>```

Set the parameters to the DocumentHome object before we call createDocument()

```<code>  @In
  DocumentHome dh = null;

  (...)

  dh.setName(...);
  dh.setMinPagesCount(...);
  dh.setFirstPageBlank(...);

  Document newDocument = dh.createDocument();
</code>```

Separate the work into different methods and call them as needed:

```<code>  @In
  DocumentHome dh = null;

  Document newDocument = dh.createDocument();
  dh.changeName(newDocument, "name");
  dh.addFirstBlankPage(newDocument);
  dh.changeMinPagesCount(new Document, 10);
</code>```

My questions:

Is the described problem really a problem?

What do you think about suggested solutions? Which one would you prefer (based on your experience)?

Can you think of any other solution?

答:
Maybe try the builder pattern? (note: fairly random Google result :)

```<code>var document = new DocumentBuilder()
                   .FirstPageBlank()
                   .Name("doc1final(2).doc")
                   .MinimumNumberOfPages(4)
                   .Build();
</code>```

I cannot give a full rundown of why I prefer builder over the options you give, but you have identified a large problem with a lot of code. If you think you need more than two parameters to a method you probably have your code structured wrongly (and some would argue one!).

The problem with a params object is (unless the object you create is in some way real) you just push the problem up a level, and you end up with a cluster of unrelated parameters forming the 'object'.

Your other attempts look to me like someone reaching for the builder pattern but not quite getting there :)

Body:
Maybe try the builder pattern? (note: fairly random Google result :)

var document = new DocumentBuilder()
                   .FirstPageBlank()
                   .Name("doc1final(2).doc")
                   .MinimumNumberOfPages(4)
                   .Build();

I cannot give a full rundown of why I prefer builder over the options you give, but you have identified a large problem with a lot of code. If you think you need more than two parameters to a method you probably have your code structured wrongly (and some would argue one!).

The problem with a params object is (unless the object you create is in some way real) you just push the problem up a level, and you end up with a cluster of unrelated parameters forming the 'object'.

Your other attempts look to me like someone reaching for the builder pattern but not quite getting there :)


问:
Why are JOINS deprecated for a in-memory database?
Correct me if I'm misunderstanding. Refer to the following sentence:

Stack Overflow copied a key part of the Wikipedia database design.
  This turned out to be a mistake which will need massive and painful
  database refactoring to fix. The refactorings will be to avoid
  excessive joins in a lot of key queries. This is the key lesson from
  giant multi-terabyte table schemas (like Google’s BigTable) which are
  completely join-free. This is significant because Stack Overflow's
  database is almost completely in RAM and the joins still exact too
  high a cost.1

Actually I'm trying to pass from the interest on single technology like Asp.net MVC to architectures design.

Can you better clarify the quoted sentence?

[1] http://highscalability.com/stack-overflow-architecture

答:
You've misread the directionality of the quote.

JOINs are generally discouraged for high-volume systems, because they are expensive (because of I/O being necessary more than one table). SO put their database into RAM specifically to avoid being hit by double disk I/O costs, and it turns out that even without physical I/O, the double table searching is still too slow. That shows you just how inefficient JOINs are on large volumes of data.


答:
Better maintenance, easy testing, faster bug-fixing are just (very pleasant) outcomes of applying SRP. The main reason (as Robert C. Matin puts it) is:

A class should have one, and only one, reason to change.

In other words, SRP raises change locality.

SRP also promotes DRY code. As long as we have classes that have only one responsibility, we may choose to use them anywhere we want. If we have a class that has two responsibilities, but we need only one of them and second is interfering, we have 2 options:

Copy-paste the class into another and maybe even create another multi-responsibility mutant (raise technical debt a little bit).

Divide the class and make it as it should be in the first place, which may be expensive due to extensive usage of the original class.


问:
Domain driven design and WCF services architecture
I am trying to figure out how to architecture my project in the DDD paradigm (a complete beginner in DDD) and stumbled upon a problem about the implementation of the web services... These are some options that I see:

Fat client, Fat server (option 1):

Server:

Repository layer: talks to database and can return domain objects.

Domain layer: contains domain objects with business logic and validations.

Service layer: acts like a façade to the domain layer.

WCF layer: exposes the service layer to web methods. It maps domain objects to appropriate DTO objects.

Client:

Infrastructure layer: talks to server through WCF services. It maps DTO objects back to domain objects.

Domain layer: contains domain objects with business logic and validations.

Service layer: acts like a façade to the domain layer.

UI layer (WinForms): uses service layer to communicate with domain objects.

Good: because the domain layer is both on client and on server, the validations happens on both (good for clients - reduces number of calls to the server, good for server - because of 'never trust the user data').

Bad: validation happens twice, a lot of mapping needed (for example a simple query to the database: domain (returned by repository) -> DTO (needed for WCF) -> domain (needed by domain layer on client) -> DTO (for WinForms). Any change in the domain should be deployed to server and client at the same time. Complicated?

Fat client, thin server (option 2):

Server:

Repository: talks to database and returns DTO objects.

WCF layer: exposes the database calls to web methods.

Client: Exactly the same as in option 1.

Good: on the client I can treat WCF services as a regular repository which returns DTO objects. Simpler as option nr. 1.

Bad: is it OK that the repository works on DTO-s instead of domain objects? Also - server doesn't perform any validation so it has to trust clients about the data.

Thin client, fat server (option 3):

Server: Exactly the same as in option 1.

Client:

Infrastructure layer: talks to server through WCF services.

UI layer (WinForms): uses presenters to communicate with the server via WCF calls in infrastructure layer.

Good: all domain logic is on the server.

Bad: the client doesn't contain any validation, so it can make a lot of unnecessary calls to the server.

I am leaning toward my first option, but it looks like I am overcomplicating things... Any advice or other options?

答:
I'd go with Option 3, with the following notes:

Try and reduce the amount of domain logic that your clients need to know to get the job done. Create services that expose that data in meaningful (to your clients) ways, so that you can request collections of domain objects which fulfil certain criteria, rather than doing that crunching on your client.

Validation should be considered optional on the client-side as, you can never guarantee that future client implementations are going to be done properly. Therefore, always validate on the server side as if it hadn't been done elsewhere. Of course, clients should be validating on the client-side too.

Rather than mapping the WCF data back to full domain objects on the client side, consider mapping them to simpler ViewModel-type objects - a slimmed down version of your full domain objects only containing properties appropriate to the client - makes client programming simpler.

The problem you're still faced with is lots of mapping. I guess this price is worth paying (and made easier with a tool such as AutoMapper) because removing the client dependency on your domain model gives you breathing room to change your domain, tweak the mapping, without breaking any client code.


问:
Git work-flow for uncertain premise (pending decision)
I am not quite sure, how to name my problem. But I will start with how I usually used git.

I am working as a single developer on one git repository. Usually I make feature-branches from master, and merge them back into master, when the feature is finished. When meanwhile another feature-branch was merged into master, I rebase the other branch on master, before merging.

That worked very good, until recently. One dependency I have in my project, needs an update. But it was not yet decided how this update will be implemented. But I can simulate the new behavior quite simply.

So I branched from master, and simulated that fix. So when the actual fix is available and merged into master, all changes above can be rebased back on master. But the decision on that fix is still pending, and my branches are stacking up:

```<code>* ee8d0ab (HEAD, featureTwo)
* e659932
* 27986c0 (featureOne)
* f0011e6
* d4187cf
* 552e35a
* 37d597f (simulatedFix)
* e0eb3d0 (origin/master, master)
* b06583c
* d295b3e
</code>```

I feel, that this is not good. It feels like I am building up dept. Imagine how this would look at featureTen, or featureTwenty.

What are the possible drawbacks of this method? And what is the best way, to handle this situation?

答:
Create a new development branch - let's call it "dev-with-dep". That branch will be rebased against master, and all the feature branches that depend on the new dependency will be rebased against dev-with-dep and merged into it when they're done.

The dependency update branch itself will be rebased against dev-with-dep(after dev-with-dep is rebased against master, ofcourse) and merged into it whenever you reach a state you want to rebase into the other feature branches.

Once the dependency can be merged back to master you do it via dev-with-dep(which contains all the features that you finished) the other feature branches will again be rebased against master.

That way you don't get a stack of finished feature branches that wait for the dependency - they all await neatly in dev-with-dep. Also, since features that depend on the dependency update are merged into dev-with-dep when they are done, you can resolve merge conflicts between them as early as you merge one. That means that if feature A is merged and feature B isn't:

If both A and B don't depend on the new dependency - A is merged into master and B rebases and solves the conflict.

If both A and B depend on the new dependency - A is merged into dev-with-dep and B rebases and solves the conflict.

If A doesn't depend on the new dependency but B does - A is merged into master, dev-with-dep is rebased against master, and B rebase againt dev-with-dep and solves the conflict.

If A depends on the new dependency but B doesn't - nothing you can do here, as A is merged into dev-with-dep which B can not yet access.

Still - I can't think of any method that allows you to solve that last case early, so my solution remains "optimal".