问:
What's the origin of foo and bar?

Possible Duplicate:

  Using “Foo” and “Bar” in examples

I know AT&T labs used them in their Unix days, but do they have even deeper histories?

答:
From the Jargon file:

When ‘foo’ is used in connection with ‘bar’ it has generally traced to the WWII-era Army slang acronym FUBAR (‘Fucked Up Beyond All Repair’ or ‘Fucked Up Beyond All Recognition’), later modified to foobar. Early versions of the Jargon File interpreted this change as a post-war bowdlerization, but it it now seems more likely that FUBAR was itself a derivative of ‘foo’ perhaps influenced by German furchtbar (terrible) — ‘foobar’ may actually have been the original form.

For, it seems, the word ‘foo’ itself had an immediate prewar history in comic strips and cartoons. The earliest documented uses were in the Smokey Stover comic strip published from about 1930 to about 1952. Bill Holman, the author of the strip, filled it with odd jokes and personal contrivances, including other nonsense phrases such as “Notary Sojac” and “1506 nix nix”. The word “foo” frequently appeared on license plates of cars, in nonsense sayings in the background of some frames (such as “He who foos last foos best” or “Many smoke but foo men chew”), and Holman had Smokey say “Where there's foo, there's fire”.

Title: What's the origin of foo and bar?


问:
What is wrong with Java's generics?
I have seen several times on this site posts that decry Java's implementation of generics. Now, I can honestly say that I have not had any issues with using them. However, I have not attempted to make a generic class myself. So, what are your issues with Java's generic support?</p>

答:
Observe that answers that have already been provided concentrate on the combination of Java-the-language, JVM and the Java Class Library.

There is nothing wrong with Java's generics as far as Java-the-language is concerned. As described in C# vs Java generics, Java's generics are pretty much fine on the language level1.

What's suboptimal is that the JVM doesn't support generics directly, which has several major consequences:

the reflection-related parts of the Class Library can't expose the full type information that was available in Java-the-language

some performance penalty is involved

I suppose the distinction I am making is a pedantic one as Java-the-language is ubiquitously compiled with JVM as the target and Java Class Library as the core library.

1 With the possible exception of wildcards, which is believed to make the type inference undecidable in the general case. This is a major difference between C# and Java generics that isn't mentioned very often at all. Thanks, Antimony.

ContentLicense: CC BY-SA 2.5

Title: What is wrong with Java's generics?

ContentLicense: CC BY-SA 3.0


问:
What is Configuration Management?
In all projects that I have been involved with that have had input from an outside consultant the question has been asked about what sort of Configuration Management we were using. In none of these cases has the consultant been able to define Configuration Management. So what is it?</p>

答:
Configuration Management has meant a lot of things over time.  I consider it more important to administrators or operations than directly to developers.  When your an operations person trying to keep servers up and running you worry about setting up machines, managing their configuration, and keep it running.  If you just log into a computer and start installing software, and changing config files on a machine you're not managing that configuration.  What happens if that machine dies?  What happens if someone goes on that machine and changing a config file and everything starts to freak out?  What if you need to start up another machine configured exactly like the one that's running?  Can you do it?

Without a configuration management strategy you can't.  And that's why it's important.  It's all about repeatability.  Developers approach repeatability differently than operations people do so we care about repeating different things.

There are some great open source tools that help you do this: Chef, Capistrano, Cook, and even SVN.  Why should SVN just be used by developers?  Check in your config files, scripts you use to configure machines, and track their versions.  Those parts of your organization are vital to keep it running.  You don't want to loose those.

Title: What is Configuration Management?


答:
What Software Configuration Management (SCM) is boils down to answering the following:

What source files where used to make our end product?

What has changed from the last time we made our end product?

Why did we change it?

This in turn can grow to a quite large and ugly "process". The process issues are why most developers eyes glaze over at the mention of SCM, as this means tracking source files, defects and requirements; then tying it all together so you can audit changes (This is an Ideal world from a management point of view as it gives a good manager tools to better see what resources he needs where.)

This is different from ITIL Configuration Management which is actually software asset tracking, what software is running where (which server/ workstation) and what is the setup for that software.

In other words your consultant more then likely wants to know is how YOUR company/development group answers the three questions at the top of my answer.

Title: What is Configuration Management?

Body: In all projects that I have been involved with that have had input from an outside consultant the question has been asked about what sort of Configuration Management we were using. In none of these cases has the consultant been able to define Configuration Management. So what is it?</p>


问:
Sharing programming fees with a fellow software developer
My question relates to how I should share the fees paid by clients to me and a fellow programmer, both of whom are freelancers.

I've thought of a few options, but I'm in a dilemma as to which one would be the most motivating for both of us.

1) The first option I've thought is a fifty-fifty share. However, more brainwork is going to be done by my colleague, while initially at least, I will be handling the communication with customers.

2) The second option is a 60-40 share, where the colleague exerting more efforts gets a bigger share. This is the option I feel most inclined to adopt, but I'm not sure how it's going to feel in the long run.

3) The third option is calculating each one's contribution in terms of the number of hours spent, and sharing the revenue accordingly.

It will be wonderful to hear everybody's thoughts on this!

答: Money is one of those things that can leave people feeling bitter and drive them apart very quickly. Regardless of the actual percentages, make sure you and your fellow programmer have a clear understanding of the profit sharing scheme. After you had a chance to discuss profit sharing, put it in writing with each of you having a signed copy. Also, agree to revisit the approach after you had a chance to work together and get an understanding of your working dynamic. As long as both of you are satisfied with the profit sharing, you can put your thoughts to solving the problems you are hired to do and not be distracted by the financial side.</p>


答:
As a programmer, it's easy to overvalue programming. Sure, without that there's no product to sell, but without the rest you're basically programming as a hobby.

I say base it on time spent, so long as you trust each other to track your times honestly. Otherwise 50/50.

Title: Sharing programming fees with a fellow software developer

Body:
My question relates to how I should share the fees paid by clients to me and a fellow programmer, both of whom are freelancers.

I've thought of a few options, but I'm in a dilemma as to which one would be the most motivating for both of us.

1) The first option I've thought is a fifty-fifty share. However, more brainwork is going to be done by my colleague, while initially at least, I will be handling the communication with customers.

2) The second option is a 60-40 share, where the colleague exerting more efforts gets a bigger share. This is the option I feel most inclined to adopt, but I'm not sure how it's going to feel in the long run.

3) The third option is calculating each one's contribution in terms of the number of hours spent, and sharing the revenue accordingly.

It will be wonderful to hear everybody's thoughts on this!


问:
What's the idea behind defining rectangles with two points?
It's not that this doesn't make sense, but it just works out awkward 99% of the time.

Often in 2D graphics rectangles are initialized, stored and manipulated as a pair of points.  In no particular language,

```<code>class Rect:
   p1, p2: point
</code>```

It makes more sense to define a rectangle as two x values and two y values, like this:

```<code>class Rect
   xleft, xright: int
   ytop, ybottom: int
</code>```

With two points, if at some place in the source code you want to make use of the y value of the top, you'd have to say rect.p1.y  (hmmm, stop and think, is it p1 or p2) but with the four values as plain data members, it's clear and direct:  rect.ytop (no thinking required!)     The use of two points means that in dealing with the vertical, you have to tangle the horizontal; there's an extraneous relation between indepenent elements.

How did this two-point idea come about and why does it persists?  Does it have some benefit over bare x and y coordinates?

ADDED NOTE: This question is in the context of X-Y aligned rectangles, such as in windows managers and GUI toolkits, not in the context of arbitrary shapes in drawing and painting app.

答:
The choice of parameters are only important to the low-level designers / coders.

High-level users only need to think about:

IsPointInRect

Area

Intersection (or Clipping)

HasOverlap (same as Intersection.Area > 0)

Union (becomes a list of rectangles)

Subtraction (a list of rectangles that represent the same point set that is in rect A but not in rect B)

Transform

Shifts in X and Y

Rotation (0, 90, 180, 270)

Scaling in X and Y (see note)

Simple syntax for properties Xmin, Xmax, Ymin, Ymax, Width, Height so that the user does not need to know the exact choice of parameters.

Note: In order to minimize loss of precision during scaling transform, it is sometimes appropriate to implement a second Rect class that uses floating-point coordinates, so that intermediate results can be stored accurately in a sequence of transforms and only rounded to integer in the last step.


问:
What is the general tech news website every programmer should read?
A link and a quick explanation why would be very helpful.

General tech news, I mean not like InfoQ which is too technical. Probably much more like P.SE than SO.

EDIT: site should help developers gain general knowledge about the industry, technologies, inventions, etc. Much like when we listen to the news every morning in our car to know what is happening in our world. But target audience must be either programmmers, geeks or any other persons interested in technology.

答:
Ars Technica

It may not have the sheer breadth of sites like Slashdot or Reddit, but it can't be beat for consistently high quality, in-depth articles.


问:
Is functional programming actually used to create applications?

Possible Duplicate:

  What are some well known applications written in F#?

I see a lot of people talking about how cool functional programming is, how awesome Lisp and Haskell and F# are, etc, but what I don't see is them actually being used.  Just about every program on my computer is written in either something in the C family, Delphi, or Python.  I see tutorials talking about how easy it is to use functional languages to do complicated math problems, but no one talking about using them to do things most people actually care about using computers for, like business applications and games.

Does anyone have any examples of actual programs that people have heard of and are using, written in a functional language?  The only one I can think of off the top of my head is Abuse, from almost 15 years ago.  (Things like Emacs, where the core program is written in C with a functional language scripting layer on top, don't count.)

答: Perhaps not in a purely functional language, but I use functional paradigms all the time when I write python and javascript.</p>


答: Not a news site as such, but I like the blogs of Joel Spolsky. Joel's Blog</p>

Title: What is the general tech news website every programmer should read?

Body:
A link and a quick explanation why would be very helpful.

General tech news, I mean not like InfoQ which is too technical. Probably much more like P.SE than SO.

EDIT: site should help developers gain general knowledge about the industry, technologies, inventions, etc. Much like when we listen to the news every morning in our car to know what is happening in our world. But target audience must be either programmmers, geeks or any other persons interested in technology.


答:
I mostly follow these

Ars Technica for good editorial style articles.

Anand Tech for hardware related stuff.

Engadget for technology reviews, live coverage of events, etc.


问:
Low level programming - what's in it for me?
For years I have considered digging into what I consider "low level" languages. For me this means C and assembly. However I had no time for this yet, nor has it EVER been neccessary.

Now because I don't see any neccessity arising, I feel like I should either just schedule some point in time when I will study the subject or drop the plan forever.

My Position

For the past 4 years I have focused on "web technologies", which may change, and I am an application developer, which is unlikely to change.

In application development, I think usability is the most important thing. You write applications to be "consumed" by users. The more usable those applications are, the more value you have produced.

In order to achieve good usability, I believe the following things are viable

Good design: Well-thought-out features accessible through a well-thought-out user interface.

Correctness: The best design isn't worth anything, if not implemented correctly.

Flexibility: An application A should constantly evolve, so that its users need not switch to a different application B, that has new features, that A could implement. Applications addressing the same problem should not differ in features but in philosophy.

Performance: Performance contributes to a good user experience. An application is ideally always responsive and performs its tasks reasonably fast (based on their frequency). The value of performance optimization beyond the point where it is noticeable by the user is questionable.

I think low level programming is not going to help me with that, except for performance. But writing a whole app in a low level language for the sake of performance is premature optimization to me.

My Question

What could low level programming teach me, what other languages wouldn't teach me? Am I missing something, or is it just a skill, that is of very little use for application development? Please understand, that I am not questioning the value of C and assembly. It's just that in my everyday life, I am quite happy that all the intricacies of that world are abstracted away and managed for me (mostly by layers written in C/C++ and assembly themselves). I just don't see any concepts, that could be new to me, only details I would have to stuff my head with. So what's in it for me?

My Conclusion

Thanks to everyone for their answers. I must say, nobody really surprised me, but at least now I am quite sure I will drop this area of interest until any need for it arises.

To my understanding, writing assembly these days for processors as they are in use in today's CPUs is not only unneccesarily complicated, but risks to result in poorer runtime performance than a C counterpart. Optimizing by hand is nearly impossible due to OOE, while you do not get all kinds of optimizations a compiler can do automatically. Also, the code is either portable, because it uses a small subset of available commands, or it is optimized, but then it probably works on one architecture only.

Writing C is not nearly as neccessary anymore, as it was in the past. If I were to write an application in C, I would just as much use tested and established libraries and frameworks, that would spare me implementing string copy routines, sorting algorithms and other kind of stuff serving as exercise at university. My own code would execute faster at the cost of type safety. I am neither keen on reeinventing the wheel in the course of normal app development, nor trying to debug by looking at core dumps :D

I am currently experimenting with languages and interpreters, so if there is anything I would like to publish, I suppose I'd port a working concept to C, although C++ might just as well do the trick.

Again, thanks to everyone for your answers and your insight.

答:
My suggestion is to play around with C as an intellectual curiosity. Do not make a heavy time investment because it is not worth it.

Suggested goals:

Refresh your memory about the basic data structures and algorithms.

It is just some good thing to know, like algebra and geometry.

Try to do some college textbook exercises or program puzzles in C.

A better appreciation of the memory (bandwidth) hierarchy, all the way from the CPU cache to transoceanic network latency. This will help your application development skills at all levels.

Most importantly, it is good to learn about scenarios in which a small inconspicuous rearrangement of high-level code can result in a dramatic speed improvement.

Sometimes the reason can only be understood in the low-level implementation in the context of memory hierarchy.

Not understanding the natural cause of this possibility leads to ignorance, fear, and eventually to denial, thinking that it is wrong for high-level developers to tap into this kind of optimization. In reality there is nothing wrong with that.

Appreciate the aesthetics of component-based software systems, which enables low-level components developed in C/C++/Assembly to be used by high-level systems.

The aesthetics are exactly the same as software usability:

Good design (powerful, easy to use, well thought-out)

Correctness

Flexibility (extensions and new behaviors via composition of existing parts, each with a clearly-defined purpose)

Performance (without complicating the usability)

While you might not design your own low-level components, your understanding will help you evaluate and choose good components to use in your high-level projects.

Finally, appreciate that low-level components are almost always more complicated in their implementations, far from fathomable by just looking at the interface.

The low level is always complicated. A good library hides the complexity without diminishing its power.

Learn to read the "technical notes" written by component developers, which are suggestions to higher-level component users on how to best make use of the components.


答: The obscene bounty of 500 reputation makes me think that http://pierre.mengal.eu/ is the right answer ;-)</p>


答:
For the UK El Reg is the main source of news, reviews and even gossip.

And for a slightly different slant on tech : LifeHacker.


问:
Is there anyone who has used Python/Ruby and PHP for a long time and still prefer PHP?
I am usually fascinated by articles defending PHP and the arguments being used. Quite often authors of these types of articles don't mention what experience they have with other languages. Personally I find it hard to imagine that somebody would know either Python or Ruby, and PHP at a high level and still prefer PHP.

So if anyone fits this description, I would be interested in hearing why you prefer PHP to either of these languages.

答:
I consider time to ship and portability. In the cases where I actually have to do some kind of web development, it usually means I'm writing some kind of control panel.

It is just stupidly easy for me to put something together using Code Igniter, I get it done quickly and get it out the door. Additionally, I'm quite sure that the app will 'just work' on many web servers.

So I guess for me, it's not a preference over the language itself, but how quickly I can say "Yess boss, it's done .. " I do want to spend some 'quality' time with Django .. and perhaps it will become my preference in the future.

While I do like Ruby, I realize that I am not nearly experienced enough to use it safely.

I also don't consider something 'inferior' just because it is written in a certain language. If the problem being solved fits well into the language's domain, what's the problem?


答:
I think there are two type of sources:

Blogs

Tech News Sites

Though only tech news sites was mentioned in the question, I have also found blogS to be helpful. Again, Tech News and Programming News, Tips and Ticks are two very different things. And both of them are interesting as well as necessary. But IMHO the main thing is-

Different people have different type of interests and needs. So, it is you who will choose the sources. I felt an RSS reader is the perfect tool for following all the sources by headline and visiting the ones I need. I use Google Reader. It also recommends other sources/websites of same type as you subscribe and visit these sites. So, you can start with the sources stated on other answers(I guess there will be many) of these question. Then after some time, you can realize some sources go with your interest and need while some others don't. Then discard and add sources accordingly.

This Stackoverflow question may help-

https://stackoverflow.com/questions/5119/what-are-the-best-rss-feeds-for-programmers-developers


答:
My personal list (as gleaned from the excellent Google Reader) is as follows (in order of how frequently I read them):

Hacker News - good for general stuff and fluff that's interesting across the board (quite a bias to

Ars Technica - deep technical articles with plenty of insight

The Register (El Reg) - for an irreverent look at IT issues (and of course the BOFH)

There are others, but these are the ones that keep my eyeballs.


答:
Not so much a news site, but I tend to use Twitter to get my news by following some of the big guys in the field I'm intersted in (i.e. Elijah Manor. Scott Guthrie, Jeff Atwood, Joel Spolsky, Jon Skeet, ...).

I find it useful for technical bits and bobs but also for the fact that they're just human and interested in the same field as I am. They tend to post bits and pieces for things they consider to be interesting or else comment on 'in the news' bits.


问:
What advantages do continuous integration tools offer on a solo project?
If you're doing a solo project - would you use CI tools to build from a repository? I've used Hudson and Cruise Control in a team environment, where it's essential to build as soon as anyone checks anything in.

I think the value of version control is still obvious, but do I need to build after every commit, seeing as I would just have built on my local machine, and no-one else is committing?

答:
Well I'm planning to use an continuous integration tool on a project and I'm the unique developer. The need comes because

One goal is to make it cross-platform, and having an integration tool helps you implicitelly (basic) check your app on several platform once you've pushed your changes in the integration repository (or the central one, or whatever is the one that will be used as authoritative).

The project is built for long-term so I will need to work with a team later. I'm not planning to recruit anyone until 2012 so the continuous integration thing can wait for the moment, until 1. becomes the priority.

Other than cross-platform and team-work preparation, I don't see the need. The main thing is to have some kind of source control software and have several repository to keep backups. That will help you setup build tools around it when needed.

About the build timing, I'm using Mercurial and setting up an integration repository that is not the teamwork repository. So, push changes in the teamwork repo until I feel it's time to make the integration system try to build. Then I push from the teamwork repo to the integration repo and that will trigger the build.
Then I also add a script that will pull the teamwork repo in the integration repo one time each day.

Here I'm assuming that I work almost all days on my project but it's not always true. You have to set a build timing that is relative to how often you need builds. In a game company I worked at before, we used CruiseControle and it built a full build each hour. We could also force a build whenever we wanted if needed.

For a home project, one time a day might be already "often". The main requirement would be to easily allow the user to force launching a build.


答:
TechCrunch - www.techcrunch.com

TechCrunch will keep you up-to-date on anything having to do with startups, and most things having to do with technology. I've been reading tech news for a while, and it is the clear winner.

The best stories will usually find their way to Hacker News and other aggregators, but if you're interested in reading about most important things going on in the technology world, this is the site to read.

Disclaimer

TechCrunch has a (deserved) reputation of often including lots of sensationalist and unimportant stuff. It's true - you're not going to find every article there interesting. I usually scan the headlines and only read the things that interest me. But I wouldn't dream of giving up TechCrunch as my main source for tech news.


答:
When I am the only one committing, I just build and test before actually committing. I usually use a makefile target like :

```<code>make sense
</code>```

That configures, builds, runs all tests (valgrind aware), runs lints, etc. As I know I'll be the only one pushing, I don't really need the power of something like Hudson.

Additionally, in an environment where you have several branches feeding a main repository, if everyone follows the always pull before you commit or push, the CI server might be a little over kill. A well written rule that the author of whatever broke the last build buys pizza on Friday usually keeps things running very smoothly :)

If it gets into a situation where a project is clearly divided into sub systems that have their own leaders, you really need to contemplate using something like Hudson. Someone might test locally, lose a race with another sub system and end up pushing something toxic.

Also, if you are maintaining a fork of a fast moving project (for instance, your own set of patches to the Linux kernel), you should really consider using something like Hudson, even though you are 'solo' on that project. This is especially true if you branch / re-base directly from mainline.

Title: What advantages do continuous integration tools offer on a solo project?

Body:
If you're doing a solo project - would you use CI tools to build from a repository? I've used Hudson and Cruise Control in a team environment, where it's essential to build as soon as anyone checks anything in.

I think the value of version control is still obvious, but do I need to build after every commit, seeing as I would just have built on my local machine, and no-one else is committing?

Body:
When I am the only one committing, I just build and test before actually committing. I usually use a makefile target like :

make sense

That configures, builds, runs all tests (valgrind aware), runs lints, etc. As I know I'll be the only one pushing, I don't really need the power of something like Hudson.

Additionally, in an environment where you have several branches feeding a main repository, if everyone follows the always pull before you commit or push, the CI server might be a little over kill. A well written rule that the author of whatever broke the last build buys pizza on Friday usually keeps things running very smoothly :)

If it gets into a situation where a project is clearly divided into sub systems that have their own leaders, you really need to contemplate using something like Hudson. Someone might test locally, lose a race with another sub system and end up pushing something toxic.

Also, if you are maintaining a fork of a fast moving project (for instance, your own set of patches to the Linux kernel), you should really consider using something like Hudson, even though you are 'solo' on that project. This is especially true if you branch / re-base directly from mainline.


问:
C# open source projects
What C# project(s) would you consider contributing to if you were a beginner trying to sharpen your skills in C# and .NET framework ? The project should be (besides all) active and not something less active and/or stagnant. </p>

答:
There are some interesting applications developed around the Stack Exchange API that could use some help. I think everything in that tag is actively maintained, but I'm not sure if the developer base is as large as you would prefer.

Still, you'd be dealing with Stack Overflow users, who tend to be helpful and (usually) patient with beginners.

OwnerDisplayName: Vicky

Title: C# open source projects


答:
IMO the real advantage of PHP is the ease of finding team members. From my experience, Python and Ruby developers are harder to find and cost more.

However, from a development standpoint, I prefer Python.

Title: Is there anyone who has used Python/Ruby and PHP for a long time and still prefer PHP?

Body:
I am usually fascinated by articles defending PHP and the arguments being used. Quite often authors of these types of articles don't mention what experience they have with other languages. Personally I find it hard to imagine that somebody would know either Python or Ruby, and PHP at a high level and still prefer PHP.

So if anyone fits this description, I would be interested in hearing why you prefer PHP to either of these languages.


问:
When is it appropriate to use Microsoft's Enterprise Library (EntLib)?
I'm not exactly sure when to use Enterprise Library, and when not to... and that is making me not learn it at all.  I feel that I have enough of a reason to start learning then perhaps one day I'll use it.

Are there times when I should use EntLib?

When shouldn't I use it?

答:
There is a lot of good stuff in EntLib, but there are reasons those things are not in the full framework.  The logging stuff is excellent, but the data parts have been surpassed by later additions to full framework in my opinion.  I have also found that some of the blocks do not fit very well in certain situations.

As mentioned the overhead is significant in some cases as well and the config can be quite confusing.

Most of my apps have some degree of performance constraints, so I tend to use the EntLib stuff as an example and write my own features more often than using the EntLib things.

Used this way it has been an excellent learning tool.


答:
I'd advise you to get a couple projects under your belt first.  Think of a simple program idea which might help you in some small way, such as a calendar or organizer.  You can decide all the functionality you'd like, but have a basic basic functionality program that you can aim for first before adding new features.  Trying to do too much at once can easily overwhelm you.

Once you feel comfortable with the general feel for C#, you can hope to help others on sourceforge.net et al.  Most people don't have problems helping you understand the project, though they do expect you to know to do basic things in C#, meaning you can't ask them for help in that regard.  That's why I would say that it would be better to have some basic experience first.

Title: C# open source projects

Body: What C# project(s) would you consider contributing to if you were a beginner trying to sharpen your skills in C# and .NET framework ? The project should be (besides all) active and not something less active and/or stagnant. </p>


问:
When do I need to use a framework?
I am new to web programming and at this time I am learning about PHP. I would like to know when do I need to use a PHP framework such as CakePHP? What are things that this and other similar PHP frameworks offer for me?  And is it really important to use a framework to be a professional?

And can I create my own framework to provide the features I like into it?

答:
After reading some of the answers, I would like to say first that you don't often have much of an option on what framework you're going to use or whether you're going to use one or not (as a professional). I don't want to intimidate you, but you will need to build enough of an understanding of PHP to allow moving from one framework to another as well using more than one framework at once.

when do I need to use a PHP framework such as CakePHP?

There isn't a universal answer to this. As a professional, you're going to be tasked to solve specific problems and this will be the deciding factor for the when's and what's of each project, especially if a client has a specific demand. But generally speaking, you will always be using some form of framework with PHP, unless you're modifying or extending a pre-existing application that has it's own framework (such as Wordpress or PHPBB).

What are things that this and other similar PHP frameworks offer for me?

As said by dirk, they offer abstraction. What this means is that they take common, multi-step procedures and try to make them as simple and streamlined as possible. In short, they try to  present just-add-water solutions for common tasks.

And is it really important to use a framework to be a professional?

Generally speaking, no it is not important to use a framework to be a professional. But realistically, you won't have much of a career if you're not familiar with at least a couple common frameworks. PHP without a framework is like C++ without a std library. You don't need it, and you can actually do more without it since you'll be directly using the lower-level builing-block functionality of the language, but it will take you much longer to do the same thing.

And can I create my own framework to provide the features I like into it?

Yes. In fact, you will likely end up doing so even if unintentionally. By this I don't mean an expansive do-all framework, but more like a tool-bag of basic functions and scripts that do tasks aren't common or generic enough to be handled by the average framework. Mine is basically made up of various file system, process handling, and rex-ex tid-bits with a few different curl and stream/socket utilities.

Title: When do I need to use a framework?


问:
Tracking correct order details in commerce database when modifying 'products'
I am implementing an ecommerce database. This is slightly different than most as the 'products' that are for sale are for services provided. For example a user (vendor) of the system may define a service to 'wash your car'.

```<code>Table: Services
--------------------------------------------------
| ID (pk) |      Title       |    Description    |
--------------------------------------------------
     1       Home Services      wash your car
</code>```

I have omitted a number of columns, but should still be able to make my point.

A client can then purchase the Home Services. So I have an orders table with a FK to the the Services table. Standard ecommerce stuff.

The issue I have is what happens if the vendor decides to slightly update the description or even the title? This may have the affect of changing the entire service. For a normal commerce site, you'd add a discrete product. If this product changed, you would create a new product and discontinue the old one. With the packages, we need to allow updates as the description is the product and the sales pitch (maybe thats my problem though - maybe separate the two?) so I have to allow changes.

For example they could change the description to 'wash your car and clean your house'.

The obvious issue with this is that existing orders will still reference the same PK on the services table but the service is now different.

I'm wondering what the best solution is to allow changes to be added, but maintain the correct data for existing orders. One solution I thought of is to not update the row, but add a new one and a version number

```<code>Table: Services
------------------------------------------------------------------------------
| ID (pk) |      Title       |            Description             |  Version |
------------------------------------------------------------------------------
     1       Home Services     wash your car                           1
     2       Home Services     wash your car and clear your house      2
</code>```

We can now access the correct information for previous orders, and existing customers can purchase the new home services option.

This feels like a sensible way to do it, but want to see if anyone knew of any other solutions?

One other solution is to allow updates on the services table, but then for each order, save the description and title (similar to how sometimes in commerce schemas the final price is saved directly to the order). Issue I have with this is a lot of duplicate data being saved.

答:
I think you are missing something fundamental about the nature of products -- they are hierarchical.  Typically you would have something like:

```<code>Brand
   Product
      Size
        Variant
           Production Batch
</code>```

So uubder the "Dove" brand you have a "Soap" product in "Large" size with the "pretty wrapper" manufactured as the zillionth batch at the Springfield plant.

The board of directors would be interested in the Brands performance, quality control would be interested in the production batch, sales in "Dove Soap", marketing in the "pretty wrapper".

So you need a hierarchical product structure:

```<code>Home Services
     Yard Work
          Mow Lawn
          Clear Snow
     House Work
          Spring Clean
          Put Up Curtains
Educational Services
     Tuition
          Maths Coaching
          Piano Lessons
Personal Services
     Childcare
          Babysit
          School Run
</code>```

When sell a new service say "Trim Hedge" you do not modify an existing product but add a new product in the "Yard Work" category. You can inherit all sorts of properties from the parent category -- but you have a unique product definition which should never change.

All the stuff that changes --> appointed time, agreed price and any other special conditions belong in the "order item".

Body:
I think you are missing something fundamental about the nature of products -- they are hierarchical.  Typically you would have something like:

Brand
   Product
      Size
        Variant
           Production Batch

So uubder the "Dove" brand you have a "Soap" product in "Large" size with the "pretty wrapper" manufactured as the zillionth batch at the Springfield plant.

The board of directors would be interested in the Brands performance, quality control would be interested in the production batch, sales in "Dove Soap", marketing in the "pretty wrapper".

So you need a hierarchical product structure:

Home Services
     Yard Work
          Mow Lawn
          Clear Snow
     House Work
          Spring Clean
          Put Up Curtains
Educational Services
     Tuition
          Maths Coaching
          Piano Lessons
Personal Services
     Childcare
          Babysit
          School Run

When sell a new service say "Trim Hedge" you do not modify an existing product but add a new product in the "Yard Work" category. You can inherit all sorts of properties from the parent category -- but you have a unique product definition which should never change.

All the stuff that changes --> appointed time, agreed price and any other special conditions belong in the "order item".


问:
Can I use Apache Software License, Version 2.0 and GNU LGPL 3 licence plugins in my commercial web application?
I have two plug-ins. One has the GNU LGPL 3 license and the other has the Apache Software License, Version 2.0. Can I use them in my commercial app?
And if yes, what precautions should I take?</p>

答:
First of all, this is not legal advise.

GPL software is not allowed to be linked to (including over network), be compiled into, or be shipped with non-GPL software of any form. LGPL loosens this up a little to allow non-GPL third party support, including for commercial products. The important part here is that it must be third-party (so to speak), which creates a small loop-hole.

In short, you link to an existing LGPL library (call this the first party), but the software that makes this link must be made LGPL. Call this this software the second party. Although the second party software must be released as LGPL, as the owner of the second party software you can allow other software to use it outside of the LGPL (as long as the second party software remains available under LGPL as well). In other words, the second party software must be made available as LGPL, but is not required to license it as LGPL under all cases. Every individual user of a software must have license to use said software by law. What I'm saying is that as long as each user has access to the software as LGPL, you can also license it using non viral terms. You can create the third-party software as well, in effect licensing the second-party software to yourself for use by the third party software under non-LGPL terms. I have even heard of people writing themselves a contract and license to use their own software. The law can be strange! The third-party software does not have to be LGPL in any case.

So what you do is create a library to link to the LGPL lib as just a wrapper, and release the wrapper as LGPL. You can then link to this wrapper (your wrapper) in non-LGPL software, as long as your wrapper is avaliable as LGPL.

I can't speak for the Apache Software License because I'm not familur with it.


答:
The Apache License does not place any restrictions on software that links to a plug-in or library that is distributed under the Apache license. The LGPL on the other hand has the requirement that either the LGPL library links dynamically (and can be replaced by a user) or the entire work must be released under a GPL-compatible open-source license.

For the use in a closed-source application, this effectively means that you can use the Apache Licensed plug-in without restriction and that the LGPL licensed plug-in must be linked dynamically.

If you distribute either of the plug-ins along with your application, then you must also either provide the sources for the plug-ins or inform your users where they can obtain those sources.

Title: Can I use Apache Software License, Version 2.0 and GNU LGPL 3 licence plugins in my commercial web application?

Body:
I have two plug-ins. One has the GNU LGPL 3 license and the other has the Apache Software License, Version 2.0. Can I use them in my commercial app?
And if yes, what precautions should I take?</p>


问:
Flat organizations vs hierarchical for software development
My organization was flat two years ago, and people felt that the general manager had disproportionate almost dictatorial powers. Also the general manager didn't have time to coach employees, so some employees were dysfunctional and nothing was done about them. However on the plus side everyone was involved in the decision making, thus motivation was very high.

So what do you think about flat vs hierarchical organizational structures in software development?

答:
What makes you think a hierarchical system would solve the 'dysfunctional employee' problem?

I've worked for both types of place, the flat one was the best IMHO. We had a director and a manager and then under those 2, everyone else. We all worked together for the benefit of the company and we were very efficient and successful because of it.

I now work for a place where my (let me get this right) boss' boss', boss' boss', boss wants a report so we've dropped everything to get a meaningless piece of nonsense done. The last place I worked was also hierarchical, but organised into teams - nevertheless there we spent months doing things that the first place would have have dusted off in a week.

Hierarchies can work to organise very large organisations, but even then they try to keep teams together and self-contained so they can work like the first place. If they succeed, the company succeeds IMHO, if they fail to do this the org starts to get too spread out and spends all its time managing itself.


问:
Declaring a field name starting with underscore
Before forming a class in Java or other programming languages that support OOP, should I use underscore (_) in each (local or private) field declaration.

More precisely:

private String _customername;

Is this a correct declaration?

答:
I think this is a matter of personal preference. I use underscores on private fields because I feel it makes it easier to read and identify the scope of the fields quickly. As far as I am aware, there are no rules defining which style you should use.

Note: I develop in C# primarily.


答:
I don't think given the question as is, you are really going to find an answer.

Some amount of hierarchy is always going to be necessary.  As far as company goes, you will always have a president/CEO and then you've got people under him.  Are those underlings all on the same level?  Maybe.  Maybe this company is only 5 or 10 people.  But how can you scale to 500? or 5000?  Self-directing teams are a great idea and I'm all for Agile and all that, but we also need to be realistic.

Management certainly fulfills and important function. Their job is to organize all the minions so they all march in the same direction and hopefully towards a common goal. With that organization comes certain amount of planning/debate/negations that is up to the management, so that you as a developer could focus on your job at hand.

I've got my own examples of various forms of organization. For example in my previous company we "went flat" for a while.  So we had a director and 25+ local people (plus bunch more outsourcing) in the department reporting to him. Because we were "agile" (so weren't but that's besides the point), we had scrum masters. And somehow our scrum masters ended up being senior engineers who had the best coding ability and yet they spent at least 75% of their time doing paperwork and going to meetings.  Why would you have an engineer come up with annual budgets??? That was their idea of flat.  Clearly one or two managers would have been helpful so that guys who write best code could actually code.

On the other end of the spectrum, I have a friend that works for a military contractor. They have a strict hierarchy with a lead for every two people. That's insane! The entire office is nothing but politics and from what she tells me, the entire environment is an absolute nightmare.

I work for a small start-up now and we are "mostly" flat, but I still have a boss and I'm glad I do because he gets to travel for various reasons 25% to 50% of his time, while I only need to hop on a plane few times a year.  More power to him.

So to come back to your question. Managers will always be necessary. There will always be paperwork, meetings and 75 other distractions on daily basis. Whereas engineer's goal is to "stay in the zone", a manager switches tasks every 60 seconds.  That's two different roles and often two very different personalities.

Besides playing interference to keep the team productive and focused, as you mentioned in your own question, a very important part of manager's responsibility is to build a productive team. That involves a) picking/hiring the right people, b) providing coaching/guidance so that those people would grow and develop and c) providing incentives/environment that would align the interests of those people with those of the manager (assuming that manager's interests are those of his boss).  So in your example, with good management you could solve your dysfunctional employee problem because they would be able to either adjust attitudes or replace the non-adjustables. Obviously that would only happen is if the guy in charge of the team has enough capacity to keep track of what's going on in that team.

Is there a need for management? Absolutely. Is there need for micromanagement? Absolutely not.  The role of the guy that is 5 levels up is to build and coach a team that is 4 levels up. He should be able to trust and rely on that team to give him the information he needs.  If he isn't capable of doing that and has to make engineers prepare reports for him, it just means that the guy 6 levels up didn't do a good job of building and coaching his team.

Funny story, as I quit my last company, I had a chance to sit for two hours with a guy 6 levels up and ask him, "what's up".  6 months later he ended up removing the guys at levels 5, 4 and 3.

Having written this answer, at the developer level, I still believe in autonomous, largely self-contained, self-organizing teams just like you in materials on Agile.

Title: Flat organizations vs hierarchical for software development

Body:
My organization was flat two years ago, and people felt that the general manager had disproportionate almost dictatorial powers. Also the general manager didn't have time to coach employees, so some employees were dysfunctional and nothing was done about them. However on the plus side everyone was involved in the decision making, thus motivation was very high.

So what do you think about flat vs hierarchical organizational structures in software development?


答:
There is a strong convention in java circles of not using _ for member names (as opposed to C++ circles, where there is a strong convention for using them). This is largely an arbitrary difference that probably has more to do with the desire to reinforce a sense of community than with measurable advantages. It is usually a good idea to go along with a convention simply because it removes one barrier for other people to understand your code quickly.

However, the necessity of marking member variables at all is questionable. In my view, if your methods are so long that a reader has trouble telling local vars from member vars, then they are too long to begin with, and you should refactor them to be smaller and more self-contained rather than disambiguate via naming conventions.

Title: Declaring a field name starting with underscore

Body:
Before forming a class in Java or other programming languages that support OOP, should I use underscore (_) in each (local or private) field declaration.

More precisely:

private String _customername;

Is this a correct declaration?


问:
Front controller in PHP
When you are reading about web application development, "front controller" and "single point of entry" are frequent words you are confronted with. To my understanding, the point is to provide a single location where you decide what to do in your program. That's all nice and well in theory, but I am confused as to how this would look in reality.

In OOP, I suppose your "controller" would commonly be instantiated in the "index.php", or whatever file is your "entry point". But how to go from there and how does the controller class look like? Is it something along the lines of this:

```<code>//Dummy-code, it's just to make a point
class Controller {

    //first function to be called
    public function main() {
        switch($appAction) {
            case "login": userLogin(); break;
            case "view" : viewArticle(); break;
            //...
        }
    }

    protected function userLogin() {
        //Sanitisation of user input
        //making instances of necessary classes etc.
    }

    //...
}
</code>```

or did I get the whole concept completely wrong? This is the only thing I can imagine to be the case, but I'm just not sure if there is a major mistake in approaching it this way or if I just misunderstood the purpose of a front controller.

答:
Front controller is just a PHP file which dispathes requests, loads configuration, initializes autoloading mechanism, etc.

Frameworks may vary on what goes into front controller, but usually there is a set of Routes, which map request URL to a (Controller, Action) pair. For example, if URL is user/login, then UserController->loginAction() should be invoked.

As an example of such architecture, you can read Symfony docs.

Title: Front controller in PHP


问:
Sql Server Data Tools & Entity Framework - is there any synergy here?
Coming out of a project using Linq2Sql, I suspect that the next (bigger) one might push me into the arms of Entity Framework. I've done some reading-up on the subject, but what I haven't managed to find is a coherent story about how SQL Server Data Tools and Entity Framework should/could/might be used together.

Were they conceived totally separately, and using them together is stroking the wrong way?

Are they somehow totally orthogonal and I'm missing the point?

Some reasons why I think I might want both:

SSDT is great for having 'compiled' (checked) and easily versionable sql and schema

But the SSDT 'migration/update' story is not convincing (to me): "Update anything" works ok for schema, but there's no way (AFAIK) that it can ever work for data.

On the other hand, I haven't tried the EF migration to know if it presents similar problems, but the Up/Down bits look quite handy.

答:
Let me put in another point of view. Entity Framework Database Maintenance is utterly useless in any enterprise or large database project.

Problems are:

Automatic schema updates. This is absolutely not what I want as it totally violates the fundamentals of database maintenance. Problems are: (a) someone running a newer version updates the database instead of getting an issue and (b) updates are scheduled with the dba normally taking a backup FIRST. So, automatic updates are useless.

Db creation only works on basically degenerate edge cases. Do not even try to use advanced database features - regardless which one. Sql server example: included fields in indices, filters on indices, partitioning, compression, validation rules for fields.

Migration - assumes degenerate edge cases again: no data transformation or multi step update easily. Example: Table X has a historical "user" field that records the user does something. New setup has a User table, so one needs to create the user table, then create the users, then create the user reference field in table x, then update this with the user it's from the user table, then delete the user field.

The only sensible way to deal with these scenarios are generation and migration scripts and proper versioning.

Now, SSDT - that is a great tool for versioning a specific database version much better than Entity Framework because it actually - works. As in: it records all features. On none of the databases I have I pretty much could use code first - because we always have filtered indices at least ;) EF would not even get me to 10% of what I need.

Our approach is:

Design database in the database, then sync down to a SSDT module that gets checked in. Schema sync allow developers to update their version fast. There is always an authoritative master database with the current version somewhere (on a special server) so we have a reference version to work against.

Generate delta scripts as needed for releases that also get versioned and have a nice mechanism to deploy them to a database.


答:
DZone is quite good.

Lots of articles touching a wide variety of matters. Keeps you informed about diverse trends in IT.

Though I don't find the community behavior intelligent. Mostly the articles of a high recreational value are upvoted. Things where you need to take some time to read through and use your brain are generally left without attention.


问:
Share data layer for outsourcing project
We are a small team of programmers, and we are now facing a situation where we have to outsource some of the work in order to complete it in time.

Project is about website that was previously build with asp.net webforms, EF and SQL server. We have previously build a data layer and optimized SQL, but we need to complete front end of the project. Clients wants asp.net MVC and HTML5.

The problem for us is how to open data layer to outsourcing team without compromising or disclosing any data?

答:
The problem for us is how to open data layer to outsourcing team without compromising or disclosing any data

then just don't give them access to the data. You will have to provide non-critical test data instead.

if you cannot do this for some kind of reason, let the outsourcing team sign a non-disclosure agreement

if you suspect the outsourcing team to misuse the data either, you should seriously consider not to hire them.


问:
Criteria for prioritizing product backlog
My list of the most important criteria is below. What do you think?

The value to the user - naturally features that are more important to the user must come first

Implementation time - the faster it is to implement a feature, the higher it should be on the list

Dependency between features - obviously you can't make a "roof" feature without developing the "walls" feature first.

Risk reduction - If a certain feature is very important for the project but we are not sure if we can actually develop it (because of either technological limitations or because we don't know how users will react to it), it climbs up on the list.

答:
In my experience, when myself or the Product Owner have needed to take into account the full complexity of the stories, we have used the following:

Business Priority

Development Effort

Development Risk

Test Effort

In our situation, we use development risk to identify items that should be done earlier to allow for more revision cycles and feedback.  We include test effort to make sure that we don't try to do a bunch of things that are easier to build, but very difficult to test.  Both Efforts are used to make cases to clients that an item should come earlier in the backlog, as it will take more time to implement.

When trying to maintain something close to a schedule, reducing risk to slipping on your delivery date is important to the business as well, not just the value of the items.

That being said, when we have ties, or things seem close, the business value needs to be weighted stronger. We can't just deliver a bunch of low value stories that are difficult to build, test, and have a high risk.  For this reason, business value gets a stronger weight in our calculations.


问:
OO Design related questions in technical interviews
I've been attending quite a few interviews recently and have been asked by companies to answer "design a [insert model]" questions more than a few times.

Is this normal in the industry nowadays? I've been in the software world for more than two  decades and have attended my share of interviews, but I am seeing this pattern in interviews emerge only recently.

I feel the question is very open ended. For example: I was asked to draw a class diagram to "Design a parking lot". I am not sure what level of detail the interviewer is expecting. This was in an online test where I was expected to attach a visio diagram, so I couldn't ask them what their expectations were.

Do you use these kind of questions in your interview process? Are they related to only class diagrams or do you also ask sequence, flowcharts and ERDs (ofcourse based on the nature of the position) Have they been effective in your hiring process?

* Edit for Kevin's response *

For example: A complete question could be "Design a parking lot management system that can be used to find vacant slots"

I can be done with 2 classes, ParkingLot and Slot or I could go on to add IVehicle and Vehicle and Car and Motorcycle classes. Where do I draw the line?

```<code>public class ParkingLot
{
   IVehicle Vehicle {set; get;}

   List<Slot> GetEmptySlots() { };
}

public class Vehicle : IVehicle
{
  Slot SlotNum {set; get;}
}

public class Slot
{
  int Row {set; get;}
  int Column {set; get; }
}
</code>```

答:
Designing a small system is actually a very relevant exercise to ask in an interview. It shows your skills at coming up with a good software solution to a domain problem.

However, I find it strange to just ask to post a class diagram online with no human interaction :

They'll miss the essential - the reasoning behind the diagram and what led you to design things that way.

There's no "parapet" to stop the applicant from going too far. If you reflect a final implementation in the diagram, you'll probably have dozens of classes and an unreadable schema.

Being able to draw a UML class diagram is not really an essential skill, it's just one OO notation among others. The ability to create solid designs is.

In a live interview, the ideal steps I'd expect a candidate to take would be :

Talk about the problem with the recruiter and start expressing a basic solution verbally, asking questions and adjusting as the recruiter gives more precise needs.

Stand up and sketch an overall view of the system and how components could interact together. Might be the purest style of UML, might be just boxes and circles.

Write a test, either high level acceptance test or unit test for one of the components/classes.

Start writing the corresponding implementation.

Hopefully at some point the recruiter will have gathered enough information about the candidate's skills and call it a day. The goal is not to implement a full working solution (unless it's one of these unpaid service in disguise interviews).


答:
PHP out of the box works like this (forgive the obviousness, but it's an important foundation to understand):

Client visits: example.com/about.php

Server (usually Apache) receives this request, looks under example.com domain file structure, and in the main directory looks for "about.php". If it is present the server executes PHP with a target of about.php.

PHP reads the file, running the script as written.

Now, what's wrong with this? Well, mostly nothing. But a few set of complaints began to be common.

One, how do you pass extra information to a script in the URL? Well, query strings of course...and some people found them ugly, and in wild and wooly ancient times lots of rumors abounded that URLs with query strings attached did not get properly credited - or even indexed - by search engines. Gasp!

Other people just found query strings ugly and hard to understand. But what about the internet isn't, amiright?

Another line of problems was with "web applications", and how most or even all pages have the same basic logic at the top. You might want to do some processing of query strings, or handle cookies, load in some template logic, etc. And that was thought to be messy to have files all around, conditional includes to keep file-sizes manageable, and so on.

In ancient times PHPophiles just had a common require() of a file that contained all this common logic. But this technique fell out of favor many years later (maybe as many as 5 years later if you can believe it), as some deemed it repetitious and old-fashioned (amongst other things).

It then came into common knowledge that you could instead use Apache to route ALL requests to a single file, and have Apache convert the extra path information in the URL and pass it as a parameter to a simple index.php file!

This basic idea, that all requests are sent to a single file instead of to individual PHP files directly, became known as a "front controller".

My favorite framework for demonstration purposes of how these things might be handled is CodeIgniter, because it isn't super magical or complex. Take a look at their index.php file to see how things might work.

Basically it's just a regular PHP file, which itself defines constants that might come in handy elsewhere, (like BASEPATH and such), handles some severe unrecoverable system errors (like the whole application folder being in an unknown place!), etc. Then, once all that is done, the next file in the application is loaded, and on down the line.

With front controllers a key function is to disconnect the real system directory file structure on the server from the URL path. Where as in the old days if you had a folder in the main directory named "errata", and a file in that named "misc-gumballs.php", the URL to get to that file was simply "example.com/errata/misc-gumballs.php".

With a front controller you might instead choose to have "example.com/super-delicious-free-samples/gumballs", and using Apache and PHP you instead run a index.php file which looks in a "default" folder, loads the "classes.php" file inside of it, executes the function inside the Page class defined in that file gumballs($param = null), and passes "super-delicious-free-samples" as the value of the parameter.

Ack, History! TLDR;

A front controller is just a simple PHP file which, using something like server-side Apache routing rules, has requests funneled to it instead of to individual PHP files directly. This lets you put all your common logic in that file, and you can conditionally choose how to proceed with the request based upon the parameterized data from the requesting path.

It can be as simple as a conditional include() or require(), or it can instantiate a complex Object Oriented design. There's really nothing magical or even especially complex about them.

Your example code is not entirely off the mark, though it is a little "public void main" for usual PHP-style coding. Most systems I've seen implement the functions themselves as page names, but this is not a strict requirement, and there is therefore nothing wrong - conceptually - with your example!

I think we got it.

Title: Front controller in PHP

Body:
When you are reading about web application development, "front controller" and "single point of entry" are frequent words you are confronted with. To my understanding, the point is to provide a single location where you decide what to do in your program. That's all nice and well in theory, but I am confused as to how this would look in reality.

In OOP, I suppose your "controller" would commonly be instantiated in the "index.php", or whatever file is your "entry point". But how to go from there and how does the controller class look like? Is it something along the lines of this:

```<code>//Dummy-code, it's just to make a point
class Controller {

    //first function to be called
    public function main() {
        switch($appAction) {
            case "login": userLogin(); break;
            case "view" : viewArticle(); break;
            //...
        }
    }

    protected function userLogin() {
        //Sanitisation of user input
        //making instances of necessary classes etc.
    }

    //...
}
</code>```

or did I get the whole concept completely wrong? This is the only thing I can imagine to be the case, but I'm just not sure if there is a major mistake in approaching it this way or if I just misunderstood the purpose of a front controller.


问:
How to handle affinities?
Assume we have an abstract class having several concrete classes which
interfaces publish an information under several equivalent forms, with
the difference that each class has a preferred form which can be
consulted at no cost while consulting the others might require a
time-consuming computation.  How to implement a strategy selecting an
algorithm based on this “affinity”of one class for one information
form?

Example

The original example is a complicated example of a very specialised
field, so I will do my best to figure out an example that will be
familiar to most programmers.

Assume we have an abstract class representing I/O devices which has
two concrete subclasses, one for char-based devices and one for
block-based devices.  Each class provides block-based access and
cahr-based access, but each class has an affinity to one of these
methods: block-based access is preferred for block-based devices,
etc.  Say, we want to implement a copy procedure, so that, if the source
and the target devices are block-based then the copy is performed
block-per-block, in all other cases, a char-by-char approach is
preferred.

Discussion

Assume now we have not only I/O devices but several abstract classes
offers access to several logically equivalent methods, but whose
implementation differ greatly in perormance, thus displaying a greater
affinity to one method over the others.

We want to implement a strategy working on an aggregate of such
classes and selecting an algorithm taking the affinities of these
classes into account.

Because of the combinatoric complexity brought by the aggregate, the
visitor-pattern does not seem useful here.

Question

How can each concrete class expose its affinity for one or the other
access method in a way that is useful to a strategy component picking
up an algorithm suited to these affinities?  The combinatorics yield a
large number of combinations of affinities and the strategy only needs
to consider a few “lucky cases”and use a generic algorithm to handle
the vast majority of combinations.

答:
Just add a method to the base class to get the preferred transport method.

```<code>TransportEnum getPreferredTransport()
</code>```

Each subclass could return whatever it is and since the base class already knows all of the possible transports, since it provides a different interface for each of them you, aren't hurting the abstraction any further.

Title: How to handle affinities?

Body:
Just add a method to the base class to get the preferred transport method.

TransportEnum getPreferredTransport()

Each subclass could return whatever it is and since the base class already knows all of the possible transports, since it provides a different interface for each of them you, aren't hurting the abstraction any further.


问:
Using function points as a metric for the velocity of a Scrum team?
I came across the idea of using function points as a metric for the velocity of a Scrum team. I saw it in a team and I found two articles mentioning a link between estimates and function points (http://www.ifpug.org/ISMA5-2010/Amol%20Keote-FunctionPointsAndAgile-Hand-in-Hand.pdf and http://www.cosmicon.com/portal/public/FromStoryPointsToCOSMIC.pdf).

I am not sure how this can work, because if I understand it correctly, function points measure the value of a feature (e.g. from the users perspective) whereas the velocity measures the effort of finished features. And in my view there's no direct connection between these two.

To put it another way: If you have (let's say) a stable Scrum Team which works 2 week Sprints, the number of functions points they deliver per Sprint should vary (possible wildly), which would render a velocity based on function points quite meaningless (e.g. for  planning purposes)...

Am I missing something here?

答:
Function Points are a structured way to split a large task into many smaller ones.

From Introduction To Function Point Analysis

Function Point Analysis was developed first by Allan J. Albrecht in
  the mid 1970s. It was an attempt to overcome difficulties associated
  with lines of code as a measure of software size, and to assist in
  developing a mechanism to predict effort associated with software
  development.

Function Point Analysis is a structured technique of classifying
  components of a system. It is a method to break systems into smaller
  components, so they can be better understood and analyzed. It provides
  a structured technique for problem solving.

Mind you, that site also says

Function Point Analysis should be performed by trained and experienced
  personnel.

so don't try this at home kids!

(or in practical terms - stick with making up rough sizes of your tasks in a "good enough" way, and keep on producing software without getting bogged down with the bureaucracy of a heavyweight process that might sound like a great idea but ultimately won't help you do anything better)


答:
In languages with language-level properties (haxe, actionscript, ..) an underscore is sometimes used when naming a private variable that is also accessible using a property.  The point here is avoiding a name collision between the property and the private value.</p>

```<code>private var _width:Number;

public function get width():Number
{
    return _width;
}
</code>```

Body:
In languages with language-level properties (haxe, actionscript, ..) an underscore is sometimes used when naming a private variable that is also accessible using a property.  The point here is avoiding a name collision between the property and the private value.

private var _width:Number;

public function get width():Number
{
    return _width;
}


问:
Creating a window to draw pixels in
I'm creating a fictional architecture and other fictional components for this computer/emulator. I'm facing an issue, this being the virtual display.

I need to be able to create a Window in which my program has access to all pixels contained inside, this is to emulate video memory/access.

For the best speed I was thinking the best way to do this is to use native system API and conditional compilation for cross platform support, but I don't know if this is the best option.

So essentially I just need some sort of way to create a cross platform window in which I can draw pixels in.

I'm writing in the D language but almost any solution in C can be translated to D with C linkage.

Thanks for any help.

答:
Sounds like you want SDL. It's easy to create a window in it and it used to be completely CPU-driven so it's based on the grid-of-pixels/framebuffer abstraction you'll be using. SDL 2.0 is hardware-accelerated so performance should be all right. Take a look at the tutorials section in their wiki. This tutorial should help get you started, and there's more in the SDL wiki.

I know there's some D bindings floating around going by the name "derelict" but I'm not sure where the most recent version of it is. You'll have to Google around a bit.

Title: Creating a window to draw pixels in


问:
Styling/formatting file for programmers, has it been done?
has there ever been a proposal for establishing a formatting style file for programmers? In web programming, we have CSS files that help separate style from 'code', so two people can see the same code while each can see it in his/her preferred way.

I was thinking something like this could theoretically be achieved for programming.  How many times have you read code from another programmer with a formatting that you can't stomach?  If you change the formatting, you're changing the source file, so whoever comes after you to read the same file could have the same issue against your formatting that you had.

You could say "define coding standards" but this is usually not done in small or individual teams before the company grows.

Why not separate formatting from code?  You could define how you like code formatted (brackets here, new line after this, etc) and the IDE would take the source code and auto-format it to your liking (without changing the source code).  I guess it wouldn't be a trivial thing, but I'm curious if there are languages or IDEs in which this has been done.

Has something like this been done or attempted ever? Is it doable?  Could something like this be incorporated in, say, Visual Studio?

答: In some way, syntax highlighting, as it is done in most editors and IDEs, could be seen as a form of CSS for program text. It seems however that most programmer do not customise the syntax highlighting according to their needs (if it is possible).</p>


答:
Yes - but not the way you're thinking.

What has been done for decades now is 'beautifying' code. You supply your code to a program that has a set of configuration options, and it formats your code accordingly.

A VS plugin that reformatted your code when you checked it out would be interesting, but... the huge problem with such things (and a formatting document too) is that your code will be re-formatted when you commit it, which will always create huge diffs so you won't be able to see the "good" changes from the automated bits.

I guess you could automatically reformat all code before it goes in, using a standard style, which would minimise this problem, but probably not eliminate it.

Title: Styling/formatting file for programmers, has it been done?

Body:
has there ever been a proposal for establishing a formatting style file for programmers? In web programming, we have CSS files that help separate style from 'code', so two people can see the same code while each can see it in his/her preferred way.

I was thinking something like this could theoretically be achieved for programming.  How many times have you read code from another programmer with a formatting that you can't stomach?  If you change the formatting, you're changing the source file, so whoever comes after you to read the same file could have the same issue against your formatting that you had.

You could say "define coding standards" but this is usually not done in small or individual teams before the company grows.

Why not separate formatting from code?  You could define how you like code formatted (brackets here, new line after this, etc) and the IDE would take the source code and auto-format it to your liking (without changing the source code).  I guess it wouldn't be a trivial thing, but I'm curious if there are languages or IDEs in which this has been done.

Has something like this been done or attempted ever? Is it doable?  Could something like this be incorporated in, say, Visual Studio?


问:
Finding most Important Node(s) in a Directed Graph
I have a large (≈ 20 million nodes) directed Graph with in-edges & out-edges. I want to figure out which parts of of the graph deserve the most attention. Often most of the graph is boring, or at least it is already well understood. The way I am defining "attention" is by the concept of "connectedness" i.e. How can i find the most connected node(s) in the graph?

In what follows, One can assume that nodes by themselves have no score, the edges have no weight & they are either connected or not.

This website suggest some pretty complicated procedures like n-dimensional space, Eigen Vectors, graph centrality concepts, pageRank etc. Is this problem that complex?

Can I not do a simple Breadth-First Traversal of the entire graph where at each node I figure out a way to find the number of in-edges. The node with most in-edges is the most important node in the graph. Am I missing something here?

答:
I assume that you want to calculate only 1st-order connectedness (i.e. counting how many edges link directly to the node).

I'll further assume you already have a list of all nodes with some place to store node weights and a list of all edges.

You'll need:

A list of all nodes, and a place to store the calculated weight for each node.

A list of all edges.  As you proposed, any full traversal technique (such as breadth- or depth-first) should work as long as the graph is connected (although you may need additional space to track the exploration status of each node).

The algorithm is simple: iterate over each edge, and increment the weights of the From and To nodes referenced to by that edge.

Interpretation of the results to find "interesting" nodes is going to depend on the data-set.  For example, web pages may be interesting if they have a high ratio of incoming to outgoing edges, but a graph of airports and flights might just look at the total traffic.


问:
Why Java does not allow function definitions to be present outside of the class?
Unlike C++, in Java, we cannot have just function declarations in the class and definitions outside of the class. Why is it so?

Is it to emphasize that a single file in Java should contain only one class and nothing else?

答:
I think most of the people who answered and their voters have misunderstood the question. It reflects that they don't know C++.

"Definition" and "Declaration" are words with a very specific meaning in C++.

The OP does not mean to change the way Java works. This is a question purely about syntax. I think it is a valid question.

In C++ there are two ways to define a member function.

First way is the Java way. Just put all code inside the braces:

```<code>class Box {
public:
    // definition of member function
    void change(int newInt) {
        this._m = newInt;
    }
private:
    int _m
}
</code>```

Second way:

```<code>class Box {
public:
    // declaration of member function
    void change(int newInt);
private:
    int _m
}

// definition of member function
// this can be in the same file as the declaration
void Box::change(int newInt) {
    this._m = newInt;
}
</code>```

Both programs are the same. The function change is still a member function: it does not exist outside of the class. Furthermore the class definition MUST include the names and types of ALL member functions and variables, just like in Java.

Jonathan Henson is right that this is an artifact of the way headers work in C++: it allows you to put declarations in the header file and implementations in a separate .cpp file so your program doesn't violate the ODR (One Definition Rule). But it has merits outside of that: it allows you to see the interface of a large class at a glance.

In Java you can approximate this effect with abstract classes or interfaces, but those cannot have the same name as the implementation class, which makes it rather clumsy.

Body:
I think most of the people who answered and their voters have misunderstood the question. It reflects that they don't know C++.

"Definition" and "Declaration" are words with a very specific meaning in C++.

The OP does not mean to change the way Java works. This is a question purely about syntax. I think it is a valid question.

In C++ there are two ways to define a member function.

First way is the Java way. Just put all code inside the braces:

class Box {
public:
    // definition of member function
    void change(int newInt) {
        this._m = newInt;
    }
private:
    int _m
}

Second way:

class Box {
public:
    // declaration of member function
    void change(int newInt);
private:
    int _m
}

// definition of member function
// this can be in the same file as the declaration
void Box::change(int newInt) {
    this._m = newInt;
}

Both programs are the same. The function change is still a member function: it does not exist outside of the class. Furthermore the class definition MUST include the names and types of ALL member functions and variables, just like in Java.

Jonathan Henson is right that this is an artifact of the way headers work in C++: it allows you to put declarations in the header file and implementations in a separate .cpp file so your program doesn't violate the ODR (One Definition Rule). But it has merits outside of that: it allows you to see the interface of a large class at a glance.

In Java you can approximate this effect with abstract classes or interfaces, but those cannot have the same name as the implementation class, which makes it rather clumsy.


问:
HMVC and Database Connections
Whilst I have good experience with OOP, I'm fairly new to the concept of (H)MVC. I understand the basic concept of modular design that comes with HMVC, it's the great attraction of it. But one thing that has been bugging me, and will hopefully help me understand HMVC better is how do you handle the database connection?

I would assume that you would have a module, lets call it Database, that would initiate the connection. Now at the start of my script I would have something along the lines of:

```<code>$dbConn = new Database();
</code>```

That would initiate the connection to the database. However, when I want to run a query I need to run something along the lines of:

```<code>$query = "my query string";
$result = $dbConn->query($query);
</code>```

So I need to access the query function of the database object. Now as far as I can tell in HMVC I shouldn't directly access $dbConn from within a model of another module. But almost every module will need to access $dbConn.

From my understanding this means that in the controller of all other modules, any time I need to run a query I would have to create a new instance of the Database module, passing in an array of arguments, telling Database which method to run and what arguments that method needs.

But then what if I need to make a call to the database half way through a method in a module's model? Quite often I will need to update a table, or select some data based on an if statement. Surely I shouldn't be moving that logic to the controller?

So that means I need to be able to access another module from within a model, which seems to break the rules of HMVC. So how do I implement a database module as this is confusing me?

答:
HMVC is about UI composition, it has nothing to do with how the underlying layers communicate with each other. I'll expand a little on the example presented here.

Let's assume you want to have a view that enables a user to make a comment to a blog post. You would have fields for name, e-mail, title and comment, but you also want to have a field country displayed as a dropdown. In the action that displays this view you would make a database query that loads the countries and then populate that dropdown. Which is ok, but it forces you to duplicate the query and the view required to display the countries if you need it in another part of your application. A better approach would be to create separate controller for countries with an action that returns a view with the dropdown and then render that action whenever you need to show a list of countries.

This is the "widgetization" that the above article is talking about.

Title: HMVC and Database Connections


问:
What is the clean way to pass my LoginContext down through the layers to the data access layer?
I have inherited an API implemented using ASP.NET WebApi 2. The actions on the controllers are all like this:

```<code>public object Get(long id) {
    LoginContext loginDetails = GetLoginDetails();
    if (loginDetails.IsAuthorised) {
        return _dependency.DoSomething(loginDetails, id);
    }

    return new HttpResponseMessage(HttpStatusCodes.Unauthorised);
}
</code>```

The _dependency will have many methods all with similar signatures, and it will have dependencies of its own, and those will also use the LoginContext class until you finally reach the bottom of the call stack at the data access layer, where the LoginContext class is actually used. Dependencies are currently all injected into the constructor by the IoC container.

So there are a number of issues here that bother me - the repetitive checking in each controller action that the user is authorized, and the need to have a LoginContext on every method of every dependency referenced anywhere by the controller. Now in the first case, I have created an action filter that handles the authentication, and writes a custom identity (which contains the LoginContext details) back to the HttpContext.

That then leaves the meat of my question - what is the best way to pass my LoginContext down through the layers to the data access layer?

UPDATE: just to clarify, in response to some of the questions below, authentication itself is not being checked by the data access layer (although the business layer will obviously do things differently based on the caller's authorisation claims); but rather we are passing data gathered during the authentication process to the data access layer, where it is then being used to access particular resources, or for infrastructure concerns such as auditing. The problem still remains though, should every method of my business layer and every method of my data layer, take a LoginContext as one of its parameters, or are there better ways?

答:
The clean and appropriate way to do this is to use the request context scoped credentials.

What I mean here relies on two pieces of knowledge - first in ASP.NET there is a context scoped to the particular request; ASP.NET creates it at the beginning of the request and kills it once that request has completed and sent the response to the requesting client.

The context scoped to the HTTP request is accessible at: System.Web.HttpContext.Current

Secondly, this context has on it an IPrincipal which you can set in the property User, this is what I refer to above as credentials scoped to the request context.

So at the beginning of each request, often in the Global.asax (or HttpApplication wherever you implement it if not in your Global.asax) the AuthenticateRequest event is fired for the explicit purpose of letting you authenticate the given request. This is the normal place to put code which creates the IPrincipal and fills in it's IIdentity and places it on the System.Web.HttpContext.Current.User property.

After you fill in that User property, it's available (thread safely) to the rest of that particular request allowing all lower layers to know which user is executing the current request.


问:
How do I better engage the users who starred my project on GitHub?
I recently put up a project, called Hebel, that I've been working on to GitHub. It's a framework for GPU accelerated deep learning written in Python and Nvidia CUDA. I posted about it on Google+ and soon afterwards it was picked up on Hacker News and went slightly viral for a few days. I later posted about it again in the Machine Learning subreddit as well and altogether my project picked up 822 stars and 47 forks on GitHub, which was really exhilarating. 822 stars means my project is in the top 200 Python projects on GitHub and in fact has more stars than some high profile and widely used Python projects like virtualenv.

Despite the considerable interest for my project, I'm very disappointed with the actual engagement I have seen so far. None of the 47 forks of my projects have ever had any commits, I haven't received any pull requests, and only three issues submitted were submitted by two people. It seems that my project is potentially very interesting to many people, but they only star or fork it once and then never return to it again or use it on a continuous basis.

How can I improve engagement in order to have users either submit bugs or enhancement requests or have contributors submit changes?

答:
You've worked really hard on this. Congrats on all the attention, but sorry it's not engaging.

The first thing I notice is there are no issues. To get people to engage you have to be visible in their GitHub news feed. When you start an issue it'll show up for people following the project (not the ones who starred it). So you're community size is actually about 80 followers. It's only the followers that you should think about. Forkers can just grab the code and walk away, and stars are kind of like bookmarks. A follower will get notified of new issues.

Try opening some easy issues.

EDIT:

Your README.md is your advertisement for the repo. It's the first thing people will read, and the first thing they turn to for help. 2/3 of your readme talks about what Hebel is in a technically specific language (i.e. I have no idea what you're talking about). The lower 1/3 has only a few installation instructions.

One of the most difficult things I've found with GitHub is getting projects to actually do what the author claims. Installing, running and getting to work takes up the most time. If someone gets your repo but can't get it to work, then you'll never get a pull request.

I can only suspect that this is the cause.

Revise your readme, and put the getting start/installation instructions right at the top. So people can jump right in and get going.

Second, include some kind of sample/example that they can get running quickly that demos the benefits of the project.


问:
How can I compensate for having gone to a JavaSchool?
In an earlier question, I asked for career advice for new software engineers who did well before and during college.  But what about people who weren't fortunate enough to go to MIT or Yale, for whatever reason?  What if you went to what Joel Spolsky calls a JavaSchool?

What can/should JavaSchool alumni do to develop their skills and make up for the things they missed in college?  (Or, was Joel wrong about those schools being disadvantageous?)

答:
Despite the claims made by Joel in that article- and he concedes the point himself- a lot of the subject areas that may be missed by a "JavaSchool" are not necessary of many jobs.

I attended something that I suppose resembles a JavaSchool in that we spend most of our time focusing on high level languages like C# and Java, but that doesn't change the fact that "Algorithms & Data Structures" is still part of the required class list- not to mention all of the other theory-oriented classes. Granted not all "JavaSchools" are the same, but that isn't the point.

In my opinion, more important than an understanding of some of the grittier development topics is being able to problem solve effectively when unique challenges arise. As software engineers we do the vast majority of our learning on the job and as such, two of the biggest aspects of our job description are being able to problem solve and being able to pick up unfamiliar concepts. If, during an interview, one is unable to make a discernible and logical attempt at solving a problem which is new to them, then their incompatibility for a given position will likely reveal itself.

Obviously, when hiring someone for a position that requires constant exposure to and use of some intricate topic that may be missed by a JavaSchool, it is often the logical choice to go with someone who has a prior understanding, but lack of experience shouldn't always preclude job eligibility.

More than likely, the 50 year old Java guy at your company that has been there for as long as anyone can remember did not have any understanding of Java until his job (current or previous) asked him to learn it- and he did so. Strictly speaking, it's bad practice to fire "the old guy" so that a younger and more "up-to-date" candidate can take his place; that being said, if the job description for any employee young or old changes, it is the responsibility of that employee to get caught up or find a new job. Just because an individual (especially a programmer with past experience) doesn't understand some concept, doesn't mean they are unwilling or incapable of learning it. In fact, if they are unwilling to learn then they probably do not belong at any job- much less yours.

It's fair to say that some "JavaSchools" are better than others, and that fact should certainly be considered when selecting a candidate for a position, but there are a lot more important personal traits than just where someone went to school.

It is our aptitude to tackle a problem and find a solution that defines us as engineers, most everything else is secondary.


问:
What to do when your company doesn't encrypt passwords
Background

I'm been contracted to help a company maintain their server. I work on some minor PHP projects but also look over performance issues and recently, scan logs for hackers.

These guys have been running their server for some time and have what I would call a legacy application on its last legs. It uses magic quotes, global variables (which allows $id to be overwritten by $_GET['id']), use .htaccess as their only security in some instances, you name it. A security and programming nightmare.

We have been hacked in the past, mostly with SQL injections, which would run SLEEP(99999999) commands and act as a DOS-attack. Luckily they didn't run "little bobby tables",

XKCD: http://xkcd.com/327/

So I re-wrote their vulnerable SQL statements from mysql_query() (not mysqli) to PDO transactions. I'm also analyzing the queries for SLEEP and UNION, which we don't use but the injections have. So far, so good.

Latest Issue

Recently we've been told records are changing in the DB for users, such as their e-mail addresses to ones presumably made by spammers.

I noticed their columns didn't have a last_modified column, so we weren't able to even know when they were being changed, let alone by who. I added that column, but that's barely a first step.

When I was looking in to this table, I noticed the passwords weren't salted nor even hashed, just saved as plaintext.

Client Communication

How can I approach them about the entire situation, as a contractor, without flailing my arms like a madman? Any advice? I was thinking a calm approach of,

```
    ISSUE #1
        Synopsis
        Why this is an issue
        What can happen if this is not fixed
        Suggested fix

    ISSUE #2
        Synopsis
        Why this is an issue
        What can happen if this is not fixed
        Suggested fix
        ```

答:
The calm approach that you suggest would be best.  Pointing out that when this data gets exposed, most of your users will be vulnerable to identity theft due to password reuse.  This would be a pretty good time to point out that this is the same issue that affected Target (assuming that the company isn't Target).  And your manager should be pretty receptive to changing this.

In regards to legalities with the data, I don't believe that username/passwords are considered the same as CC Data, Personal Information, etc.  Though it could depend upon what ever information that you have for your users.  I am not a lawyer and these aspects would be best brought up in your revelation and should be brought to your companies legal department to determine legalities.

https://en.wikipedia.org/wiki/Information_privacy_law

And you have this XKCD to help you out too:

OwnerDisplayName: bafromca


答:
C#, which is very similar to Java, does have this kind of feature through the use of partial methods, except that partial methods are exclusively private.

Partial Methods:  http://msdn.microsoft.com/en-us/library/6b0scde8.aspx

Partial Classes and Methods:  http://msdn.microsoft.com/en-us/library/wa80x488.aspx

I don't see any reason why Java couldn't do the same, but it probably just comes down to whether there is a perceived need from the user base to add this feature to the language.

Most code generation tools for C# generate partial classes so that the developer can easily add manually written code to the class in a separate file, if desired.

Title: Why Java does not allow function definitions to be present outside of the class?

Body:
Unlike C++, in Java, we cannot have just function declarations in the class and definitions outside of the class. Why is it so?

Is it to emphasize that a single file in Java should contain only one class and nothing else?