答: Yes, it should and it will. Accidentally erasing your coworker's work is only possible if you update and resolve all conflicts in your favor, and then commit your version. It is not unthinkable that people have automated their update process so that it automatically chooses "choose my version" because they don't know any better; find and eliminate such errors.</p>

Title: Shouldn't SVN warn me if I'm about to commit files which have newer versions in the repository?

Body: We use SVN and PhpStorm at work. Recently our team has grown a bit so there are several people working on the same project at a time, sometimes on the same file. We've run into the problem where people don't update before comitting and overwrite the changes that were made by someone else. This is a hassle. I don't know SVN very well, but it seems like this shouldn't even be possible. What are we doing wrong?</p>


问:
Why it is necessary to to test my iPhone app on actual iPhone device
I developed one application for iPhone and now I want it on App Store. So many my iOS geek friends told me to test it on actual device i.e. on iPhone.

So I wonder that why it is necessary to to test my iPhone app on actual iPhone device though they (Apple) have given "simulator" which is near about same as my device?

答:
The user experience varies from one device to another due to different OS and

hardware specifications. Hence, it is necessary to test an iPhone app on the actual

devices – mobile devices running various versions of iOS in the marketplace.

Although a simulator is useful in identifying any issues faced by the end-user,

testing the app on the original device will help in identifying and addressing major

concerns of the user.

ContentLicense: CC BY-SA 3.0


问:
A completely free and open programming language
With Oracle vs Google trial, it seems that Java is not entirely Open and free (as free software) as I expected. Although there exists completely free/open JVM, it's hard to know what is a copyright infringement with Java, and what is not.

So I'd like to know if there is a completely Open and free language with open and free IDE (Eclipse-like) out there, Object Oriented if possible, and able to make window-based applications for the main OSs (Linux, Mac, Windows).

答:
The D programming language is open source (at least if using the open source gdc and ldc compilers, see info on this here). It was designed to fix the deficiencies in C++, such as adding (optional) garbage collection and making the language a lot simpler and safe to use, while still being statically compiled for optimal performance.

It is thus combines of the best of two worlds: (almost) script-like syntax, with the performance of statically compiled language.

In addition the transition should be easy for C/C++/Java/C# coders, due to the many syntax similarities. Since you seem to come from Java, be sure to read the "D for Java programmers" page, to get you started.

It has good IDE support on Linux through the Mono-D plugin for MonoDevelop (Functioning debugging and code completion, and syntax highlighting of course).


问:
Checking "instanceof" rather than value using a switch statement
Is there some syntax (other than a series of if statements) that allows for the use of a switch statement in Java to check if an object is an instanceof a class?  I.e., something like this:

```<code>switch (object) {
     case instanceof SecondObject:
        break;
     case instanceof ThirdObject:
        break;
}
</code>```

Sidenote:  I recognize that as a design pattern, checking against instanceof and making decisions based on it is not as preferable as using inheritance.  To give some context why this would be useful to me, here's my situation:

I'm working on a project that involves a kryonet client/server.  For communication over KryoNet, you pass objects that it serializes using kryo.  Anything added to the object increases the size of these packets,1 so to minimize the network traffic, you keep these objects as light weight as possible.  When you receive a packet, you need to know what to do with it, so I'm making this determination based on what type of packet object the passed object is an instanceof.  This approach is the same undertaken in the examples included with Kryonet's distribution.  I'd love to clean up the hideous class that translates these packets into action, and figure a switch statement would at least make it look moderately more organized.

1As I wrote the statement above, I had doubts about whether what I was saying was accurate. The answer below seems to disagree:

Methods don't add anything to the runtime size of an object. The
  method code is not transmitted, and nothing about the methods requires
  any representation in an object's state. This is not a sound reason
  for instanceof testing, etc.

I guess the real issue is I don't know what happens under the hood for Kryo to serialize an object and I was nervous to do anything that increased the bandwidth.  Your answers have inspired me to do it with inheritance and add the appropriate methods to the objects.  So thank you!

答:
In Java, it's only possible to switch on primitives. But you could do something similar.

I think it's some kind of design pattern though I could not find it...

You could hide the if-then-else stuff (which is needed in this case) and wrap it in a kind of switch-class:

```<code>public abstract MySwitch{
    public MySwitch(MyObject obj){

        if (obj instanceof SecondObject)
            secondObject((SecondObject)obj);
        else if (obj instanceof ThirdObject)
            thirdObject((ThirdObject)obj);
        else
            onDefault(obj);
    }

    protected abstract void secondObject(SecondObject obj);
    protected abstract void thirdObject(ThirdObject obj);
    protected abstract void onDefault(MyObject obj);
}
</code>```

You could use it then like this in your code:

```<code>new MySwitch(obj){

    @Override protected void secondObject(SecondObject obj){

    }
    @Override protected void thirdObject(ThirdObject obj){

    }
    @Override protected void onDefault(MyObject obj){

    }
};
</code>```

Just be aware that normally, calling abstract methods from constructor is a bad idea... I think, in this case, it could be OK, because this is and always will be a stateless class. If you don't like it, add an additional method to do the stuff.

This also has the advantage that if you add new classes to your inheritance tree and add a new case, you are forced to update all occurrences and don't forget a switch somewhere.

Body:
In Java, it's only possible to switch on primitives. But you could do something similar.

I think it's some kind of design pattern though I could not find it...

You could hide the if-then-else stuff (which is needed in this case) and wrap it in a kind of switch-class:

public abstract MySwitch{
    public MySwitch(MyObject obj){

        if (obj instanceof SecondObject)
            secondObject((SecondObject)obj);
        else if (obj instanceof ThirdObject)
            thirdObject((ThirdObject)obj);
        else
            onDefault(obj);
    }

    protected abstract void secondObject(SecondObject obj);
    protected abstract void thirdObject(ThirdObject obj);
    protected abstract void onDefault(MyObject obj);
}

You could use it then like this in your code:

new MySwitch(obj){

    @Override protected void secondObject(SecondObject obj){

    }
    @Override protected void thirdObject(ThirdObject obj){

    }
    @Override protected void onDefault(MyObject obj){

    }
};

Just be aware that normally, calling abstract methods from constructor is a bad idea... I think, in this case, it could be OK, because this is and always will be a stateless class. If you don't like it, add an additional method to do the stuff.

This also has the advantage that if you add new classes to your inheritance tree and add a new case, you are forced to update all occurrences and don't forget a switch somewhere.


问:
Algorithm for dividing a range into ranges and then finding which range a number belongs to
Having

a minimum

a maximum

number of ranges

a value between minimum and maximum

I'm trying to come up with a method, or two, which would calculate which range the provided value belongs to.

For min=1, max = 10, number of ranges=5 the ranges would be
[1,2],[3,4],[5,6],[7,8],[9-10]

The other method would behave like shown below:

method(1)->[1-2]

method(2)->[1-2]

method(3)->[3-4]

method(4)->[3-4]

method(5)->[5-6]

method(6)->[5-6]

method(7)->[7-8]

method(8)->[7-8]

method(9)->[9-10]

method(10)->[9-10]

This would be used for generating a legend for a map where the size of the marker depends on the range a value belongs to.

I wonder if there is a nice algorithmic solution for this.

The numbers I work with are integers.

Edit:

Another example:

For min=1, max = 3, number of ranges=2 the ranges would be

a) [1-2],[3-3]

or

b) [1-1],[2-3]

The other method would behave like shown below:

a)

method(1)->[1-2]

method(2)->[1-2]

method(3)->[3-3]

or
b)

method(1)->[1-1]

method(2)->[2-3]

method(3)->[2-3]

I don't have a preference for a) or b).

答:
Let n be the number of ranges. If you can divide your range into equal subranges, you can do it like this:

```<code>length_of_range = (max - min + 1) / n

For i = 1 to n:
start_of_range(i) = length_of_range * (i-1) + min
end_of_range(i) = start_of_range(i) + length_of_range - 1

method(number) = (number - min) / length_of_range + 1   // '/' is integer division
</code>```

If you can't divide them into equal subranges, the first (max - min + 1) % n subranges should have length ((max - min + 1) / n) + 1 and the rest should have length (max - min + 1) / n. Knowing that, you should be able to adjust the above formulas yourself.

Body:
Let n be the number of ranges. If you can divide your range into equal subranges, you can do it like this:

length_of_range = (max - min + 1) / n

For i = 1 to n:
start_of_range(i) = length_of_range * (i-1) + min
end_of_range(i) = start_of_range(i) + length_of_range - 1

method(number) = (number - min) / length_of_range + 1   // '/' is integer division

If you can't divide them into equal subranges, the first (max - min + 1) % n subranges should have length ((max - min + 1) / n) + 1 and the rest should have length (max - min + 1) / n. Knowing that, you should be able to adjust the above formulas yourself.


问:
FizzBuzz - really?
When it comes to "interview test" questions, the subject of FizzBuzz often comes up. There is also a Coding Horror post about it.

Now, if you bother reading sites such as this, you are probably less likely to be in the demographic of programmers who would find FizzBuzz anything but trivial.

But is it really true that 99% of programmers will struggle with it?

Really?

What is the evidence to back this up?

Some real-life examples would be very helpful in answering this question.

答:
It's hard to believe that developers can't code FizzBuzz until you see the "nine-to-fivers" that copy and paste their work together and conciously try not to write code. I couldn't believe it when I heard one of our senior developers teaching a C# developer, with 3 years "experience", how to use a Dictionary. Interfaces? Design patterns? stdout? YAGNI? My lead had never heard of YAGNI! It's amazing what these people don't know.

I believe it now. I also think there's too many developers just doing enough.

Title: FizzBuzz - really?

ContentLicense: CC BY-SA 2.5


问:
Is changing the type of a variable partway through a procedure in a dynamically typed language bad style?
In Python (and occasionally PHP) where variables do not have fixed types, I'll frequently perform 'type transformations' on a variable part-way through my code's logic. I'm not (necessarily) talking about simple casts, but about functions that change the type of a variable while leaving it basically representing the same value or data.

For example, I might write code like this when doing a web request, using the response variable to store an addurlinfo object, then the string content of that object, and the dictionary returned by parsing the string as JSON:

```<code>response = urlopen(some_url)
assert response.info().type == 'application/json'

response = response.read()
logger.debug('Received following JSON response: ' + response)

response = json.loads(response)
do_something(response)
</code>```

(Okay, it's a slightly contrived example, but I think it demonstrates the idea fine). My feeling is that this is better than using three separate variable names because a) it conveys that the response variable contains basically the same information, just 'transformed' into a different type, and b) it conveys that the earlier objects aren't going to be needed any further down the function, since by reassigning over their variable I've made them unavailable to later code.

The tradeoff, I guess, is that the reader could become confused about what type the variable is at any given moment.

Is this bad style, and should I be using three different variables in the above example instead of reassigning to one? Also, is this standard practice in dynamically typed languages, or not? I haven't seen enough of other people's code to know.

答:
I'll go out on a limb and say: No, this is a terrible idea.

It's just a special case of reusing a variable, which is a bad idea - mainly because it makes it hard to understand what a variable contains at any given point in the program flow. See e.g. Should I reuse variables?

About your points: The points you raise are valid, it's just that reusing the variable is not a good solution :-).

a) it conveys that the response variable contains basically the same
  information, just 'transformed' into a different type

Providing this information is a good idea. However, don't do this by using the same variable, because then you obscure the fact that it the information was transformed. Rather, use names with a common pre-/postfix. In your example:

```<code>rawResponse = urlopen(some_url)
[...]
jsonResponse = response.read()
[...]
responseData = json.loads(response)
[...]
</code>```

This makes it clear that the variables are closely related, but also that they do not contain the same data.

b) it conveys that the earlier objects aren't going to be needed any
  further down the function, since by reassigning over their variable
  I've made them unavailable to later code.

Again, communicating this "no longer needed" is good, but don't do it by reusing the variable: The reuse assignement will usually be hard to see, so you only confuse the reader.

Rather, if a variable lives long after its last use, that is an indication the method/function is too long. Split the part with the short-lived variables into a sub-function; that makes the code easier to read, and limits the variable lifetime.

Note: I usually even go one step further than not reusing variables, and try to even only assign a value once (i.e. never change the value, make it immutable). This is an idea mainly from functional languages, but I found it can make code much clearer. Of course, in non-functional languages, you sometimes need to change a variable (obvious example being a loop variable), but once you start looking, you'll see that in most cases a "fresh" variable makes for more readable and less bug-prone code.

Body:
I'll go out on a limb and say: No, this is a terrible idea.

It's just a special case of reusing a variable, which is a bad idea - mainly because it makes it hard to understand what a variable contains at any given point in the program flow. See e.g. Should I reuse variables?

About your points: The points you raise are valid, it's just that reusing the variable is not a good solution :-).

a) it conveys that the response variable contains basically the same
  information, just 'transformed' into a different type

Providing this information is a good idea. However, don't do this by using the same variable, because then you obscure the fact that it the information was transformed. Rather, use names with a common pre-/postfix. In your example:

rawResponse = urlopen(some_url)
[...]
jsonResponse = response.read()
[...]
responseData = json.loads(response)
[...]

This makes it clear that the variables are closely related, but also that they do not contain the same data.

b) it conveys that the earlier objects aren't going to be needed any
  further down the function, since by reassigning over their variable
  I've made them unavailable to later code.

Again, communicating this "no longer needed" is good, but don't do it by reusing the variable: The reuse assignement will usually be hard to see, so you only confuse the reader.

Rather, if a variable lives long after its last use, that is an indication the method/function is too long. Split the part with the short-lived variables into a sub-function; that makes the code easier to read, and limits the variable lifetime.

Note: I usually even go one step further than not reusing variables, and try to even only assign a value once (i.e. never change the value, make it immutable). This is an idea mainly from functional languages, but I found it can make code much clearer. Of course, in non-functional languages, you sometimes need to change a variable (obvious example being a loop variable), but once you start looking, you'll see that in most cases a "fresh" variable makes for more readable and less bug-prone code.


问:
Why Android created emulator rather simulator?
From https://stackoverflow.com/questions/4544588/difference-between-iphone-simulator-and-android-emulator

The difference between emulators and simulators is that emulators mimic the software and hardware environments found on actual devices. Simulators, on the other hand, only mimic the software environment; they otherwise have access to all of the host system's hardware resources such as disk space, memory and processor speed.

Apple always harps on the importance of device testing because iPhone Simulator does not emulate an iPhone processor, disk drive, memory constraints and whatnot. You hardly ever get memory warnings unless your Mac is struggling to manage resources itself, unless you simulate (again) memory warnings from the Simulator's menu item.

Though android emulator emulates the ARM processors and certain hardware, it still doesn't do a good job of matching the CPU performance.

Being an emulator it can match Memory consumption well, it can emulate certain simple devices well but fails when the devices gets complicated for example mobile GPU and HW media decoders. And as the emulation logic works on translating each ARM instruction to X86 instruction and executing its a performance hog and by design not cycle accurate.

My Question: Why Android created emulator rather simulator?

答:
Nobody but Google knows why they made that decision, but here's my best guess:

Android is an open platform, so there are a lot of different hardware configurations out there. Being able to emulate different hardware configurations is a big boon for developers, in that it greatly reduces the need to have actual devices to test on. This keeps the costs down for developers, so encourages them to develop for Android.

Trying to match performance without using the actual hardware is a fool's game in this context - PCs have different specs too! It's also of not of concern to many (I would guess most) developers.


问:
How do I convince my boss (and other devs) to use/consider Unobtrusive JavaScript
I'm pretty new in our develepors team.

I need some strong arguments and/or "pitfall" examples, so my boss will finally understand the advantages of Unobtrusive JavaScript, so that he, and the rest of the team, stops doing things like this:

```<code><input type="button" class="bow-chicka-wow-wow"
       onclick="send_some_ajax(); return false;" value="click me..." />
</code>```

and

```<code><script type="text/javascript">

function send_some_ajax()
{
  // bunch of code ... BUT using jQuery !!!
}
</script>
</code>```

I suggested using a pretty common pattern:

```<code><button id="ajaxer" type="button">click me...</button>
</code>```

and

```<code><script type="text/javascript">

// since #ajaxer is also delivered via ajax, I bind events to document
//  -> not the best practice but it's not the point....

$(document).on('click', '#ajaxer', function(ev) {
var $elem = $(this);
ev.preventDefault();

});
</code>```

The reason why my boss (and others) do not want to use this approach is that the Event-Inspection in FireBug (or Chrome Dev Tools) isn't simple anymore, e.g. with

```<code><input type="text" name="somename" id="someid" onchange="performChange()">
</code>```

he can immediately see what function executes on change-event and jump right to it in a huge JS file full of spaghetti-code.

In the case of Unobtrusive JavaScript the only thing he would see is:

```<code><input type="text" name="somename" id="someid" />
</code>```

and he has no idea whether some events, if any, were bound to this element and which function will be triggered.

I was looking for a solution and found it:

```<code>$(document).data('events') // or .. $(document).data('events').click
</code>```

but, this "approach" caused it to take "too long ..." to find out which function fires on which event, so I was told to stop bind events like that.

I'm asking you for some examples or strong advantages or any other kind of suggestions for "Why we should use UJS"

UPDATE: suggestion to "change the job" is not an ideal solution.

UPDATE 2: Ok, I've not only suggested to use jQuery event-binding, I did so. After I wrote all Event-Delegation, the Boss came to me and asked me, why am I doing event delegation with different approach and approach he dind't know

I mentioned some obvious benefits, like - There are 15 input-fields and all of then have an onchange event (not only, some of them have also onkeyup) So it's more pragmatic to write this kind of event-delegation ones for ALL input-fields, instead of doing it 15 times, especially if all of the HTML will be rendered with PHP's echo -> echo '... <input type="text" id="someid" ... />...'

答:
The obvious answer is that you can only bind one function to your button with the onclick attribute, whereas the JQuery event allows you to bind multiple functions. A common problem with the onload event: if your document is composed of more than one file, collisions often happen.

Another solution that could satsify both you and your boss is the use of data-binding, with a library like Knockout or Angular, which would keep track of modifications on your view and suppress the need for a large part of the event handlers.


问:
Algorithm for tracking progress of controller method running in background
I am using Codeigniter framework for PHP on Windows platform. My problem is I am trying to track progress of a controller method running in background. The controller extracts data from the database(MySQL) then does some processing and then stores the results again in the database. The complete aforesaid process can be considered as a single task. A new task can be assigned while another task is running. The newly assigned task will be added in a queue. So if I can track progress of the controller, I can show status for each of these tasks. Like I can show "Pending" status for tasks in the queue, "In Progress" for tasks running and "Done" for tasks that are completed.

Main Issue:

Now first thing I need to find is an algorithm to track the progress of how much amount of execution the controller method has completed and that means tracking how much amount of method has completed execution. For instance, this PHP script tracks progress of array being counted. Here the current state and state after total execution are known so it is possible to track its progress. But I am not able to devise anything analogous to it in my case.

Maybe what I am trying to achieve is programmtically not possible. If its not possible then suggest me a workaround or a completely new approach. If some details are pending you can mention them. Sorry for my ignorance this is my first post here. I welcome you to point out my mistakes.

EDIT:

Database outline:

The URL(s) and keyword(s) are first entered by user which are stored in a database table called link_master and keyword_master respectively. Then keywords are extracted from all the links present in this table and compared with keywords entered by user and their frequency is calculated which is the final result. And the results are stored in another table called link_result. Now sub-links are extracted from the domain links and stored in a table called sub_link_master. Now again the keywords are extracted from these sub-links and the corresponding results are stored in a table called sub_link_result.

The number of records cannot be defined beforehand as the number of links on any web page can be different. Only the cardinality of link_result table can be known which will be equal to multiplication of number of keyword(s) and URL(s) .

I insert multiple records at a time using this resource.

Controller outline:

The controller extracts keywords from a web page and also extracts keywords from all the links present on that page. There is a method called crawlLink. I used Rolling Curl to extract keywords and web page content. It has callback function which I used for extracting keywords alongwith generating results and extracting valid sub-links. There is a insertResult method which stores results for links and sub-links in the respective tables.

Yes, the processing depends on the number of records. The more the number of records, the more time it takes to execute:

Consider this scenario:

Number of Domain Links = 1

Number of Keywords = 3

Number of Domain Links Result generated = 3 (3 x 1 as described in the question)

Number of Sub Links generated = 41

Number of Sub Links Result = 117 (41 x 3 = 123 but some links are not valid or searchable)

Approximate time taken for above process to complete = 55 seconds.

The above result is for a single link. I want to track the progress of the above results getting stored in database. When all results are stored, the task is complete. If results are getting stored, the task is In Progress. I am not clear how can I track this progress.

答:
Although it would be near impossible to track % complete accurately due to an undetermined number of links and keywords it is possible to show a rough status via depth. For example the first depth would be the url/s processed from the top level.

(100/Total Pages) * Pages Processed = % current status

Total Pages = Select count() from master_links

Pages Processed = Select count() from master_links where processed=true. When you have processed the page simply set the flag in the db.

(This could similarly be done by populating an array with your db values and using the index value as your pages processed)

Note: You can only get the status for each level. Do not start crawling your sub_links until all the master_links are crawled - this will also allow you to avoid duplicate url crawls and should have a minimal impact on the total time.

The squares in the diagram below represent the pages which need to be processed. Inside each box is the percentage complete if you were processing them left to right. This is for illustrative purposes the percentage would be based on this:

Your output would show percentage complete of that level:

e.g. Master Links 40% complete

or

e.g. Master Links 100%

     Sub Links    49.8%

This should still give you enough info to indicate the progress, after all you cannot guess the actual density of keywords and links...


问:
overworld vs on-screen 2d tile organization
I am developing a 2d game where the world is made up of tiles.

I have an overworld and a "current world":

the current world represent the current tiles on screen at any given time, currently this is in a 2d array (14x10 elements).

the overworld is the entire world, currently 28x20 elements, which means there are four screens of tiles. Again these are planned to be stored in a 2d array

I had originally thought to take the entire group of tiles and break them in to 'current world' sized 2d arrays that get passed to the current world object. This would mean however, having to work with a 4d array in the overworld level, which seems to be pretty ugly and more confusing to set up and play with later on.

It would have looked something like:

```<code>tiles[overworldX][overworldY][currentWorldX][currentWorldY]
</code>```

where "tiles" is the 4d array and:

```<code>tiles[overworldX][overworldY]
</code>```

would get you a 2d array of the group of tiles that fit on a screen/current world. The only idea I can come up with to make this slightly better is to create a helper object that just wraps around a 2d array, breaking up a 4d array in to two 2d arrays, but in essence it is still a 4d array.

Any suggestions on a better way to do this or perhaps a different data structure I can use? Or maybe keeping only a large group of 2d tiles for the overworld, then coming up with some fancy indexing/slicing algorithm that can pull out 'current world' sized parts?

答:
You're overcomplicating it. Just have a single 2d tiles array, and index it like so:

tiles[overworldX + currentWorldX][overworldY + currentWorldY]


问:
Algorithm for deciding change in gesture
I am developing an application where I am taking dynamic gestures as input and then mapping them to keyboard controls. By dynamic gesture, I mean for example hand moving from left to right or hand moving right to left.

I have four gestures: hand moving bottom to top, top to bottom, left to right and right to left.

I am able to recognize gestures but the problem is how to decide the start and ending of the gesture on a continuous video input.

What is the most efficient and effective algorithm for detecting this on a video input?

答:
One way of dealing with this problem is to have a finite state machine with at least three states:

not detecting anything

detection phase

gesture dectected

Then you need to carefully design conditions for each state modification (ie going from detection phase back to "not detecting anything" in case of failure) an run them at each frame of your video stream.

You may need one state machine for each gesture you want to detect, and more than one "detection phase" ("hand at the top", then "hand middle" ...).

When you reach the "gesture detected" phase, you can fire events associated to this gesture.

The robustness of your gesture detection feature depends a lot on how you define your states (do you measure the position or the movement?) and how do you tune the state change parameters.


问:
Validation of the input parameter in caller: code duplication?
Where is the best place to validate input parameters of function: in caller or in function itself?

As I would like to improve my coding style, I try to find the best practices or some rules for this issue. When and what is better.

In my previous projects, we used to check and treat every input parameter inside the function, (for example if it is not null). Now, I have read here in some answers and also in Pragmatic Programmer book, that the validation of input parameter is responsibility of caller.

So it means, that I should validate the input parameters before calling of the function. Everywhere the function is called. And that raises one question: doesn't it create a duplication of checking condition everywhere the function is called?

I am not interested just in null conditions, but in validation of any input variables (negative value to sqrt function, divide by zero, wrong combination of state and ZIP code, or anything else)

Are there some rules how to decide where to check the input condition?

I am thinking about some arguments:

when the treating of invalid variable can vary, is good to validate it in caller side (e.g sqrt() function - in some case I may want to work with complex number, so I treat the condition in caller)

when the check condition is the same in every caller, it is better to check it inside the function, to avoid duplications

validation of input parameter in caller takes place only one before calling of many functions with this parameter. Therefore the validation of a parameter in each function is not effective

the right solution depends on the particular case

I hope this question is not duplicate of any other, I searched for this issue and I found similar questions but they don't mention exactly this case.

答:
Within the function itself. If the function is used more than once, you wouldn't want to verify the parameter for every function call.

Moreover, if the function is updated in such way that will affect the validation of the parameter, you have to search for every occurrence of the caller validation to update them. It ain't lovely :-).

You may refer to Guard Clause

Update

See my reply for each scenario you've provided.

when the treating of invalid variable can vary, is good to validate it in caller side (e.g sqrt() function - in some case I may want to work with complex number, so I treat the condition in caller)

Answer

Majority of programming languages supports integer and real numbers by default, not complex number, hence their implementation of sqrt only accepts non-negative number. The only case you have a sqrt function that returns complex number is when you use programming language oriented towards math, like Mathematica

Moreover, sqrt for most programming languages is already implemented, hence you couldn't modify it, and if you try to replace the implementation (see monkey patching), then your collaborators will be utterly shock on why sqrt suddenly accepts negative numbers.

If you wanted one you can wrap it around your custom sqrt function that handles negative number and returns complex number.

when the check condition is the same in every caller, it is better to check it inside the function, to avoid duplications

Answer

Yes, this is a good practice to avoid scattering the parameter validation across your code.

validation of input parameter in caller takes place only one before calling of many functions with this parameter. Therefore the validation of a parameter in each function is not effective

Answer

It will be nice if the caller is a function, don't you think?

If the functions within the caller are used by other caller, what prevents you from  validating the parameter within the functions called by the caller?

the right solution depends on the particular case

Answer

Aim for maintainable code. Moving your parameter validation ensures one source of truth on what the function can accept or not.


答:
Parameter validation should be the concern of the function being called. The function should know what is considered valid input and what is not. Callers may not know this, especially when they don't know how the function is implemented internally. The function should be expected to handle any combination of parameter values from callers.

Because the function is responsible for validating parameters, you can write unit tests against this function to ensure it behaves as intended with both valid and invalid parameter values.

Title: Validation of the input parameter in caller: code duplication?

Body:
Where is the best place to validate input parameters of function: in caller or in function itself?

As I would like to improve my coding style, I try to find the best practices or some rules for this issue. When and what is better.

In my previous projects, we used to check and treat every input parameter inside the function, (for example if it is not null). Now, I have read here in some answers and also in Pragmatic Programmer book, that the validation of input parameter is responsibility of caller.

So it means, that I should validate the input parameters before calling of the function. Everywhere the function is called. And that raises one question: doesn't it create a duplication of checking condition everywhere the function is called?

I am not interested just in null conditions, but in validation of any input variables (negative value to sqrt function, divide by zero, wrong combination of state and ZIP code, or anything else)

Are there some rules how to decide where to check the input condition?

I am thinking about some arguments:

when the treating of invalid variable can vary, is good to validate it in caller side (e.g sqrt() function - in some case I may want to work with complex number, so I treat the condition in caller)

when the check condition is the same in every caller, it is better to check it inside the function, to avoid duplications

validation of input parameter in caller takes place only one before calling of many functions with this parameter. Therefore the validation of a parameter in each function is not effective

the right solution depends on the particular case

I hope this question is not duplicate of any other, I searched for this issue and I found similar questions but they don't mention exactly this case.


问:
How can I scale spring application context?
I'm currently working on a project that need to be dynamically scaled on demand according to the need.

My question is about scaling spring context. My web application has a classical multi module core (service, persistence, domain), which use use by client application (webapp, api).

The user end application could be clustered, database too, but I don't know how to proceed with spring context.

I plan to use Scala Akka actors on Spring service, but I can't be persuaded by the solution of using one context exposed by actors. All of the rest of the application is built with event driven techniques (Spring events are produced by the service layer).

I already built different webapps by user profile to scale according to user role (Eg. admin, enduser), however the only thing is Spring Context for business operations.

Question: Do I have to merge in one single context shared by all client applications or should I initialize one context per application?

答:
Its kinda hard to understand your diagrams, like is the front end section on the left part is the whole client application architecture?? and the right section is the server side? even though, it is, still I can't get to understand why you have the database and spring layer in the front end?is it a database uniquely local to each client application?

But to give my idea, the common trend in using Spring application context is making it as singleton meaning one spring context in the server side,thats the essence of it, or else you have already defy its purpose. The beans (e.g services) should be stateless so not to produce undesirable result that concurrency issues could results from more than one client requesting the same thing and would need to use the same beans/services.
making them singleton of course is the ideal way to save memory and avoid the instance creation on demand and after using is just to be garbage collected. There will be no bottleneck but instead it would be actually faster cause the object is already loaded in the memory and each request will have its own heap when executing that object once called.
So basically, singleton is faster and saves more memory.


问:
Is there a cleaner way of caching data
We've started implementing some caching code in our MVC project.  We've derived from .Net's ObjectCache to store it in a SQL database.

What we do right now is in each method we want to cache we have code like this:

```<code>public StatusCounts GetCounts()
{
   var cache = new SqlCache<StatusCounts>("mykey");
   if(cache.HasCachedData())
      return cache.GetCachedData();

   var data = StatusRepository.GetCounts();

   cache.SetData(data, DateTime.Now.AddHours(2));
}
</code>```

As far as caching goes, it works. But my concern is it seems like now GetCounts has multiple responsibilities. It's no longer just calculating counts, it's getting them from a cache (if they exist) and saving them to a cache before returning.

Is there a cleaner way to do this?

答:
I built a little tool for this some time ago, https://code.google.com/p/mbcache, that we use with success in our shop. It uses AOP the way @Peri describes behind the scenes.

No matter using this or another tool, I would defiantly favor AOP for this. As you write yourself, you shouldn't mix responsibilities within your classes (extract caching logic to a seperate method don't matter IMHO - it just moves the dependency instead of getting rid of it).

Title: Is there a cleaner way of caching data


答:
Most often you can't know who, when and how will call the function you wrote. It is best to assume the worst: your function will be called with invalid parameters. So you should definitely cover that. </p>

<p>Nevertheless, if the language you use supports exceptions, you might not check for certain errors and be sure that an exception will be thrown, but in this case you must be sure to describe the case in the documentation (you need to have documentation). The exception will give the caller enough information about what happened, and will also drive attention to the invalid arguments. </p>

Body:
Most often you can't know who, when and how will call the function you wrote. It is best to assume the worst: your function will be called with invalid parameters. So you should definitely cover that.

Nevertheless, if the language you use supports exceptions, you might not check for certain errors and be sure that an exception will be thrown, but in this case you must be sure to describe the case in the documentation (you need to have documentation). The exception will give the caller enough information about what happened, and will also drive attention to the invalid arguments.


答:
One major advantage of your suggested technique is you only have to bind once the event handler to a parent such as "document" and this handler will be able to catch the events coming from all children that satisfied the given selector such as "button.anyclass". Saves memory and maintainable such that only need one edit instance and it affects all elements.

With regards to not being able to recognize at once the bound function, your team just could standardize a way on declaring such functions probably on the bottom most part of the page.
So you all know where to look at, naming convention also is very important.Comments would be hugely beneficial, but make sure it is being stripped away by the server before serving it as response to the browser.

Also, if you want to provide obfuscation and minification of javascript for security purposes, your technique would make it possible, unlike the old style your team is still using.

Title: How do I convince my boss (and other devs) to use/consider Unobtrusive JavaScript

Body:
I'm pretty new in our develepors team.

I need some strong arguments and/or "pitfall" examples, so my boss will finally understand the advantages of Unobtrusive JavaScript, so that he, and the rest of the team, stops doing things like this:

```<code><input type="button" class="bow-chicka-wow-wow"
       onclick="send_some_ajax(); return false;" value="click me..." />
</code>```

and

```<code><script type="text/javascript">

function send_some_ajax()
{
  // bunch of code ... BUT using jQuery !!!
}
</script>
</code>```

I suggested using a pretty common pattern:

```<code><button id="ajaxer" type="button">click me...</button>
</code>```

and

```<code><script type="text/javascript">

// since #ajaxer is also delivered via ajax, I bind events to document
//  -> not the best practice but it's not the point....

$(document).on('click', '#ajaxer', function(ev) {
var $elem = $(this);
ev.preventDefault();

});
</code>```

The reason why my boss (and others) do not want to use this approach is that the Event-Inspection in FireBug (or Chrome Dev Tools) isn't simple anymore, e.g. with

```<code><input type="text" name="somename" id="someid" onchange="performChange()">
</code>```

he can immediately see what function executes on change-event and jump right to it in a huge JS file full of spaghetti-code.

In the case of Unobtrusive JavaScript the only thing he would see is:

```<code><input type="text" name="somename" id="someid" />
</code>```

and he has no idea whether some events, if any, were bound to this element and which function will be triggered.

I was looking for a solution and found it:

```<code>$(document).data('events') // or .. $(document).data('events').click
</code>```

but, this "approach" caused it to take "too long ..." to find out which function fires on which event, so I was told to stop bind events like that.

I'm asking you for some examples or strong advantages or any other kind of suggestions for "Why we should use UJS"

UPDATE: suggestion to "change the job" is not an ideal solution.

UPDATE 2: Ok, I've not only suggested to use jQuery event-binding, I did so. After I wrote all Event-Delegation, the Boss came to me and asked me, why am I doing event delegation with different approach and approach he dind't know

I mentioned some obvious benefits, like - There are 15 input-fields and all of then have an onchange event (not only, some of them have also onkeyup) So it's more pragmatic to write this kind of event-delegation ones for ALL input-fields, instead of doing it 15 times, especially if all of the HTML will be rendered with PHP's echo -> echo '... <input type="text" id="someid" ... />...'


答:
What you can do is give them a demo of debugging a USJ html using the tools FireQuery as well as Chrome Query.

FireQuery is a firebug extension and does a pretty good job at it.
As for Chrome Query, I cannot vouch for how much it is good, but it definitely is used by some of the devs (a post at stackoverflow).

Also know that the .data function is removed to return the internal event data since jQuery 1.8.0, and replaced with $._data(element, "events") which can be unstable, as per the official changelog

This is now removed in 1.8, but you can still get to the events data for debugging purposes via $._data(element, "events"). Note that this is not a supported public interface; the actual data structures may change incompatibly from version to version.

UPDATE:

When I started working I had the same dilemma. But upon creation of a demo with fully functional GUI (single page application) which included dynamically opening tabs (closable too), Accordion menu (dynamically created from db), they finally understood that it is better to use USJ all the way.

Also the plus of using USJ is that you can minify your entire application into a small (unreadable) script. Also show them the scripts for google.com / github.com (as an example), and point out that even they are having the code compressed, which is always better, as the viewer of site will have a hard time decoding the security flaws and utilize them to start a full-fledged attack on your site (scare them), even though unlikely.

UPDATE 2:

Btw, I didn't knew I was doing USJ until I saw this question, so thanks in one way.


答:
Stop using buzzwords and try making strong arguments instead. Even the Wikipedia page for Unobtrusive JavaScript says that the term isn't formally defined. It may be a blanket term for a number of good ideas, but if it sounds like a mere fad or fashion your boss and coworkers won't pay a lot of attention. Worse, if you keep going on about something they view as useless, they may start to discount completely unrelated ideas that you advocate.

Figure out why you think the Unobtrusive JavaScript ideas are important. Is it because you read that they're considered best practices? Have you run into problems that you can attribute to not following these ideas? How much will adopting these ideas impact the company's bottom line?

Get inside your boss's head. Why does he do things the way he does, and why has he rejected your changes? He's probably not stupid, and he's probably more experienced than you are, so he probably has some good reasons for doing things his way. You've already alluded to some of them -- follow that thread to its end. Then figure out if and how your suggestions will improve the things that he's most concerned about.

Hint 1: Managers like money. The more directly you can tie your suggestions to increased income or reduced spending, the more impact your argument will have. Hint 2: Time is money. Hint 3: By itself, the aesthetic appeal of code doesn't make money. The opposite, in fact -- it takes time to make code look nice. Ugly code that works well is just fine with most managers.

Don't just talk about it, do it. If you're lucky enough to have a small, self-contained project come your way, ask your manager if you can do it using the "UJS" style as a sort of demonstration. When you're ready, hold a code review where you can explain how it all works and why you think it's better than the current style.

Idealism is great, but don't let it get in the way. It's more important to be seen as someone who gets things done than as a dilettante who complains about uncouth coding style. This is especially true if you're the new guy. If you can't get traction with UJS now, get some good work done instead and slowly build a case for the changes you'd like to make as you gain credibility.

Read Switch: How to Change Things When Change is Hard. It'll give you a lot more good ideas about how to build your case effectively.


问:
A Web application as a REST API client: how to handle resource identifiers
Several concepts related to REST conflict in my head when I try implementing it.

I have a REST-ful back-end API system that holds the business logic, and a web application that provides the UI. From various resources about REST (particularly, REST in Practice: Hypermedia and Systems Architecture) I know that I should not expose raw identifiers of my entities, but rather return hyperlinks with rel="self".

Consider the example. The REST api has a resource that returns a person:

```<code><Person>
  <Links>
    <Link rel="self" href="http://my.rest.api/api/person/1234"/>
  </Links>
  <Pets>
    <Link rel="pet" href="http://my.rest.api/api/pet/678"/>
  </Pets>
</Person>
</code>```

The problem arises with the web application. Let's assume it returns a page that contains a hyperlink to browsers:

```<code><body class="person">
  <p>
    href="http://my.web.app/pet/???????" />
  </p>
</body>
</code>```

What should I put into the href attribute? How do I keep the API entity URL in the web application to be able to get the entity when a user opens the target page?

The requirements seem conflicting:

The hyperlink href should lead to the web application because it is the system hosting the UI

The href should have some id of the entity because the web app must be able to address the entity when the target page opens

The web app should not parse/construct REST URLs beacuse it's not REST-ful, The mentioned book says

URIs should be opaque to consumers. Only the issuer of the URI knows how to interpret it and map it to a resource.

So, I cannot just take 1234 from the API response URL because as a RESTful client I should treat it as if it was something like http://my.rest.api/api/AGRIDd~ryPQZ^$RjEL0j. On the other hand, I must give some URL that leads to my web app and is enough for the app to somehow restore the API's original URL and use that URL to access the API resources.

The simplest way is probably just using the API URLs of resources as their string identifiers. But web page urls like http://my.web.app/person/http%3A%2F%2Fmy.rest.api%2Fapi%2Fperson%2F1234 are ugly.

It all seems quite easy for a desktop app or a single-page javascript app. Since they live continuously, they can just keep the URLs in memory together with the service objects for the application lifetime and use them when necessary.

With a web app I can imagine several approaches, but all seem weird:

Replace the host in the API URLs and keep the result only. The huge downside is that it requires the web application to handle whatever URL the API generates, meaning monstrous coupling. Moreover, it's not RESTful again, because my web app starts interpreting the URLs.

Expose the raw ids in the REST API together with the links, use them to build Web App's URLs, and then use the ids on the web app server to find the required resources in the API. This is better, but will affect the web app server performance because the web app will have to go through the REST service navigation issuing a chain of get-by-id requests of some form to handle any request from a browser. For a somewhat nested resource this might be costly.

Store all self URLs returned by the api in a persistent (DB?) mapping on the web app server. Generate some ids for them, use the ids to build the web app page URLs and to get the URLs of the REST service resources. I.e. I keep the http://my.rest.api/pet/678 URL somewhere with a new key, say 3, and generate the web page URL as http://my.web.app/pet/3. This looks like a HTTP Cache implementation of some sort. I don't know why, but it seems weird to me.

Or Does it all mean that RESTful APIs cannot serve as backends for web applications?

答:
Edited to address question updates, previous answer removed

Looking over your changes to your question I think I understand the problem you are facing a bit more. As there is no field that is an identifier on your resources (just a link) you have no way to refer to that specific resource within your GUI (i.e. a link to a page describing a specific pet).

The first thing to determine is if a pet ever makes sense without an owner. If we can have a pet without any owner then I would say we need some sort of unique property on the pet that we can use to refer to it. I do not believe this would violate not exposing the ID directly as the actual resource ID would still be tucked away in a link that the REST client wouldn't parse. With that in mind our pet resource may look like:

```<code><Entity type="Pet">
    <Link rel="self" href="http://example.com/pets/1" />
    <Link rel="owner" href="http://example.com/people/1" />
    <UniqueName>Spot</UniqueName>
</Entity>
</code>```

We can now update the name of that pet from Spot to Fido without having to mess with any actually resource IDs throughout the application. Likewise we can refer to that pet in our GUI with something like:

http://example.com/GUI/pets/Spot

If the pet does not make any sense without an owner (or pets are not allowed in the system without an owner) then we can use the owner as part of the "identity" of the pet in the system:

http://example.com/GUI/owners/John/pets/1  (first pet in the list for John)

One small note, if both Pets and People can exist separate of each-other I would not make the entry point for the API the "People" resource. Instead I would create a more generic resource that would contain a link to People and Pets. It could return a resource that looks like:

```<code><Entity type="ResourceList">
    <Link rel="people" href="http://example.com/api/people" />
    <Link rel="pets" href="http://example.com/api/pets" />
</Entity>
</code>```

So by only knowing the first entry point into the API and not processing any of the URLs to figure out system identifiers we can do something like this:

User logs into the application. The REST client accesses the entire list of people resources available which may look like:

```<code><Entity type="Person">
    <Link rel="self" href="http://example.com/api/people/1" />
    <Pets>
        <Link rel="pet" href="http://example.com/api/pets/1" />
        <Link rel="pet" href="http://example.com/api/pets/2" />
    </Pets>
    <UniqueName>John</UniqueName>
</Entity>
<Entity type="Person">
    <Link rel="self" href="http://example.com/api/people/2" />
    <Pets>
        <Link rel="pet" href="http://example.com/api/pets/3" />
    </Pets>
    <UniqueName>Jane</UniqueName>
</Entity>
</code>```

The GUI would loop through each resource and print out a list item for each person using the UniqueName as the "id":

```<code><a href="http://example.com/gui/people/1">John</a>
<a href="http://example.com/gui/people/2">Jane</a>
</code>```

While doing this it could also process each link that it finds with a rel of "pet" and get the pet resource such as:

```<code><Entity type="Pet">
    <Link rel="self" href="http://example.com/api/pets/1" />
    <Link rel="owner" href="http://example.com/api/people/1" />
    <UniqueName>Spot</UniqueName>
</Entity>
</code>```

Using this it can print a link such as:

```<code><!-- Assumes that a pet can exist without an owner -->
<a href="http://example.com/gui/pets/Spot">Spot</a>
</code>```

or

```<code><!-- Assumes that a pet MUST have an owner -->
<a href="http://example.com/gui/people/John/pets/Spot">Spot</a>
</code>```

If we go with the first link and assume that our entry resource has a link with a relation of "pets" the control flow would go something like this in the GUI:

Page is opened and the pet Spot is requested.

Load the list of resources from the API entry point.

Load the resource that is related with the term "pets".

Look through each resource from the "pets" response and find one that matches Spot.

Display the information for spot.

Using the second link would be a similar chain of events with the exception being that People is the entry point to the API and we would first get a list of all people in the system, find the one that matches, then find all pets that belong to that person (using the rel tag again) and find the one that is named Spot so we can display the specific information related to it.

Body:
Several concepts related to REST conflict in my head when I try implementing it.

I have a REST-ful back-end API system that holds the business logic, and a web application that provides the UI. From various resources about REST (particularly, REST in Practice: Hypermedia and Systems Architecture) I know that I should not expose raw identifiers of my entities, but rather return hyperlinks with rel="self".

Consider the example. The REST api has a resource that returns a person:

```<code><Person>
  <Links>
    <Link rel="self" href="http://my.rest.api/api/person/1234"/>
  </Links>
  <Pets>
    <Link rel="pet" href="http://my.rest.api/api/pet/678"/>
  </Pets>
</Person>
</code>```

The problem arises with the web application. Let's assume it returns a page that contains a hyperlink to browsers:

```<code><body class="person">
  <p>
    <a href="http://my.web.app/pet/???????" />
  </p>
</body>
</code>```

What should I put into the href attribute? How do I keep the API entity URL in the web application to be able to get the entity when a user opens the target page?

The requirements seem conflicting:

The hyperlink href should lead to the web application because it is the system hosting the UI

The href should have some id of the entity because the web app must be able to address the entity when the target page opens

The web app should not parse/construct REST URLs beacuse it's not REST-ful, The mentioned book says

URIs should be opaque to consumers. Only the issuer of the URI knows how to interpret it and map it to a resource.

So, I cannot just take 1234 from the API response URL because as a RESTful client I should treat it as if it was something like http://my.rest.api/api/AGRIDd~ryPQZ^$RjEL0j. On the other hand, I must give some URL that leads to my web app and is enough for the app to somehow restore the API's original URL and use that URL to access the API resources.

The simplest way is probably just using the API URLs of resources as their string identifiers. But web page urls like http://my.web.app/person/http%3A%2F%2Fmy.rest.api%2Fapi%2Fperson%2F1234 are ugly.

It all seems quite easy for a desktop app or a single-page javascript app. Since they live continuously, they can just keep the URLs in memory together with the service objects for the application lifetime and use them when necessary.

With a web app I can imagine several approaches, but all seem weird:

Replace the host in the API URLs and keep the result only. The huge downside is that it requires the web application to handle whatever URL the API generates, meaning monstrous coupling. Moreover, it's not RESTful again, because my web app starts interpreting the URLs.

Expose the raw ids in the REST API together with the links, use them to build Web App's URLs, and then use the ids on the web app server to find the required resources in the API. This is better, but will affect the web app server performance because the web app will have to go through the REST service navigation issuing a chain of get-by-id requests of some form to handle any request from a browser. For a somewhat nested resource this might be costly.

Store all self URLs returned by the api in a persistent (DB?) mapping on the web app server. Generate some ids for them, use the ids to build the web app page URLs and to get the URLs of the REST service resources. I.e. I keep the http://my.rest.api/pet/678 URL somewhere with a new key, say 3, and generate the web page URL as http://my.web.app/pet/3. This looks like a HTTP Cache implementation of some sort. I don't know why, but it seems weird to me.

Or Does it all mean that RESTful APIs cannot serve as backends for web applications?

Body:
Edited to address question updates, previous answer removed

Looking over your changes to your question I think I understand the problem you are facing a bit more. As there is no field that is an identifier on your resources (just a link) you have no way to refer to that specific resource within your GUI (i.e. a link to a page describing a specific pet).

The first thing to determine is if a pet ever makes sense without an owner. If we can have a pet without any owner then I would say we need some sort of unique property on the pet that we can use to refer to it. I do not believe this would violate not exposing the ID directly as the actual resource ID would still be tucked away in a link that the REST client wouldn't parse. With that in mind our pet resource may look like:

<Entity type="Pet">
    <Link rel="self" href="http://example.com/pets/1" />
    <Link rel="owner" href="http://example.com/people/1" />
    <UniqueName>Spot</UniqueName>
</Entity>

We can now update the name of that pet from Spot to Fido without having to mess with any actually resource IDs throughout the application. Likewise we can refer to that pet in our GUI with something like:

http://example.com/GUI/pets/Spot

If the pet does not make any sense without an owner (or pets are not allowed in the system without an owner) then we can use the owner as part of the "identity" of the pet in the system:

http://example.com/GUI/owners/John/pets/1  (first pet in the list for John)

One small note, if both Pets and People can exist separate of each-other I would not make the entry point for the API the "People" resource. Instead I would create a more generic resource that would contain a link to People and Pets. It could return a resource that looks like:

<Entity type="ResourceList">
    <Link rel="people" href="http://example.com/api/people" />
    <Link rel="pets" href="http://example.com/api/pets" />
</Entity>

So by only knowing the first entry point into the API and not processing any of the URLs to figure out system identifiers we can do something like this:

User logs into the application. The REST client accesses the entire list of people resources available which may look like:

<Entity type="Person">
    <Link rel="self" href="http://example.com/api/people/1" />
    <Pets>
        <Link rel="pet" href="http://example.com/api/pets/1" />
        <Link rel="pet" href="http://example.com/api/pets/2" />
    </Pets>
    <UniqueName>John</UniqueName>
</Entity>
<Entity type="Person">
    <Link rel="self" href="http://example.com/api/people/2" />
    <Pets>
        <Link rel="pet" href="http://example.com/api/pets/3" />
    </Pets>
    <UniqueName>Jane</UniqueName>
</Entity>

The GUI would loop through each resource and print out a list item for each person using the UniqueName as the "id":

<a href="http://example.com/gui/people/1">John</a>
<a href="http://example.com/gui/people/2">Jane</a>

While doing this it could also process each link that it finds with a rel of "pet" and get the pet resource such as:

<Entity type="Pet">
    <Link rel="self" href="http://example.com/api/pets/1" />
    <Link rel="owner" href="http://example.com/api/people/1" />
    <UniqueName>Spot</UniqueName>
</Entity>

Using this it can print a link such as:

<!-- Assumes that a pet can exist without an owner -->
<a href="http://example.com/gui/pets/Spot">Spot</a>

or

<!-- Assumes that a pet MUST have an owner -->
<a href="http://example.com/gui/people/John/pets/Spot">Spot</a>

If we go with the first link and assume that our entry resource has a link with a relation of "pets" the control flow would go something like this in the GUI:

Page is opened and the pet Spot is requested.

Load the list of resources from the API entry point.

Load the resource that is related with the term "pets".

Look through each resource from the "pets" response and find one that matches Spot.

Display the information for spot.

Using the second link would be a similar chain of events with the exception being that People is the entry point to the API and we would first get a list of all people in the system, find the one that matches, then find all pets that belong to that person (using the rel tag again) and find the one that is named Spot so we can display the specific information related to it.


问:
Is it possible to use a "non-commercial" REST API in a for-pay app?
I am interested in integrating the results of 3rd-party news API's into my for-pay application. The APIs would be a very small part of the app (e. g. the app is not just reselling the APIs). I have found that many APIs such as Yahoo have "non-commercial" conditions like the following:

YOU SHALL NOT: Sell, lease, share, transfer, or sublicense the Yahoo!
  APIs or access or access codes thereto or derive income from the use
  or provision of the Yahoo! APIs, whether for direct commercial or
  monetary gain or otherwise, unless the API Documents specifically
  permit otherwise or Yahoo! gives prior, express, written permission...

(from Yahoo Local Search API page)

Does this prevent the API from being used as part of any app which costs money to use? For example, if I charge you to get into my site, and then display some content from this API, is that OK? If I let you see the content from the API for free, but then charge you to do something else on the site, is that OK?

I'm obviously not expecting specific legal advice. Instead, I'd like to know about either:
(1) a good reference on this topic that can answer my question
(2) an "answer by example", i. e. an example of a real-world app that does something similar

答:
You're in a gray zone that would require an attorney to provide a definitive answer.  There are a couple of nuances that you should think about prior to consulting with one though.

The primary question concerns how you are deriving income from your application.

I can think of three configurations in your example:

For-pay site that only exposes the Y! news API feed(s)

For-pay site that exposes the Y! news API feed(s) along with a gaggle of other feeds that you think your customers are interested in.

For-pay site that exposes the gaggle of other feeds along with a freebie site that exposes the Y! news API feeds.

Example 1 is clearly in violation of the Yahoo license.

Example 2 is questionable about being in violation.  The argument you have to make is that you're not charging for the Y! feeds and you're only charging for the other feeds.  Without supporting evidence, I think you'll have a hard time with this line.

Example 3 is an evolution of example 2, and makes it easier to argue that you're not making money off of the Y! news feed(s).  You're giving away that aspect in the hopes of drawing the customer in, and getting them to pay for the other feeds.

Keep in mind that showing ads on your freebie site could be considered as generating revenue from the Y! news feeds.  The license doesn't specify where the funds come from, it simply says you can't make money off of it.

You can always contact Yahoo! and ask if your configuration is acceptable to them.  There are a number of benefits to doing this.  If you're in a gray zone, you'll have a definitive answer from the potential plaintiff.  If they come back with "that's fine" then you've got a green light to proceed.  Alternatively, they may present you with a licensing model that allows you to bypass some of the structural complexity in not charging for their feeds.


问:
Are there any empirical studies about the effects of commenting source code on software quality, maintainability and developer productivity?
I am an advocate of commenting on source code and documenting software products. It is my personal experience and observation that working on source code that is rigorously commented has helped me in different ways when I have had to grow software or maintain it.

However there's another camp that says commenting is ultimately worthless or its value is questionable. Numerous proponents of coding without commenting argue that:

If a piece of code is well-written, it is self explanatory and hence does not need commenting

If a piece of code is not self-explanatory, then refactor it and make it self-explanatory so that it does not need any comments

Your test suite is your live documentation

Over time code and comments get out of sync and it becomes another source of headaches

Agile says working code is more important than piles of documentation, so we can safely ignore writing comments

To me this is just dogma. Again, my personal observation has been that software written by teams of smart and experienced developers ultimately end up with a considerable amount of code that is not self-explanatory.

Again, the Java API, Cocoa API, Android API, etc. show that if you want to write and maintain quality documentation, it is possible.

Having said all these, conversations about pros and cons of documentation and commenting on source code that are based on personal beliefs usually do not end well and lead to no satisfying conclusions.

As such I am looking for academic papers and empirical studies about the effects of software documentation, especially commenting source code, on its quality and maintainability as well as its effects on team productivity.

Have you stumbled upon such articles and what's been the outcome of them, if any?

答:
In "The effect of modularization and comments on program comprehension" (1981), Woodfield, Dunsmore, and Shen found that "subjects whose programs contained comments were able to answer more questions than those without comments."

However, in "Learning a Metric for Code Readability" (2010), Raymond P.L. Buse and Westley Weimer found that comments have only a limited effect on readability and quality:

From the abstract:

We construct an automated readability measure and... show that this metric correlates strongly with three measures of software quality: code changes, automated defect reports,
and defect log messages... Our data suggests that comments, in of themselves, are less
important than simple blank lines to local judgments of readability.

From page 12:

We found that comments were are only moderately well-correlated
with our annotators’ notion of readability (33% relative
power). One conclusion may be that while comments
can enhance readability, they are typically used in code
segments that started out less readable: the comment
and the unreadable code effectively balance out. The
net effect would appear to be that comments are not
always, in and of themselves, indicative of high or low
readability.

Keep in mind that the "coding without commenting" proponents aren't saying that code without comments is better than code with comments.  They're arguing that a particular style of code without comments - one that extracts code into methods with self-describing names, one that introduces explaining variables, one that has a good test suite - is better than code that doesn't do those things but does have comments.  This could complicate the applicability of any studies that have been done.


答:
It's a matter of convention, documentation and use case.

Not all functions are equal. Not all requirements are equal. Not all validation is equal.

For example, if your Java project tries to avoid null pointers whenever possible (see the Guava style recommendations, for example), do you still validate every function argument to make sure it is not null? It's probably not necessary, but chances are that you still do it, to make it easier to find bugs. But you may use an assert where you previously threw a NullPointerException.

What if the project is in C++? Convention/tradition in C++ is to document preconditions, but only verify them (if at all) in debug builds.

In either case, you have a documented precondition on your function: no argument may be null. You could instead extend the domain of the function to include nulls with defined behavior, e.g. "if any argument is null, throws an exception". Of course, that's again my C++ heritage speaking here - in Java, it's common enough to document preconditions this way.

But not all preconditions even can be reasonably checked. For example, a binary search algorithm has the precondition that the sequence to be searched must be sorted. But verifying that it definitely is so is an O(N) operation, so doing that on every call kinda defeats the point of using an O(log(N)) algorithm in the first place. If you're programming defensively, you can do lesser checks (e.g. verifying that for each partition you search, the start, mid and end values are sorted), but that doesn't catch all errors. Typically, you will just have to rely on the precondition being fulfilled.

The one real place where you need explicit checks is at boundaries. External input to your project? Validate, validate, validate. A gray area is API boundaries. It really depends on how much you want to trust the client code, how much damage invalid input does, and how much assistance you want to provide in finding bugs. Any privilege boundary must count as external, of course - syscalls, for example, run in an elevated privilege context and therefore must be very careful to validate. Any such validation must of course be internal to the syscall.


问:
Is C# namespace should be Project-Name?
I am working with multiple websites (freelancer) and a good amount of them I write using C# MVC4.

I created a very good boilerplace project that I plan to use on every next starting mvc4 application I build, however the namespace is named Website. I also do a lot of copy-paste from one project to another and then I always have to refactor namespaces, if I will use single namespace (Website) on all my websites then this problem dissapears.

However - will this somehow impact my application, is it considered a very bad practice?

答: The namespaces should be a little more meaningful than that. If you have some general purpose classes for processing CSV files, maybe use the namespace Qmal.CSVUtil. This makes it easier and less confusing to reuse that code later in other (possibly non-website) projects. You might have some other general purpose web-site related classes that could be reused in other web projects, so maybe use the namespace Qmals.GeneralWebStuff but something simpler such as Qmal.Website might actually be OK for that. Then there's the stuff that's very project specific, and for that you can use a namespace such as Client3.WebProject.

Title: Is C# namespace should be Project-Name?


问:
Do dynamic typed languages deserve all the criticism?
I have read a few articles on Internet about programming language choice in the enterprise. Recently many dynamic typed languages have been popular, i.e. Ruby, Python, PHP and Erlang. But many enterprises still stay with static typed languages like C, C++, C# and Java.

And yes, one of the benefits of static typed languages is that programming errors are caught earlier, at compile time, rather than at run time. But there are also advantages with dynamic typed languages. (more on Wikipedia)

The main reason why enterprises don't start to use languages like Erlang, Ruby and Python, seem to be the fact that they are dynamic typed. That also seem to be the main reason why people on StackOverflow decide against Erlang. See Why did you decide "against" Erlang.

However, there seem to be a strong criticism against dynamic typing in the enterprises, but I don't really get it why it is that strong.

Really, why is there so much criticism against dynamic typing in the enterprises? Does it really affect the cost of projects that much, or what? But maybe I'm wrong.

答:
The reason enterprises use C, C++, C# and Java isn't because they are statically typed (at least not directly). Enterprise decision makers aren't making these kind of choices on the basis of an objective comparison of type systems, I assure you.

Enterprises do care about:

Long term maintenance costs: can you reasonably expect things to continue to work well in 10 years time? It's actually a good thing if language evolution is conservative and backwards-compatible (as with Java). The static typing is helpful here because it catches a major type of bugs at compile time before they get into your production systems.....

Talent availability - will you be able to find developers to maintain your shiny new system? what if the original developer leaves, will everyone else understand the code? This places a high hurdle on introducing any "new" language (especially if it also creates new requirements for deployment, build systems, operational support etc.). This gives a massive advantages to the languages that are widely used (C, C++, C# and Java)

Integration costs: is it easy to connect / integrate with other technologies that you already have in place or are likely to acquire? If you already have a stack of legacy J2EE systems then you need to integrate with them. A new Java EE solution is likely to be much more practical for this than e.g. Python.

Predicatbility / low risk: is the platform / language proven, and can I be sure that it will work? This is usually more important than simple productivity. It's much easier for a manager to persuade his boss to give him a big budget for manpower to build a new system than it is for him to go back later and say that it hasn't worked.....

Enterprise Backing / support - are major international organisations committed to supporting the language and platform? Will they sign a contract to support me so that I have someone to call on if things go wrong?

Vendor neutrality / platform independence - am I going to get locked in to a single supplier? Or do I have a wide range of future supplier options / transition paths available? You don't want to be stuck in an architectural dead-end, unable to make progress while your competitors eat your lunch. If you are doing your job properly as an enterprise architect, you need to be thinking at least 5-10 years ahead on this stuff.

Personally, I think that if you want to use dynamic languages in the Enterprise, then your best chance by far is to use something that piggy-backs on an existing enterprise ecosystem. Most notable are the new dynamic JVM languages: e.g. JRuby, Groovy, Clojure. As far as IT management concerned, these are "safe" dynamic language choices because they operate within and play nicely with the rest of the Java enterprise ecosystem.


答:
A function should state its pre- and post-conditions.

The pre-conditions are the conditions that must be met by the caller before it can correctly use the function and can (and often do) include the validity of input parameters.

The post-conditions are the promises that the function makes to its callers.

When the validity of a function's parameters is part of the pre-conditions, then it is the caller's responsibility to ensure those parameters are valid. But that does not mean every caller has to explicitly check each parameter prior to the call. In most cases, no explicit tests are needed because the internal logic and the pre-conditions of the caller already ensure that the parameters are valid.

As a safety measure against programming errors (bugs), you can check that the parameters passed in to a function really do meet the stated pre-conditions. As these tests can be costly, it is a good idea to be able to switch them off for release builds. If these tests fail, then the program should be terminated, because it has provably run into a bug.

Although at first glance the check in the caller seems to invite code duplication, it is actually the other way around. The check in the callee results in code duplication and lots of unneeded work being done.

Just think about it, how often do you pass parameters through several layers of functions, making only small changes to some of them along the way. If you consistently apply the check-in-callee method, each of those intermediate functions will have to re-do the check for each of the parameters.

And now imagine that one of those parameters is supposed to be a sorted list.

With the check in the caller, only the first function would have to make sure that list is really sorted. All the others know the list is already sorted (as that is what they stated in their pre-condition) and can pass it on without further checks.


问:
How to handle committed and merged code that has no tests?
When developing an application in a team not everyone on this team will be equally good developers. Some will be skilled in some things and some in others and some not at all.

As a team working in an agile process you usually have a definition of 'done' to follow. In our DoD it says never to merge code that is not documented and have proper tests. Sometimes though, a feature is so critical to some team member so the code has to be merged without tests. Sometimes a lazy developer might merge and call it a weekend.

A merge like this means that when other team members pull the code, they will receive code that may or may not function properly and since there are no tests it is hard to verify. It can be very cumbersome to walk through that code to make sure it works before the team member can work on their task.

It has happened on several occasions that the code that was committed without tests has been broken by other team members without them noticing.

So my question becomes:

How would you handle issues like this?

Does it point to bad planning rather then bad behaviour?

Who is to "blame" if code that lacks tests is broken?

答:
I think I may have inadvertantly answered your question in another question.  To summarize what I wrote there, it is always bad practice to commit broken code (or code which breaks tests) if other programmers often pull from that code repository.  I think the proper approach is simply to expect that such things will happen, and set up the code repository in such a way that it won't affect others regardless.

In other words, general practice should be to branch upon doing significant (or even insignificant in the interests of being thorough) changes and committing to the main trunk only when you've established that it won't cause problems.

I would argue that, yes, this is a sign of bad planning rather than bad behavior.  The only people to "blame" if code that lacks tests is broken is those who set up the code repository and/or set up the system for code submission.  It is perfectly normal if programmers make mistakes.  However, it is not acceptable to build a system that cracks when such mistakes are made.


答:
It depends. Deciding where to put validation should be based on the description and strength of the contract implied (or documented) by the method. Validation is a good way to bolster adherence to a specific contract. If for whatever reason the method has a very strict contract, then yes, it is up to you to check before calling.

This is an especially important concept when you create a public method, because you are basically advertising that some method performs some operation. It better do what you say it does!

Take the following method as an example:

```<code>public void DeletePerson(Person p)
{
    _database.Delete(p);
}
</code>```

What is the contract implied by DeletePerson?  The programmer can only assume that if any Person is passed in, it will be deleted. However, we know that this isn't always true.  What if p is a null value?  What if p doesn't exist in the database? What if the database is disconnected? Therefore, DeletePerson does not appear to fulfill its contract well. Sometimes, it deletes a person, and sometimes it throws a NullReferenceException, or a DatabaseNotConnectedException, or sometimes it does nothing (such as if the person is already deleted).

APIs like this are notoriously difficult to use, because when you call this "black box" of a method, all sorts of terrible things can happen.

Here are a couple of ways you can improve the contract:

Add validation and add an exception to the contract.  This makes the contract stronger, but requires that the caller perform validation. The difference, however, is that now they know their requirements. In this case I communicate this with a C# XML comment, but you could instead add a throws (Java), use an Assert, or use a contract tool like Code Contracts.

```<code>///<exception>ArgumentNullException</exception>
///<exception>ArgumentException</exception>
public void DeletePerson(Person p)
{
    if(p == null)
        throw new ArgumentNullException("p");
    if(!_database.Contains(p))
        throw new ArgumentException("The Person specified is not in the database.");

    _database.Delete(p);
}
</code>```

Side note: The argument against this style is often that it causes excessive pre-validation by all calling code, but in my experience this is often not the case. Think of a scenario where you are trying to delete a null Person. How did that happen? Where did the null Person come from? If this is a UI, for example, why was the Delete key handled if there is no current selection? If it were already deleted, shouldn't it have been removed from the display already? Obviously there are exceptions to this, but as a project grows you will often thank code like this for preventing bugs to permeate deep into the system.

Add validation and code defensively. This makes the contract looser, because now this method does more than just deletes the person. I changed the method name to reflect this, but might not be necessary if you are consistent in your API. This approach has its pros and cons. The pro being that that you can now call TryDeletePerson passing in all sorts of invalid input and never worry about exceptions. The con, of course, is that users of your code will probably call this method too much, or it might make debugging difficult in cases where p is null.  This could be considered a mild violation of the Single Responsibility Principle, so keep that mind if a flame war erupts.

```<code>public void TryDeletePerson(Person p)
{
    if(p == null || !_database.Contains(p))
        return;

    _database.Delete(p);
}
</code>```

Combine approaches. Sometimes you want a little of both, where you want external callers to follow the rules closely (to force them to code responsible), but you want your private code to be flexible.

```<code>///<exception>ArgumentNullException</exception>
///<exception>ArgumentException</exception>
public void DeletePerson(Person p)
{
    if(p == null)
        throw new ArgumentNullException("p");
    if(!_database.Contains(p))
        throw new ArgumentException("The Person specified is not in the database.");

    TryDeletePerson(p);
}

internal void TryDeletePerson(Person p)
{
    if(p == null || !_database.Contains(p))
        return;

    _database.Delete(p);
}
</code>```

In my experience, concentrating on the contracts you implied rather than a hard rule works best.  Defensive coding appears to work better in cases where it's hard or difficult for the caller to determine whether an operation is valid. Strict contracts appear to work better where you expect the caller to only make method calls when they really, really make sense.

Body:
It depends. Deciding where to put validation should be based on the description and strength of the contract implied (or documented) by the method. Validation is a good way to bolster adherence to a specific contract. If for whatever reason the method has a very strict contract, then yes, it is up to you to check before calling.

This is an especially important concept when you create a public method, because you are basically advertising that some method performs some operation. It better do what you say it does!

Take the following method as an example:

public void DeletePerson(Person p)
{
    _database.Delete(p);
}

What is the contract implied by DeletePerson?  The programmer can only assume that if any Person is passed in, it will be deleted. However, we know that this isn't always true.  What if p is a null value?  What if p doesn't exist in the database? What if the database is disconnected? Therefore, DeletePerson does not appear to fulfill its contract well. Sometimes, it deletes a person, and sometimes it throws a NullReferenceException, or a DatabaseNotConnectedException, or sometimes it does nothing (such as if the person is already deleted).

APIs like this are notoriously difficult to use, because when you call this "black box" of a method, all sorts of terrible things can happen.

Here are a couple of ways you can improve the contract:

Add validation and add an exception to the contract.  This makes the contract stronger, but requires that the caller perform validation. The difference, however, is that now they know their requirements. In this case I communicate this with a C# XML comment, but you could instead add a throws (Java), use an Assert, or use a contract tool like Code Contracts.

///<exception>ArgumentNullException</exception>
///<exception>ArgumentException</exception>
public void DeletePerson(Person p)
{
    if(p == null)
        throw new ArgumentNullException("p");
    if(!_database.Contains(p))
        throw new ArgumentException("The Person specified is not in the database.");

    _database.Delete(p);
}

Side note: The argument against this style is often that it causes excessive pre-validation by all calling code, but in my experience this is often not the case. Think of a scenario where you are trying to delete a null Person. How did that happen? Where did the null Person come from? If this is a UI, for example, why was the Delete key handled if there is no current selection? If it were already deleted, shouldn't it have been removed from the display already? Obviously there are exceptions to this, but as a project grows you will often thank code like this for preventing bugs to permeate deep into the system.

Add validation and code defensively. This makes the contract looser, because now this method does more than just deletes the person. I changed the method name to reflect this, but might not be necessary if you are consistent in your API. This approach has its pros and cons. The pro being that that you can now call TryDeletePerson passing in all sorts of invalid input and never worry about exceptions. The con, of course, is that users of your code will probably call this method too much, or it might make debugging difficult in cases where p is null.  This could be considered a mild violation of the Single Responsibility Principle, so keep that mind if a flame war erupts.

public void TryDeletePerson(Person p)
{
    if(p == null || !_database.Contains(p))
        return;

    _database.Delete(p);
}

Combine approaches. Sometimes you want a little of both, where you want external callers to follow the rules closely (to force them to code responsible), but you want your private code to be flexible.

///<exception>ArgumentNullException</exception>
///<exception>ArgumentException</exception>
public void DeletePerson(Person p)
{
    if(p == null)
        throw new ArgumentNullException("p");
    if(!_database.Contains(p))
        throw new ArgumentException("The Person specified is not in the database.");

    TryDeletePerson(p);
}

internal void TryDeletePerson(Person p)
{
    if(p == null || !_database.Contains(p))
        return;

    _database.Delete(p);
}

In my experience, concentrating on the contracts you implied rather than a hard rule works best.  Defensive coding appears to work better in cases where it's hard or difficult for the caller to determine whether an operation is valid. Strict contracts appear to work better where you expect the caller to only make method calls when they really, really make sense.


答:
How would you handle issues like this?

Take a look at continuous integration. When people commit, there should be an automatic build that runs the unit tests. This will catch regressions introduced in the new commit. It won't catch errors that have no tests - that will require changing behavior. Consider adding unit tests to your code review - if they don't exist, they don't commit.

For a specific case, I'd probably revert the merge (if possible) and let them do it again once the issue is resolved. If the revert isn't possible, I'd have whoever pushed the commit drop everything until they fix what they committed. Remember, as long as the build is broken everyone is blocked.

Does it point to bad planning rather then bad behaviour?

Not exactly. It might be bad planning in that there's a rush to commit before something is done (it sounds like you define done as tested), but it's more likely having a definition of done that doesn't match your DoD (which is behavior).

Who is to "blame" if code that lacks tests is broken?

The person who committed the coded and whoever approved the untested commit (reviewers, technical leadership, etc).

Title: How to handle committed and merged code that has no tests?

Body:
When developing an application in a team not everyone on this team will be equally good developers. Some will be skilled in some things and some in others and some not at all.

As a team working in an agile process you usually have a definition of 'done' to follow. In our DoD it says never to merge code that is not documented and have proper tests. Sometimes though, a feature is so critical to some team member so the code has to be merged without tests. Sometimes a lazy developer might merge and call it a weekend.

A merge like this means that when other team members pull the code, they will receive code that may or may not function properly and since there are no tests it is hard to verify. It can be very cumbersome to walk through that code to make sure it works before the team member can work on their task.

It has happened on several occasions that the code that was committed without tests has been broken by other team members without them noticing.

So my question becomes:

How would you handle issues like this?

Does it point to bad planning rather then bad behaviour?

Who is to "blame" if code that lacks tests is broken?


问:
Setting up a simple Ruby\Rails environment
I am coming from a .NET background and beginning my journey into the Mac OSX\Ruby\Rails environment.

A lot of the resources I have found such as this one have between 5-10 steps for setting up a Ruby\Rails environment.

My question is, what are the bare minimum requirements for setting up a working Ruby\Rails environment?

Can I use RailsInstaller and be done?
Should I install all of the tools that the above link suggests (XQuartz, Homebrew, RVM, etc) even though I don't really know what they do?

Right now I am not being paid to do this, but am also curious what professional Rails developers do when setting up an environment.

I am also more concerned about the why as in why I shouldn't use RailsInstaller or why I should install RVM.

答:
Use this:
 http://ruby.railstutorial.org/ruby-on-rails-tutorial-book

It has an excellent walkthrough of the setup process.  I've set up RoR environments on OS X, Linux, and even FreeBSD (haven't tried Windows yet) using it.

I would also suggest picking up a good book on the Ruby language itself.  There's a lot of coolness there that you might not come across if you're doing standard CRUD-type stuff in Rails :)

Also, if you're a fan of IDEs (coming from .NET/VS), I would recommend RubyMine.  Some of the handholding it provides can be nice while you're learning.


答:
How would you handle issues like this?

This Depends in what position you are. If you're their boss - take actions to discipline then. If not, try to explain them, that working code ist the value of the company you're in. Everybody must be aware of this fact. I'm quite sure they will recognize what's wrong.

On the other hand, you should add the tests by yourself. If you don't make sure it will be tested now it might never get tested. Because, according to LeBlanc, later equals never.

Does it point to bad planning rather then bad behaviour?

Not if Tests has been included in the planning.

Who is to "blame" if code that lacks tests is broken?

As stated by thegrinner - the person who commited the code.