答:
Should a web developer know to do slicing also?

Strictly speaking: no a web developer should not also know how to do slicing.

However on a personal growth level: I would say yes. Learning to do more is never a hindrance. Becoming a master is not the goal. However knowing how to handle the odd case is going to be good for you in the long run.

Title: Should a web developer know how to do slicing?

Body:
I am a web developer. I'm doing all kinds of web-sites and web applications.

It's very strange for me that a lot of customers do not know the difference between a web developer and a slicer. They just want to "give you the PSD" and expect you to give them a web site with a DB back-end and so on...

I'm just asking here: am I wrong in my thinking?

Of course, a web developer MUST know html and css but I don't think that he should slice the PSD and do all the work a css guru can do...

I would like to hear your opinions on this.


问:
What is a good rule of thumb to do technical writing that doesn't confuse people
Sometimes I'm such a nerd that not even nerds understand me, or rather, sometimes I cannot put stuff in understandable and simple-enough terms... and sometimes I can but cannot really tell until after.

I like the details on technical stuff, I enjoy writing about them, but sometimes I cannot stop or tell when it is too technical or too abstract to understand. I often end up putting too much detail into stuff thinking that it will help the understanding of some concept, but it sometimes it backfires.

These are all edge cases, I'm not that bad at writing (I hope), but, what would be a good rule of thumb to know when you are probably going to make people dizzy when reading your stuff?, how do you test your analogies?, I'm looking for one or more rules of thumb to know if I'm writing technical explanations right, knowing what to reference and what not, etc.

What is your golden rule for writing about technical stuff to technical people who are not necessarily familiar with what you are writing but are also not noobies in your area?, where is the line?

答:
There is no silver bullet. This is like asking "How do you know if your software is bug free?". The only answer is: it isn't. Same for technical writing (and all kind of writing): your text will confuse some people. The only way to tell if someone is confused by a document is to make him read.

The important thing is that you should care about how people read and what is their background. A given document should target an audience. And You should try to get all the feedback you can. With experience you should be able to put yourself more easily in someone else's shoes.

In the end writing good technical documents is as wide and complex as writing good code. Remember that the best scientist out there are the one who are able to explain thing in a book or on tv something that took 20 year to discover. So I suggest you follow Yannis suggestion and ask your question on writers because they may help you to ask a more specific question.

ContentLicense: CC BY-SA 3.0


问:
What is the significance of 10 characters in this Uncle Bob post?
In this blog posting by Uncle Bob

http://blog.8thlight.com/uncle-bob/2012/04/20/Why-Is-Estimating-So-Hard.html

Author states a possible solution to the problem at hand. He writes "Try this. Break some long string of text up into columns that are 10 characters long. Each time you break a line, record the position of the break, and why you decided to use that position."

The problem is about breaking the Address into 13 character columns, so where does 10 come into play? Or is he using that as another example unrelated to the Gettysburg one?

I'd like to present this to my team in a presentation I have to do soon. I plan to describe the posting, describe the problem and ask my team members for their estimates. After I would go on to explain the rest of the postings premise about why estimations are often blown.

Feel free to offer suggestion on how I can make this a good presentation. I can visualize most of it but towards the end it feels light. After the quick survey, I focus on the problem of estimating the wrong thing and then offer the solution.

答:
It's a tiny bit clumsy, but he's trying to separate the example at the end (take any long text and break it down into 10-character lines) from the more specific one earlier (take the Gettysburg address and break it into 13-character lines). But he could have picked any number there, 10 is just a nice round number from which to extrapolate the three parts of the procedure.

If I were using this as a presentation (assuming my audience have access to computers), I would:

pick a well-known text (probably an amusing one, just to inject some fun).

pick a number which hits as many test conditions as possible -- at least the three that Uncle Bob describes.

get each pair in the room to do the job manually and then estimate the programming task.

let them code it (within some kind of time limit).

see how many hit their estimates (or still believe they will, after the time limit expires).

I'll bet most don't.

In the spirit of interactivity but the absence of hardware, I'd do the coding myself, still letting the audience both estimate the task and tell me what to code and when. For example, let them identify a test, write it, make it pass until you're sure it's complete.


问:
What do you think of "Planning Poker"?
Planning Poker

Summary, in case you don't want to read the wiki article:

Get a list of tasks you want to do for the upcoming iteration

For each task:

2.1 Discuss with the group what it entails

2.2 Everyone writes down / selects an estimation of how much effort is required for the task

2.3 Everyone reveals their estimation

2.4 The highest and lowest outliers explain their reasoning

2.5 Repeat until a consensus is reached

Usually something similar to numbers from the Fibonacci sequence like 0, ½, 1, 2, 3, 5, 8, 13, 20, 40, 100 are the allowed values, so you don't get long arguments over close values like 23 vs 27.

Further, the numbers represent a unit-less value of effort, whose value is determined by a baseline task that everyone agrees equals about a 1, and all else is relative to that.

Ultimately, the goal is to get a good feel for a given team's "velocity", which is the number of these points that can be completed in a given iteration.  With that, it's possible to make reasonably accurate estimates of how long any given feature will take.

We did this at iteration planning meetings at one company I worked at, and I thought it was one of the few good things about that particular company.  So, what I'm wondering is, has anyone used this?  Do you think it's a useful tool for estimation?  Does it work in all situations, or does it lend itself to certain teams, projects, etc?

答:
I dislike it in my current team, primarily because we have people who fundamentally don't buy into it.  We spend a significant portion of any grooming session debating whether pointing is worthwhile, and our product owner never breaks down epics, so we usually end up with wildly out of kilter estimates or stories where the points indicate that the thing just needs to be broken down.

Nothing like having a 40 and two 20s in a single sprint!

ContentLicense: CC BY-SA 2.5

Title: What do you think of "Planning Poker"?


问:
How can I evaluate a candidate's knowledge of Html/CSS during an interview?
I am trying to determine some good interview questions to assess the ability of people coming in for a Html/CSS job, however that topic is extremely broad, and I'm not sure what sort of questions I can ask to properly evaluate someone's HTML/CSS knowledge.

What sort of questions can I ask to evaluate a candidate's Html/CSS abilities during an interview?

Ideally I would like to ask few questions and then give them a real life scenario to combat.

答:
HTML and CSS are difficult to interview for a few reasons:

They are too basic, compared, for example, to a programming language,

They depend very much on the context of the job. Examples:

If you create Google scale, hugely fast and optimized websites, the people you interview for the job cannot ignore what CSS sprites are.

If you create XHTML W3C valid websites, you should ensure that the candidates know the difference between XHTML 1.0 and XHTML 1.1, or what are the mandatory attributes for , etc.

If you create terrible websites full of hacks, you should ask the people you interview about how they will do such or such hack, how they serve different CSS for different browsers, etc.

etc.

If it's a pure HTML and CSS job, the person will have to work with designers on one hand, and developers on other hand. They must know HTML and CSS, but what is much more valuable is their ability to interact with those people, and to understand both the needs of the designers, the requirements of the developers, and the constraints of HTML and CSS.

For example, they must know how to structure their HTML in a such way that it would be easy for a JavaScript developer to add interactivity later.

You may want to start by some basic questions:

What is your favorite browser?

If the person answers "Internet Explorer", stop the interview immediately: you don't need somebody like that.

No, I'm kidding. The answer is irrelevant. Instead, you can ask the following:

Tell me about the debug tools you use in your favorite browser.

Primary using Chrome, I work daily with Developer Tools. Those tools allow me to:

View the requests made from a page,

Study the time it takes for a page and the related resources to load, especially the DNS lookup, waiting and receiving times,

Study the headers of the elements sent, as well as the cache indicator,

View the DOM and study how CSS selectors are applied,

I also use YSlow which serves me as a checklist for optimization of a website which require high scalability. YSlow is also a good tool when it comes to determining if the server is configured correctly (sending correct headers, etc.).

In Firefox, I use Firebug, the tool very similar to Developer Tools from Chrome. Developer tools are also available in new versions of Internet Explorer, and also enable me to switch to IE7 to IE10 compatibility views. This last feature is very helpful, since without it, I would be forced to install several virtual machines just for legacy testing, or to use much more often the paid services like Litmus.

Please, explain me what
 tag is about? What was the intended use for this tag? How is it used in practice? What do you think about this extended usage?

Here, you want the person to be able to explain that
 is for dictionaries, associating one key,
, with one or several values,
. While the primary use of this tag was purely related to semantics, in practice it was extensively used to replace tables, a good example being PHPBB3. This is a good thing when tables are slowing the rendering of the page, but it must be used with caution: not only tables are still appropriate in lots of cases to better describe the data, but also there may be other means, such as ordinary lists, to describe the content without using
.

What is the difference between fixed and fluid layouts? What are the pros and cons of each?

The fixed layout has predefined widths of the elements. The elements of a fluid layout depend on the width of the page.

The fixed layout makes it easier to design the page, especially when there are lots of full-width graphics. Even without graphics, it's still easier, because you care only for a precise case. For example, Programmers.SE being a fixed layout website, the column which displays the questions and the answers has always the same size. If a fluid layout would be used for this column, this would create an issue: on small screens, the text would be unreadable, because the lines would be too short, while on large screens, the lines would be extremely large, so the text would be unreadable too.

The problem with the fixed layout is that it works well for a few, most used resolutions, but fails more or less for everything else. It becomes especially important since the adoption of very large, wide monitors, and the increasing usage the internet on small, mobile devices.

The fluid layout helps with that, but the design is more difficult to do for such website. In some scenarios on badly managed projects, this may lead to HTML and CSS hacks, large pages, low maintainability and, during development, to higher costs and missed deadlines.

On a page with a fluid layout, how can you avoid the situation where a column of text becomes too large to stay readable?

You can limit the width of a zone of text by using max-width property.

What do you think about this piece of code:
Text here
?

The piece of code has a flaw to mix presentation logic inside HTML. Presentation logic must be put in CSS for several reasons:

It helps the separation of concerns and clean code, meaning cheaper maintenance later,

It makes the styles reusable from page to page, which (outside maintainability concerns) helps ensuring that you're using the same styles on the whole website,

It helps reducing the bandwidth, since CSS files will be cached.

After a few basic questions like that, you may ask some more tricky ones:

How do you avoid duplicating colors or fonts in CSS, when those colors or fonts are applied to multiple elements which cannot be targeted by a single selector? Are there drawbacks?

You do that by using CSS preprocessors, like Sass or LESS. They allow to define colors, fonts and other parts of the style inside variables that you can use later in your styles.

The drawbacks of CSS preprocessors are that:

They sometimes require to change the development and deployment workflow, in order to have the up-to-date CSS code in the browser,

They are known only by a few developers, which makes it harder for a new person to join or maintain the project later,

There are no both good and fast IDEs for Sass or LESS, and the integration inside the most popular IDEs is rather disappointing.

Give me an example of a href value of an image which is on CDN, given that this image is displayed on a website which may be accessed both through HTTP and HTTPS.

Since HTTPS needs every called resource to be on HTTPS too (otherwise, a security warning will be displayed to the user in many cases), it is not possible to specify the link as http://cdn.example.com/image.png. To properly link to the image, //cdn.example.com/image.png must be used; the browser will then prepend http: or https: depending on the context.

Given that the size of the pages and the number of requests on a website cannot be optimized and the content cannot be changed nor AJAX be added, how do you give the impression to the user that the website is faster? What it involves from HTML perspective?

If HTTP 1.1 is used, the page may be chunked. This means that the first parts will appear faster, giving an impression that the website is faster than it is in reality. Chunked transfer encoding is impossible in HTTP 1.0, which means that there is nothing to do in this case.

Being able to serve the chunked content requires from HTML perspective to reorder the elements, putting the most critical ones at the top of the file (which doesn't mean that they would have to appear at the top of the page). For example, on an e-commerce website, when the user wants to see the details of the product, the first chunk may contain the  and the product details. The next chunk may contain the primary elements like the logo of the website, the main menu, the copyright, etc. Finally, the last chunk may contain the "People who bought this also bought" section, the comments and ratings of the product, the "Share on Facebook", etc.

Finally, you may ask the candidate to work on a real-world scenario. It may be anything, like the easiest one below, to the complex scenarios where the person has to deal with CSS sprites or other advanced optimization techniques, with browser inconsistencies, etc.

Please, can you create an XHTML page with two zones: the left one, with a list, and the right one, with text. Two zones are separated by a vertical line, which extends from the very top to the very bottom of the page. List and text varying in size, you can't predict which one will have the biggest height. You cannot use
s.

Actually, it's pretty simple but shows if the person has the reflex to think about heights. An inexperienced candidate will create the float:left zone and the border-left:solid 1px #ccc; zone, but forget adding the border to the left zone and extending it so that two borders will be at the same place.

Body:
HTML and CSS are difficult to interview for a few reasons:

They are too basic, compared, for example, to a programming language,

They depend very much on the context of the job. Examples:

If you create Google scale, hugely fast and optimized websites, the people you interview for the job cannot ignore what CSS sprites are.

If you create XHTML W3C valid websites, you should ensure that the candidates know the difference between XHTML 1.0 and XHTML 1.1, or what are the mandatory attributes for <img/>, etc.

If you create terrible websites full of hacks, you should ask the people you interview about how they will do such or such hack, how they serve different CSS for different browsers, etc.

etc.

If it's a pure HTML and CSS job, the person will have to work with designers on one hand, and developers on other hand. They must know HTML and CSS, but what is much more valuable is their ability to interact with those people, and to understand both the needs of the designers, the requirements of the developers, and the constraints of HTML and CSS.

For example, they must know how to structure their HTML in a such way that it would be easy for a JavaScript developer to add interactivity later.

You may want to start by some basic questions:

What is your favorite browser?

If the person answers "Internet Explorer", stop the interview immediately: you don't need somebody like that.

No, I'm kidding. The answer is irrelevant. Instead, you can ask the following:

Tell me about the debug tools you use in your favorite browser.

Primary using Chrome, I work daily with Developer Tools. Those tools allow me to:

View the requests made from a page,

Study the time it takes for a page and the related resources to load, especially the DNS lookup, waiting and receiving times,

Study the headers of the elements sent, as well as the cache indicator,

View the DOM and study how CSS selectors are applied,

I also use YSlow which serves me as a checklist for optimization of a website which require high scalability. YSlow is also a good tool when it comes to determining if the server is configured correctly (sending correct headers, etc.).

In Firefox, I use Firebug, the tool very similar to Developer Tools from Chrome. Developer tools are also available in new versions of Internet Explorer, and also enable me to switch to IE7 to IE10 compatibility views. This last feature is very helpful, since without it, I would be forced to install several virtual machines just for legacy testing, or to use much more often the paid services like Litmus.

Please, explain me what <dl/> tag is about? What was the intended use for this tag? How is it used in practice? What do you think about this extended usage?

Here, you want the person to be able to explain that <dl/> is for dictionaries, associating one key, <dt/>, with one or several values, <dd/>. While the primary use of this tag was purely related to semantics, in practice it was extensively used to replace tables, a good example being PHPBB3. This is a good thing when tables are slowing the rendering of the page, but it must be used with caution: not only tables are still appropriate in lots of cases to better describe the data, but also there may be other means, such as ordinary lists, to describe the content without using <dl/>.

What is the difference between fixed and fluid layouts? What are the pros and cons of each?

The fixed layout has predefined widths of the elements. The elements of a fluid layout depend on the width of the page.

The fixed layout makes it easier to design the page, especially when there are lots of full-width graphics. Even without graphics, it's still easier, because you care only for a precise case. For example, Programmers.SE being a fixed layout website, the column which displays the questions and the answers has always the same size. If a fluid layout would be used for this column, this would create an issue: on small screens, the text would be unreadable, because the lines would be too short, while on large screens, the lines would be extremely large, so the text would be unreadable too.

The problem with the fixed layout is that it works well for a few, most used resolutions, but fails more or less for everything else. It becomes especially important since the adoption of very large, wide monitors, and the increasing usage the internet on small, mobile devices.

The fluid layout helps with that, but the design is more difficult to do for such website. In some scenarios on badly managed projects, this may lead to HTML and CSS hacks, large pages, low maintainability and, during development, to higher costs and missed deadlines.

On a page with a fluid layout, how can you avoid the situation where a column of text becomes too large to stay readable?

You can limit the width of a zone of text by using max-width property.

What do you think about this piece of code: <p color="Red" align="Center">Text here</p>?

The piece of code has a flaw to mix presentation logic inside HTML. Presentation logic must be put in CSS for several reasons:

It helps the separation of concerns and clean code, meaning cheaper maintenance later,

It makes the styles reusable from page to page, which (outside maintainability concerns) helps ensuring that you're using the same styles on the whole website,

It helps reducing the bandwidth, since CSS files will be cached.

After a few basic questions like that, you may ask some more tricky ones:

How do you avoid duplicating colors or fonts in CSS, when those colors or fonts are applied to multiple elements which cannot be targeted by a single selector? Are there drawbacks?

You do that by using CSS preprocessors, like Sass or LESS. They allow to define colors, fonts and other parts of the style inside variables that you can use later in your styles.

The drawbacks of CSS preprocessors are that:

They sometimes require to change the development and deployment workflow, in order to have the up-to-date CSS code in the browser,

They are known only by a few developers, which makes it harder for a new person to join or maintain the project later,

There are no both good and fast IDEs for Sass or LESS, and the integration inside the most popular IDEs is rather disappointing.

Give me an example of a href value of an image which is on CDN, given that this image is displayed on a website which may be accessed both through HTTP and HTTPS.

Since HTTPS needs every called resource to be on HTTPS too (otherwise, a security warning will be displayed to the user in many cases), it is not possible to specify the link as http://cdn.example.com/image.png. To properly link to the image, //cdn.example.com/image.png must be used; the browser will then prepend http: or https: depending on the context.

Given that the size of the pages and the number of requests on a website cannot be optimized and the content cannot be changed nor AJAX be added, how do you give the impression to the user that the website is faster? What it involves from HTML perspective?

If HTTP 1.1 is used, the page may be chunked. This means that the first parts will appear faster, giving an impression that the website is faster than it is in reality. Chunked transfer encoding is impossible in HTTP 1.0, which means that there is nothing to do in this case.

Being able to serve the chunked content requires from HTML perspective to reorder the elements, putting the most critical ones at the top of the file (which doesn't mean that they would have to appear at the top of the page). For example, on an e-commerce website, when the user wants to see the details of the product, the first chunk may contain the <head/> and the product details. The next chunk may contain the primary elements like the logo of the website, the main menu, the copyright, etc. Finally, the last chunk may contain the "People who bought this also bought" section, the comments and ratings of the product, the "Share on Facebook", etc.

Finally, you may ask the candidate to work on a real-world scenario. It may be anything, like the easiest one below, to the complex scenarios where the person has to deal with CSS sprites or other advanced optimization techniques, with browser inconsistencies, etc.

Please, can you create an XHTML page with two zones: the left one, with a list, and the right one, with text. Two zones are separated by a vertical line, which extends from the very top to the very bottom of the page. List and text varying in size, you can't predict which one will have the biggest height. You cannot use <table/>s.

Actually, it's pretty simple but shows if the person has the reflex to think about heights. An inexperienced candidate will create the float:left zone and the border-left:solid 1px #ccc; zone, but forget adding the border to the left zone and extending it so that two borders will be at the same place.


答:
Here are some questions I would ask about CSS:

CSS box model. Margins, padding, etc. IE model vs. W3C model. How can one switch between the two? What are their benefits and drawbacks?

CSS positioning. What does it mean for an element to be "in the flow" and "out of the flow"

inline-block and other display values. Difference between display: none; and visibility: hidden; (this is a good and easy question for people new to CSS)

inline-block vs float for layouts.

Selectors.

CSS resets. Why they are needed and what they accomplish?

Media-queries and responsive design.

How to organize styles and how to keep the number of selectors small. LESS, Sass and other CSS pre-processors. Object-Oriented CSS.

And some questions about HTML:

Doctype and browser modes.

Why are some tags more preferable than the others (em vs i for example)?

What are the basic principles one should follow to keep HTML and CSS manageable and easy to maintain?

In general I put more emphasize on CSS since it's the area many people find difficult to grasp and to use effectively. I meet a lot of candidates that put "CSS" in their CVs but are not able to answer any questions about it. Most people just saying straight "No-no, I know CSS good enough to deal with it but not good enough to talk about it."

Sometimes it's good idea to just give a simple task for and interviewee to complete. Say, design a simple page with layout and block styling that supports multiple screen sizes and adjusts accordingly. It should take about an hour or two and the candidate should explain what he's doing and why.

Good luck with interviewing!

Title: How can I evaluate a candidate's knowledge of Html/CSS during an interview?

Body:
I am trying to determine some good interview questions to assess the ability of people coming in for a Html/CSS job, however that topic is extremely broad, and I'm not sure what sort of questions I can ask to properly evaluate someone's HTML/CSS knowledge.

What sort of questions can I ask to evaluate a candidate's Html/CSS abilities during an interview?

Ideally I would like to ask few questions and then give them a real life scenario to combat.


问:
Why is Global State so Evil?
Before we start this, let me say I'm well aware of the concepts of Abstraction and Dependency Injection. I don't need my eyes opened here.

Well, most of us say, (too) many times without really understanding, "Don't use global variables", or "Singletons are evil because they are global". But what really is so bad about the ominous global state?

Let's say I need a global configuration for my application, for instance system folder paths, or application-wide database credentials.

In that case, I don't see any good solution other than providing these settings in some sort of global space, which will be commonly available to the entire application.

I know it's bad to abuse it, but is the global space really THAT evil? And if it is, what good alternatives are there?

答:
There are several factors to consider with global state:

Programmer memory space

Immutable globals/write once globals.

Mutable globals

Dependency on globals.

The more globals you have, the greater the chance of introducing duplicates, and thus breaking things when duplicates get out of sync. Keeping all of the globals in your falible human memory is becomes both necessary and pain.

Immutables/write once are generally OK, but watch out for initialization sequence errors.

Mutable globals are often mistaken for immutable globals …

A function that uses globals effectively has extra "hidden" parameters, making refactoring it harder.

Global state isn't evil, but it does come at a definite cost – use it when the benefit outweighs the cost.

Title: Why is Global State so Evil?


答:
First of all for dependency injection to be "stateful", you would need to use singletons, so people saying this is somehow an alternative are mistaken. People use global context objects all the time... Even session state for example is in essence a global variable. Passing everything around whether by dependency injection or not isn't always the best solution. I work on a very large application currently that uses a lot of global context objects (singletons injected via an IoC container) and it has never been a problem to debug. Especially with an event driven architecture it can be preferred to use global context objects vs. passing around whatever changed. Depends who you ask.

Anything can be abused and it also depends on the type of application. Using static variables for instance in a web app is completely different than a desktop app. If you can avoid global variables, then do so, but sometimes they have their uses. At the very least make sure your global data is in a clear contextual object. As far as debugging, nothing a call stack and some breakpoints can't solve.

I want to emphasize that blindly using global variables is a bad idea. Functions should be reusable and shouldn't care where the data comes from -- referring to global variables couples the function with a specific data input. This is why it should be passed in and why dependency injection can be helpful, although you are still dealing with a centralized context store (via singletons).

Btw... Some people think dependency injection is bad, including the creator of Linq, but that isn't going to stop people from using it, including myself. Ultimately experience will be your best teacher. There are times to follow rules and times to break them.

Title: Why is Global State so Evil?

Body:
Before we start this, let me say I'm well aware of the concepts of Abstraction and Dependency Injection. I don't need my eyes opened here.

Well, most of us say, (too) many times without really understanding, "Don't use global variables", or "Singletons are evil because they are global". But what really is so bad about the ominous global state?

Let's say I need a global configuration for my application, for instance system folder paths, or application-wide database credentials.

In that case, I don't see any good solution other than providing these settings in some sort of global space, which will be commonly available to the entire application.

I know it's bad to abuse it, but is the global space really THAT evil? And if it is, what good alternatives are there?


问:
Why we don't import a package while we use String functions?
I asked myself why we didn't import a package while we use String functions such as toUpperCase()? How they get in there without importing packages?

答: The java.lang package is imported by default. If you take a look at the classes in the package, you'll see that they are very common classes that you end up using frequently, independent of what your program is actually trying to do. Rather than essentially requiring every file to have import statements for these classes, the creators decided to include it for you behind the scenes.


答: the String object is part of java.lang which is considered core and is always included (like for example Object)

Title: Why we don't import a package while we use String functions?

Body: I asked myself why we didn't import a package while we use String functions such as toUpperCase()? How they get in there without importing packages?


答:
Java tutorials > Learning the Java Language > Packages:

For convenience, the Java compiler automatically imports three entire packages for each source file: (1) the package with no name, (2) the java.lang package, and (3) the current package (the package for the current file)...

Class String is in java.lang package, hence it is imported automatically per above rule.


问:
Open source code with no license... can I fork it?
Years ago somebody created a bunch of really awesome and popular scripts. But they were not updated for a long, now they no-longer work (target platform were updated, and some changes are needed).

He hasn't released it under any license.  I want to fix the bug (currently, many of the target users can't use it), and post it on GitHub, preferably under a public-domain style OSS license. I wonder what the legal ramifications might be?

I have sent an email to the author, but (let's say) he didn't reply to my email.

What we should do in the following this into 2 cases:

If the script is posted on a private website (without any source control).

If the script is posted on GitHub (without any licensing hints).

However, one can clearly see, that it seems open source - intended to be used/modified/whatever.

答:
You can provide patches. As the distributor of those patches, you're not liable for infringement anyway (they're trivial: filepath X has become filepath Y).

The combination of the original, copyrighted work and your patches is protected as a derived work. That means the combination cannot be distributed, but that's not needed anyway: the patching will be done by (or on behalf) of the end users.

ContentLicense: CC BY-SA 4.0


问:
Should a web developer know how to do slicing?
I am a web developer. I'm doing all kinds of web-sites and web applications.

It's very strange for me that a lot of customers do not know the difference between a web developer and a slicer. They just want to "give you the PSD" and expect you to give them a web site with a DB back-end and so on...

I'm just asking here: am I wrong in my thinking?

Of course, a web developer MUST know html and css but I don't think that he should slice the PSD and do all the work a css guru can do...

I would like to hear your opinions on this.

答:
It's very strange for me that a lot of customers do not know the difference between a web developer and a slicer.

Every time I find something a customer asked strange, I ask them about their jobs, and quickly find out that I have absolutely no idea what it is that they are doing (apart from a very high level overview sometimes). It's not strange, it's perfectly normal.

Unless of course your customers are web designers ;)

Of course, a web developer MUST know html and css but I don't think that he should slice the PSD and do all the work a css guru can do...

The line between web development and web design is fuzzy at best, where one ends and the other begins is debatable. There is nothing wrong in having some basic web / graphics design skills, and slicing a PSD is a very basic skill, something that you can pick up in hours.

Whether it's a skill that you must use or not is up to you, your specific situation and your relations with your customers. Still use and know are different things, even if you are never again asked to slice a PSD, why not be able to do it?


问:
Understanding C++ for windows desktop application
I've been programming C++ for almost a year, and I've written complex programs however there are a couple of programming features of C++ which I didn't cover up (Classes & pointers), however I felt ready to develop a desktop application. I didn't get any books nor did I find any REAL documentation. I said to myself "Practicing is the most important thing in programming. I'll do that".

Obviously I didn't learn much. After 4 months of programming in Visual studio C++/CLI I barely understand what I'm doing. I know how to do very basic operations, converting data types, but I am clueless on how the program works, how I add anything except events or how I change my GUI in code and not in the GUI builder.

What should I do? Practice didn't really help, I only know some very easy things since I started working with Visual Studio, but the rest of the concepts leave me clueless. Should I hit the books, or should I just keep practicing?

答: Download QT Creator and look at the example programs supplied with it. A lot of them are very useful. Sure, QT has some unique quirks but it's the easiest way I can think of to get you started writing GUI apps.</p>


答:
From personal experience, working with other developers, I think questions on HTML & CSS won't sort out the people who know what they are talking about from those that know what they are actually doing.

I'd recommend a mock test/prototype based on the realistic experience of your company's needs.


答:
I hate to say this, but it depends on your situation.

I currently am at a company that has an in house CSS/UI team.  So I don't touch much, if anything, on the front-end.  I was hired as a back-end developer and that's all they want me to do.

To contrast that, I used to work at a small tech consulting company.  Each person had their own "clients" and we rarely worked as a team.  Almost all of us were "one man armies".  So when a client came to us with a PSD or image of what they wanted the site to look like, we were the ones that had to convert it to valid HTML/CSS.  We were responsible for ALL aspects of the project, from start to finish.

If you're going to be doing independent consulting, you definitely must have strong CSS skills.  But if you work for a larger company with a devoted CSS team/person, then it is up to them to get the HTML/CSS how the client wants it.


答:
I draw a line between a web developer and a web programmer. To me a programmer handles the server side programming, all the back end stuff. The web developer is responsible for understanding everything between the back end output and the designer's intention. The developer absolutely MUST know how the graphical design translates into semantic markup. It's absolutely critical from a technical standpoint that the developer knows the browser standards, css markup, etc to be able to pull it off properly, and it's proper that a customer would expect that knowledge from a developer.

While a programmer is a more specialized position within the web arena, I would say it is not critical that the programmer doesn't understand or know how to do these things. That being said, I probably wouldn't hire a web programmer who didn't have a knowledge of design-to-markup translation. I personally feel that a web programmer who has that experience will be more well-rounded with respect to his own position and be more capable of working well with either development or design staff.


问:
What alternatives are there for cross cutting concerns other than aspect oriented programming?
Aspect oriented programming promises to deal with cross cutting concerns, but I'm not completely sold on it yet. Have there been any other attempts to deal with this problem?</p>

答:
I'm no expert on AOP, but from reading about it over the years, it has always seemed like a weaker form of the metaprogramming offered by Lisp, especially parts like its metaobject protocol.

This should come as no surprise, I suppose: Gregor Kiczales was one of the authors of AMOP, and later wrote AspectJ for Java!


问:
How should I build the data structure for a dynamic, unlimited-size "maze"?
I'm not actually sure that "maze" is the correct term. Basically users start in a single Room that has 4 doors (N, S, E, and W). They can go in any direction, and each subsequent room is contains another room with anywhere from 1 to 4 doorways that go to other rooms.

The "maze" is supposed to be unlimited in size, and to grow as you move rooms. There is a limited number of Rooms available, however the available number is dynamic and can change.

My problem is, I'm not sure of the best data structure for this type of pattern

I first thought about just using a [X][X] array of Room objects, but I'd really rather avoid that since the thing is supposed to grow in any direction, and only rooms that are "visited" should be built.

The other thought was to have each Room class contain 4 linked Room properties for N, S, E, and W, and just link to the previous Room, but the problem with that I don't know how to identify if a user goes into a room that has an adjacent room already "built"

For example,

```
---    ---            ----------
|        |            |        |
   Start        5          4
|        |            |        |
---    ---            ---    ---
---    --- ---------- ---    ---
|        | |        | |        |
|    1          2          3
|        | |        | |        |
---    --- ---    --- ----------

```

If the user moves from Start > 1 > 2 > 3 > 4 > 5, then Room #5 needs to know that W contains the starting room, S is room #2 and in this case should not be available, and N can be either a new Room or a wall (nothing).

Perhaps I need a mix of the array and the linked rooms, or maybe I'm just looking at this the wrong way.

Is there a better way of building the data structure for this type of "maze"? Or am I on the right track with my current thought process, and am just missing a few pieces of information?

(In case you're interested, the project is a game very similar to Munchkin Quest)

答:
Give each Room coordinates (start would be (0,0)) and store each generated Room in a dictionary/hashmap by coordinates.

It's trivial to determine the adjacent coordinates for each Room, which you can use to check if a Room already exists. You could insert null values to represent locations where it is already determined that no Room exists. (or if that's not possible, i'm not sure atm, a seperate dictionary/hasmap for coordinates that do not contain a Room)


答:
In most cases, what you're describing sounds like a graph. Given some of your requirements (the growing aspect) I'd probably choose an adjacency list as the implementation (the other common option would be an adjacency matrix).

I'm not sure what language you're using, but a good tutorial/explanation with implementation details for a graph implemented with an adjacency list in .NET is here.

Title: How should I build the data structure for a dynamic, unlimited-size "maze"?

Body:
I'm not actually sure that "maze" is the correct term. Basically users start in a single Room that has 4 doors (N, S, E, and W). They can go in any direction, and each subsequent room is contains another room with anywhere from 1 to 4 doorways that go to other rooms.

The "maze" is supposed to be unlimited in size, and to grow as you move rooms. There is a limited number of Rooms available, however the available number is dynamic and can change.

My problem is, I'm not sure of the best data structure for this type of pattern

I first thought about just using a [X][X] array of Room objects, but I'd really rather avoid that since the thing is supposed to grow in any direction, and only rooms that are "visited" should be built.

The other thought was to have each Room class contain 4 linked Room properties for N, S, E, and W, and just link to the previous Room, but the problem with that I don't know how to identify if a user goes into a room that has an adjacent room already "built"

For example,

```
---    ---            ----------
|        |            |        |
   Start        5          4
|        |            |        |
---    ---            ---    ---
---    --- ---------- ---    ---
|        | |        | |        |
|    1          2          3
|        | |        | |        |
---    --- ---    --- ----------

```

If the user moves from Start > 1 > 2 > 3 > 4 > 5, then Room #5 needs to know that W contains the starting room, S is room #2 and in this case should not be available, and N can be either a new Room or a wall (nothing).

Perhaps I need a mix of the array and the linked rooms, or maybe I'm just looking at this the wrong way.

Is there a better way of building the data structure for this type of "maze"? Or am I on the right track with my current thought process, and am just missing a few pieces of information?

(In case you're interested, the project is a game very similar to Munchkin Quest)


答:
You could consider a 4 way linked list...

I first thought about just using a [X][X] array of Room objects, but I'd really rather avoid that since the thing is supposed to grow in any direction, and only rooms that are "visited" should be built.

You can still use a [][] for that.  The dynamic growing might be slow, especially when adding at the beginning, but maybe not all that bad.  You should profile to check.  Trying to manipulate some linked list or map might actually be worse, and on a constant level rather than occasional.

You can build only visited rooms by implementing lazy evaluation.  An object can be in place that contains a room, and doesn't build that room until room() is called on it.  Then it just returns the same one every time after that.  Not hard to do.


答:
You should absolutely know how to slice up a design and make useful HTML/CSS.  If you can't, then I don't think you can call yourself a web developer.

"Web developer" is a very generalist title, and you need to be familiar with many technologies, as well as understanding how to build a page.  If you can't take a design and interpret how that should be built, I believe you are missing a key skill to "web development".  It is crucial for you to know how all of the pieces fit together.

Now, I'm not saying that if you are a programmer that knows a few of the server-side languages commonly used in web development that you don't have useful skills.  I'm just making a distinction between those who actually know how to develop websites, and those who know how to write programs that run on web servers.  You can absolutely find web work strictly writing back-end code, especially on larger sites.  You won't find job titles such as "web developer" there very often.


问:
New Silverlight app. MVVM. RIA Services vs CSLA
Another 2 days of reading and watching demos and here we go.

For my enterprise LoB Silverlight app I'm going to use:

Prism for UI aspects and modularity.

MVVM pattern (using Prism)

??? to bring data over and validations...

Entity Framework for Data access

SQL Server for data

Ok, main dilemma is #3. If I won't use any framework then I will have to figure out how to do all CRUD stuff myself. I can do RESTful WCF, I can do SOAP. All that == MANUAL coding.

I can do RIA Services. I kind of see what it does and it is nice for direct match with my data layer BUT it is not that great if there will be lot of business logic. Where would I put it? In my ViewModel? Another question is how those services maintained. Once I generated it - I should maintain them by hand if data changes?

I also found CSLA which seems to be nice on one hand but receives lot's of critique.. CSLA will allow me to write business logic and shape object as I needed and than I can pass it "through" ViewModel and all is well.

Something tells me that RIA Services will be much quicker to write. Also, I like the fact that I don't have to include extra dependencies.

There is no blogs or mentioning of RIA Services since 2010. Is it going under table? Not widely accepted? Not scaling well for big apps?

I'm trying to decide which one I need to bet on. CSLA or RIA Services. OR?

答:
We're about 1.5 years into a 3 year project using CSLA, Prism, TSQL and Silverlight. Given the chance, I'd toss CSLA out as quickly as possible. One of the biggest problems I have with CSLA is that it tries to do everything. If you watch Rich Hikey's talk on Simple vs Easy (http://www.infoq.com/presentations/Simple-Made-Easy) you'll notice he talks about "complecting" things. That is, entangling code so that a single object is responsible for more than one thing.

CSLA violates this principle (and that of SOLID) left, right, and center. You basically end up with a situation where your business rules are in your data transfer objects. You end up using the same object that you populated with DB data (either directly from EF or via DTOs), and that same exact object ends up on the client being bound to the UI. Or you can wrap them in View Models, if you wish, but that just adds more and more complexity.

On top of that you're locking your client software into a .NET language. If in the future you want to provide service feeds or simply access your data from JS and HTML, you're suddenly forced to wrap hundreds of lines of code to present to these different platforms.

Keep it simple...have your web server spit out JSON...have you client and servers completely de-coupled (share code files if desired, but don't couple them). The simpler your code is, the easier it will be to fix bugs, understand what's going on, and keep everything under control


问:
Separation of concerns in an RMR framework
I'm working on a new framework for PHP that utilises an architectural pattern called RMR, instead of the more common (pseudo)-MVC that most PHP frameworks currently implement.  So far it feels like a better fit for web-apps than MVC was.

I'm currently separating the various concerns involved with managing a page request/response cycle and have so far implemented objects for form validation, representing the request, representing the response, a front controller to wrap a complete HTTP request/response, a resolver to route a request to the appropriate resource and so on.

This has led to an interesting question regarding separation of concerns, however.

In an MVC framework I'd normally have a form validation object and a business object (model) wrapped in a controller action.  The action would validate the input and hand it off to the business object if it passed validation, or back to the view for error display.

However, in RMR, there is no controller.  The architecture I'm considering has a form validation class like the MVC frameworks such as zend, but without a controller there isn't an obvious place to invoke it.

I could invoke the form validation object from within the resource (the RMR equivalent of a model), but this feels wrong, because the resource needs to know more about how it's going to be used in this case.  I know from the description of RMR that this isn't completely avoidable, the resource has to be able to understand a HTTP request, but I'd rather keep it to a minimum if at all possible so that resources can still be used outside of the context of the RMR framework without major modification.

I could do form validation in the object that encapsulates the HTTP request, but this implies that the request object needs to know how the resource is intending to use the given input.  For example, a resource representing a blog entry may allow comments to be added, votes to be collected or the original poster to edit it.  If all three kinds of operations are submitted via a POST then the request object will need to be able to determine whether the given POST is for editing the blog, adding a comment or submitting a vote.  If more functionality is added to the blog article resource, or if some functionality is removed, then the request needs to know about it.  This seems to break encapsulation.

I also considered moving form validation to the front controller, but this would have similar problems to having it in the request object.  The front controller would need to know something about the inner workings of the resource before it could validate input for it.

If anyone has any alternative approaches or commentary regarding this problem I'd appreciate any input you have.  Maybe this problem is just highlighting that the approach I used in the past with MVC was wrong, and having form validation in the controller wasn't the proper way of doing things?

答:
In MVC, I firmly believe validation belongs in the Model.  The Model is the authority on what the data is and what it is allowed to be.  A Model should not allow a caller to set one of its fields to an invalid value, so it has to validate its inputs, and DRY means you do not duplicate that elsewhere.  </p>

<p>So I guess that means in RMR, validation would go in the Resource. The Method would be responsible for handling a validation failure by returning a Representation of the form with an error message instead of the Representation of the successful result.  </p>

Body:
In MVC, I firmly believe validation belongs in the Model.  The Model is the authority on what the data is and what it is allowed to be.  A Model should not allow a caller to set one of its fields to an invalid value, so it has to validate its inputs, and DRY means you do not duplicate that elsewhere.

So I guess that means in RMR, validation would go in the Resource. The Method would be responsible for handling a validation failure by returning a Representation of the form with an error message instead of the Representation of the successful result.


答:
Why is Global State so Evil?

Mutable global state is evil because it's very hard for our brain to take into account more than a few parameters at a time and figure out how they combine both from a timing perspective and a value perspective to affect something.

Therefore, we are very bad at debugging or testing an object whose behavior has more than a few external reasons to be altered during the execution of a program. Let alone when we have to reason about dozens of these objects taken together.

Title: Why is Global State so Evil?


问:
If you were the manager of a team of 25 developers, how would you motivate them?
Imagine yourself hired by a new startup backed with few millions coming from venture capitalists.

Your mission: organize the development of the next killer app.

25 developers is too much to take care of each individually, so what decision(s) you would make to motivate them?

I will appreciate any answers from stock options to free cookies ;)

Of course the trick here (unless you are really a manager of a such startup), is put yourself in the shoes of one of those programmers.

EDIT: it's an imaginary context. The purpose of this story is to stimulate your wishes. I want to capture what motivates developers.

答: I'm ready to be voted down, but you can motivate me any way you want (make me work hard hours, give me a 386 for a machine on which to code, work on a shaking card table in the dark in a basement, yell at me, work weekends and holidays, and provide no free coffee) and I will be your crack team as long as you pay me a ridiculous amount of money.


答:
How about this..

Give each cell a link to each of it's neighbors.  Give each cell some sort of name (ie "0/0", "-10/0" (Assume you start at 0,0)).  Add a HashSet with all the names in it.  As you try to move to another cell, just check that the neighbor does not already exist in the HashSet.

Also, if you create an opening to another room, does that imply that the rooms exists?  So you'd create a link to an empty room with no links to any rooms.  You'd probably also want to check the new rooms neighbors.  If one exists, and would open to your new room, add a door to that room.

```<code>   Empty
   (0,1)

---    ---            ----------
|        |            |        |
    0,0       1,0        2,0       Empty
|        |            |        |   (3,0)
---    --- ---------- ---    ---
|        | |        | |        |
|   0,-1      1,-1       2,-1      Empty
|        | |        | |        |   (3,-1)
---    --- ---    --- ----------

   Empty     Empty
  (0,-2)    (1,-2)
</code>```

HashSet = { 0|0, 1|0, 2|0, 3|0, 0|-1, 1|-1 .... }
1,0 : W = 0,0/Door ; 1,0 : N = 1,1/Empty ; E = 2,0/Door ; S = 1,-1/Wall

You'd also have to make sure that you give each new room at least one non-adjacent (to another room) door so that the maze can grow in that direction.

Body:
How about this..

Give each cell a link to each of it's neighbors.  Give each cell some sort of name (ie "0/0", "-10/0" (Assume you start at 0,0)).  Add a HashSet with all the names in it.  As you try to move to another cell, just check that the neighbor does not already exist in the HashSet.

Also, if you create an opening to another room, does that imply that the rooms exists?  So you'd create a link to an empty room with no links to any rooms.  You'd probably also want to check the new rooms neighbors.  If one exists, and would open to your new room, add a door to that room.

   Empty
   (0,1)

---    ---            ----------
|        |            |        |
    0,0       1,0        2,0       Empty
|        |            |        |   (3,0)
---    --- ---------- ---    ---
|        | |        | |        |
|   0,-1      1,-1       2,-1      Empty
|        | |        | |        |   (3,-1)
---    --- ---    --- ----------

   Empty     Empty
  (0,-2)    (1,-2)

HashSet = { 0|0, 1|0, 2|0, 3|0, 0|-1, 1|-1 .... }
1,0 : W = 0,0/Door ; 1,0 : N = 1,1/Empty ; E = 2,0/Door ; S = 1,-1/Wall

You'd also have to make sure that you give each new room at least one non-adjacent (to another room) door so that the maze can grow in that direction.


答:
State is unavoidable in any real application. You can wrap it up any way you like, but a spreadsheet must contain data in cells. You can make cell objects with only functions as an interface, but that doesn't restrict how many places can call a method on the cell and change the data. You build whole object hierarchies to try to hide interfaces so other parts of the code can't change the data by default. That doesn't prevent a reference to the containing object from being passed around arbitrarily. Nor does any of that eliminate concurrency issues by itself. It does make it harder to proliferate access to data, but it doesn't actually eliminate the perceived problems with globals. If someone wants to modify a piece of state, they're going to do it weather it's global or through a complex API (the later will only discourage, not prevent).

The true reason not to use global storage is to avoid name collisions. If you load multiple modules which declare the same global name, you either have undefined behavior (very hard to debug because unit tests will pass) or a linker error (I'm thinking C - Does your linker warn or fail on this?).

If you want to reuse code, you've got to be able to grab a module from another place and not have it accidentally step on your global because they used one with the same name. Or if you're lucky and get an error, you don't want to have to change all the references in one section of code to prevent the collision.

Title: Why is Global State so Evil?


答:
A couple thoughts on the implementation (I've thought of Carcassonne which has a number of other challenging aspects to building the matrix - it was even an interview question I once was asked).

There are some questions that are asked of this structure:

is there a room at X,Y?

is there a room [N/S/E/W] of the empty location X,Y?

The problem with simple lists and graphs

The difficulty with simple lists is that one has to walk the structure in order to test if something can be placed at a given location.  The system needs a way of accessing an arbitrary location O(1).

Consider:

```<code>1 2 3 ? 4
5 . . * 6
7 8 9 A B
</code>```

To find the information the possible location '?', when at 3, one has to walk all the way around to get to 4.  The answer of link with extra information on how many nodes it jumps (so that 3 would be linked to 4 with a 'jump 1' extra info) still requires walks when finding the adjacency of '*' from 6 or A.

Simple, big, arrays

There is a limited number of Rooms available

If this is a not large number, just create a 2N x 2N array and leave it there.  A 100 x 100 array is 'only' 10,000 pointers and 50 objects.  Index directly into the array.

This could be reduced to just NxN if out of bounds activities shifted the array around to always be within the constraints.  For example, if a room was to be added that would underflow the array, have the grid to shift every element one position so that there would be no underflow anymore.  At this point, the size of the world for 50 rooms would be 2500 pointers and 50 objects.

Sparse arrays and matrices

To more optimally create this, look into a sparse array in which the majority of the elements are 0 or null.  For two dimensions, this is known as a sparse matrix.  Many programming languages have various libraries for working with this structure.  If the library restricts to integers, one could use this integer as an index into a fixed array of rooms.

My preferred approach would be to have the rooms as a structure (pointers to adjacent rooms, and coordinates) and have the room also a pointer from a hash table which is hashed on coordinate.  In this situation to ask what room is [N/S/E/W] from a null room, one would query the hash table.  This, incidentally, is the 'DOK' format for storing a sparse matrix.

Body:
A couple thoughts on the implementation (I've thought of Carcassonne which has a number of other challenging aspects to building the matrix - it was even an interview question I once was asked).

There are some questions that are asked of this structure:

is there a room at X,Y?

is there a room [N/S/E/W] of the empty location X,Y?

The problem with simple lists and graphs

The difficulty with simple lists is that one has to walk the structure in order to test if something can be placed at a given location.  The system needs a way of accessing an arbitrary location O(1).

Consider:

1 2 3 ? 4
5 . . * 6
7 8 9 A B

To find the information the possible location '?', when at 3, one has to walk all the way around to get to 4.  The answer of link with extra information on how many nodes it jumps (so that 3 would be linked to 4 with a 'jump 1' extra info) still requires walks when finding the adjacency of '*' from 6 or A.

Simple, big, arrays

There is a limited number of Rooms available

If this is a not large number, just create a 2N x 2N array and leave it there.  A 100 x 100 array is 'only' 10,000 pointers and 50 objects.  Index directly into the array.

This could be reduced to just NxN if out of bounds activities shifted the array around to always be within the constraints.  For example, if a room was to be added that would underflow the array, have the grid to shift every element one position so that there would be no underflow anymore.  At this point, the size of the world for 50 rooms would be 2500 pointers and 50 objects.

Sparse arrays and matrices

To more optimally create this, look into a sparse array in which the majority of the elements are 0 or null.  For two dimensions, this is known as a sparse matrix.  Many programming languages have various libraries for working with this structure.  If the library restricts to integers, one could use this integer as an index into a fixed array of rooms.

My preferred approach would be to have the rooms as a structure (pointers to adjacent rooms, and coordinates) and have the room also a pointer from a hash table which is hashed on coordinate.  In this situation to ask what room is [N/S/E/W] from a null room, one would query the hash table.  This, incidentally, is the 'DOK' format for storing a sparse matrix.


问:
Do you start migrating your Swing project to JavaFX
I have a 4 years old project which is written in Swing + SwingX. Currently, it is still alive and still kicking.

However, as more GUI related feature requests coming in (For instance, a sortable tree table), I start to feel the difficulty in fulling the requests. This is true especially since there isn't any active development going around SwingX project.

Also, I can hardly find any good, yet actively maintained/ developed/ evolving GUI Java framework.

I was wondering, do any of the Swing developers feel the same thing? Have you start to migrate your Swing project to a much more active developed GUI framework, like JavaFX?

答: Swing is becoming a legacy technology, or is already. However, it's quite good in what it does and isn't going away in any foreseeable future, so I see no reason to move away from it, particularly if one has invested in it already. JIDE Software makes good (commercial) Swing components to replace what's missing from the standard Swing. For example, sortable treetable is in their Grids out of the box.</p>


问:
Should one check for null if he does not expect null?
Last week, we had a heated argument about handling nulls in our application's service layer. The question is in the .NET context, but it will be the same in Java and many other technologies.

The question was: should you always check for nulls and make your code work no matter what, or let an exception bubble up when a null is received unexpectedly?

On one side, checking for null where you are not expecting it (i.e. have no user interface to handle it) is, in my opinion, the same as writing a try block with empty catch. You are just hiding an error. The error might be that something has changed in the code and null is now an expected value, or there is some other error and the wrong ID is passed to the method.

On the other hand, checking for nulls may be a good habit in general. Moreover, if there is a check the application may go on working, with just a small part of the functionality not having any effect. Then the customer might report a small bug like "cannot delete comment" instead of much more severe bug like "cannot open page X".

What practice do you follow and what are your arguments for or against either approach?

Update:

I want to add some detail about our particular case. We were retrieving some objects from the database and did some processing on them (let's say, build a collection). The developer who wrote the code did not anticipate that the object could be null so he did not include any checks, and when the page was loaded there was an error and the whole page did not load.

Obviously, in this case there should have been a check. Then we got into an argument over whether every object that is processed should be checked, even if it is not expected to be missing, and whether the eventual processing should be aborted silently.

The hypothetical benefit would be that the page will continue working. Think of a search results on Stack Exchange in different groups (users, comments, questions). The method could check for null and abort the processing of users (which due to a bug is null) but return the "comments" and "questions" sections. The page would continue working except that the "users" section will be missing (which is a bug). Should we fail early and break the whole page or continue to work and wait for someone to notice that the "users" section is missing?

答:
I normally check for nulls but I "handle" unexpected nulls by throwing an exception that gives a bit more detail about exactly where the null occurred.

Edit:  If you get a null when you don't expect one something is wrong--the program should die.


问:
What is considered best practice for printing usage / help (--help)?
When writing tools for the CLI of UNIX, how should I make the program print out help and/or usage?

I usually use fprintf(stderr, "help text here");, but there are several issues with that.

First, I'm not sure, whether I should use stderr. Is that OK, or should I use stdout?

As you can imagine, the help text is quite long, depending on how many options the tool has. Now, I usually, just put several "strings like that\n" in the second parameter. This however, fills my source code with fifty or more lines of help text. It is not easy manageable at all. What should I do instead?

When a tool is not written in C or a C-like language, I tend to use here-docs where possible (most prominently with Perl). I can't use that in C, but is there something like that, that I could use?

I was considering putting it in a headerfile.h inside a #define HELP "help text here", I've never seen it in the wild, don't know whether I should actually use that.

Ideally, I could put the text in an external file, and include it. Using #include for that seems wrong, though. What should I do then?

The idea is, to have a help text, that is easily manageable. Having it inside the source code isn't really convenient.

答:
I use the gnu getopts library. For an example with help, see this sample project, specifically the main method at the bottom of parser.y.

Since it is wrapped in curly braces, the vim editor I use can fold the lines together, and I don't even notice them when I don't need to.


问:
AJAX driven "page complete" function? Am I doing it right?
This one might get me slaughtered, since I'm pretty sure it's bad coding practice, so here goes:

I have an AJAX driven site which loads both content and javascript in one go using Mootools' Request.HTML.

Since I have initialization scripts that need to be run to finish "setting up" the template, I include those in a function called pageComplete(), on every page

Visiting one page to another causes the previous pageComplete() function to no longer apply, since a new one is defined.

The javascript function that loads pages dynamically calls pageComplete() blindly when the AJAX call is completed and is loaded onto the page:

```<code>function loadPage(page, params) {
    // page is a string, params is a javascript object
    if (pageRequest && pageRequest.isRunning) pageRequest.cancel();
    pageRequest = new Request.HTML({
        url: '<?=APPLICATION_LINK?>' + page,
        evalScripts: true,
        onSuccess: function(tree, elements, html) {
            // Empty previous content and insert new content
            $('content').empty();
            $('content').innerHTML = html;
            pageComplete();
            pageRequest = null;
        }
    }).send('params='+JSON.encode(params));
}
</code>```

So yes, if pageComplete() is not defined in one the pages, the old pageComplete() is called, which could potentially be disastrous, but as of now, every single page has pageComplete() defined, even if it is empty.

Good idea, bad idea?

答:
You could place a line like

```<code>pageComplete=function(){};
</code>```

somewhere in the code to make sure that the old function is not called for the new page. Possible places would be:

First line of loadPage

First line of onSuccess

after the call pageComplete();

That said, it still smells.

Body:
You could place a line like

pageComplete=function(){};

somewhere in the code to make sure that the old function is not called for the new page. Possible places would be:

First line of loadPage

First line of onSuccess

after the call pageComplete();

That said, it still smells.


答:
I see no purpose for pageComplete() in your example.  You already have evalScripts set to true.

I doubt this concept would even work, because the browser is unlikely to have parsed html and inserted the new HTML by the next line, where pageComplete() is called.

Both Prototype and (I'm fairly certain) jQuery have an alternative AJAX call that does the .innerHTML = html for you.  I'd be very surprised if mootools didn't.

Consider this template, which looks like something similar to what html would contain:

```<code><div id='content1'>Stuff is here</div>
<script type='text/javascript'>
   function pageComplete() {
      console.log('foo');
   }
</script>
</code>```

Drop the function definition, and don't call pageComplete().  This should work much better:

```<code><div id='content1'>Stuff is here</div>
<script type='text/javascript'>
   console.log('foo');
</script>
</code>```

evalScripts should run that javascript after the AJAX loads, without you having to fiddle around with redefining any functions.

Title: AJAX driven "page complete" function? Am I doing it right?

Body:
This one might get me slaughtered, since I'm pretty sure it's bad coding practice, so here goes:

I have an AJAX driven site which loads both content and javascript in one go using Mootools' Request.HTML.

Since I have initialization scripts that need to be run to finish "setting up" the template, I include those in a function called pageComplete(), on every page

Visiting one page to another causes the previous pageComplete() function to no longer apply, since a new one is defined.

The javascript function that loads pages dynamically calls pageComplete() blindly when the AJAX call is completed and is loaded onto the page:

```<code>function loadPage(page, params) {
    // page is a string, params is a javascript object
    if (pageRequest && pageRequest.isRunning) pageRequest.cancel();
    pageRequest = new Request.HTML({
        url: '<?=APPLICATION_LINK?>' + page,
        evalScripts: true,
        onSuccess: function(tree, elements, html) {
            // Empty previous content and insert new content
            $('content').empty();
            $('content').innerHTML = html;
            pageComplete();
            pageRequest = null;
        }
    }).send('params='+JSON.encode(params));
}
</code>```

So yes, if pageComplete() is not defined in one the pages, the old pageComplete() is called, which could potentially be disastrous, but as of now, every single page has pageComplete() defined, even if it is empty.

Good idea, bad idea?

Body:
I see no purpose for pageComplete() in your example.  You already have evalScripts set to true.

I doubt this concept would even work, because the browser is unlikely to have parsed html and inserted the new HTML by the next line, where pageComplete() is called.

Both Prototype and (I'm fairly certain) jQuery have an alternative AJAX call that does the .innerHTML = html for you.  I'd be very surprised if mootools didn't.

Consider this template, which looks like something similar to what html would contain:

<div id='content1'>Stuff is here</div>
<script type='text/javascript'>
   function pageComplete() {
      console.log('foo');
   }
</script>

Drop the function definition, and don't call pageComplete().  This should work much better:

<div id='content1'>Stuff is here</div>
<script type='text/javascript'>
   console.log('foo');
</script>

evalScripts should run that javascript after the AJAX loads, without you having to fiddle around with redefining any functions.


问:
Data/Object Design Problem
Goal:

I'm trying to figure out the best way to model/design and then implement a "user" feature in a system.

Background:

I am designing an on-line access request system, so our company can use a web-based method for users to request access to various software systems. Since the system is all about the "user", the user is the focal point of the system.

So, a User can request access to a system. Then, the User's Manager will approve/reject the request. After that, the System Owner will approve/reject the request. Then it's the System Admin who approves/rejects, and finally the Security Administrator approves/rejects and adds them to the appropriate Active Directory group so they have access to the target Active Directory-driven application (not this application).

Problem:

I see all entities that represent a User as a core (set of) class(es) in the system. The User object is straight-forward - just pass their Windows login to Active Directory (AD) via an LDAP query and get their info and load it into an object. In an LDAP query, if there are other Users that report to them (a user's manager is stored in our AD), then this "user" is not only a User in this system but also a Manager. If this User is also in the database as a System Owner, they are also a System Owner.

So Far:

(Assume a Manager is someone with at least one direct report assigned to them in AD.)

I've considered a single User object, with properties such as IsManager or IsSystemOwner. However, should I construct an object hierarchy where (for example) a Manager class inherits from User? There are quirks with this, because a System Owner could inherit from User or Manager. Not all system owners are managers. However, Managers, System Owners, System Admins, and Security Admins are all Users, because they can be requesting access to some software system where there role in this system is only as a User. Here is an overview of "is a" for all of the user entities:

A User can request access to some other software system in this system.

A Manager is a User.

A System Owner is a User.

A System Admin is a User.

A Security Admin is a User (but unlikely to be, due to our organization).

A Manager may be a System Owner, but not always.

A System Owner may be a Manager, but not always.

A System Admin may be a Manager, but not always.

A System Admin may be a System Owner, but not likely.

A Security Admin may be a Manager, but not always.

A Security Admin may be a System Owner, but not likely.

Some additional info:

I don't anticipate Security Admins to be using the system as a User to request access, but it's always a possibility.

A Manager may create an access request on behalf of one of their employees (to revoke access to a fired employee, for example)

All employees in the Windows domain will have access to this site. I assume that I will have some Active Directory groups created for System Admins and Security Admins, as the users in these groups will not be dynamic, rather, users in one team are Sys Admins and users in another team are Security Admins.

The System Owner is subject to changed and will be stored in the database, along with the option to designate an alternate approver when on vacation, etc.

I may need a Manager to have an alternate approver, but I didn't plan on storing all users on the domain in the database!

This seems like it's so easy to model on paper, but getting it into good, flexible code is stumping me. All suggestions are welcome.

EDIT: Based on Karl's feedback, I have this prototype model. Does it look solid from an OOP perspective, based on my intended use?

```<code>Public Class MyCustomUserObject

    Public Property LoginID As String
    Public Property FirstName As String
    Public Property LastName As String
    Public Property EmailAddress As String

    Public Property Roles As List(Of Role)

    Public Function IsManager() As Boolean
        ' If List(Of Role) contains an object of type ManagerRole, then True, else False.
    End Function

    Public Function IsSystemOwner(systemName As String) As Boolean
        ' If List(Of Role) contains an object of type SystemOwnerRole with matching name
        ' in SystemOwnerRole.SoftwareSystems, then True, else False.
    End Function

    Public Function IsSystemAdministrator(systemName As String) As Boolean
        ' If List(Of Role) contains an object of type SystemAdministratorRole with matching name
        ' in SystemAdministratorRole.SoftwareSystems, then True, else False.
    End Function

    Public Function IsSecurityAdministrator() As Boolean
        Return My.User.IsInRole("My Active Directory group name for Security Admins")
    End Function

End Class

Public Class SoftwareSystem

    Public Property ID As String
    Public Property Name As String

End Class

Public MustInherit Class Role

    Public Property DesignatedApproverLoginID As String

End Class

Public Class ManagerRole
    Inherits Role

    Public Property Subordinates As List(Of AafUser)
    ' Or this, with a List of login IDs?
    ' Public Property Subordinates As List(Of String)

End Class

Public Class SystemOwnerRole
    Inherits Role

    Public Property SoftwareSystems As List(Of SoftwareSystem)

End Class

Public Class SystemAdministratorRole
    Inherits Role

    Public Property SoftwareSystems As List(Of SoftwareSystem)

End Class

Public Class SecurityAdministratorRole
    Inherits Role

    ' Explictly a Security Admin for all Software Systems.

End Class
</code>```

答:
My suggestion is rather than making different User classes for different roles, have a single User class that contains a list of Role objects.  Role would be a base class, with Manager, SystemOwner, SecurityAdmin, and SystemAdmin being derived classes, with fields specific to their needs.  Manager would have a list of subordinates, SystemOwner would have descriptions of the system, etc.  Role could have common fields, like an alternate approver, for example.

That architecture opens a lot of possibilities.  Someone can easily be the owner of multiple systems, for example.  That also makes queries like "list all system owners" easier.

Title: Data/Object Design Problem


问:
Learning the Operating Systems concepts and Programming Languages for elderly
I am not sure if this would be the right forum to ask the question (Please let me know and I will move the question to appropriate forum).

I would like to know what can be the best way for elders (in my case, my parents) to learn how  to program. I was looking at Qimo 4 kids as a possible platform so that my parents can have a closer look at Linux environments. But it seems like Qimo mostly consists of educational games. I also don't know about which programming language would make the best choice.

If anyone can provide me with information on how to go about with this "project", that would be grateful!!!

答:
codecademy.com

It has easy to understand and easy to follow videos to learn coding. I think it's a great resource for all ages.

It covers Ruby, Python and Javascript - high-level languages per se - but it still is a nice introduction to understanding what is a programming language, what are the common concepts shared by different languages, what are functions, conditionals, loops, objects, etc.

It follows the exercice and apply pattern, the finality being to code a black jack game, at least for the javascript lessons (see JavaScript fundamentals).

Finally, you don't need an IDE, which might confuse the user at first. You only need a browser.


问:
Ajax race conditions
Is there a pattern or standard way to handle Ajax race conditions? Take the following example. You have two tables. Clicking a row on table 1 removes the data from DB and then updates table 2 (which would now be showing  all the rows of table 1 less the row that was clicked).

If someone where to click a bunch of rows in fast succession you could get a scenario where table 2 doesn't update for all the clicks do to timing/lag issues.

What might be a good way to approach this? I was thinking of using a possible queue but that kind of defeats the purpose of doing it asynchronously. However I would still have the benefit of the UI not locking.

答:
Just a thought, perhaps you could create a list for your Ajax callback methods. You would wrap your actual Ajax callback in a method that adds that callback to a slot in an list.

This list waits for callbacks in a specific order and only executes if the top element (the callback you want called first) is filled.

Title: Ajax race conditions


答:
This is not a race condition.

A race condition would occur when the behavior between two asynchronous threads becomes undefined. You can solve this problem by nesting the callback from the first call

Title: Ajax race conditions

Body:
Is there a pattern or standard way to handle Ajax race conditions? Take the following example. You have two tables. Clicking a row on table 1 removes the data from DB and then updates table 2 (which would now be showing  all the rows of table 1 less the row that was clicked).

If someone where to click a bunch of rows in fast succession you could get a scenario where table 2 doesn't update for all the clicks do to timing/lag issues.

What might be a good way to approach this? I was thinking of using a possible queue but that kind of defeats the purpose of doing it asynchronously. However I would still have the benefit of the UI not locking.


问:
C++11 includes std::stoi, why not std::itos?
I noticed to my glee that C++11 has a std::sto@ family of functions for easily unpacking ints/floats/longs whatever from strings. I'm surprised however, that the opposite isn't implemented. Why didn't the standards committee include a std::itos family of functions for going from ints/floats/whatever (back) to strings?

答:
I was mistaken, there is a set of "Xtos" functions, they are all just named to_string. Each to_string is overloaded to take a different basic type, i.e.:

```<code>std::string to_string(float f);
std::string to_string(int f);
...
</code>```

See here for more info.

Body:
I was mistaken, there is a set of "Xtos" functions, they are all just named to_string. Each to_string is overloaded to take a different basic type, i.e.:

std::string to_string(float f);
std::string to_string(int f);
...

See here for more info.


答: I'm personally moving to JavaFX (2.1+, not the old weird 1.x version with the nasty scripting language). The new JavaFX isn't 100% perfect, but it's already a darn sight more pleasurable to use than Swing, I see a reasonable future for it (especially given the embedded Webkit engine).</p>

Title: Do you start migrating your Swing project to JavaFX

Body:
I have a 4 years old project which is written in Swing + SwingX. Currently, it is still alive and still kicking.

However, as more GUI related feature requests coming in (For instance, a sortable tree table), I start to feel the difficulty in fulling the requests. This is true especially since there isn't any active development going around SwingX project.

Also, I can hardly find any good, yet actively maintained/ developed/ evolving GUI Java framework.

I was wondering, do any of the Swing developers feel the same thing? Have you start to migrate your Swing project to a much more active developed GUI framework, like JavaFX?


问:
Is there a way to track data structure dependencies from the database, through the tiers, all the way out to a web page?
When we design applications, we generally end up with the same tiered sets of data structures:

A persistent data structure that is described using DDL and implemented as RDBMS tables and columns.

A set of domain objects that consist primarily of data structures, usually combined with business-rule level logic, that are implemented in a programming language such as Java.

A set of service layer interfaces that directly support use case implementations (which use the domain data structures as parameters), implemented as EJBs or something equivalent in another programming language.

UI screens that allow users to C reate, R etrieve, U pdate, and (maybe) D elete all manner of data structures and graphs of data structures, with numerous screens and with multiple UI widgets, all structured to support the same data structures.

But if you want to change the data structures in any of these tiers, it always seems extremely difficult to assess the impact(s) the change will have across the application. UML can help, but tracing through diagram after diagram is not a real solution to this problem. The best I have ever seen was a homespun data tracking spreadsheet document that listed all of the data structures and walked the relationships from tier-to-tier.

Is there a tool or accepted approach that makes it easy to identify a data structure in any tier and easily obtain a list of all dependent:

database table and column data structures

domain object data structures

service layer interface methods and parameter data structures

screen & UI component data structures

答:
In Java you can get at least some help from Hibernate and JPA.  With that combination you can describe the complete data structure in Java objects with annotations and Hibernate will generate the DDL and, if configured to do so, update the database schema when you change the objects.

On the front end, you could deliver the data in JSON format so that you could implement a data-driven UI in JavaScript and dynamically build your CRUD operations using labels and values present in the JSON representation.  There are libraries that convert Java objects to JSON using introspection, so there would be little to no additional support needed in the data objects.

Typically the front end CRUD operations need a lot of fine tuning to make them palatable for users, and maybe even help text, for example, and there's no getting around that.

It's probably even easier using Ruby on Rails, but I haven't looked into it yet.


问:
Should I use the new C++11 'auto' feature, especially in loops?
What are the pros/cons to using the auto keyword, especially in for loops?

```<code>for(std::vector<T>::iterator it = x.begin(); it != x.end(); it++ )
{
   it->something();
}

for(std::map<T>::iterator it = x.begin(); it != x.end(); it++ )
{
   it->second->something();
}

for(auto it = x.begin(); it != x.end(); it++ )
{
   it->??
}
</code>```

Seems like if you don't know whether you have an iterator for a map or a vector you wouldn't know whether to use first or second or just directly access properties of the object, no?

This reminds me of the C# debate on whether to use the keyword var.  The impression I'm getting so far is that in the C++ world people are ready to adopt the auto keyword with less of a fight than var in the C# world.   For me my first instinct is that I like to know the type of the variable so I can know what operations I can expect to perform on it.

答:
In your example:

```<code>for(auto it = x.begin(); it != x.end(); i++)
{
  it->??
}
</code>```

there has to be a declaration for x visible.  Therefore the type of it should be obvious.  If the type of x isn't obvious, then the method is too long, or the class is too large.

Body:
In your example:

for(auto it = x.begin(); it != x.end(); i++)
{
  it->??
}

there has to be a declaration for x visible.  Therefore the type of it should be obvious.  If the type of x isn't obvious, then the method is too long, or the class is too large.


答:
The motivations in C++ are more extreme, as types can become vastly more convoluted and complex than C# types due to metaprogramming and other things. auto is faster to write and read and more flexible/maintainable than an explicit type. I mean, do you want to start typing

```<code>boost::multi_map<NodeType, indexed_by<ordered_unique<identity<NodeType>>, hashed_non_unique<identity<NodeType>, custom_hasher>>::iterator_type<0> it
</code>```

That's not even the full type. I missed off a couple template arguments.

Title: Should I use the new C++11 'auto' feature, especially in loops?

Body:
What are the pros/cons to using the auto keyword, especially in for loops?

```<code>for(std::vector<T>::iterator it = x.begin(); it != x.end(); it++ )
{
   it->something();
}

for(std::map<T>::iterator it = x.begin(); it != x.end(); it++ )
{
   it->second->something();
}

for(auto it = x.begin(); it != x.end(); it++ )
{
   it->??
}
</code>```

Seems like if you don't know whether you have an iterator for a map or a vector you wouldn't know whether to use first or second or just directly access properties of the object, no?

This reminds me of the C# debate on whether to use the keyword var.  The impression I'm getting so far is that in the C++ world people are ready to adopt the auto keyword with less of a fight than var in the C# world.   For me my first instinct is that I like to know the type of the variable so I can know what operations I can expect to perform on it.

Body:
The motivations in C++ are more extreme, as types can become vastly more convoluted and complex than C# types due to metaprogramming and other things. auto is faster to write and read and more flexible/maintainable than an explicit type. I mean, do you want to start typing

boost::multi_map<NodeType, indexed_by<ordered_unique<identity<NodeType>>, hashed_non_unique<identity<NodeType>, custom_hasher>>::iterator_type<0> it

That's not even the full type. I missed off a couple template arguments.


问:
Correct For Loop Design
What is the correct design for a for loop?

Felix currently uses

```<code>if len a > 0 do
  for var i in 0 upto len a - 1 do
    println a.[i];
  done
done
</code>```

which is inclusive of the upper bound. This is necessary to support the full range of values of a typical integer type. However the for loop shown does not support zero length arrays, hence the special test, nor will the subtraction of 1 work convincingly if the length of the array is equal to the number of integers.
(I say convincingly because it may be that 0  - 1 = maxval: this is true in C for unsigned int, but are you sure it is true for unsigned char without thinking carefully about integral promotions?)

The actual implementation of the for loop by my compiler does correctly handle 0 but this requires two tests to implement the loop:

```<code>continue:
  if not (i <= bound) goto break
  body
  if i == bound goto break
  ++i
  goto continue
break:
</code>```

Throw in the hand coded zero check in the array example and three tests are needed.

If the loop were exclusive it would handle zero properly, avoiding the special test, but there'd be no way to express the upper bound of an array with maximum size.

Note the C way of doing this:

```<code>for(i=0; predicate(i); increment(i))
</code>```

has the same problem. The predicate is tested after the increment, but the terminating increment is not universally valid!

There is a general argument that a simple exclusive loop is enough: promote the index to a large type to prevent overflow, and assume no one will ever loop to the maximum value of this type.. but I'm not entirely convinced: if you promoted to C's size_t and looped from the second largest value to the largest you'd get an infinite loop!

答:
C in fact does not have the same problem.  The C for loop does not execute the iteration step before checking the predicate.  See section 6.8.5.3 of the ISO C standard, which states this clearly.

The argument about promotion you are referring to is as you say, incorrect, but for a more direct reason: there may be no widening promotion.   For example, nothing in the C standard guarantees that there is any type wider than unsigned char (that is, implementations in which all unsigned types are the same width are allowed).

Title: Correct For Loop Design


答:
What you're designing sounds a lot like a graph.

These are often represented as a set of states Q, an initial state q0 ∈ Q, and some transitions Δ. So, I'd suggest you store it like this.

A set Q: {s, 1, 2, 3, 5, 6}

An initial state q0: s

A map of transition relations Δ: {s → 1, s → 5, 1 → 2, 2 → 3, 3 → 4, 4 → 5}

Most reasonable languages have both maps and sets.


问:
Splitting Logic, Data, Layout and "Hacks"
Sure, we all heard of programming patterns such as MVVM, MVC and such.

But that isn't really what I'm looking into as Layout, Data and Logic is already pretty much split up (XML-Layout markup, Database, insert your language of choice here).

The platform I am developing for is hard to maintain over the updated versions and older OSes. The project significantly grew up over the last few months and dealing with different platform versions really is a pain.

For example simply disabling an user interface control for all existing versions took me around 40 lines of code in the logic layer, wrangling around with invocation, delegation, singletons that provide UI handling and so on.

Is there a clean way to keep track of those "hacks" by maybe excluding it into separate classes or even packages? Should I overwrite existing framework code in order to handle my requirements correctly? If so, does that concept have a name?

答:
Inversion of control could help combined with feature toggles. Try to put your hacks into derived classes that override certain bits. Alternatively you can sometimes do with an interface you could implement in an alternative way. Through dependency injection you can 'configure' any client code to unknowingly use your (temporary) hack.

For instance when using a MVC pattern you could derive from a certain controller. Override a method and make it return a different view then it would normally do.


问:
What is required for a scope in an injection framework?
Working with libraries like Seam, Guice and Spring I have become accustomed to dealing with variables within a scope.  These libraries give you a handful of scopes and allow you to define your own.  This is a very handy pattern for dealing with variable lifecycles and dependency injection.

I have been trying to identify where scoping is the proper solution, or where another solution is more appropriate (context variable, singleton, etc).  I have found that if the scope lifecycle is not well defined it is very difficult and often failure prone to manage injections in this way.

I have searched on this topic but have found little discussion on the pattern.  Is there some good articles discussing where to use scoping and what are required/suggested prerequisites for scoping?

I interested in both reference discussion or your view on what is required or suggested for a proper scope implementation.  Keep in mind that I am referring to scoping as a general idea, this includes things like globally scoped singletons, request or session scoped web variable, conversation scopes, and others.

Edit:

Some simple background on custom scopes: https://stackoverflow.com/questions/9429221/google-guice-custom-scope/9435182#9435182

Some definitions relevant to above:

“scoping” - A set of requirements that define what objects get injected at what time.  A simple example of this is Thread scope, based on a ThreadLocal.  This scope would inject a variable based on what thread instantiated the class.  Here's an example of this:

“context variable” - A repository passed from one object to another holding relevant variables.  Much like scoping this is a more brute force way of accessing variables based on the calling code.

Example:

```<code>methodOne(Context context){
    methodTwo(context);
}

methodTwo(Context context){
    ...
    //same context as method one, if called from method one
}
</code>```

“globally scoped singleton” - Following the singleton pattern, there is one object per application instance.  This applies to scopes because there is a basic lifecycle to this object: there is only one of these objects instantiated.

Here's an example of a JSR330 Singleton scoped object:

```<code>@Singleton
public void SingletonExample{
...
}
</code>```

usage:

```<code>public class One {
     @Inject
     SingeltonExample example1;
}

public class Two {
     @Inject
     SingeltonExample example2;
}
</code>```

After instantiation:

```<code>one.example1 == two.example2 //true;
</code>```

答:
Do not inject objects that have a smaller scope then the object you inject it into. In that case inject a factory so the dependant can manage the scope.

All other scope can be handled through the DI framework. The DI framework should be able to query some object or method you provide to see if it should re-instantiate a new instance or not.

In other words, a DI framework should delegate complex scope management to you.