答:
In Chain of responsibility, a processing object which is unable to process a given entry will pass it to the next processing object.

For example, if you're building a system which will process messages from a hardware device, one processing object (PO₁) may be able to handle the control messages, another one (PO₂) — errors, and the last one (PO₃) — data flow.

If a message is neither a control message, nor an error, it is passed by the PO₁ to PO₂ and by the PO₂ to the PO₃ who will either process the message or throw an exception, because the message is not recognized.

Chain of responsibility pattern is convenient when you need to process something uniform, without modifying it.

If you use Chain of responsibility pattern, it would mean that:

Every processing object will be required to handle or pass a bunch of objects (probably grouped into one huge object) with information about sessions, request, etc. When one should pass so many information from a method to another, this is a sign that something may be wrong.

Some processing objects will modify the context. This is not something current in Chain of responsibility pattern.

The current flow in your question looks like an ordinary application flow. There is no need to use Chain of responsibility for that. For example, in this situation:

Check if the file exists and is readable.

Open the file.

Read its contents.

Check the header to ensure that the format is correct.

Verify the CRC.

Parse contents.

Compute the statistics from the parsed contents.

Return the statistical results.

the workflow is very similar, i.e. some of the steps may indicate that others shouldn't be done: for example if contents can't be parsed, it wouldn't make sense to compute the statistics, or if the header is invalid, there is no need to verify the CRC. However, Chain of responsibility pattern doesn't fit well here, because different steps use different data, and can modify it (or create additional data).

Title: Get rid of long/Complex if..else statements using Chain of Responsibility?

Body:
I've an HttpHandler, which allows users to login to a system by passing in an encrypted code.

Inside the ProcessRequest it performs quite a few steps.

Retrieve the encrypted code from request (could be in Form/X-Header/Query)

Decrypt it. (Results in an JSON string)

Deserialize to a dynamic type

Determine the type of request, could be login/register/activate

Validate request

Load user subscription

Load User entity

If Req.Type = Login -> Login using FormsAuth

If Req.Type = Register -> Create user

If Req.Type = Register -> Send Activation email

This goes on. Currently this is something like a long if/else statement which I'm trying to refactor.
I'm thinking of using the Chain Of Responsibility pattern to convert these steps in if/else to a chain which executes sequentially.
However, this will be different from original CoR as only last few steps will actually "handle" the request, first steps will just do some pre-processing and make stage for last steps to perform it's job.

My main problem is, different steps in the chain will work on different input data. First few steps (Decryption, Deserialization, etc) will work on strings while latter half should ideally work on deserialized dynamic object. I don't like the way it sounds.

Am I trying to fit a round lid to an square bottle? Is this not a scenario where CoR can/should be applied? Are there any other patterns/strategies I could use to solve such scenarios.

I thought of using the decorator pattern as well, but that doesn't suite me very well, as I'd like to be able to switch certain steps in and out (ex: email activation) for some scenarios.

NOTE: I've seen this question as well, but not sure if it answers my question.


问:
Get rid of long/Complex if..else statements using Chain of Responsibility?
I've an HttpHandler, which allows users to login to a system by passing in an encrypted code.

Inside the ProcessRequest it performs quite a few steps.

Retrieve the encrypted code from request (could be in Form/X-Header/Query)

Decrypt it. (Results in an JSON string)

Deserialize to a dynamic type

Determine the type of request, could be login/register/activate

Validate request

Load user subscription

Load User entity

If Req.Type = Login -> Login using FormsAuth

If Req.Type = Register -> Create user

If Req.Type = Register -> Send Activation email

This goes on. Currently this is something like a long if/else statement which I'm trying to refactor.
I'm thinking of using the Chain Of Responsibility pattern to convert these steps in if/else to a chain which executes sequentially.
However, this will be different from original CoR as only last few steps will actually "handle" the request, first steps will just do some pre-processing and make stage for last steps to perform it's job.

My main problem is, different steps in the chain will work on different input data. First few steps (Decryption, Deserialization, etc) will work on strings while latter half should ideally work on deserialized dynamic object. I don't like the way it sounds.

Am I trying to fit a round lid to an square bottle? Is this not a scenario where CoR can/should be applied? Are there any other patterns/strategies I could use to solve such scenarios.

I thought of using the decorator pattern as well, but that doesn't suite me very well, as I'd like to be able to switch certain steps in and out (ex: email activation) for some scenarios.

NOTE: I've seen this question as well, but not sure if it answers my question.

答:
Don't forget to consider the different responsibilities here.

You have

an encrypted request object that needs to be decrypted

a JSON deserializer

something that determines the request type

a request validator

some data access stuff

and something that chooses the next step to take

I would not advise you to put all that stuff in one IHttpHandler (SRP violation). Split if off along responsability lines and use composition in your handler. That will probably make it easier to read and you can test the different components in isolation.

OwnerDisplayName: BuddhiP

ContentLicense: CC BY-SA 3.0


问:
Best Practices To Create Error Codes Pattern For an Enterprise Project
I'm working on an enterprise project which will be deployed in many SMBs and Enterprises.

The support for this project would be struggling and so I want to create a coding pattern for errors (Like HTTP status Codes). This will enable help desk people to refer to documents and troubleshoot the problems as soon as possible.

What are the best practices and recommendations to do this?

Any help to do this will be useful.

答: I would go for custom exceptions with descriptive names and clear messages and throw those. It's a lot easier to use the existing exception infrastructure of a language than to build in support for passing error codes around and interpreting them.</p>

ContentLicense: CC BY-SA 4.0


问:
When was the earliest time that the term "snake case" was used?
Many people use the term Snake Case to describe variables or other symbols with_the_form_of_underscores.

In the past week, I've launched several broad searches. I can't find anything about the origin of this term that is more detailed than what Wikipedia says (above)

When did the earliest record of this term enter into use?

答:
The earliest use I found in Usenet is in a post by Gavin Kistner to comp.lang.ruby on 23rd February 2004:

While writing my ValidForm library (http://phrogz.net/RubyLibs/) I

realized that I was mixing camelCase [which I love] with

whatever_you_call_this_case [which I don't, but I see that Ruby uses a

lot of]. (BTW...what do you call that naming style? snake_case? That's

what I'll call it until someone corrects me.)

Ruby still uses this term today, for example in The Ruby Style Guide:

Use snake_case for symbols, methods and variables.

Use SCREAMING_SNAKE_CASE for other constants.


问:
Is there any functional difference between immutable value types and immutable reference types?
Value types are types which do not have an identity. When one variable is modified, other instances are not.

Using Javascript syntax as an example, here is how a value type works.

```<code>var foo = { a: 42 };
var bar = foo;
bar.a = 0;
// foo.a is still 42
</code>```

Reference types are types which do have an identity. When one variable is modified, other instances are as well.

Here is how a reference type works.

```<code>var foo = { a: 42 };
var bar = foo;
bar.a = 0;
// foo.a is now 0
</code>```

Note how the example uses mutatable objects to show the difference. If the objects were immutable, you couldn't do that, so that kind of testing for value/reference types doesn't work.

Is there any functional difference between immutable value types and immutable reference types? Is there any algorithm that can tell the difference between a reference type and a value type if they are immutable? Reflection is cheating.

I'm wondering this mostly out of curiosity.

答:
In brief: A Value Type holds the data within its own memory allocation and a Reference Type contains a pointer to another memory location that holds the real data. Reference Type variables are stored in the heap while Value Type variables are stored in the stack.

More: difference between a Value Type and a Reference Type

OwnerDisplayName: Kendall Frey


问:
What is the (craziest, stupidest, silliest) thing a client/boss asked you to do?
See title, but I am asking from a technical perspective, not

Take my 40 year old virgin niece on a date or you're fired.

答: To learn a whole new programming language over the weekend.</p>

ContentLicense: CC BY-SA 2.5


问:
What justifies the use of an IDE versus a standard editor?
I find myself using my text editor of choice (vim, nano, gedit, pick your poison) much more often than any IDE as of late.

After noticing my ide shortcuts getting dusty I started to think about this and wonder: what justifies use of an IDE for you opposed to a text editor?

For that matter what rationale would you have for not using an IDE and merely relying on an editor?

答:
Depending of course on your language, some IDE's also include visual Form/Window designers.

Though it should be pointed out, the line between a programmer's text editor and an IDE is not a well defined one.  Many editors can be extended to handle compiling, code completion, debugging, etc.


问:
ASP.NET without viewstate input, How comes?
I got surprised when I visited some sites with an 'aspx' extension at the end of their URLs and when I looked at their html source I didn't see any view state like the follwing:

```<code><input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="SNIKalxBOk0/lp+SgXklgi/0/IUoRXTjEjp6NrL2ColFXGht1bTDit5V+wHdkcuM3YVmVNKG1jpM6zAg+MQCnvPDvlEvK8RNwHblq8NN1Ys=" />
</code>```

How did they prevent this to happen? even if you turn the view state off you'll get at least of of the above input in your HTML output.

Here is one of the examples that I looked at: http://www.ada.org/index.aspx

答:
The site, or at least the pages I clicked on, are almost certainly not using WebForms. One of the key give-aways is the complete lack of a single top-level form such as:

```<code><body>
   <form method="post" action="/">
</code>```

That combined with the lack of __VIEWSTATE and __EVENTTARGET and __EVENTARGUMENT hidden inputs  seems fairly conclusive. However looking at the HTML for the site the following jumps out at me:

```<code><span id="ADASlideShow1_rptSlideshow_ctl03_lblVideoType" style="display: none;">None</span>
</code>```

The id is typical webforms output so this would suggest that either:

They have ported an ASP.NET WebForms site over to some other technology (possibly just plain HTML contained in a .aspx file - as the previous poster mentioned the functionality seems to be done using Flash and jQuery) and retained the HTML structure and ids in order to keep the CSS and Javascript in working condition.

Or they are using ASP.NET WebForm controls but with all ViewState and control interactions turned off - however I'm fairly sure that without the top level form tag webform controls just won't work at all (however it's been a while since I did any webforms work so I could be proved wrong).

Body:
The site, or at least the pages I clicked on, are almost certainly not using WebForms. One of the key give-aways is the complete lack of a single top-level form such as:

<body>
   <form method="post" action="/">

That combined with the lack of __VIEWSTATE and __EVENTTARGET and __EVENTARGUMENT hidden inputs  seems fairly conclusive. However looking at the HTML for the site the following jumps out at me:

<span id="ADASlideShow1_rptSlideshow_ctl03_lblVideoType" style="display: none;">None</span>

The id is typical webforms output so this would suggest that either:

They have ported an ASP.NET WebForms site over to some other technology (possibly just plain HTML contained in a .aspx file - as the previous poster mentioned the functionality seems to be done using Flash and jQuery) and retained the HTML structure and ids in order to keep the CSS and Javascript in working condition.

Or they are using ASP.NET WebForm controls but with all ViewState and control interactions turned off - however I'm fairly sure that without the top level form tag webform controls just won't work at all (however it's been a while since I did any webforms work so I could be proved wrong).


问:
Should you write automated tests to check that data is correct (the contents of config files, databases, etc.)?
Simply put: is there a best practice for whether developers should write automated tests to check that data is correct (the contents of config files, databases, etc.)? If so, what is it?

Assume that the data is static for a given release, and specified as part of requirements.

答:
A tester must control the relationship between inputs and outcomes of its tests in order to reliably check the correctness of the execution. This relationship is called an oracle.

Usually this is performed by owning the input data, in which case data check is useless.

If the oracle is straightforward, the tester doesn't need to control input data: run the oracle on input and outcome to tell whether the test has succeded or failed. Data check is useless again. The drawback is that the tester doesn't control the execution path and therefore the test coverage.

The only case when data check is required is when assumptions are made by the software under test about its inputs and these inputs are not under tester control (e.g., a division algorithm implementing successive substractions: a null divider puts the execution in an infinite loop).


答:
Your ProcessRequest method is doing too much in one block of code.  Chain of Responsibility is an inappropriate pattern because some of these steps are mandatory and some are alternatives.

Look at the last 3 steps - 8 to 10.  Your main method should not care what has to be done for each individual type of request.  All that should be happening here is

Is the request type in my set of permitted types?

If yes, invoke the corresponding class

If no, handle the error.

That's going to be a very short block of code.  It does require you, somewhere else in your code, to create your request-type-specific class (and subclasses) and the set to contain them, but the benefit is that this block of code in your main method need never change.

Step 5 should be a method of the type-specific class.

Steps 6 and 7 can probably be encapsulated in a User object but also only mean something for existing users, so the User-object handling stuff should go inside the type-specific class.

So we've already reduced the code to

Retrieve the encrypted code from request (could be in Form/X-Header/Query)

Decrypt it. (Results in an JSON string)

Deserialize to a dynamic type

Determine the type of request, could be login/register/activate

if type in set-of-allowed-types then request-type = new type-specific-class else fail.

if not request-type.validate() then fail

request-type.dostuff()

See?  No patterns involved.  If-then-else chains are a bad smell, yes, but they can usually be replaced with a set of valid options or a switch statement.  Try that simple approach before going all pattern-mad.


答:
You first have to isolate the areas where errors might occur, and are user-visible. Then you can document them. Its that simple.

Well, simple in theory.. in practice errors can occur all over the damn place, and reporting them can turn nice code into a monster of logging, exception throwing and handling, and passing return values.

I would recommend a 2-step approach then. First is to log, log lots and lots.

Second is to determine the major components and their interfaces, and to define what major error cases these components can find themselves in. You can then log in a more visible manner when one of these errors (how you handle the error internally is up to you - exceptions or error codes make no difference here). A user will generally then see the error and go to the logs for more detailed information.

The same approach is used for web servers and your http error code example. If the user sees a 404, and reports it to support, they will look in the logs for the details of what was going on, which page was visited, when, and will glean any other info they can from where-ever else make sense, be in the DB, the network or the application.

Title: Best Practices To Create Error Codes Pattern For an Enterprise Project

Body:
I'm working on an enterprise project which will be deployed in many SMBs and Enterprises.

The support for this project would be struggling and so I want to create a coding pattern for errors (Like HTTP status Codes). This will enable help desk people to refer to documents and troubleshoot the problems as soon as possible.

What are the best practices and recommendations to do this?

Any help to do this will be useful.


问:
Where should I put methods that make an Http Request to get data from a web service in iOS development?
I have a Model Car in my iOS application where it's parameters like name, year, value etc are fetched from a web service in order to fill a list with cars data.

Where should I put the method that asynchronously goes to the server and returns an array of cars (this method already converts the JSON to a Car array)?

My current approach is a static method in my Car class that receives an HttpClient (so I'm able to unit test it mocking the client) and returns an NSArray of cars, is this good?

What have you guys done in this situation?

I'm concerned because I recently started reading clean code which says that a Class should do only one thing, and the way I have it now appears to do 2 things (hold information about a Car and get a list of cars).

答:
I would recommend a CarBroker Object that handles requests for Cars and exposes methods like:

getCars - for getting a list of all cars.

getCarByID - for a specific car.

Further such an object can handle request from other car brokers(should it need to). Either way it has one real area of responsibility - Brokering Cars - as opposed to being a Car Object with the responsibilities of a Car Object and an Object Broker.

OwnerDisplayName: Raphael Oliveira


问:
How can I send audio input as chunked HTTP?
I am trying to create an interface with an external server, and don't know where to start.   I would need to take audio as input to my computer, and send it to the remote server as a chunked HTTP request.  The API that I'm trying to connect to is described here p1-5

http://dragonmobile.nuancemobiledeveloper.com/public/Help/HttpInterface/HTTP_Services_for_NDEV_v1.2_Silver_Version.pdf

I have never worked with audio programmatically, so don't know what would be the most straightforward way to go about this?   Are there solutions that exist out there that already do this?

I've come across references to Shoutcast, VLC, Icecast, FFMPeg, Darkice, but I don't know if those are appropriate for what I'm trying to accomplish or not.

答:
IceCast, ShoutCast and the like aren't going to help you except in that they employ the ffmpeg library to do their encoding and stream utility functions.

You'll need to download the ffmpeg library it is written in c but has wrappers written most languages if you are not comfortable writing in native c code.  You will also want to check out the ffmpeg develper docs.

Do not, I mean it DO NOT attempt to do the encoding yourself unless you already are extremely comfortable with this procedure or have a LOT of time to spend on this. Use the standard PCM encoding that is offered by ffmpeg.


问:
things to think of when moving into C-land
Hello

Over the years have I made a programming journey from C in 1990 to Pascal, C++ with I programmed commercially, java VHDL, C# and now I'm taking a look on F#.

In the spring I will go back to study embedded programming in C in a university course so before I do that I will refresh my knowledge in C.

I don't remember much of the C that I learnt and I think I am thankful for that for probably learned some bad habits back then.

I have some questions to get me on the way.

--edit--

To clarify: I am thankful for tips that have been given regarding embedded programming but now I am more interested in relearning C in general. Sorry if my question was unclear,

Compiler, Debugger, IDE? As a microslave I was thinking about 2010 C++ Express, any alternatives?

Where do you find good libraries with code for C. I'm thinking something similar to Boost, POCO in C++

Source for procedural programming patterns and best practices. Where can you find good code learn from?

Thanks in advance

Gorgen

答:
GCC, GDB, Eclipse can be a decent multi-platform alternative.

From my experience, especially in embedded environment, you more often have to build your own specific library, than use a third party library that may be too big, or not enough. There is always small code snippets for FTP connection, or bigger libraries for SQL support, but I find it really project-specific so far, not widespread like boost. I'd like to hear from others as well for this specific point.

K&R, C interfaces and implementations , Expert C Programming are good C readings.


问:
Does Scrum make sense when implementing a new compiler backend?
I have an existing language that I need to port to a new platform. I'll probably attempt this by changing the backend of the existing compiler.

It is a significant amount of work to re-write the backend. I can't see a way breaking this down into sensible stories without violating INVEST criteria.

I can't see how each story can be Negotiable - they are all required for a working compiler. The stories are all of equal priority and it doesn't matter what order I deliver them. I need to do them all.

There are some parts of the software I'm implementing that are lower priority than others and I can see that we can deliver that incrementally. However, there is a significant core that is Must Have.

I plan on trying to follow Scrum, but am I just going through the motions?

Are there recommended practices for this kind of project?

答:
Yes it does, as long as you remember that Scrum is not a set of strict rules to follow. You can adjust it to your project. Sprints, standups, weekly scrums will still be useful in order to foster better communication between team members and to make sure the project continues in the direction that was intended.

All stories might seem to have an equal priority, but you need to take into account the relative difficulty of implementing them. You don't want to keep your most difficult items until the end of the project. You will want to start working on them as soon as possible.


答:
Bear in mind that the main reason Agile processes were created was to cope with shifting requirements. If requirements are set in stone (truly fixed requirements are rare but I'll take you at your word here!) then some of the best practices for dealing with changing requirements - e.g. Negotiable stories - become somewhat irrelevant. That said, following a Scrum workflow still has a lot of potential value in terms of scheduling and providing deliverables. Even if your deliverables won't constitute a fully usable product for a while, there's still something to be said for being able to demonstrate progress to your customer (and the team!).

Consider that all those 'must have' stories comprise a single epic: "Be able to compile on platform X". In this case the whole epic needs to be completed before any value is delivered to the user, but this is often the case at the start of large projects. Start with a story to compile the simplest possible program, then create further stories to support more and more language features.

Above all, don't get too hung up on trying to force every situation to fit into a highly generalised approach. Agile is supposed to work for you, not the other way around!

Title: Does Scrum make sense when implementing a new compiler backend?

Body:
I have an existing language that I need to port to a new platform. I'll probably attempt this by changing the backend of the existing compiler.

It is a significant amount of work to re-write the backend. I can't see a way breaking this down into sensible stories without violating INVEST criteria.

I can't see how each story can be Negotiable - they are all required for a working compiler. The stories are all of equal priority and it doesn't matter what order I deliver them. I need to do them all.

There are some parts of the software I'm implementing that are lower priority than others and I can see that we can deliver that incrementally. However, there is a significant core that is Must Have.

I plan on trying to follow Scrum, but am I just going through the motions?

Are there recommended practices for this kind of project?


答:
Of course Scrum is useful. It's a methodology that does two things for you:

It allows your project to adapt to change and

It allows you to track progress, and get an idea on when it will be finished

So, there's some value in using it.

I think some of your preconditions are not correct and that's where you are getting lost.

I can't see how each story can be Negotiable - they are all required for a working compiler

This is not true. You can support a subset of the language and still have a compiler that works under certain conditions. Surely less valuable than a full compiler, but still valuable.

Also, you misunderstand what "Negotiable" means: it does not necessarily mean "Optional" and there is no requirement that stories are optional in INVEST. A story is a valuable objective and the negotiation is on how to reach that objective. Surely there's going to be more than way of implementing the backend of each language feature. There's where you need negotiation.

The stories are all of equal priority and it doesn't matter what order I deliver them.

This is not correct, as you say below that some stories are not "must have", so certainly some are less valuable. But even in the "must have" category: some language features are much more fundamental than others, and measurably so.

One way to measure this is "how much more lines of code we can compile on an existing codebase" or "how many more tests pass" if you have a predefined suite of tests.

There are also other options. If you were compiling a C-like language, strictly speaking you only need a if and goto loop to have a (barely) functional language and you can implement while, for and repeat as macros. Assuming it's easy enough to write a use a precompiler, you can have a cheap stopgap solution (hey, are we negotiating? :-)

Regarding, adaptability, supporting a language is a fairly static set of requirements, but languages also change and also your knowledge of your needs change. Do you need to implement everything? Are there things you don't need specifically for your aims? One of the basic tenants of agile is the knowledge of having incomplete knowledge, can you leverage it?

In conclusion, to answer your question more directly: do you need agile processes when your requirements are unchangeable? Definitely not! Are they usable? Probably yes! Are they worth your time? Probably not - but are your requirements unchangeable? In my past experiences, "unchangeable requirements" => "lazy product owner" - not a rule, but worth keeping in mind.


答:
TL;DR

All project management controls add overhead. Don't add overhead you don't need.

Scrum is the Wrong Hammer Here (Don't Be a Nail)

Scrum is a project management framework rather than a set of development practices suitable for an individual developer. Unless you are doing project management, Scrum is probably the wrong choice.

In addition, when you say:

The stories are all of equal priority and it doesn't matter what order I deliver them. I need to do them all.

you are implying a couple of things:

The project has zero value unless all stories are 100% complete.

The stories are not dependent on one another.

If both of these statements are true, then there's really no point in using a framework or practice designed to prioritize work by value or dependency-order.

Suggested Alternatives

Any development project could potentially benefit from some agile practices. In particular, in your specific case I would recommend:

Ensure all your stories have a "definition of done" that includes unit- and acceptance-testing.

Integrate and refactor often; don't leave yourself with a giant integration task at the end of the project.

Additionally, even if your product truly has zero value unless all stories are done, I'd spend some time grouping the stories into themes that you can treat as completed milestones. Being able to say "I've completed the foo feature" is often more useful than saying "I've got 23/117 random stories done." YMMV.


问:
How i may develop in php and html?
I am learning php from the internet on codeacademy.com. I have also learned html and css but the problem that i dont know how can i build a complete website then !

I study everything on its side. But how to put all my knowledge together its very hard! like when should i use this php code? When should i use the html code? So that i can make a full website.

答:
like when should i use this php code? and when i should use that html code etc.

You would need first to understand the concept of server-side technology(C#, java, Php, et..) and client-side technology (HTML, CSS, JS, etc..). The good source of learning is starting with a good book of web-development. Jumping from one video tutorial to another will not help.

Basic terminology on web development could be found here,
and a related SE discussion on thus terminology could be found here.

Here is a good SE question and discussion on this topic.

Title: How i may develop in php and html?


答:
There is a difference between error codes and error return values. An error code is for the user and help desk. An error return value is a coding technique to indicate that your code has encountered an error.

One can implement error codes using error return values, but I would advice against that. Exceptions are the modern way to report errors, and there is no reason why they should not carry an error code within them.

This is how I would organize it (Note that points 2-6 are language agnostic):

Use a custom exception type with an additional ErrorCode property. The catch in the main loop will report this field in the usual way (log file / error pop-up / error reply). Use the same exception type in all of your code.

Do not start at 1 and don't use leading zeros. Keep all error codes to the same length, so a wrong error code is easy to spot. Starting at 1000 usually is good enough. Maybe add a leading 'E' to make them clearly identifiable for users (especially useful when the support desk has to instruct users how to spot the error code).

Keep a list of all error codes, but don't do this in your code. Keep a short list on a wiki-page for developers, which they can easily edit when they need a new code. The help desk should have a separate list on their own wiki.

Do not try to enforce a structure on the error codes. There will always be hard-to-classify errors and you don't want to discuss for hours whether an error should be in the 45xx group or in the 54xx group. Be pragmatic.

Assign each throw in your code a separate code. Even though you think it's the same cause, the help desk might need to do different things in different cases. It's easier for them to have "E1234: See E1235" in their wiki, than to get the user to confess what he has done wrong.

Split error codes if the help desk asks for it. A simple if (...) throw new FooException(1234, ".."); else throw new FooException(1235, ".."); line in your code might save half an hour for the help desk.

And never forget that the purpose of the error codes is to make life easier for the help desk.


答:
I understand your concerns, but I believe there is still value for you in using scrum.

Admittedly, the user stories are much more fixed than in a consumer facing application. So that aspect of scrum will provide less value.

Where I think you will get value is from the iterative and frequent releases. Having a potentially releasable product at the end of every sprint compels you to keep code quality high and technical debt low. It is also a great way to find defects early.

I think you would also benefit from knowing your velocity. After several sprints, you can see how many effort points your team is finishing each sprint. This gives you an objective metric to help determine your ship date.

Above all, remember that agile is adjective. At the end of every sprint, you ought to be holding a retrospective meeting and then tailoring your process to your needs. If there is a part of the scrum process that doesn't apply to compiler development, remove it. If there is some other process element that would benefit you, add it. The most important part of agile in my opinion is to be cognizant of your process and be constantly improving for your specific situation.

(Please note, I've never done scrum on a compiler project; take my advice with a grain of salt.)


答: HTML is used for semantically formatting (structuring) the data that you get from PHP (or any other such backend...), to put it very simply. CSS is used to change how the HTML looks. JS can be used to do special graphical effects or simple data processing (remove things after clicking, and so on) with the HTML.</p>

Title: How i may develop in php and html?

Body:
I am learning php from the internet on codeacademy.com. I have also learned html and css but the problem that i dont know how can i build a complete website then !

I study everything on its side. But how to put all my knowledge together its very hard! like when should i use this php code? When should i use the html code? So that i can make a full website.


问:
Java exception redundancy
To what extent should one make exceptions redundant or atomic to a method.

For instance, suppose I have a method public void authenticate(String username, String password) that calls private void invokeServer(String username, String password).

Both methods require those params to be non-zero length, and as such I would raise a NullPointerException if needed. Should I sanity check in invokeServer as well as authenticate on the basis that it could potentially be used independently at a later date?

答:
First of all, non-empty and NullPointerException are two different beasts, so you should definitely not throw a NPE for a non-null empty string.

In general, it makes sense to think about your exceptions on a higher level than just the null/non-empty-kind of level. In your case, you are taking about a username, or even more general, when you combine the two attributes you are talking about Login Credentials. And lo and behold, both of your methods in one way or another deal with login credentials, so a InvalidLoginCredentialsException or some such nicely fits both places (and probably others as well).

When you think about the error cases from the viewpoint of your business or customers, by assigning use-cases or domains (or any fancy word like that, which is currently en vogue), then you should have a much easier time to deduce exceptions at a useful granularity level.

Title: Java exception redundancy


答:
They are using viewstate --- but it looks like they did disable it for the home page and some of the major landing pages, see http://www.ada.org/productguide/c/28/Caries-Detection-Systems for an example of a page with viewstate.

Really not too hard a trick to pull off if your site is largely a brochure site such as this one.

Title: ASP.NET without viewstate input, How comes?

Body:
I got surprised when I visited some sites with an 'aspx' extension at the end of their URLs and when I looked at their html source I didn't see any view state like the follwing:

```<code><input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="SNIKalxBOk0/lp+SgXklgi/0/IUoRXTjEjp6NrL2ColFXGht1bTDit5V+wHdkcuM3YVmVNKG1jpM6zAg+MQCnvPDvlEvK8RNwHblq8NN1Ys=" />
</code>```

How did they prevent this to happen? even if you turn the view state off you'll get at least of of the above input in your HTML output.

Here is one of the examples that I looked at: http://www.ada.org/index.aspx


答:
Short version

In your case one check should be enough. In which method depends on your code and coding-guidelines.

Long version

First of all, you need to sanity-check input on the server. If there is a problem, the server should throw a BusinessException (with an appropriate message).

On the client side, you have two options:

give it a try, send the input to the server, and present the potential error to the user.

sanity-check the input-values to tell the user something's wrong even before sending data to the server (e.g. in JSF you can register validators for components).

Finally, you still have to cope with the potentially thrown BusinessExceptions on the client side, because it is possible that the input seems valid but the server still reports an error. Therefore you should implement some kind of GeneralErrorHandler on the client, which catches any uncaught exceptions and presents them in a human readable way.

(Keep in mind, that the user's language may differ to the one of the exception-message.)

Title: Java exception redundancy

Body:
To what extent should one make exceptions redundant or atomic to a method.

For instance, suppose I have a method public void authenticate(String username, String password) that calls private void invokeServer(String username, String password).

Both methods require those params to be non-zero length, and as such I would raise a NullPointerException if needed. Should I sanity check in invokeServer as well as authenticate on the basis that it could potentially be used independently at a later date?


问:
Rationale behind C library functions never setting errno to zero
The C standard mandates that no C standard library functions shall set errno to zero. Why exactly is this?

I could understand it being useful for calling several functions, and only checking errno after the last one - for example:

```<code>errno = 0;
double x = strtod(str1, NULL);
long y = strtol(str2, NULL);
if (errno)
    // either "strtod" or "strtol" failed
else
    // both succeeded
</code>```

However, is this not considered "bad practice"? Since you're only checking errno at the very end, you only know that one of the functions did fail, but not which function failed. Is simply knowing that something failed good enough for most practical programs?

I tried looking for various C Rationale documents, but many of them don't have much detail for <errno.h>.

答:
You can do error check for both of the function call, if you really care about.

```<code>errno = 0;
double x = strtod(str1, NULL);
if (errno)
    // strtod"  failed
else
    // "strtod" succeeded

long y = strtol(str2, NULL);
if (errno)
    // "strtol" failed
else
    // "strtol" succeeded
</code>```

Since we never know how mach function called in a process , how can the lib set errnos for each function call, Right?

OwnerDisplayName: Drew McGowen

Body:
You can do error check for both of the function call, if you really care about.

errno = 0;
double x = strtod(str1, NULL);
if (errno)
    // strtod"  failed
else
    // "strtod" succeeded

long y = strtol(str2, NULL);
if (errno)
    // "strtol" failed
else
    // "strtol" succeeded

Since we never know how mach function called in a process , how can the lib set errnos for each function call, Right?

OwnerDisplayName: Lidong Guo


答:
The C library does not set errno to 0 for historical reasons1. POSIX no longer claims its libraries will not alter the value in case of success, and the new Linux man page for errno.h reflects this:

The <errno.h> header file defines the integer variable errno, which is set by system calls and some library functions in the event of an error to indicate what went wrong. Its value is significant only when the return value of the call indicated an error (i.e., -1 from most system calls; -1 or NULL from most library functions); a function that succeeds is allowed to change errno.

The ANSI C Rationale states that the committee felt it was more practical to adopt and standardize the existing practice of using errno.

The error reporting machinery centered about the setting of errno is generally regarded with tolerance at best.  It requires a ``pathological coupling'' between library functions and makes use of a static writable memory cell, which interferes with the construction of shareable libraries.  Nevertheless, the Committee preferred to standardize this existing, however deficient, machinery rather than invent something more ambitious.

There is almost always a way to check for error outside of checking if errno got set. Checking if errno got set is not always reliable, since some calls require calling a separate API to get the error reason. For instance, ferror() is used to check for an error if you get a short result from fread() or fwrite().

Interestingly enough, your example of using strtod() is one of the cases where setting errno to 0 before the call is required to correctly detect if an error has occurred. All the strto*() string to number functions have this requirement, because a valid return value is returned even in the face of an error.

```<code>errno = 0;
char *endptr;
double x = strtod(str1, &endptr);
if (endptr == str1) {
    /*...parse error */
} else if (errno == ERANGE) {
    if (x == 0) {
        /*...underflow */
    } else if (x == HUGE_VAL) {
        /*...positive overflow */
    } else if (x == -HUGE_VAL) {
        /*...negative overflow */
    } else {
        /*...unknown range error? */
    }
}
</code>```

The above code is based on the behavior of strtod() as documented on Linux. The C standard only stipulates that underflow cannot return a value greater than the smallest positive double, and whether or not errno is set to ERANGE is implementation defined2.

There is actually an extensive cert advisory write-up that recommends always setting errno to 0 before a library call and checking its value after the call indicates a failure has occurred. This is because some library calls will set errno even if the call itself was successful3.

The value of errno is 0 at program startup, but it is never set to 0 by any library function. The value of errno may be set to nonzero by a library function call whether or not there is an error, provided the use of errno is not documented in the description of the function in the C Standard. It is meaningful for a program to inspect the contents of errno only after an error has been reported. More precisely, errno is meaningful only after a library function that sets errno on error has returned an error code.

1. Previously I claimed it was to avoid masking an error from an earlier call. I can't find any evidence to support this claim. I also had a bogus printf() example.

2. Thanks to @chux for pointing this out. Reference is C.11 §7.22.1.3 ¶10.

3. Pointed out by @KeithThompson in a comment.

Title: Rationale behind C library functions never setting errno to zero

Body:
The C standard mandates that no C standard library functions shall set errno to zero. Why exactly is this?

I could understand it being useful for calling several functions, and only checking errno after the last one - for example:

```<code>errno = 0;
double x = strtod(str1, NULL);
long y = strtol(str2, NULL);
if (errno)
    // either "strtod" or "strtol" failed
else
    // both succeeded
</code>```

However, is this not considered "bad practice"? Since you're only checking errno at the very end, you only know that one of the functions did fail, but not which function failed. Is simply knowing that something failed good enough for most practical programs?

I tried looking for various C Rationale documents, but many of them don't have much detail for <errno.h>.

Body:
The C library does not set errno to 0 for historical reasons1. POSIX no longer claims its libraries will not alter the value in case of success, and the new Linux man page for errno.h reflects this:

The <errno.h> header file defines the integer variable errno, which is set by system calls and some library functions in the event of an error to indicate what went wrong. Its value is significant only when the return value of the call indicated an error (i.e., -1 from most system calls; -1 or NULL from most library functions); a function that succeeds is allowed to change errno.

The ANSI C Rationale states that the committee felt it was more practical to adopt and standardize the existing practice of using errno.

The error reporting machinery centered about the setting of errno is generally regarded with tolerance at best.  It requires a ``pathological coupling'' between library functions and makes use of a static writable memory cell, which interferes with the construction of shareable libraries.  Nevertheless, the Committee preferred to standardize this existing, however deficient, machinery rather than invent something more ambitious.

There is almost always a way to check for error outside of checking if errno got set. Checking if errno got set is not always reliable, since some calls require calling a separate API to get the error reason. For instance, ferror() is used to check for an error if you get a short result from fread() or fwrite().

Interestingly enough, your example of using strtod() is one of the cases where setting errno to 0 before the call is required to correctly detect if an error has occurred. All the strto*() string to number functions have this requirement, because a valid return value is returned even in the face of an error.

errno = 0;
char *endptr;
double x = strtod(str1, &endptr);
if (endptr == str1) {
    /*...parse error */
} else if (errno == ERANGE) {
    if (x == 0) {
        /*...underflow */
    } else if (x == HUGE_VAL) {
        /*...positive overflow */
    } else if (x == -HUGE_VAL) {
        /*...negative overflow */
    } else {
        /*...unknown range error? */
    }
}

The above code is based on the behavior of strtod() as documented on Linux. The C standard only stipulates that underflow cannot return a value greater than the smallest positive double, and whether or not errno is set to ERANGE is implementation defined2.

There is actually an extensive cert advisory write-up that recommends always setting errno to 0 before a library call and checking its value after the call indicates a failure has occurred. This is because some library calls will set errno even if the call itself was successful3.

The value of errno is 0 at program startup, but it is never set to 0 by any library function. The value of errno may be set to nonzero by a library function call whether or not there is an error, provided the use of errno is not documented in the description of the function in the C Standard. It is meaningful for a program to inspect the contents of errno only after an error has been reported. More precisely, errno is meaningful only after a library function that sets errno on error has returned an error code.

1. Previously I claimed it was to avoid masking an error from an earlier call. I can't find any evidence to support this claim. I also had a bogus printf() example.

2. Thanks to @chux for pointing this out. Reference is C.11 §7.22.1.3 ¶10.

3. Pointed out by @KeithThompson in a comment.

OwnerDisplayName: jxh


问:
Must OpenCL code be compiled for a specific GPU?
Most OpenCL Tutorials give a nice introduction to OpenCL, yet I have not found information on the question of interoperability of the compilation targets. It seems that I have to compile OpenCL code for the target GPU. Now when making a binary distribution of an application using OpenCL, does one have to make several builds for the vendor-platforms?</p>

答: No, you do not need to have a per-target-platform compiled binary: OpenCL's API supports compiling kernel binaries for several different devices, and obtaining the compiled code with clGetProgramInfo(). You can do this for several target platforms, place all your binaries in your distribution, and ship that.


问:
Mixing Angular and ASP.NET MVC/Web api?
I come from using ASP.NET MVC/Web API and now I am starting to use Angular but I am not clear on the proper way to mix them.

Once I am using Angular does the MVC server side concepts still provide any value? Or should I strictly be using Web API purely to get data for the angular HTTP calls?

Is there maybe a more stripped down starting point I should use if the VS template is adding a lot of stuff I don't need?

I like the idea of a strict divide of server side = pure data and client side = pure HTML processing.

答:
Is there maybe a more stripped down starting point I should use if the VS template is adding a lot of stuff I don't need?

These VS templates are good to trim down initial setup and learning curve in the beginning, however you would need to customize them for your real project needs.

For example, on this site http://www.reviewstoshare.com, my friend using AngularJS along with ASP.NET MVC. Keep in mind that this site was already built using ASP.MVC + Jquery for in page interaction as needed.

On the other hand there is still some "Ajaxy" nature to the site like comments, voting, flagging etc. Not too different than Stackoverflow itself. Before AngularJS it was a mess of Jquery plugins and functions within $(document).ready() callback, not to mention the JS code was not testable much.

Overall, having a proper mix of both make your site slick and functional.

Some good references to look:

My Experience With AngularJS - The Super-heroic JavaScript MVW Framework

More FlipBoard Magazines: Azure, XAML, ASP.NET MVC & Web API

AngularJS for .NET developers

Cookbook for ASP.NET MVC and Angular.js Web Apps

Single-Page App with AngularJS and ASP.NET MVC 4

Title: Mixing Angular and ASP.NET MVC/Web api?


答:
The easiest way to think about it is that the server serves a state. Angular can manage collecting the updates to that state and send it to an web/api on the server. If you want to go more single page app, then the server side code would be just the initial state of your app.

Web API is a excellent place to start for for pulling your data into your app. You will eventfully update the default routs to meet your environments design requirements and if you want, to be strictly rest-full.

There are quire a few libraries that ASP4 included by default and those were also included in the MVC4 templates. There really are many things included in the page that are not needed, as wells as included in the project and never even referenced by their default pages. You should be safe removing everything except jQuery and I even go as far as taking out jQueryUI. Many of the defaults mean well but once you start to fill in your domain knowledge you will use libs that meets your specific needs.

Even with a strict divide you will find server side mvc is still a very clean backing to a single page app. Effective routing in delivering your page and your api calls is a prime example. Another useful feature are controllers that return views that don't use the master page or are only a partial view. Angular has a "view" that it can fill with a template, which can be a static file or a partial from one of your routes.

I read you comment earlier today and threw together a demo solution to show what I originally mentioned. The solution also has some of the original "fluff" removed though when adding Angular and Bootstrap you get the core libraries and every derivation there with. That's the trade off of using nuGet.

Check it out:
https://github.com/QueueHammer/AngularWithPartialViewViews

In learning Angular I found the Angular-Seed program fairly helpful. Especially after I tried the demos on their site. The sample project is just different enough that it helps you learn. After that I looked at Angular-Require-Seed but that's another post.
Angular Step by Step
http://docs.angularjs.org/tutorial
Angular Seed:
https://github.com/angular/angular-seed

Title: Mixing Angular and ASP.NET MVC/Web api?

Body:
I come from using ASP.NET MVC/Web API and now I am starting to use Angular but I am not clear on the proper way to mix them.

Once I am using Angular does the MVC server side concepts still provide any value? Or should I strictly be using Web API purely to get data for the angular HTTP calls?

Is there maybe a more stripped down starting point I should use if the VS template is adding a lot of stuff I don't need?

I like the idea of a strict divide of server side = pure data and client side = pure HTML processing.


问:
How will I restrict the number of users logged in based on session?
I have a software (in cloud) with so many registered users.

I want to restrict the number of users logged in at a time to certain number (configuration based, let's say 100).

If the 101 user tries to login he should be placed in queue with priority 1, subsequently 102 user should be 2 in queue, I know at every time a logged in users request is hitting the server the sess_file access time will be updated.

What should be the logic from here? Should I check the last accessed time of all the sess_file and log-out the uses that are idle? and how will I manage the waiting queue?

Software is done with PHP-MySQL.

When the user is logged in I mark the column as logged in in user table, and when the log-in page is loaded if the total logged in user count is 100, the 101 user who is trying to log-in is directed to a intermediate page which will check via ajax call fired at an interval of 5 mins that if any user is logged out. If a slot is available it redirects to the log-in page, automatically logs in and redirects to the user dashboard. But I want to know any better practice is there.

Mostly I want to know the invalidation of logged in user by checking the access time of sess_file is the right way to do it?

答:
My first ideia is to run a function when an user logs in, then increment the count +1, and then when the user logs out, decreases the count in -1. A single database field can work this out and make what you're proposing when the count reach 100 logged users!

I mean it's pretty simple actually and very usefull, send me your login and logout functions (session-based) and i can show you some ways to do that!


问:
What about using MVC as the way to provide Responsive Web Design?
Responsive Web Design shows the user different elements -- or elements arranged in different ways -- by using media queries (if the device is a desktop or laptop, show them this; if a tablet, show them that; if a "phone," show them the other thing) or other methodologies.

What about, though (especially if your app/site uses MVC anyway), leveraging MVC to return different Views based on the type of device / user agent?

Each Model/Controller pair could have at least three Views (desklaptop, tablet, phone, as well as perhaps more granular gradations and/or Views tailored to larger devices) and, based on the size of the user agent's real estate, invoke the appropriate View.

I'm thinking this might be a more natural and easier to implement way of optimizing the experience for all users, at least for those conversant with MVC. How exactly this is implemented (how the user agent is determined and the appropriate Controller ActionResult is invoked) I'm not sure, though... thoughts?

UPDATE

Response to the comment and answer:

I'm thinking more along the lines of this scenario, for which, IMO, media-queries won't satisfactorily handle:

Your app/site has as its centerpiece a map. There are ancillary but vital pieces that are placed around the map (top, botton, and side) that all fit on a tablet (barely) and larger devices just fine. On a phone, though - no way - there's only room for the map, and even then the map is almost too puny.

The only way I can think of to deal with this is to show the map full-screen on the phone, with buttons or links in states like Wyoming, Montana, and Nevada that will invoke the parts that surround the map on larger devices but will monopolize the screen on a phone. In each case, the currently displaying View will need links to [re]open the other portions of the app/site.

Otherwise, the only way it could be usable with a phone is if the user is carrying a magnifying glass around with him (or zooming and swiping around the screen like a madman, but IMO that's a pain in the gluteus maximus).

And so, in such a scenario it seems to me that Views would be easier to implement than altering the CSS, as this is a major renovation of the screen, not just a rearranging of furniture.

答:
Take a look at Sencha Touch.

http://www.sencha.com/products/touch/

It doesn't tell you exactly how to do it, but it implements a very powerful version of "profiles", which utilize not only the screen size / resolution of your device, but also the type of device (ex. tablet, phone, etc.), and the OS of the device (Windows Phone 8, iOS, Android, etc.) and caters the layout to that of your device.

It's much more powerful than just attempting to build a website utilizing CSS and Media queries to determine what to build, where to build it, and if to build it.  Granted, I'm sure it utilizes a wrapper to wrap a lot of those functions and abstract them away from the developer.  However, it provides a nice, clean, easy way to build an application that spans over multiple different devices and types of devices.

In the case of your map example, you could implement something similar to that in Sencha Touch so that on a larger-screen device (tablet, or even an HTML5 compliant desktop browser) has a fullscreen viewport defined where the map takes up the bulk of the screen, with a navigation bar docked to the left side of the screen with your various critical functions to choose from, and a possible navigational structure on the top.  If you want to move this to a smaller tablet (iPad Mini, for example), you could drop certain parts of the navigation out of there so that it doesn't take up needed screen space, but could be accessible instead by a "menu" button that overlays the corner of the map, or slides up from the bottom via a hidden docking bar.

The options are really endless with what you may want to do.  I think the best bet though would be to utilize some sort of framework (you don't have to use Sencha Touch - it's just what I use and like, but I'm sure there are plenty of other good options out there), so that you don't need to go through the work of reinventing the wheel and attempting to do this type of thing yourself.  Overall though, I think you will definitely want to go with a solution that much more provides you with functionality above and beyond simple CSS rules and/or JavaScript/jQuery.

Good luck!


答:
I can't see why not. Imagine you have a config file that contains a database connection string, this gets run perfectly well on the dev environment but when you come to run it on the integration environment it still contains the old dev DB server connection.. disaster! (well, probably not as the dev box would surely pass all tests, but disaster if your DB upgrade scripts that you ran to bring the integration DB up to spec didn't work and you never noticed because all your tests got run against the dev DB!)

so yes, I'd consider some form of test for config to be perfectly valid. The question then is, what should the data be, and how should you test it.

To test, I'd suggest a set of regex expressions that just print out what you expect to be valid. That'd be simple to implement and could run on any form of config file (ie no need to go parsing that xml or json).

For DB config, simple select and compare the contents of the (valid) recordset is effective.

I wouldn't store these tests in the same place as the rest of the code though (or it wouldn't be useful to test that the connection string is correct on the integration environment by comparing the DB server instance with "DEV" - as is likely to happen if the test and the config is stored in the same place). That means you're better off with an integration test that can be run externally to the main source code. And would also form something you can give to support engineers to run against customer site's config to check if they're the right ones, and also that no-one had fiddled with them.

Title: Should you write automated tests to check that data is correct (the contents of config files, databases, etc.)?

Body:
Simply put: is there a best practice for whether developers should write automated tests to check that data is correct (the contents of config files, databases, etc.)? If so, what is it?

Assume that the data is static for a given release, and specified as part of requirements.


答: Arbitrarily changing the errorno is analogous to 'catching and swallowing' an exception.  Before there were exceptions that would propagate through different layers of a program and finally reach a point where the caller will either catch and respond to the exception in some way or simple pass the buck, there were errnos.  Not altering the errno, unless you are somehow handling, overriding, treating as irrelevant, the error, is essential to this first generation error handling propagation paradigm.</p>


问:
Why do development devices give you more resources than a typical device?
I have created an app that works on my 4th generation iPod Touch and my company's 5th generation iPod touch.

We were about to release, when we found a crash that occurs after any non-developer device runs the app*.

The notion came up that a device registered as a 'developer device' gives your app more resources to use. This doesn't seem right to me, since I couldn't think of any reason that would exist - I feel like it is more likely an issue with building or provision profiling.

However, that prompted a discussion. Why do devices such as game console development kits, devices that have more capabilities than the target platform, exist in the first place? Of course it is nice to stress test a program, but wouldn't a more accurate representation of the target platform make more sense?

TL;DR - Why do development kits have more resources than target platforms?

*With a non-developer device being any >3rd gen. iOS device  that downloads the app from our server, not directly from a computer with the app & xcode installed.

Note there is another question that reads similar, but it is actually different, because that other question is asking about simulator, and I understand that there are massive differences between using a simulator and an actual device.

答:
It allows you to create a resource-greedy proof-of-concept which you can later optimize.

It makes no sense in crashing an app because it's 5 bytes over the memory limit (which can be solved by setting the optimizer to conserve space in release but you are running a debug version),

having a warning pop up in the log when you go over the consumer limit while testing will be nice here.


答:
It's partly a matter of "trust."  Developers are assumed to know what they're doing, and are therefore given unfettered access to the device and all of its resources.  This can be a big help to small companies and development teams, where unused resources are wasted resources.

In a larger corporate environment, or especially the general public, this kind of access becomes a liability, due to security concerns and the need to play well with other applications that also need resources.

This isn't really a new idea. I have two machines at work.  On my developer machine I have administrative access, but it is isolated from the internet.  My other machine, which I use for email, Office and Internet access, doesn't even give me the ability to install programs.

This is why you have to test your application on a non-developer device before you deploy it, to make sure that it is well-behaved. :)

Title: Why do development devices give you more resources than a typical device?

Body:
I have created an app that works on my 4th generation iPod Touch and my company's 5th generation iPod touch.

We were about to release, when we found a crash that occurs after any non-developer device runs the app*.

The notion came up that a device registered as a 'developer device' gives your app more resources to use. This doesn't seem right to me, since I couldn't think of any reason that would exist - I feel like it is more likely an issue with building or provision profiling.

However, that prompted a discussion. Why do devices such as game console development kits, devices that have more capabilities than the target platform, exist in the first place? Of course it is nice to stress test a program, but wouldn't a more accurate representation of the target platform make more sense?

TL;DR - Why do development kits have more resources than target platforms?

*With a non-developer device being any >3rd gen. iOS device  that downloads the app from our server, not directly from a computer with the app & xcode installed.

Note there is another question that reads similar, but it is actually different, because that other question is asking about simulator, and I understand that there are massive differences between using a simulator and an actual device.


答:
The development environment (for anything - be it a stand alone java application, or a mobile environment, or embedded device) typically has the ability to do remote debugging, enhanced logging and other types of introspection of the enviroment (one typically doesn't want to add all the hooks for a logic analyzer on a production embeded device).

These additional things take additional resources.  Opening up a remote debugger against a vm or other remote enviroment takes some resources on the other end.  In the severely limited realm of mobile, it is possible that these additional resources will put it over the limit granted to a standard application.  Thus, more resources are given to the development environment so that it won't hit the resource limit when it starts doing additional logging or debugging.

This goes further to the point that you always need to test something in a mirror of the production environment.  Trusting that it works on the developer's machines with all their tweaks and different variables isn't sufficient to verify it works correctly in production.


问:
C++ Linkage Languages other than C?
The C++ language allows intermixing of both C++ and C in one source file. For example,

```<code>extern "C" {
    struct bar { /* ... */ }
}
</code>```

Does C++ or has it ever supported any other "linkage languages" other than C? e.g. extern "Pascal" or extern "Haskell"

答:
G++ at some point supported extern "Java" to interact with GCJ-compiled Java code.

https://stackoverflow.com/questions/15167867/extern-java-block-in-gcc

Title: C++ Linkage Languages other than C?


问:
Should I put the datatype of a class attribute in its name?
Most of my system's class attributes are just text, but in this case it makes more sense to place this particular class's attributes into one single hash (from a "keep the source code pretty" aspect). Basically, a list of attributes is returned, and instead of writing a bunch of static attributes for each one, I just loop over them and collect them into a hash.

Is it a good idea to name this particular attribute @contents_hash, as opposed to @contents? I assume that users may figure out pretty quickly that @contents.split ' ' will return a NoMethodError: undefined method 'split' for Hash, but on first glance of the code, is it useful to know right away that this is a hash? Do you think it will make the implementation redundant to say @contents_hash.keys?

答:
I would only put the datatype in an identifier if it clearly adds value and clarity.

Nowadays, intellisense (or "on-the-fly code analysis," as Jetbrains calls it) and type inference has pretty much eliminated the need for identifying types in your variable names.  Write clear code in the first place, so that you don't need to identify the type.


答:
First off, put the session data in a database, don't rely on files.  Once in the database, it'd be easy enough to track the number of active sessions with a simple query.

The main problem you are going to face is determining whether a user is idle or has closed their browser instead of manually logging out.  You'll want some sort of 'keep alive' connection that tells your server the person is still logged in.  A simple ajax request every 30 seconds or so should do the trick.  If the server stops receiving that, you know to mark that session as logged out.

Title: How will I restrict the number of users logged in based on session?

Body:
I have a software (in cloud) with so many registered users.

I want to restrict the number of users logged in at a time to certain number (configuration based, let's say 100).

If the 101 user tries to login he should be placed in queue with priority 1, subsequently 102 user should be 2 in queue, I know at every time a logged in users request is hitting the server the sess_file access time will be updated.

What should be the logic from here? Should I check the last accessed time of all the sess_file and log-out the uses that are idle? and how will I manage the waiting queue?

Software is done with PHP-MySQL.

When the user is logged in I mark the column as logged in in user table, and when the log-in page is loaded if the total logged in user count is 100, the 101 user who is trying to log-in is directed to a intermediate page which will check via ajax call fired at an interval of 5 mins that if any user is logged out. If a slot is available it redirects to the log-in page, automatically logs in and redirects to the user dashboard. But I want to know any better practice is there.

Mostly I want to know the invalidation of logged in user by checking the access time of sess_file is the right way to do it?


问:
A way to include SQlite into an application where the drivers aren't already installed on the system?
I'm an open source web application for use in my university.  Currently professors usually have a website, but do to the fact that they're teaching multiple classes in a given term, they don't care to spend time and make an extensible, functional website.

The purpose of this project is to create an OSS website that can be dropped in place and enabled by simply running an init.php file.

I'm curious though as how to handle information storage for such a task.  A full server database is a bit outside of the scope I'm looking for, but something like SQlite would fit very well.

The problem I'm running into is that not all departments have SQlite installed on their servers, and getting them all to do so won't happen.

Can anyone think of a way to include SQlite into an application where the drivers aren't already installed on the system, or a more common alternative that would provide a similar level of power/flexibility?

答:
Since you have this tagged as PHP...

For PHP versions 5.0 up to but not including 5.4, SQLite was included in PHP by default.  So there's nothing to install unless your particular build was compiled specifically not to include it.

For later versions, you'll need to install the SQLite extension.  On linux you can do this by installing the php5-sqlite3 package.


问:
Is there too much abstraction in the Ruby on Rails community?
Rails, to me, seems like a perfect level of abstraction for most types of web development. However, having watched some seasoned Rails consultants build an application, I'm finding that they use Gems to an extent that it's often pretty difficult to figure out what's going on in the code. As an intermediate-level Rails developer, I've had a pretty hard time digging through their code to figure out how things work, and I'm really struggling to see the payoff of this approach.

So is it me, or does Rails, by dint of the fact that it has such a vibrant community of contributors, kind of encourage over-abstraction?

答:
Your question reminded me of a point Paul Graham makes in On Lisp:

If people complain that using utilities makes your code hard to read, they
probably don’t realize what the code would look like if you hadn’t used them.
Bottom-up programming makes what would otherwise be a large program look
like a small, simple one. This can give the impression that the program doesn’t
do much, and should therefore be easy to read. When inexperienced readers look
closer and find that this isn’t so, they react with dismay.

Also, this is a minor nitpick, but most people are referring to something else when they use the word "abstraction."


问:
What is a reasonable way to structure relationships in MongoDB
I am also using Node - which I am not the most familiar with - if the articles/books/tutorials pertained to this also - that would help even more.

I come from a mostly MySQL background - but in this api, all data is going to be served as JSON - so at first glance, using Mongo made a lot of sense (I could be wrong). One thign I have been unable to wrap my head around though, is relational models. e.b. Object has many Assets.

To use some examples most people would be familiar with, let's assume I am trying to do something like:

Select a blog post and all of its comments. or

Select a photo gallery and all of its photos

Is it as simple as storing a call back inside of my assets like this?:

```<code>Photo {
    __id: 5,
    content: '...',
    gallery_id: 9
}
</code>```

And performing a .find({ gallery_id: 9 })?

I know this would work, but is that best practice? I am very new to Document Databases, and have not seen much on this particular topic.

答:
MongoDB models relationships by using references.

To normalize data, store references between two documents to indicate
  a relationship between the data represented in each document.

In general, use normalized data models:

when embedding would result in duplication of data but would not provide sufficient read performance advantages to outweigh the
  implications of the duplication.

to represent more complex many-to-many relationships.

to model large hierarchical data sets.


答:
Ruby (and other dynamic-typed languages) don't generally put the type in the name of variable, largely because that type could potentially change. That type of naming convention is generally seen more in statically-typed languages (namely, Visual Basic), because it's a safer environment in which to do that (the variables can't change types as easily), but it's falling out of favor even there.

What happens if somewhere you have content = 'some string'? Well, now, had you used content_hash, the variable would be lying about its type. This makes things confusing.

Instead, think about naming things in a way that makes it more clear that the type is likely to be a hash. "contents" is pretty generic, and could mean either a string or a hash, but maybe "settings" or "attributes" would be a better choice, because "settings"/"attributes" has a connotation of being a collection of key-value pairs (a hash), or at least an array of values, without actually being tied to the exact type.

See also:

Ruby style guide

Duck Typing (technically applies to inheritance, but the idea applies here - if it looks and acts like a hash, then it's probably a hash)

Title: Should I put the datatype of a class attribute in its name?

Body:
Most of my system's class attributes are just text, but in this case it makes more sense to place this particular class's attributes into one single hash (from a "keep the source code pretty" aspect). Basically, a list of attributes is returned, and instead of writing a bunch of static attributes for each one, I just loop over them and collect them into a hash.

Is it a good idea to name this particular attribute @contents_hash, as opposed to @contents? I assume that users may figure out pretty quickly that @contents.split ' ' will return a NoMethodError: undefined method 'split' for Hash, but on first glance of the code, is it useful to know right away that this is a hash? Do you think it will make the implementation redundant to say @contents_hash.keys?


问:
What are CPU registers?
This question has been bothering me for some time now and today I figured I would Google it. I've read some stuff about it and it seemed very similar to what I've always known as processor cache.

Is there a difference between the two or am I right when I think they are the same?
Is a register actually required to be inside a CPU for it to work?

According to Wikipedia a register is a place in the CPU where memory can be quickly accessed and modified before being sent back to the RAM. Did I understand this wrong or are the cache and register actually the same?

答:
They're not quite the same.  The registers are the places where the values that the CPU is actually working on are located.  The CPU design is such that it is only able to actually modify or otherwise act on a value when it is in a register.  So registers can work logic, whereas memory (including cache) can only hold values the CPU reads from and writes to.

Imagine a carpenter at work.  He has a few items in his hands (registers) and then, very close by on his workbench (cache) things he is frequently working on, but not using right this moment, and then in the workshop (main memory) things that pertain to the project at hand but that are not immediately important enough to be on the workbench.

EDIT: Here's a simple explanation for how register logic works.

Let's imagine we have four registers named R1..R4.  If you compile a statement that looks like this:

```<code>x = y + z * 3;
</code>```

the compiler would output machine code that (when disassembled) looks something like this:

```<code>LOAD  R1, ADDRESS_Z //move the value of Z into register 1
MUL   R1, 3         //multiply the value of register 1 by 3
LOAD  R2, ADDRESS_Y //move the value of Y into register 2
ADD   R1, R2        //adds the value in R2 to the value in R1
STORE R1, ADDRESS_X //move the value of register 1 into X
</code>```

Since most modern CPUs have registers that are either 32 or 64 bits wide, they can do math on any value up to the size they can hold.  They don't need special registers for smaller values; they just use special ASM instructions that tell it to only use part of the register.  And, much like the carpenter with only two hands, registers can only hold a small amount of data at once, but they can be reused, passing active data in and out of them, which means that "a lot of registers" don't end up being needed.  (Having a lot available does allow compilers to generate faster code, of course, but it's not strictly necessary.)

Title: What are CPU registers?

Body:
They're not quite the same.  The registers are the places where the values that the CPU is actually working on are located.  The CPU design is such that it is only able to actually modify or otherwise act on a value when it is in a register.  So registers can work logic, whereas memory (including cache) can only hold values the CPU reads from and writes to.

Imagine a carpenter at work.  He has a few items in his hands (registers) and then, very close by on his workbench (cache) things he is frequently working on, but not using right this moment, and then in the workshop (main memory) things that pertain to the project at hand but that are not immediately important enough to be on the workbench.

EDIT: Here's a simple explanation for how register logic works.

Let's imagine we have four registers named R1..R4.  If you compile a statement that looks like this:

x = y + z * 3;

the compiler would output machine code that (when disassembled) looks something like this:

LOAD  R1, ADDRESS_Z //move the value of Z into register 1
MUL   R1, 3         //multiply the value of register 1 by 3
LOAD  R2, ADDRESS_Y //move the value of Y into register 2
ADD   R1, R2        //adds the value in R2 to the value in R1
STORE R1, ADDRESS_X //move the value of register 1 into X

Since most modern CPUs have registers that are either 32 or 64 bits wide, they can do math on any value up to the size they can hold.  They don't need special registers for smaller values; they just use special ASM instructions that tell it to only use part of the register.  And, much like the carpenter with only two hands, registers can only hold a small amount of data at once, but they can be reused, passing active data in and out of them, which means that "a lot of registers" don't end up being needed.  (Having a lot available does allow compilers to generate faster code, of course, but it's not strictly necessary.)


答:
When the user is logged in I mark the column as logged in in user table, and when the log-in page is loaded if the total logged in user count is 100, the 101 user who is trying to log-in is redirected

I would alter that approach to allow all users to log in, but if the number of active users exceeds 100 then redirect the new user to a holding page. Their session is created but they are now in a queue to leave the holding page.

This makes giving users access a lot easier, because you no longer have to track the 100 logged in users. You can simply order by the record ID of session table. This approach assumes you are tracking sessions with a session table in your database. When a user logs out you delete their session record from the table.

It's assumed you are using an auto-increment integer for your ID column.

To check if the current user should be place on hold is very easy.

```<code>SELECT `id` FROM `sessions` ORDER BY `id` LIMIT 1;
</code>```

Using the first id in the table you can quickly check if the user is in the top 100 sessions.

```<code>$id = query('SELECT `id` FROM `sessions` ORDER BY `id` LIMIT 1');
if($my_session_id > $id+100)
{
   // this user is placed in holding
}
else
{
   // this user has full access
}
</code>```

As soon as a record above the current use is deleted. They automatically move up in the queue.

Body:
When the user is logged in I mark the column as logged in in user table, and when the log-in page is loaded if the total logged in user count is 100, the 101 user who is trying to log-in is redirected

I would alter that approach to allow all users to log in, but if the number of active users exceeds 100 then redirect the new user to a holding page. Their session is created but they are now in a queue to leave the holding page.

This makes giving users access a lot easier, because you no longer have to track the 100 logged in users. You can simply order by the record ID of session table. This approach assumes you are tracking sessions with a session table in your database. When a user logs out you delete their session record from the table.

It's assumed you are using an auto-increment integer for your ID column.

To check if the current user should be place on hold is very easy.

SELECT `id` FROM `sessions` ORDER BY `id` LIMIT 1;

Using the first id in the table you can quickly check if the user is in the top 100 sessions.

$id = query('SELECT `id` FROM `sessions` ORDER BY `id` LIMIT 1');
if($my_session_id > $id+100)
{
   // this user is placed in holding
}
else
{
   // this user has full access
}

As soon as a record above the current use is deleted. They automatically move up in the queue.


问:
Why do some programmers hate the UI part of the development?
Lots of programmers that I've met always says that "He is not a UI guy." The fact is that development nowadays, whether web, Windows, Linux, OSX, or any other type of development now comprises software with a good-looking UI.  Why do so many developers seem to not like UI work?</p>

答:
Having worked on both sides of the coin i.e. UI design and the backend code, I found that both sides of the coin are basically the same thing.

Requirements that differ from what you do day to day do not come all the time and now in the era where all services revolve around CRUD then it becomes boring.

Anyway, coding the frontend allows better interaction and crazy dynamisms that basically screw an inexperienced hand in frontend design. I personally learnt the hard way in frontend and can comfortably say that designing frontend is far much more interesting and challenging.


问:
catch(Exception ex) would this example be a code smell?
We have production code that is not easily deployed in a test area. We also have a new library of code that we would like to "plug in" to the production code.

The production code would be making a few calls to the new code. Each of these calls are not mission critical (updating analytic information in a database).

If I surrounded all the calls to the new code with "try{...} catch(exception)" to avoid crashing the production code....

A) What are some problems I am exposing the new code to

B) How stinky is this.

c) what would you do.

答:
A) You could be introducing new bugs when your new code throws exceptions and your usual production code doesn't complete. And what are the secondary affects of your new code?  For example, do they write new values to the database or change program flow or business rules?  You could also introduce new performance issues.

B) Pretty stinky to put new code live to test it.

C) I would make sure the test systems are set up correctly, no matter how difficult, so the new code could be accurately and safely tested.  It's worth the investment.


问:
How do you maximise the knowledge that you gain from a programming book?
Not because I care how long it takes someone to read a book, but more because I'm interested in how people get the knowledge from a book (or I guess other sources) into their brains in the best, most efficient way.

Personally I take a multi-pass approach (from my answer to the original question):

Skim through contents, dip in and read anything with an interesting looking heading and finally gawp at any nice diagrams and illustrations. I won't take much in at this stage, but it gives me a mental view of the book (an hour or so at most)

First pass through the book, generally I'll read the opening chapters thoroughly for a book that is either very heavy going or introduces something completely new. For books that cover a subject I already know about I'll skim or skip bits that seem trivial. The remainder of the book I'll go through reasonably quickly but not so quickly that I'm just page flipping. (about a week)

Not all books that I read make it this far, but if I find a book interesting or useful enough I'll then study it properly. I will go through the book at a slower pace and do some or all of the examples, try out code, etc. I will often skip entire chapters here unless the book is really good (1-3 weeks depending on the book).

Finally when I've finished reading it and am reading other books I will often dip into it again and again to cross-reference, compare, look things up, browse, etc - so many of my favourite books don't just end up gathering dust on the bookshelf.

I rarely take notes when reading (although I may do some planning on paper if I'm working through something like a code sample). I've also considered starting to use a personal kanban for organising my progress, but have never quite got around to using that technique. Mindmaps are another thing I like the idea of but rarely do.

What other methods to people have? How successful do you find them? Are there any commonly recommended techniques that you feel are a waste of time?

答:
Due to an attention deficiency of mine, I find it hard to focus when I'm learning in a traditional, start-to-finish approach. I skip to the end of the chapter and go straight to the exercises, and then use a combination of the book and the internet as reference to solve the problems.

Once I put myself into a position where I have to use the book material as means to an end instead of studying it "because I should know it", the concepts become much easier to pick up and practice.

My focus issues also mean I don't type out the code examples directly, and instead think of my own examples and use the code in the book to help me realize them. Being creative with the learning process ensures that I'm having fun with it, and the uniqueness of whatever I create makes it easier to remember what I'm doing.


问:
Working with Multiple XML Schema Classes in C#
I'm working with a data import process in C#, which takes a zip file filled with XML files and saves specific data points into a database.  This is accomplished by loading the XML data into classes compiled from the schema.  The import logic retrieves the data by digging down into the right classes and fields.

The XML schema is defined by a different company, and the schema changes every one to years when an updated version of their software is released.  What my company would like to do is be able to import different versions of the schema so that we could support older files.  There is also debate on whether this change is worth the effort.

My plan to accomplish this would be to determine which schema to use at the beginning of an import, and then use different interfacing classes to get the data from the XML and pass it back to the import classes, which would then save the values to the database.  There are over 200 classes generated based on the schema, but we only need to access data in about half of them.

Are there other ways to approach supporting multiple XML schemas that may be easier?

答:
You can put each set of classes of a schema into an assembly of its own. Then, load the right assembly dynamically at runtime after you identified the schema version. This technique is often used to create plug-ins (see here for an example).

To avoid the need of having all of your 200 classes implementing an interface, your import code can make use of the C# 4.0 dynamic keyword for accessing schema objects, regardless from which assembly they are loaded, as long as the method signature does not change between versions. See here for an example.

The drawback is that you will loose type-safety, you will have to decide if this is  acceptable in your case.


问:
How does google code prettify works?
I am using google code prettify. After a page renders, I decided to check how  and ``` tags and their contents were manipulated.

But in view source, I found no changes were made (in contrast to online syntax highlighters, which generate css style code with code text).

So, how/where is info about keywords, variable, comments, etc (from code tag text) stored and manipulated?

答:
In "view source", you see the original source downloaded. What you'd get with wget or lynx for example.

The end result you see has been manipulated by Google Code Prettify's JavaScript code, and can be seen with tools such as Chrome Dev Tools or Firefox Dev Tools.

As Servy said, the DOM is riddled with  tags and the likes.

Title: How does google code prettify works?

Body:
In "view source", you see the original source downloaded. What you'd get with wget or lynx for example.

The end result you see has been manipulated by Google Code Prettify's JavaScript code, and can be seen with tools such as Chrome Dev Tools or Firefox Dev Tools.

As Servy said, the DOM is riddled with <span> tags and the likes.


问:
Changing a variable through a series of statements ... What is this technique called?
I'm looking at a function that that has several statements like this:

```<code>n = returnDifferentVersionOf(n);
</code>```

I.e., the value of the same variable n changes progressively several times during the course of a subroutine -- rather than a newly named variable being assigned at each change.

What is the generic name of this technique (if there is one)?

A more full example might be (in Ruby):

```<code># reuse same var
def cromulentize(str="")
   str = "wowza" if str.empty?
   str += " adios!"
   str = str * 3
   str.gsub!('a', 'X')
   str = str[0..-3]
   str.upcase
end
</code>```

What is that technique called, as opposed to this one:

```<code># uses diff vars
def cromulentize(str="")
   non_empty_str = str.empty? ? "wowza" : str
   adios_str = non_empty_str += " adios!"
   multiplied_str = adios_str * 3
   gsubbed_str = multiplied_str.gsub!('a', 'X')
   spliced_str = gsubbed_str[0..-3]
   upcased_str = spliced_str.upcase
end
</code>```

(Note that in Ruby the value of a method's last expression is the return value.)

答:
In some cases, n might be called an accumulator, or you might say that you're accumulating the result in n. That's especially true if n is used to gather the result of a number of similar calculations, like adding up a list:

```<code>n = 0;
n += foo.price;
n += bar.price;
n += baz.price;
n += qux.price;
print("The total is: %f", n);
</code>```

accumulator is an old computing term for a variable (or in hardware, a register) that stores results for further use. You can see how the name applies when the operations are all the same, as above... the value in n piles up the way falling leaves accumulate on the ground. But I think you can still use the term accumulator even if the operations are not all the same, as in your example.

Body:
In some cases, n might be called an accumulator, or you might say that you're accumulating the result in n. That's especially true if n is used to gather the result of a number of similar calculations, like adding up a list:

n = 0;
n += foo.price;
n += bar.price;
n += baz.price;
n += qux.price;
print("The total is: %f", n);

accumulator is an old computing term for a variable (or in hardware, a register) that stores results for further use. You can see how the name applies when the operations are all the same, as above... the value in n piles up the way falling leaves accumulate on the ground. But I think you can still use the term accumulator even if the operations are not all the same, as in your example.


问:
Where should I put methods that make an Http Request to get data from a web service in iOS development?
I have a Model Car in my iOS application where it's parameters like name, year, value etc are fetched from a web service in order to fill a list with cars data.

Where should I put the method that asynchronously goes to the server and returns an array of cars (this method already converts the JSON to a Car array)?

My current approach is a static method in my Car class that receives an HttpClient (so I'm able to unit test it mocking the client) and returns an NSArray of cars, is this good?

What have you guys done in this situation?

I'm concerned because I recently started reading clean code which says that a Class should do only one thing, and the way I have it now appears to do 2 things (hold information about a Car and get a list of cars).

答:
Here keeping another object should need to be retained somewhere which could not be guaranteed that the parent will always be alive to process the response.

I suggest to keep these implementation in a singleton class. Keeping this class will also be useful for some generic method implementation that can be called very often.


答:
I would call it a mess.  None of those changes are related, either in cause or in effect.  Making all those checks and changes in one place in your code is pointless.  If this string is a significant property of a domain object, there should be meaningful, distinct methods which change it, each change being separate.  Unless you can provide some better evidence to show otherwise.

That is garbage code.

Edit: as I hope is clear from the discussion in the comments, this isn't a dig at mtoast.

Title: Changing a variable through a series of statements ... What is this technique called?

Body:
I'm looking at a function that that has several statements like this:

```<code>n = returnDifferentVersionOf(n);
</code>```

I.e., the value of the same variable n changes progressively several times during the course of a subroutine -- rather than a newly named variable being assigned at each change.

What is the generic name of this technique (if there is one)?

A more full example might be (in Ruby):

```<code># reuse same var
def cromulentize(str="")
   str = "wowza" if str.empty?
   str += " adios!"
   str = str * 3
   str.gsub!('a', 'X')
   str = str[0..-3]
   str.upcase
end
</code>```

What is that technique called, as opposed to this one:

```<code># uses diff vars
def cromulentize(str="")
   non_empty_str = str.empty? ? "wowza" : str
   adios_str = non_empty_str += " adios!"
   multiplied_str = adios_str * 3
   gsubbed_str = multiplied_str.gsub!('a', 'X')
   spliced_str = gsubbed_str[0..-3]
   upcased_str = spliced_str.upcase
end
</code>```

(Note that in Ruby the value of a method's last expression is the return value.)