问:
JSON - Ruby objects key naming
Ruby object has method/property:

```<code>def tentakles_count
  8
end
</code>```

JavaScript object has key/property:

```<code>{ justEnough: true }
</code>```

Now, when JavaScript gets serialised ruby object via XHR or WebSocket, developer has to use alien naming convention to access tentacles_count.

The same goes for Ruby, when it gets json object POSTed, developer has to use alien naming convention to access justEnough.

What would you do to deal with this little imperfection without going too crazy?

答:
Ruby and its commonly used libraries and gems tend to blur the lines between method/property and key/property using attr_accessor, essentially giving an object both a property and getter/setter methods in one line. Either explicitly or implicitly, you'd have

```<code>def tentacles_count
  @tentacles_count
end

def tentacles_count=(n)
  @tentacles_count = n
end

def to_json
  # loop over all instance variables and convert them to json key-value pairs
end
</code>```

(variables beginning with @ have object scope instead of method scope).

If it's not possible to do exactly this (say tentacles_count needs to dynamically count tentacles while you're in Ruby), to_json can be defined so as to include public methods as keys and their return values as values.

On the flip side, a json object parses most naturally into a Ruby Hash object (a dictionary). The syntax for accessing hashes is different from method notation (obj['justEnough']), but there are several library gems that will let you use the familiar convention if you really want to. I think the best pattern is to use the hash as an argument to an initializer: for example, OpenStruct.

Obviously there is no fully general answer to this question: there is, and of rights ought to be, awkwardness at the interface between different high-level languages. You can look at these little imperfections as a reminder to avoid tight coupling or duplicated logic between the different systems.

Title: JSON - Ruby objects key naming

Body:
Ruby and its commonly used libraries and gems tend to blur the lines between method/property and key/property using attr_accessor, essentially giving an object both a property and getter/setter methods in one line. Either explicitly or implicitly, you'd have

def tentacles_count
  @tentacles_count
end

def tentacles_count=(n)
  @tentacles_count = n
end

def to_json
  # loop over all instance variables and convert them to json key-value pairs
end

(variables beginning with @ have object scope instead of method scope).

If it's not possible to do exactly this (say tentacles_count needs to dynamically count tentacles while you're in Ruby), to_json can be defined so as to include public methods as keys and their return values as values.

On the flip side, a json object parses most naturally into a Ruby Hash object (a dictionary). The syntax for accessing hashes is different from method notation (obj['justEnough']), but there are several library gems that will let you use the familiar convention if you really want to. I think the best pattern is to use the hash as an argument to an initializer: for example, OpenStruct.

Obviously there is no fully general answer to this question: there is, and of rights ought to be, awkwardness at the interface between different high-level languages. You can look at these little imperfections as a reminder to avoid tight coupling or duplicated logic between the different systems.


问:
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?

答:
I call BS on everyone who said that variable name spelling errors and formatting don't matter. Obviously, they've only read their own code. And notice that word right there - read. Imagine reading a book with lots of spelling mistakes, mish-mashed formatting, inconsistent line spacing, and various other laziness prevalent in a lot of source code. It would be tedious.

For a profession where your syntax must be 100% correct to work, there is simply no excuse for any real developer to not have a clean, consistent code style. Anything else is sloppiness and laziness. I always question sloppily formatted code's correctness in implementation.

ContentLicense: CC BY-SA 2.5


问:
Are closures considered impure functional style?
Are closures considered impure in functional programming?

It seems one can generally avoid closures by passing values directly to a function. Therefore should closures be avoided where possible?

If they are impure, and I am correct in stating that they can be avoided, why do so many functional programming languages support closures?

One of the criteria for a pure function is that "The function always evaluates the same result value given the same argument value(s)."

Suppose

```<code>f: x -> x + y
</code>```

f(3) will not always give the same result. f(3) depends on the value of y which is not an argument of f. Thus f is not a pure function.

Since all closures rely on values which are not arguments, how is it possible for any closure to be pure? Yes, in theory the closed value could be constant but there is no way of  knowing that just by looking that the source code of the function itself.

Where this leads me to is that the same function may be pure in one situation but impure in another. One cannot always determine if a function is pure or not by studying its source code. Rather, one may have to consider it in context of its environment at the point when it is being called before such distinction can be made.

Am I thinking about this correctly?

答:
Others have covered the general question nicely in their answers, so I'll only look at clearing the confusion you signal in your edit.

The closure doesn't become an input of the function, rather it 'goes' into the function body. To be more concrete, a function refers to a value in the outer scope in its body.

You are under the impression that it makes the function impure. That is not the case, in general. In functional programming, the values are immutable most of the time. That applies to the closed-over value as well.

Let's say you have a piece of code like this one:

```<code>let make y =
    fun x -> x + y
</code>```

Calling make 3 and make 4 will give you two functions with closures over make's y argument. One of them will return x + 3, the other x + 4. They are two distinct functions however, and both are pure. They were created using the same make function, but that's it.

Note the most of the time a few paragraphs back.

In Haskell, which is pure, you can only close over immutable values. There is no mutable state to close over. You are sure to get a pure function that way.

In impure functional languages, like F#, you can close over reference cells and reference types, and get an impure function in effect. You are right in that you have to track the scope within which the function is defined to know if it's pure or not. You can easily tell if a value is mutable in those languages, so it's not much of a problem.

In OOP languages that support closures, like C# and JavaScript, the situation is similar to impure functional languages, but tracking the outer scope gets more tricky since variables are mutable by default.

Note that for 2 and 3, those languages don't offer any guarantees about purity. The impurity there is not a property of the closure, but of the language itself. Closures don't change the picture much by themselves.

ContentLicense: CC BY-SA 3.0

Body:
Others have covered the general question nicely in their answers, so I'll only look at clearing the confusion you signal in your edit.

The closure doesn't become an input of the function, rather it 'goes' into the function body. To be more concrete, a function refers to a value in the outer scope in its body.

You are under the impression that it makes the function impure. That is not the case, in general. In functional programming, the values are immutable most of the time. That applies to the closed-over value as well.

Let's say you have a piece of code like this one:

let make y =
    fun x -> x + y

Calling make 3 and make 4 will give you two functions with closures over make's y argument. One of them will return x + 3, the other x + 4. They are two distinct functions however, and both are pure. They were created using the same make function, but that's it.

Note the most of the time a few paragraphs back.

In Haskell, which is pure, you can only close over immutable values. There is no mutable state to close over. You are sure to get a pure function that way.

In impure functional languages, like F#, you can close over reference cells and reference types, and get an impure function in effect. You are right in that you have to track the scope within which the function is defined to know if it's pure or not. You can easily tell if a value is mutable in those languages, so it's not much of a problem.

In OOP languages that support closures, like C# and JavaScript, the situation is similar to impure functional languages, but tracking the outer scope gets more tricky since variables are mutable by default.

Note that for 2 and 3, those languages don't offer any guarantees about purity. The impurity there is not a property of the closure, but of the language itself. Closures don't change the picture much by themselves.


问:
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?

答:
The best way to understand the importance of these principles is to have the need.

When I was a novice programmer, I didn't give much thought to design, in fact, I didn't even know design patterns existed. As my programs grew, changing one thing meant changing many other things. It was hard to track down bugs, the code was huge and repetitive.  There wasn't much of an object hierarchy, things were all over the place.  Adding something new, or removing something old would bring up errors in the other parts of the program.  Go figure.

On small projects, it might not matter, but in big projects, things can be very nightmarish.  Later when I came across the concepts of design patters, I said to myself, "oh yah, doing this would've made things so much easier then".

You really can't understand the importance of design patterns until the need arises.  I respect the patterns because from experience I can say they make code maintenance easy and code robust.

However, just like you, I'm still uncertain about the "easy testing", because I haven't had the need to get into unit testing yet.


问:
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?

答:
Here is a simple solution.

Track the features that this person has implemented and go to each commit on that branch which was updated per feature. Take this commit and merge it with the master repo.

Let me break this down in the form of an example.

```<code>> Let: Branch A be the branch from the master
>      Branch A+ = Branch A + new feature 1
>      Branch A++ = Branch A + new feature 2
>      and so on and so forth
>
> What you need to do is to go back to: Branch A+
>
> Take Branch A+ and merge it with Master.
>
> Now go to Branch A++ and merge it with (Master + Branch A+).
>
> Repeat until you've reached the final Branch A+...+ that is stable.
</code>```

This method may sound counter-intuitive at first, but if you merge each separate new feature on its own with the master, it becomes easy to cycle between the master branch "per added feature"

What ways can we avoid branches getting a very large number of commits away from master in the future?

I think my solution above indicates what future method you should be adopting. Go with a per feature or per task method for each branch.

I would suggest using an approach of:

pre-master and master

master: Final/production level. Is modified not often. Is considered always stable

pre-master: the area where a new feature is added to existing code. Is tested thoroughly to work with existing code-base, and is the place where other branches can fork for new feature implementation.

You should also try bundling features and aiming for version-targeting.

Version-targeting: Specify an arbitrary number that will act as the placeholder for the master branch. "In V1.0.0, we will want to achieve X, Y, Z features. V1.0.0 will also have all these functionalities available: ..."

By maintaining a version against master, it can also be a way of keeping "master" stable and production-ready at all times.

ContentLicense: CC BY-SA 4.0

Title: Dealing with a large pull request

Body:
Here is a simple solution.

Track the features that this person has implemented and go to each commit on that branch which was updated per feature. Take this commit and merge it with the master repo.

Let me break this down in the form of an example.

> Let: Branch A be the branch from the master
>      Branch A+ = Branch A + new feature 1
>      Branch A++ = Branch A + new feature 2
>      and so on and so forth
>
> What you need to do is to go back to: Branch A+
>
> Take Branch A+ and merge it with Master.
>
> Now go to Branch A++ and merge it with (Master + Branch A+).
>
> Repeat until you've reached the final Branch A+...+ that is stable.

This method may sound counter-intuitive at first, but if you merge each separate new feature on its own with the master, it becomes easy to cycle between the master branch "per added feature"

What ways can we avoid branches getting a very large number of commits away from master in the future?

I think my solution above indicates what future method you should be adopting. Go with a per feature or per task method for each branch.

I would suggest using an approach of:

pre-master and master

master: Final/production level. Is modified not often. Is considered always stable

pre-master: the area where a new feature is added to existing code. Is tested thoroughly to work with existing code-base, and is the place where other branches can fork for new feature implementation.

You should also try bundling features and aiming for version-targeting.

Version-targeting: Specify an arbitrary number that will act as the placeholder for the master branch. "In V1.0.0, we will want to achieve X, Y, Z features. V1.0.0 will also have all these functionalities available: ..."

By maintaining a version against master, it can also be a way of keeping "master" stable and production-ready at all times.


问:
Why do JavaScript frameworks/libraries have functions which already exist in pure JavaScript?
I wonder why frameworks/libraries have their own helpers although they exist natively already.

Let's take jQuery and AngularJS. They have their own each iterator functions:

jQuery.each()

angular.forEach()

But we have Array.prototype.forEach.

Similarly,

jQuery.parseJSON()

angular.fromJson()

But we have the JSON.parse() function in vanilla JavaScript.

答:
Because when those libraries were written, some major browsers did not support those features.  Once written and used, these features cannot be removed from these libraries without breaking many applications.

(In this case, "major browser" means a browser that still has large market share, which includes older versions of browsers like Internet Explorer, where large number of users don't necessarily upgrade to the latest version.)


答:
Because different browsers have different implementations and features baked in their JavaScript engine. The same "vanilla-JS" code could run differently on two different browsers, or even two different versions of the same browser.

The abstraction layer provided by popular JS libraries is a way around this. Behind the scenes, it works around the different browsers capacities and limitations and offers a unified, easy to use API on top of those. This, in turn, allows common operations such as getting a DOM object or fetching JSON data to be consistent, efficient and browser-agnostic.

This makes life a lot easier for developers who can now focus on what code should do, rather than how it should be written to work with browser X or Y.

Title: Why do JavaScript frameworks/libraries have functions which already exist in pure JavaScript?

Body:
I wonder why frameworks/libraries have their own helpers although they exist natively already.

Let's take jQuery and AngularJS. They have their own each iterator functions:

jQuery.each()

angular.forEach()

But we have Array.prototype.forEach.

Similarly,

jQuery.parseJSON()

angular.fromJson()

But we have the JSON.parse() function in vanilla JavaScript.


答:
There are a number of reasons, but the the one I like is the approach used by many of the early UNIX programs: Do one thing well.  It is hard enough to do that with one thing, and increasing difficult the more things you try to do.

Another reason is to limit and control side effects.  I loved my combination coffee maker door opener.  Unfortunately, the coffee usually overflowed when I had visitors.  I forgot to close the door after I made coffee the other day and someone stole it.

From the psychological standpoint, you can only keep track of a few things at a time.  General estimates are seven plus or minus two. If a class does multiple things you need to keep track of all of them at once.  This reduces your capability to track what you are doing.  If a class does three things, and you want only one of them, you may exhaust your capability to keep track of things before you actually do anything with the class.

Doing multiple things increases code complexity.  Beyond the simplest code, increasing complexity increases the likelihood of bugs.  From this standpoint you want classes to be as simple as possible.

Testing a class that does one thing is much simpler.  You don't have to verify that the second thing the class does did or did not happen for every test.  You also don't have to fix the broken conditions and retest when one of these tests fails.

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?


问:
How to get money from reluctant client?
I completed this website 4 months ago. (I would like to keep the website anonymous - if this post comes up on google search by customers, it will have a negative impact on their business). We did several iterations, the client was very demanding (and nosy), I complied with every single thing that was wanted, including the font-size of the footer which destroyed the aesthetic looks by quite a bit; (and they messed with the colours too, making it look dangerously childish and unprofessional).

Anyway, the client was very friendly during the whole process. After getting all the requirements I accepted to build the website for £950 and I charged him £150 in advance so he wouldn't want to bail out after I started the work. The requirements kept changing quite a lot, I made adjustments as and completed the website just 5 days late, w.r.t. the agreed date, in-spite all the changes in requirements.

That was four months ago. They have never returned my calls nor replied to my emails since then. How do I get the money back from them? I really need some advice on this, this is the second time someone has not paid me.

Points to be noted:

We did not sign any contract - the client was a friend of a friend.

I still hold the passwords for ftp, cpanel and everything. I don't want to bring the site down; somehow it doesn't seem ethical to me.

I posted this on Stack Overflow and it was closed, I was redirected here.

EDIT

Thank you everyone, for your enormous support. I thought I should include some more details: The client is hosting the site; as in, I made them register and use their own debit card to buy the domain name, webspace and everything, I just have the passwords for his cpanel, and ftp (well, I have access to cpanel that pretty much gives me access to many things).

Now, if I give them a warning, he might change the password to cpanel, but I am fairly sure they doesn't know about ftp's.

UPDATE

I followed Anna Lear's advice and sent the final invoice, on Saturday, with a warning that I will take the site down if he doesn't respond to my email before this Tuesday. They havn't replied to my emails yet, but I will let you know how this goes. Thanks much for your support. I plan to put up a holding page as Darknight suggested after Tuesday.

Points

I don't have a server space of my own, however I have few web spaces of my clients but I don't want to use them for this kind of purpose.

RESULTS

After my follow up of final invoice and warning, the client refused to anything. workman's advice seemed to be the most sensible to me. I mirrored the site to my own webspace, logged into his CPanel and forwarded the website to my site. Once that was done, I put up a holding page on my site so anyone going to the website would see a holdup page (nothing fishy, just an Under Construction page). Of course, this was all very weak in the sense that if my client knew about CPanel he could just remove the redirection. But, I had this second chance to get back to him and I was relying on him not knowing anything.

Two hours later, I got a call from the said client, (and  acting as if they did not get any of my voice mails or emails) and asked me to get the site back up. I, of-course, said I had to be paid and two days after that I received a bank transfer. The site's back up and running now.

Just wanted to say thank you all very much, I was very desperate when I had started this question. You are the best, not only you told me to learn the lesson (which I did) you also gave me a very very good solution that seemed to be very ethical (almost) to me.

A BIG thank you to workman!

If I could choose more than once answer, I would have chosen Anna Lear  too, but since I followed workman's advice I had to pick that up. People who made a point about not taking the site down without consulting a lawyer, thanks a lot.

答:
You mentioned "After getting all the requirements I accepted to build the website for £950 ".  Did you exchange requirements discussions and the number 950 in EMails?  Do you have Emails of the constant changing requirements requests?  In absence of a contract, I think (please check with a lawyer) these represent an agreement to do the work from both sides, since the client can not deny asking you to do the work.  If you can reproduce the ongoing "negotiation" of requirements and delivery through an EMail trail, a lawyer might be able to prove intent.  I realize the lawyer may cost more than the payment, but this may be your only foundation for the case.

I would agree with the other posters recommending against shutting down the site.  While you have some rights to the software, that doesn't give you the right to directly access his site/servers (since he pays the bill for them) to get your software back.  This would be similar to someone stealing something from me and then I break into their house to get it back.

Title: How to get money from reluctant client?


问:
Is a popular site like www.google.com served up by one computer?
In basic networking, we talk about DNS servers, that they resolve human readable addresses (www.google.com) into an actual IP address. As far as I understand, at least using the basics, an IP address refers to a single device (say a router). Surely, www.google.com cannot be served up by one computer? How is www.google.com distributed across multiple servers?</p>

答:
The simple answer is, its not.

First off, google is not servers by one IP address.  For me, when looking at Google's domain:

```
$ nslookup
> www.google.com
Server:     192.168.1.254
Address:    192.168.1.254#53

Non-authoritative answer:
Name:   www.google.com
Address: 173.194.46.52
Name:   www.google.com
Address: 173.194.46.48
Name:   www.google.com
Address: 173.194.46.49
Name:   www.google.com
Address: 173.194.46.50
Name:   www.google.com
Address: 173.194.46.51
```

It is served by one of those 5 different IP addresses... for me.  However, tossing www.google.com into an online nslookup tool gives me:

```
173.194.115.115
173.194.115.112
173.194.115.116
173.194.115.113
173.194.115.114
```

For you, it could be different.

Google wants to serve its data to me as fast as it can.  So, instead of having me contact a machine in Mountain view, California I am instead contacting a machine that is somewhere closer to me (probably Chicago or Minneapolis for me).

That particular style of dns is known as round robin dns and gives me one of those addresses.  Behind the address there is likely another pool of machines behind another load balancer.  The load balancer is a machine (or set of machines) that takes individual queries and then sends to to another machine (or set of machines) that is least busy.

That said, there's still more machines behind that.  From Computer Weekly, an article from 2009: Single Google search uses 1,000 servers.  I'm not sure if that is still accurate but it gives you an idea that there is not a single computer behind the search.

You may also find Inside Search a useful bit to read - there is lots that can be said about search and how it works.  This Google Talk is a set of slides that is also a good bit to read.

Body:
The simple answer is, its not.

First off, google is not servers by one IP address.  For me, when looking at Google's domain:

$ nslookup
> www.google.com
Server:     192.168.1.254
Address:    192.168.1.254#53

Non-authoritative answer:
Name:   www.google.com
Address: 173.194.46.52
Name:   www.google.com
Address: 173.194.46.48
Name:   www.google.com
Address: 173.194.46.49
Name:   www.google.com
Address: 173.194.46.50
Name:   www.google.com
Address: 173.194.46.51

It is served by one of those 5 different IP addresses... for me.  However, tossing www.google.com into an online nslookup tool gives me:

173.194.115.115
173.194.115.112
173.194.115.116
173.194.115.113
173.194.115.114

For you, it could be different.

Google wants to serve its data to me as fast as it can.  So, instead of having me contact a machine in Mountain view, California I am instead contacting a machine that is somewhere closer to me (probably Chicago or Minneapolis for me).

That particular style of dns is known as round robin dns and gives me one of those addresses.  Behind the address there is likely another pool of machines behind another load balancer.  The load balancer is a machine (or set of machines) that takes individual queries and then sends to to another machine (or set of machines) that is least busy.

That said, there's still more machines behind that.  From Computer Weekly, an article from 2009: Single Google search uses 1,000 servers.  I'm not sure if that is still accurate but it gives you an idea that there is not a single computer behind the search.

You may also find Inside Search a useful bit to read - there is lots that can be said about search and how it works.  This Google Talk is a set of slides that is also a good bit to read.


问:
Is it wrong to have HTML strings within PHP objects, or is it only wrong in controllers?
I've always thought that in typical MVC design it is bad practice to build & concatenate HTML strings in any PHP file or class that isn't strictly a template.

I'm working on a large project with strict guidelines in place, and while it is forbidden to put any HTML code in the PHP controller, it is fair game to have PHP sub-objects that might generate lots of HTML code strings which then get passed into the template.

These "sub-objects" contain additional logic that could change the HTML depending on conditions.

Thus my 2 main questions are:

Is this considered MVC?

Are these objects considered part of the View, or are they a frankenstein of the Model and the View?

Example:

```<code><?php
/* controller.php */
class KittenController {

    protected $view = 'view.html';

    public function render (Request $request) {
        $data = $this->getDynamicData(); // get some data
        $object = $this->getObject();  // get a PHP object
        $this->setField('foo', $data['bar']);
        $this->setField('baz', $object->render());
    }
}
</code>```

```<code><?php
/* object.php */

class Object {
    public function render () {
        $html = '';
        $html .= '<div class="my-cool-html">';
        if ($this->hasDuck()) {
            $html .= '<p>I have a duck...</p>';
        }
        else {
            $html .= '<p>No duck here...</p>';
        }
        $html .= '</div>';

        return $html;
    }
}
</code>```

```<code><!-- an html template -->
<html>
<body>
<div class="blah">
    [[foo]]
</div>
<footer>
    [[baz]]
</footer>
</body>
</html>
</code>```

答:
You need to look at these sub-objects and what logic they contain.

Something has to decide how to mark up the text. As your question makes clear, the controller should not (and in your case, is not) the place where this occurs.

Those sub-objects may be considered part of the view, in that they contain code responsible for assembling the dynamic parts of the view.

If you have data objects that are part of the model, and they emit HTML? That is a violation of the separation of MVC. Some object performs decisions not strictly related to the view (e.g. calculating how many rows in a table) and also emit HTML? Also a violation of the separation.

Sometimes you may find that you are unable to apply MVC or any other pattern 100% due to constraints outside of your control such as language or framework. It is okay to fudge it a little to apply MVC in that case, just document it and try to localize the ugliness to one class or small set of classes. I am not sure if that is what is happening here, however. Just keep in mind that you should try to stick to MVC as much as possible if that is the pattern you have chosen, but it is okay to deviate slightly if there is a good enough reason. It comes down to understanding the principles and how to apply them, then reviewing the code as a team to determine how well it adheres to any particular design pattern. If it does not adhere strictly to MVC, the important question becomes is it worth it to refactor to make it "better" or is the code manageable as-is? But that would be a separate question.


答:
Let the developer who went for a couple of months without merging fix it.  Maybe they can get one big chunk of code to merge, maybe they can get a bunch of little chunks to merge one at a time.  In any case, they should be doing the legwork to fix the problem, since they caused it.

What is the best way to deal with such a situation where one branch is really far away from the others?

In general, don't worry about it: it's the other developer's problem.  If two branches are really too far apart to merge, then they aren't really part of the same project anymore and you have a defacto fork.  If it's an open source project, that may not even be a problem.

If this developer is really brilliant, and their code is better/smarter/more important than the rest of the team combined, then it's worth making it your problem instead of theirs.  Otherwise, it isn't.

To answer the literal question: the best way to deal with this kind of situation is to not get in that kind of situation.

What ways can we avoid branches getting a very large number of commits away from master in the future?

Make sure everyone notices that the developer who went for months without merging is having to fix the problem they caused.  Make sure everyone knows that it's easier to commit to master frequently than infrequently, since fewer changes means fewer opportunities for conflicts.

Make sure that people know that they can pull from master to stay up-to-date with other people's changes.

"If you merge every day, suddenly you never get to the point where you have huge conflicts that are hard to resolve." --Linus Torvalds

That quote is from a talk he gave at Google, here's the transcript, and here's the video.

Title: Dealing with a large pull request

Body:
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?


问:
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/

答:
Before you learn any of the web development details (DOM etc.) learn the core language. You can learn in many ways - books, videos etc. You will, of course, need to read and write code.

ECMAScript (that's the name of the language standard - javascript refers to several implementations) is a very interesting language. It is a dynamic, functional and a prototype based object oriented language, therefore, you should take your time to understand the principles of these paradigms.

Learn using an interactive console in your browser (in Chromium, you can access this by pressing Ctrl+Shift+J) which is similar to tools like IRB and the interactive Python interpreter. This is useful for testing language features and debugging.

Use JSLint to quality check your code.

When you start doing 'real' development using DHTML, make your life easier by using a framework, such as JQuery, to handle the frustrating cross browser issues.

Title: What is the path to JavaScript mastery?


问:
Organising data access for dependency injection
In our company we have a relatively long history of database backed applications, but have only just begun experimenting with dependency injection. I am looking for advice about how to convert our existing data access pattern into one more suited for dependency injection.

Some specific questions:

Do you create one access object per table (Given that a table represents an entity collection)?
One interface per table?
All of these would need the low level Data Access object to be injected, right?

What about if there are dozens of tables, wouldn't that make the composition root into a nightmare?

Would you instead have a single interface that defines things like GetCustomer(), GetOrder(), etc?

If I took the example of EntityFramework, then I would have one Container that exposes an object for each table, but that container doesn't conform to any interface itself, so doesn't seem like it's compatible with DI.

What we do now, in case it helps:

The way we normally manage data access is through a generic data layer which exposes CRUD/Transaction capabilities and has provider specific subclasses which handle the creation of IDbConnection, IDbCommand, etc.

Actual table access uses Table classes that perform the CRUD operations associated with a particular table and accept/return domain objects that the rest of the system deals with.  These table classes expose only static methods, and utilise a static DataAccess singleton instantiated from a config file.

答:
I typically prefer to see interfaces (and injections) that describe actions that can be performed on the domain rather than just raw access into data. For example, I'd rather see a Customer interface that gives access to customer data without revealing the underlying data structure instead of just providing CRUD operations.

But then again, it depends on what level of abstraction you're at. At some point, you do need to access the lower-level CRUD operations. And yes, you may want to be able to inject the actual objects that interact with the database.

When I used Entity Framework 4 for a previous project, we had some test limitations so we moved all the code for the actual database queries into "thin" classes that had no conditional logic. So we ended up relying on the EF contract objects directly and didn't inject them. Instead we injected an abstraction which worked on those objects.

So... for your scenario, you might try creating some "wrapper" classes which provide the interface you want to expose via injection. Or it's also possible to edit the EF code generation to do this for you (though I've forgotten how to do it...)


答:
Fixing the issue of the large pull request is one thing, and there are some good answers regarding that. But as for dealing with branches that get far out of date, you might want to revisit your processes for dealing with team work.

If you're working within an Agile or SCRUM framework, the team should really be asking why the feature wasn't completed and merged as part of the iteration/sprint. If it was "too big" to fit within an iteration, it should have been broken down into smaller chunks.

It also raises a question of code ownership -- within your team, do individual developers own their own work separately, or does the full team work together to ensure that items done?

Of course, the above assumes that your team is within some kind of company structure. If this is an open-source project with volunteer contributors, that's another story. Generally such projects have looser control over workflows, but the onus for generating acceptable pull requests falls more often on the individual contributors.

In many ways this becomes a process question. Maybe your needed process includes checking periodically (weekly? monthly?) for long-running, unmerged branches. Some tools make this simple to check visually; e.g. on github visit the "branches" link and it shows how far ahead/behind each branch is.

Title: Dealing with a large pull request


答:
I'd be tempted to suggest having a private chat and see if both of you could find a root cause:

Is the co-worker rushed and because someone wanted the code yesterday the person is trying to get something working as fast as they can?  This can be an opportunity to inform this person to focus more on quality than speed in their work.  A mantra like, "Take your time," could be useful if this isn't counter-productive.

How does the person view their work?  If there is a sense of pride, then you may have an angle to use in getting one to improve.  If it is just a job that pays the bills, it may be a lot harder to get changes.  Do they know they aren't doing a great job but are so close to it?

Does this person disagree with the conventions and is trying to code in protest?  If so, then you may have a big problem, but this is worth finding out if this is the case or is the person merely lazy?  What kinds of motivation may be useful here,e.g. could you appeal to greed, pride, or some other vice to get the person to improve.  This is sneaky but possibly effective if trying the nice guy route gets one nowhere.

How to Win Friends and Influence People has a few suggestions in terms of being persuasive that may work, such as praising improvements and giving the person a fine reputation to uphold.

As for why this has to be done privately, here are a few reasons:

There is a good chance for humiliation, criticism or other unpleasantness that is better kept behind a door than left out in the open where someone may feel their character is being assassinated.

You want to encourage this other person to open up a bit.  A challenge here is that some people are so guarded it can take a long time to get them to take their walls down.

If possible, I'd suggest trying to do this a little away from the office.  Go out for lunch, take a walk, or do something so that the surroundings are altered enough that the person may feel a bit more comfortable.  This can be a challenge and requires knowing the person, but the idea here is that in the office some people will wear a work mask that isn't likely to be helpful here.

Be prepared for the conversation to get rather heated or ugly, but this could well be a good sign if you can keep the other person engaged and have a good dialogue.  Some people like to keep things out in the open and others may prefer more subtle ways of getting things done.  The key is to make sure you are listening to the other person enough to empathize and try to understand their side.

Title: Dealing with co-workers who do not have a consistent coding style?

Body:
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 whole idea of MVC is Separation of Concern and by introducing any method that builds/generates any form of mark-up like what you are doing in your example, even without directly outputting them, you're violating that. So this is not MVC anymore.

In your example changing the desing/mark-up by a designer needs modification in your object.php by a programmer. Also you might end up with a mess like mark-up is everywhere in your project classes and your actual Views are just the general layout.

If you are not building anything on top of MVC, then of course you can build different layers, structure you application differently and also have some mark-up generated by classes like what you have in your example; However the later approach is not generally recommended.

What I recommend is to re-factor your Object class to something like the following, where you still have the separation of concern applied; Your PHP code inside the render method will take care of the business logic and the proper Partial View will be loaded and returned in the end.

```<code>class PetHelper {

    private $view = null;

    public function render ( Child $child ) {

        if ( true === (bool) $child->hasPuppy() ) {
            $this->view = 'walk-the-puppy.html';
        } else {
            $this->view = 'play-with-kitten.html';
        }

        return $this->view;
    }
}
</code>```

Title: Is it wrong to have HTML strings within PHP objects, or is it only wrong in controllers?

Body:
I've always thought that in typical MVC design it is bad practice to build & concatenate HTML strings in any PHP file or class that isn't strictly a template.

I'm working on a large project with strict guidelines in place, and while it is forbidden to put any HTML code in the PHP controller, it is fair game to have PHP sub-objects that might generate lots of HTML code strings which then get passed into the template.

These "sub-objects" contain additional logic that could change the HTML depending on conditions.

Thus my 2 main questions are:

Is this considered MVC?

Are these objects considered part of the View, or are they a frankenstein of the Model and the View?

Example:

```<code><?php
/* controller.php */
class KittenController {

    protected $view = 'view.html';

    public function render (Request $request) {
        $data = $this->getDynamicData(); // get some data
        $object = $this->getObject();  // get a PHP object
        $this->setField('foo', $data['bar']);
        $this->setField('baz', $object->render());
    }
}
</code>```

```<code><?php
/* object.php */

class Object {
    public function render () {
        $html = '';
        $html .= '<div class="my-cool-html">';
        if ($this->hasDuck()) {
            $html .= '<p>I have a duck...</p>';
        }
        else {
            $html .= '<p>No duck here...</p>';
        }
        $html .= '</div>';

        return $html;
    }
}
</code>```

```<code><!-- an html template -->
<html>
<body>
<div class="blah">
    [[foo]]
</div>
<footer>
    [[baz]]
</footer>
</body>
</html>
</code>```

Body:
The whole idea of MVC is Separation of Concern and by introducing any method that builds/generates any form of mark-up like what you are doing in your example, even without directly outputting them, you're violating that. So this is not MVC anymore.

In your example changing the desing/mark-up by a designer needs modification in your object.php by a programmer. Also you might end up with a mess like mark-up is everywhere in your project classes and your actual Views are just the general layout.

If you are not building anything on top of MVC, then of course you can build different layers, structure you application differently and also have some mark-up generated by classes like what you have in your example; However the later approach is not generally recommended.

What I recommend is to re-factor your Object class to something like the following, where you still have the separation of concern applied; Your PHP code inside the render method will take care of the business logic and the proper Partial View will be loaded and returned in the end.

class PetHelper {

    private $view = null;

    public function render ( Child $child ) {

        if ( true === (bool) $child->hasPuppy() ) {
            $this->view = 'walk-the-puppy.html';
        } else {
            $this->view = 'play-with-kitten.html';
        }

        return $this->view;
    }
}


问:
Why have private static methods?
I just wanted to clear up a question I have. What is the point of having a private static method as opposed to a normal method with private visibility?

I would have thought an advantage to having a static method is that it can be called without an instance of a class, but since its private is there even a point to it being static?

The only reason I can think of is that it helps conceptually understanding the method on the class level as opposed to object level.

答:
Very simple example I can think of is, if you want to do some processing on input arguments (or some manipulation) which are passed to main function.
So in this case if processing is big and same functionality will not be used anywhere else it will make sense to have a private function as it will not be used/called from anywhere else + static as main is static.</p>

Title: Why have private static methods?


答:
The answer is, as others have pointed out, all of them are correct, and they all feed into each other, easier to test makes maintenance easier makes code more robust makes maintenance easier and so forth...

All of this boils down to a key principal -- code should be as small and do as little as necessary in order to get the job done. This applies to an application, a file, or a class just as much as to a function.  The more things that a piece of code does, the harder it is to understand, to maintain, to extend, or test.

I think it can be summed up in one word: scope. Pay close attention to the scope of artifacts, the fewer things in scope at any particular point in an application the better.

Expanded scope = more complexity = more ways for things to go wrong.


问:
What is the main goal of MVVM pattern?
Could you tell me what is the goal of the MVVM pattern? What are the arguments or the reasons I can give to a team and product owner to respect and develop according to this pattern?

I would like a simple answer. Something in one sentence or one word. Is it for

maintenance

security

testing

something else?

答:
My simplistic answer is that in the standard MVC concept, the Model knows nothing about the View. However, on GUI platforms that support data binding, the View needs bind to something that is responsive to changes in what the user sees, and the Model cannot satisfactorily fill that role. Data Binding is a Good Thing, but not easily reconciled with MVC.

The ViewModel is specifically a set of data structures provided for data binding, so that it can contain all the data items required by the View and be updated as necessary, without polluting the Model. In doing so it acts as a layer between the View and Model, where both the Model and ViewModel are updated by the Controller, often via event driven code.

I'm not convinced that Microsoft invented it, but I do think it originated in the Microsoft community, since data binding is a prominent part of Microsoft architectures (particularly those based on XAML).

Wikipedia is pretty good: http://en.wikipedia.org/wiki/Model_View_ViewModel

Title: What is the main goal of MVVM pattern?


问:
How should one debug a PHP web application securely without exposing secrets to competitors?
Recently I made a program. I forget to delete 2 line of codes. That mistake cost me $800 per day every day.

I was programming with PHP. If a visitor uses proxy it redirect somewhere else. Using debugger was impossible because some code contains ioncube. Because the program simply redirect somewhere else no matter what, it's hard to see which part of the code is executed.

So I put a bunch debugging info everywhere. I thought I'll delete them latter anyway.

The most natural way to debug is of course to put debugging info into a file. The problem is I often use proxy. So after I change the program, I often have to download the text file with filezilla. Often the text file does not show what I think it should show. Finally I decided to just display error on the web.

I considered having debugging mode. However, I am afraid I will forget to delete debugging info.

I considered having debugging mode if user do ?debuggingmode=1 for example. However, I was paranoid that somehow my competitor can guess the secret keyword.

I deleted most debugging info. I forget to delete one and that one only show up if users use proxy from the right country. Turns out I do not have proxy from the right country and didn't realize that. After the program works for 24 hours, I uploaded that to my main domain.

My competitor, using proxy, see the debugging code. He copy the idea and that's how I lost $800 per day.

In retrospect, I really have a hard time seeing where I went wrong. I have been super careful. Yet it happened.

How should one debug a PHP web application securely without exposing secrets to competitors?

答:
What others say about debugging in production is right. But I have done it sometimes anyway. And I think there are safer ways to do it than yours, though nothing is foolproof.

I don't need such high security myself, I just don't want users to see a bunch of gibberish on their screens.

```<code>$debug = true;
$allowed_ips = array('192.168.0.220','173.46.89.255'); // limit to your own ip's. If your competitor knows them, though, he can spoof it! But if your stuff is not top secret, it's ok.

if(!in_array($_SERVER['REMOTE_ADDR'],$allowed_ips) ) {
  $debug = false;
}

if($debug) {
  echo '```' . print_r($some_variable) . '```';
}
</code>```

Now users won't see your debugging unless they really want to. If your $800/day depends on keeping this debug information a secret, then don't use the above code. But if the information is not that sensitive, the above will be much better than depending on a GET variable or revealing your secrets to an entire country.

Alternatively, you can create a debug class or function that will check if printing is allowed or not based on your criteria. That's what I do.

Something like this:

```<code>class debug {
  public $on = false;
  public static function print($variable) {
    if($on) {
      echo '```' . print_r($some_variable) . '```';
    }
  }
}

debug::print($some_variable); // class checks if printing is allowed. If not, no printing occurs.
</code>```

For my program that will make me $800/day (in development), I use apache mod auth to require a password to access any part of the site, as well as restricting debug information to certain IPs. Your question makes me think I should look into better security though.

Body:
What others say about debugging in production is right. But I have done it sometimes anyway. And I think there are safer ways to do it than yours, though nothing is foolproof.

I don't need such high security myself, I just don't want users to see a bunch of gibberish on their screens.

$debug = true;
$allowed_ips = array('192.168.0.220','173.46.89.255'); // limit to your own ip's. If your competitor knows them, though, he can spoof it! But if your stuff is not top secret, it's ok.

if(!in_array($_SERVER['REMOTE_ADDR'],$allowed_ips) ) {
  $debug = false;
}

if($debug) {
  echo '<pre>' . print_r($some_variable) . '</pre>';
}

Now users won't see your debugging unless they really want to. If your $800/day depends on keeping this debug information a secret, then don't use the above code. But if the information is not that sensitive, the above will be much better than depending on a GET variable or revealing your secrets to an entire country.

Alternatively, you can create a debug class or function that will check if printing is allowed or not based on your criteria. That's what I do.

Something like this:

class debug {
  public $on = false;
  public static function print($variable) {
    if($on) {
      echo '<pre>' . print_r($some_variable) . '</pre>';
    }
  }
}

debug::print($some_variable); // class checks if printing is allowed. If not, no printing occurs.

For my program that will make me $800/day (in development), I use apache mod auth to require a password to access any part of the site, as well as restricting debug information to certain IPs. Your question makes me think I should look into better security though.


问:
How to Learn Doing it Right Way?
I am self taught web developer. I do not have any computer science degree from university. I know HTML5, CSS3, Javascript, PHP and some Python. But I am having difficulties about being efficient. When I create a project, I am buried into files, folders, bugs and todoes. Because I am managing multiple projects at a time, I totally feel stressed and not in control.

I see real programmers whom have computer science degrees use utilities like Git for source management. They use Unit tests for testing and other tools for Debugging in an easy and quick way. I am sure there are lots of other tools they have which help them stay safe and calm while they manage their projects.

But because I do not have any computer science degree, I do not know how to do things in a right and efficient way. I just do it, in an organized way. It works but it burns out me, too.

I Googled a bit and find some books from Amazon about Project Management but I feel intimidated. The tools and resources I found also very scattered which seems getting them together to create an organized routine is also requires another expertise.

As a self taught web developer what can I do to learn doing things right way? Do I need a computer science degree or a course about programming? Can I learn the right way by Googleing or from books?

答:
A compSci degree will not teach you how to organise your work, or how to use tools like git.

Go for source control basics to better manage your projects, once you've learned how to use them, yu might find yourself less stressed because you'll know your code is more secure.

Then just do less, 1 thing at a time works well - finish it before staring on the next, even if that "thing" is just a discrete task for one project. Try a project tracking/bug tracking system (eg redmine) to help you keep track of what you're doing, what you have left to do, and what you have done.

Title: How to Learn Doing it Right Way?


问:
How to guarantee invariants / Inner logic in setter methods
According to DDD-principles I use factory-methods to create consistent objects and to ensure that the objects are in the right state.

Now I'm in doubt about inner logic of setter methods. I'm tied up with an object, that's similar to the following code snippet, so let's take it as an example:

```<code>public class UserCredentials {

    private String username;

    private UserCredentials() {
        super();
    }

    public static UserCredentials create (final String username) {
        String username = username.toUpperCase();
        UserCredentials newInstance = new UserCredentials(username);
        return newInstance;
    }

    private UserCredentials(final String username) {
        this.username = username;
    }

    public String getUsername() {
        return this.username;
    }

    public void setUsername(final String username) {
        this.username = username;
    }

    public void checkConsitency() {
        ...
        isUppercase();
        ...
    }
}
</code>```

We do have an invariant: The username of the credentials must always be uppercase. Now I want to make sure, that changing the username doesn't violate the invariant.

But how do I guarantee the rule?

I do rewrite the setter method and add the conversion logic to the setter. Drawback: Setter contains logic.

I rely on clients, that they always provide uppercase username and I will throw consistency exceptions in the case of violation. Drawback: Origin of the wrong usage is hard to discover, moreover its bad practice at all.

I remove the setter method and replace it with a domain method like changeUsername(String username) that contains the conversion logic. Drawback: external developers may miss the setter method.

Because of the statement "username of credential must always be uppercase" I tend to prefer alternative 3.

But is there a smarter solution?

答:
Choose solution #1. There is nothing wrong with setters containing validation or coercion logic. In fact, that is the only reason why we'd use setters and getters instead of public member fields!

Your create factory method is also a bit awkward, as there is no reason not to use the constructor instead:

```<code>public class UserCredentials {

    private String username;

    public UserCredentials(final String username) {
        super();
        this.username = coerceUsername(username);
    }

    public String getUsername() {
        return this.username;
    }

    public void setUsername(final String username) {
        this.username = coerceUsername(username);
    }

    private static String coerceUsername(final String username) {
        return username.toUpperCase();
    }
}
</code>```

Body:
Choose solution #1. There is nothing wrong with setters containing validation or coercion logic. In fact, that is the only reason why we'd use setters and getters instead of public member fields!

Your create factory method is also a bit awkward, as there is no reason not to use the constructor instead:

public class UserCredentials {

    private String username;

    public UserCredentials(final String username) {
        super();
        this.username = coerceUsername(username);
    }

    public String getUsername() {
        return this.username;
    }

    public void setUsername(final String username) {
        this.username = coerceUsername(username);
    }

    private static String coerceUsername(final String username) {
        return username.toUpperCase();
    }
}


答:
Actually, I would have two extra validations here. One is the &debug=1 parameter in the request. You can also use some special session variable or cookie setup that only you can activate via a call to a "secret" page (preferably with authentication).

The second validation would be to have in the configuration file, an array with a range of IPs and only calls from an IP in that array can trigger the debugging functionality. something like

In the config:

```<code>$debugAllowedIPs = array('127.0.0.1', '192.168.0.1', /* add more IPs here */);
</code>```

Have the following method somewhere where it can be accessed globally:

```<code>function getClientIp() {
    if (!empty($_SERVER['HTTP_CLIENT_IP']))  return $_SERVER['HTTP_CLIENT_IP'];
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) return $_SERVER['HTTP_X_FORWARDED_FOR'];
    return $_SERVER['REMOTE_ADDR'];
}
</code>```

And in your code call something like:

```<code>if (in_array(getClientIp(), $debugAllowedIPs)) { /* show debug info here */ }
</code>```

Please keep in mind that the code in the getClientIp() method is not safe as the value for $_SERVER['HTTP_X_FORWARDED_FOR'] is easily spoofed, however it should serve the purpose of getting the point across for your question.

Body:
Recently I made a program. I forget to delete 2 line of codes. That mistake cost me $800 per day every day.

I was programming with PHP. If a visitor uses proxy it redirect somewhere else. Using debugger was impossible because some code contains ioncube. Because the program simply redirect somewhere else no matter what, it's hard to see which part of the code is executed.

So I put a bunch debugging info everywhere. I thought I'll delete them latter anyway.

The most natural way to debug is of course to put debugging info into a file. The problem is I often use proxy. So after I change the program, I often have to download the text file with filezilla. Often the text file does not show what I think it should show. Finally I decided to just display error on the web.

I considered having debugging mode. However, I am afraid I will forget to delete debugging info.

I considered having debugging mode if user do ?debuggingmode=1 for example. However, I was paranoid that somehow my competitor can guess the secret keyword.

I deleted most debugging info. I forget to delete one and that one only show up if users use proxy from the right country. Turns out I do not have proxy from the right country and didn't realize that. After the program works for 24 hours, I uploaded that to my main domain.

My competitor, using proxy, see the debugging code. He copy the idea and that's how I lost $800 per day.

In retrospect, I really have a hard time seeing where I went wrong. I have been super careful. Yet it happened.

How should one debug a PHP web application securely without exposing secrets to competitors?

Body:
Actually, I would have two extra validations here. One is the &debug=1 parameter in the request. You can also use some special session variable or cookie setup that only you can activate via a call to a "secret" page (preferably with authentication).

The second validation would be to have in the configuration file, an array with a range of IPs and only calls from an IP in that array can trigger the debugging functionality. something like

In the config:

$debugAllowedIPs = array('127.0.0.1', '192.168.0.1', /* add more IPs here */);

Have the following method somewhere where it can be accessed globally:

function getClientIp() {
    if (!empty($_SERVER['HTTP_CLIENT_IP']))  return $_SERVER['HTTP_CLIENT_IP'];
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) return $_SERVER['HTTP_X_FORWARDED_FOR'];
    return $_SERVER['REMOTE_ADDR'];
}

And in your code call something like:

if (in_array(getClientIp(), $debugAllowedIPs)) { /* show debug info here */ }

Please keep in mind that the code in the getClientIp() method is not safe as the value for $_SERVER['HTTP_X_FORWARDED_FOR'] is easily spoofed, however it should serve the purpose of getting the point across for your question.


问:
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.

答: As I've gotten older, I've realized that is is best if developers don't do their own deployments (I fought this one tooth and nail). They should not have any rights to the production database except select rights. Our code got a lot less buggy (and the same thing didn't crop up multiple times because the change was only made in prod and a later dev deployment overwrote it again then fixed only on prod in a hurry, rinse and repeat)when we had to start giving it to other people to deploy and not being allowed to make quick fix production changes because the deployment wasn't quite right. Further we stopped having those accidental "updates without the where clause highlighted that changed every record in the table" issues.</p>

Title: What hat should a programmer not wear?


问:
Should interface names begin with an "I" prefix?
I have been reading "Clean Code" by Robert Martin to hopefully, become a better programmer.  While none of it so far has been really ground breaking it has made me think differently about the way I design applications and write code.

There is one part of the book that I not only don't agree with, but doesn't make sense to me, specifically in regards to interface naming conventions.  Here's the text, taken directly from the book.  I have bolded the aspect of this I find confusing and would like clarification on.

I prefer to leave interfaces unadorned. The preceding I, so common in today’s legacy wads, is a distraction at best and too much information at worst. I don’t want my users knowing that I’m handing them an interface.

Perhaps it is because I'm only a student, or maybe because I have never done any professional or team based programming but I would want the user to know it is an interface.  There's a big difference between implementing an interface and extending a class.

So, my question boils down to, "Why should we hide the fact that some part of the code is expecting an interface?"

Edit

In response to an answer:

If your type is an interface or a class is your business, not the business of someone using your code. So you shouldn't leak details of your code in this thrid party code.

Why should I not "leak" the details of whether a given type is an interface or a class to third-party code?  Isn't it important to the third-party developer using my code to know whether they will be implementing an interface or extending a class?  Are the differences simply not as important as I'm making them out to be in my mind?

答:
Most answers seem to assume that the programming language is either Java or C# where there is a concept (or keyword) for interfaces / abstract classes. In these cases, in a decent IDE, it is immediately visible with which type of class one deals and writing public interface IMyClass is unnecessary duplication. It is like you wouldn't write public final FinalMyClass - imagine putting every keyword in the classes name.

However, in my opinion in C++ the situation is a little different as one has to dive into the header file and see if the class has any virtual methods to find out if it is an abstract class. In that case, I can clearly see an argument for writing class AbstractMyClass.

So my answer would be: It depends on the programming language.

Updated 2016: 2 years of C++ experience later I would now probably consider it bad practice to prefix class names with Abstract, though I'd say there are probably code bases that are so complex that it might make sense.


答:
The book is full of good stuff, but I would still add "I" to the interface name.

Imagine you have public interface ILog with a default implementation public class Log.

Now, if you decide to have public interface Log, all of a sudden you have to change Log class to public class LogDefault or something on those lines. You went from having one extra character to seven - surely that's wasteful.

There is often a fine line between theory and practice. In theory this is a really good idea, but in practice it's not so good.

Title: Should interface names begin with an "I" prefix?

Body:
I have been reading "Clean Code" by Robert Martin to hopefully, become a better programmer.  While none of it so far has been really ground breaking it has made me think differently about the way I design applications and write code.

There is one part of the book that I not only don't agree with, but doesn't make sense to me, specifically in regards to interface naming conventions.  Here's the text, taken directly from the book.  I have bolded the aspect of this I find confusing and would like clarification on.

I prefer to leave interfaces unadorned. The preceding I, so common in today’s legacy wads, is a distraction at best and too much information at worst. I don’t want my users knowing that I’m handing them an interface.

Perhaps it is because I'm only a student, or maybe because I have never done any professional or team based programming but I would want the user to know it is an interface.  There's a big difference between implementing an interface and extending a class.

So, my question boils down to, "Why should we hide the fact that some part of the code is expecting an interface?"

Edit

In response to an answer:

If your type is an interface or a class is your business, not the business of someone using your code. So you shouldn't leak details of your code in this thrid party code.

Why should I not "leak" the details of whether a given type is an interface or a class to third-party code?  Isn't it important to the third-party developer using my code to know whether they will be implementing an interface or extending a class?  Are the differences simply not as important as I'm making them out to be in my mind?


问:
How do you get over tooling problems in a communal open-source project?
Two different teams (from different companies) are uniting to work on a communal open-source project. Agreeing on technical design is something we have no trouble with, but I'm struggling with tooling/workflow problems.

I really like a BDD testing tool called phpspec (analogous to RSpec), whilst a lot of my teammates stick to what they know (phpunit) regardless of the pros and cons of either tool. How do you move forward with a project when members are in disagreement like this? Should you enforce a standard testing tool? Is there a way of using both?

I think it boils down to whether members will break out of their comfort zones to learn new technologies that are better for the job. I'm of the strong opinion that you should always be willing to learn new things, but I get the impression that others are purely concerned with getting things done in the quickest way possible - thereby using tools they've used before.

答:
Every project needs some kind of central leadership to call the shots and make decisions like that.

In a company, this is usually the project leader appointed by management. In a large open source community, the leadership is often some kind of meritocratic community process where every participant can make suggestions and an expert group votes on them.

Your project appears to be somewhere between these two. Two companies are involved in equal parts, and letting one take the sole project leadership seems to be unacceptable for the other. But you don't seem to be large enough to justify a community process with all the red tape and paperwork involved.

One possible solution could be to appoint two project leaders, one from each company, who agree on a common workflow process together and enforce it in their respective companies.

Another solution would be to hire an independent project leader who isn't part of either company. This could be done by forming a 3rd company as a joint-venture which is owned in equal parts by both partners and has the sole mission to create that software. The only regular employee of that company would be an independent project leader. Your team and that of the other company would still be employed by their respective companies, but get assigned to work as contractors for the joint-venture. Both teams would report to the project leader, who in turn reports to the owners of his company (your respective bosses).


答:
I think you answered your own question; whilst you'd like to use 1 tool, "a lot" of your colleagues prefer to use something else. Without a 'boss' to decide tooling, the majority rules and you need to go with the preferred tool.

Now, there's no reason why you can't try to engage with them in discussion of tooling. You will have to take the initiative and lead the debate around changing, you will also have to persuade them to agree with you and that will take a bit of effort.

Think of this question from their point of view. Unless you collaborate with them, one of them might post a question "how to deal with one developer who insists on using a different tool to our standard?". How would you react if one developer decided to change a tool you have already agreed to use?

Ultimately you have to agree to use common tools, just like common design. If you don't there will be chaos.

Title: How do you get over tooling problems in a communal open-source project?

Body:
Two different teams (from different companies) are uniting to work on a communal open-source project. Agreeing on technical design is something we have no trouble with, but I'm struggling with tooling/workflow problems.

I really like a BDD testing tool called phpspec (analogous to RSpec), whilst a lot of my teammates stick to what they know (phpunit) regardless of the pros and cons of either tool. How do you move forward with a project when members are in disagreement like this? Should you enforce a standard testing tool? Is there a way of using both?

I think it boils down to whether members will break out of their comfort zones to learn new technologies that are better for the job. I'm of the strong opinion that you should always be willing to learn new things, but I get the impression that others are purely concerned with getting things done in the quickest way possible - thereby using tools they've used before.


答:
I recommend you review the needs and decide on what tools need to be common.
For example you can't have some people using svn and others using git when there is a lot of code sharing.  However when it comes to editors, differences may be ok.  The time, cost and motivation for people to switch tools that are essentially about preferences is often not worth it.

Some practical examples:

Need to be common:

The database being used

The language being used

The source control system

ok to be different:

git tools - gui's, cli, etc.  The end artifact (code is in git) is the same.

Editor - there are many choices here

An important factor is sharing is freqently the editor.  Basically if folks are good in different editor you have to accept it initially.  On an open source style project it's most likely that people will stick to what they know and are comfortable.

If you need to pair on code you have three options:

One person does the typing and uses the editor are comfortable and proficient with.

Both people use a very simple editor (notepad, gedit, etc).

One person invests the time to learn the editor that the other uses.

My personal experience for editors (while working in the Ruby on Rails community for the last few years) is that people are fairly split between editors (usually between emacs and vi).  When it comes to writing code or even pairing, it doesn't matter that much, as long as the person coding is proficient in their tool and the person watching can follow along and see the code ok.

In your case, it's more about tooling than tools per se perhaps.  The issue about which testing framework (phpspec vs. phpunit) to use when writing code, that's certainly tricky.  I think this comes down to what's going to happen as you move forward.  Will each group/person ever have to read or alter tests written in another framework that they don't know?  Open source collaboration frequently requires this.  If so you'll need to reach agreement on the framework.  You'll need to work through the difficult and often contentious discussions.  It's best to start out with agreement on things... that you can agree on... such as 'we do need to pick one' and 'whatever we decide at the end of the discussion, we all agree to be bound by it', 'first thing we'll do is listen to each other carefully', etc.

For this issue of different tools, I would put my efforts into showing why my tool works fine instead of others.  For example with editor, its the same output at the end anyway.  If tests are used to generate code (i.e. tdd) and discarded after, their implementation is less important.  If they are retained afterwards and used as regression tests than it probably makes most sense to use the same framework.


答:
If a class is too big, it becomes hard to maintain, test and understand, other answers have covered this will.

It is possible for a class to have more than one responsibility without problems, but you soon hit problems with too complex classes.

However having a simple rule of “only one responsibility” just makes it easier to know when you need a new class.

However defining “responsibility” is hard, it does not mean “do everything the application spec says”, the real skill is in know how to break the problem down into small units of “responsibility”.


答:
1. Backwards compatibility

JavaScript is an implementation of ECMAScript. Most of those functions were introduced in ECMAScript 5 (ES5) however many older browsers which still have a significant enough share of the market do not support these functions (see ECMAScript 5 compatibility table), the most notable of these being IE8.

Generally libraries will revert to the native implementation if it exists otherwise use their own polyfill, for example let's look at AngularJS's implementation (angular.js L203-257):

```<code>function forEach(obj, iterator, context) {
  var key;
  if (obj) {
    if (isFunction(obj)){
      for (key in obj) {
        // Need to check if hasOwnProperty exists,
        // as on IE8 the result of querySelectorAll is an object without a hasOwnProperty function
        if (key != 'prototype' && key != 'length' && key != 'name' && (!obj.hasOwnProperty || obj.hasOwnProperty(key))) {
          iterator.call(context, obj[key], key);
        }
      }
    } else if (obj.forEach && obj.forEach !== forEach) {
      obj.forEach(iterator, context);
    } else if (isArrayLike(obj)) {
      for (key = 0; key < obj.length; key++)
        iterator.call(context, obj[key], key);
    } else {
      for (key in obj) {
        if (obj.hasOwnProperty(key)) {
          iterator.call(context, obj[key], key);
        }
      }
    }
  }
  return obj;
}
</code>```

The following lines check whether the forEach method exists on the object and whether it is the AngularJS version or not. If not it uses the already specified function (the native version):

```<code>} else if (obj.forEach && obj.forEach !== forEach) {
  obj.forEach(iterator, context);
}
</code>```

2. Convenience

In native JavaScript Array.prototype.forEach is a method exclusive to an instance of Array, however most any Object is iterable too.

For this reason many library creators make their functions polymorphic (able to accept multiple types as input). Let's take the AngularJS code above and see what inputs it accepts:

Functions:

```<code>if (isFunction(obj)){
  for (key in obj) {
    // Need to check if hasOwnProperty exists,
    // as on IE8 the result of querySelectorAll is an object without a hasOwnProperty function
    if (key != 'prototype' && key != 'length' && key != 'name' && (!obj.hasOwnProperty || obj.hasOwnProperty(key))) {
      iterator.call(context, obj[key], key);
    }
  }
</code>```

Arrays (with native forEach support):

```<code>} else if (obj.forEach && obj.forEach !== forEach) {
  obj.forEach(iterator, context);
</code>```

Array-like objects including Array (without native forEach support), String, HTMLElement, Object with a valid length property:

```<code>} else if (isArrayLike(obj)) {
  for (key = 0; key < obj.length; key++)
    iterator.call(context, obj[key], key);
</code>```

Objects:

```<code>} else {
  for (key in obj) {
    if (obj.hasOwnProperty(key)) {
      iterator.call(context, obj[key], key);
    }
  }
}
</code>```

Conclusion

As you can see AngularJS will iterate over most any JavaScript Object, although it works in the same way as the native function it accepts far more different types of input and thus is a valid addition to the library as well as a way of bringing ES5 functions to legacy browsers.

Body:
1. Backwards compatibility

JavaScript is an implementation of ECMAScript. Most of those functions were introduced in ECMAScript 5 (ES5) however many older browsers which still have a significant enough share of the market do not support these functions (see ECMAScript 5 compatibility table), the most notable of these being IE8.

Generally libraries will revert to the native implementation if it exists otherwise use their own polyfill, for example let's look at AngularJS's implementation (angular.js L203-257):

function forEach(obj, iterator, context) {
  var key;
  if (obj) {
    if (isFunction(obj)){
      for (key in obj) {
        // Need to check if hasOwnProperty exists,
        // as on IE8 the result of querySelectorAll is an object without a hasOwnProperty function
        if (key != 'prototype' && key != 'length' && key != 'name' && (!obj.hasOwnProperty || obj.hasOwnProperty(key))) {
          iterator.call(context, obj[key], key);
        }
      }
    } else if (obj.forEach && obj.forEach !== forEach) {
      obj.forEach(iterator, context);
    } else if (isArrayLike(obj)) {
      for (key = 0; key < obj.length; key++)
        iterator.call(context, obj[key], key);
    } else {
      for (key in obj) {
        if (obj.hasOwnProperty(key)) {
          iterator.call(context, obj[key], key);
        }
      }
    }
  }
  return obj;
}

The following lines check whether the forEach method exists on the object and whether it is the AngularJS version or not. If not it uses the already specified function (the native version):

} else if (obj.forEach && obj.forEach !== forEach) {
  obj.forEach(iterator, context);
}

2. Convenience

In native JavaScript Array.prototype.forEach is a method exclusive to an instance of Array, however most any Object is iterable too.

For this reason many library creators make their functions polymorphic (able to accept multiple types as input). Let's take the AngularJS code above and see what inputs it accepts:

Functions:

if (isFunction(obj)){
  for (key in obj) {
    // Need to check if hasOwnProperty exists,
    // as on IE8 the result of querySelectorAll is an object without a hasOwnProperty function
    if (key != 'prototype' && key != 'length' && key != 'name' && (!obj.hasOwnProperty || obj.hasOwnProperty(key))) {
      iterator.call(context, obj[key], key);
    }
  }

Arrays (with native forEach support):

} else if (obj.forEach && obj.forEach !== forEach) {
  obj.forEach(iterator, context);

Array-like objects including Array (without native forEach support), String, HTMLElement, Object with a valid length property:

} else if (isArrayLike(obj)) {
  for (key = 0; key < obj.length; key++)
    iterator.call(context, obj[key], key);

Objects:

} else {
  for (key in obj) {
    if (obj.hasOwnProperty(key)) {
      iterator.call(context, obj[key], key);
    }
  }
}

Conclusion

As you can see AngularJS will iterate over most any JavaScript Object, although it works in the same way as the native function it accepts far more different types of input and thus is a valid addition to the library as well as a way of bringing ES5 functions to legacy browsers.


问:
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?

答: If you use Eclipse, then enable Save Actions for the Java Editors, and tell everybody to use it.  This fixes formatting issues on every save, but does not fix bad capitalization.  It might be quite helpful though!


答:
MVVM is basically just a modern refinement of the MVC pattern, so the main goal is still the same as that of MVC: to provide a clear separation between domain logic and presentation logic. This can be boiled down to code quality: by adhering to the concepts of high cohesion and loose coupling, you stand a much better chance of sustaining productivity over time. Clear separations of concerns simplifies the use and maintenance of your code, and loose coupling between components makes testing and code reuse easier.

That would be my general argument for using MVVM over not using any such pattern. Whether it's a good idea to use MVVM in particular over e.g. MVC or MVP is indeed subjective and depends on the application.

Title: What is the main goal of MVVM pattern?

Body:
Could you tell me what is the goal of the MVVM pattern? What are the arguments or the reasons I can give to a team and product owner to respect and develop according to this pattern?

I would like a simple answer. Something in one sentence or one word. Is it for

maintenance

security

testing

something else?


答:
The basic reasons of using MVVM are Separation of Concerns (SOC) and Single Responsibility Principle (SRP). Then you have Flexibility, Maintenance and Testing.

The goal of MVVM was to apply the above on WPF. WPF provides "plumbing" to allow easy use of MVVM through Data Binding.

For SOC and SRP read: Separation of Concerns(Wikipedia) and Single Responsibility Principle(Wikipedia). But the basis is: The logic doesn't care that the button is red and situated on the left top corner. Only the UI cares about it.

Flexibility on this case is the ability that one ViewModel can provide to different Views, or one View can use several ViewModels, that one ViewModel can use more that one Model, and that a Model can be used on separate ViewModels.

Maintenance is a consequence of SOC and SRP. It is much easier to change parts of the code or UI without affecting other sections.

For Testing, now you can do automated testing of your logic without having a window pop up. You can isolate the tests and mock whatever is needed (if at all).

To the product owner what you have to say is that it will become easier to make changes and to affirm(test) that the application is behaving as expected.

To the developers: it will make your life easier.

If you are not using WPF, maybe look into MVC(Wikipedia) or MVP(Wikipedia)

Title: What is the main goal of MVVM pattern?


问:
Client/server model where the server rejects connections from *newer* clients
I'm using a piece of commercial software where the server will reject any attempt to connect to it from a newer client.  In other words, you can use version 8 of the client to connect to a v10.0 server, but not version 10.1 of the client.

Obviously, this software is what it is.  But why would it be designed that way?  Why would clients not be backwards compatible?  What benefits (if any) does this arrangement have?

This setup just seems very counter-intuitive to me, and I want to try and understand it.

(The software happens to be a database, but I don't think it matters to the question.)

答:
It is odd that a 10.1 can't communicate with a 10.0 version (I'd expect at least a major version difference before that happened).

The designer probably didn't want the client app to be weighed down by the compatibility layer needed to connect to the older server, while the server can fall back on the older protocol if needed.


答:
If the server only responds to requests from the client and new interface versions only add new requests (existing requests and responses are never changed), then disallowing newer clients means that neither client nor server need to explicitly support multiple versions of the protocol.

In that case, if a version 8 client connects to a version 10 server, then all the version 8 functionality is just there and the newer (version 9 and 10) functionality never gets requested.

On the other hand, if a version 10.1 client would successfully connect to a version 10 server, then the client would need to know which functionality was newly introduced in version 10.1 compared to version 10 (and possibly all the way back to version 1). This is quite a burden for the client and it is way easier to just blindly disallow such connections and work on the premise that if the connection succeeds, then the server supports at least all the commands that the client knows about.

Title: Client/server model where the server rejects connections from *newer* clients

Body:
I'm using a piece of commercial software where the server will reject any attempt to connect to it from a newer client.  In other words, you can use version 8 of the client to connect to a v10.0 server, but not version 10.1 of the client.

Obviously, this software is what it is.  But why would it be designed that way?  Why would clients not be backwards compatible?  What benefits (if any) does this arrangement have?

This setup just seems very counter-intuitive to me, and I want to try and understand it.

(The software happens to be a database, but I don't think it matters to the question.)


问:
Was getting a computing science degree easier 10 years ago
I am currently a 3rd year computing science student at a Canadian University. I find it quite challenging, and extremely interesting. One thing  that i have noticed is that each person i speak to that took a class 3 or so years ago learned much less than i did in the same class, and people who are taking 1st year classes are doing more than i remember doing in my 1st year classes. Is this just me remembering stuff bad, or do you believe that getting a computing science degree was easier 10 (or even 5) years ago? </p>

答:
Good question.  Given that I graduated 13 years ago, I do remember a lot of what I took pretty well, so I could likely compare some things but there are a lot of differences.  There are some advances in the field that encourage a shift to some degree in terms of what courses should there be and how should this all flow.  Another side is that the administrators of the program may try to improve things by adding another course here or there.

If you look at what Waterloo has today and what I took, there are more than a few differences.  Man-made things tend to evolve and why shouldn't university programs be like that?  In my day, this is the break down of my CS course run: 2 first-year(130/134), 2 second-year(246/241), 6 third-year(340/342/351/354/360/370) and then 4 fourth-year(464/466/486/487).  Now, there were also a bunch of Math courses there too, but 2007-2008 lists 5 courses at the second year level, in addition to some other changes and that was only a few years back.  I'd have had to take a different 4th year course as I didn't take any 4th year courses involving programming directly.

Would it be harder today?  I don't think so, but there are more than a few other changes that would also impact things as in my day there was Grade 13 in Ontario high schools that was very similar to first year university in some subjects.

Compsci.ca may be a good place to ask this if you want to compare Canadian schools as the creators are from Canadian schools and some alumni may have had their degrees from years back.


问:
UML class diagrams: How to show dependency
Please consider a program with four classes: Class A, B, C and D.

Classes A and B are subclasses of abstract super-class C.

Class D is dependent on C. Meaning: It holds a C objectOfTypeC field.

As we know, polymorphically the objectOfTypeC reference may hold objects of classד A and B. The value of this reference may change dynamically during runtime.

This kind of situtation is very common in OOP.

A common example is the Strategy pattern, where several classes all inherit or  implement the abstract-class or interface SuperType. Another class SomeClass holds a reference of type SuperType, and is able to dynamically hold different instances of SuperType subclasses in that reference.

My question is this: I have two ideas how this can be shown in a UML class diagram, but I'm not sure which one is correct.

(Please note: in these examples, the super type is an interface, but it could also be an abstract class, or even a regular super class).

Which option is more correct?

答: If you look at UML of strategy pattern you mentioned, you will notice Option 1 is correct. To explain it properly. In UML, the association relation (eg. the arrow) usually means the entity has attribute that is of type the arrow is pointing at. Which is exactly your case of association between SomeClass and SuperType. Option 2 would mean SomeClass has 3 attributes one for each of Class1, Class2 and Class3, which is not what you want.