问:
Do your stories include tasks across disciplines? How do you do capacity planning?
My organization does web projects and employs a handful of disciplines like backend dev, frontend, BA, UX, graphic design, QA. We've been pushing to have tasks for every discipline in our sprints with explicit dependencies (Can't build a page without comps, can't do comps without wires, etc). I've heard some other organizations say that scrum is only for dev tasks. Are we barking up the wrong tree? And, if not, are there any good tools for doing capacity planning when only certain resources can do certain tasks?</p>

答:
This is a tricky question. The issue is that you require some of the artifacts (like you mentioned comps, wire frames) as input for the other tasks (development). Based on this, I would say that estimating the development tasks is hard to impossibly without this input, which is obviously something you want to avoid.

I can see two approaches to help with this:

Separate Stories

Treat the tasks to come up with the input required for development as separate stories, e.g. have a story for "Account Screen UI" and a second one for "Account Screen Dev", with a dependency between each other. Then the UI team can work on the first story in Sprint X, and the Dev team can work on the second story in Sprint X+n, given that the UI story is done.

You might run into issues with this due to the dependency, e.g. if it's not clear that there is a dependency.

UI work outside of the Sprint

In this approach, work on the UI tasks outside of the development Sprint. You still treat the UI work as a dependency for development, but the UI team doesn't work as part of the Dev team and not within the frame of the same Sprint.

This is the way we're currently working, since we have some of the same dependencies. We created a Definition of Ready, which defines the information that needs to be available for a story to be deemed ready, i.e. it can be moved to development. One part in this Definition of Ready is that all UI stories have mockups, screenshots or wireframes attached to them. As part of the Story Grooming, we work with the UI team to go through the stories, and they create mockups etc. Once these are there and the story has acceptance criteria, it can be estimated (Planning Poker). Once that is done, it's ready.

In this model, the grooming or UI work can be done in an agile manner as well, where the grooming and/or UI team is using an agile process. It could be Scrum, or it could also be Kanban, which might be better suited for this kind of work.


问:
Why do books say, "the compiler allocates space for variables in memory"?
Why do books say,  "the compiler allocates space  for variables in memory". Isn't it the executable which does that? I mean, for example, if I write the following program,

```<code>#include <iostream>
using namespace std;

int main()
{
   int foo;
   return 0;
}
</code>```

and compile it, and get an executable (let it be program.exe), now, if I run program.exe, this executable file will itself command to allocate some space for the variable foo. Won't  it ? Please explain why books keep on saying, "the compiler will do this...do that".

答:
what the compiler will do is take your code and compile it into machine code. What you mention is a good example where a compiler only needs to translate.

For instance, when you write

```<code>int foo;
</code>```

You can view that as 'I am telling the compiler to [in the output it generates] request that the computer reserve enough ram for an int that I can reference later The compiler will probably use a resource id or some mechanism to track foo in the machine code, you get to use foo in a text file instead of writing assembly! Hurray!

So you might also look at this as the compiler is writing a letter (or perhaps a novel/encyclopedia) to all targeted processors and devices. The letter is written in binary signals that (generally) may be translated to different processors by changing the target. Any 'letter' and/or combo can be sending all sorts of requests and/or data - like please allocate space for this variable that the programmer used.

ContentLicense: CC BY-SA 3.0

Body:
what the compiler will do is take your code and compile it into machine code. What you mention is a good example where a compiler only needs to translate.

For instance, when you write

int foo;

You can view that as 'I am telling the compiler to [in the output it generates] request that the computer reserve enough ram for an int that I can reference later The compiler will probably use a resource id or some mechanism to track foo in the machine code, you get to use foo in a text file instead of writing assembly! Hurray!

So you might also look at this as the compiler is writing a letter (or perhaps a novel/encyclopedia) to all targeted processors and devices. The letter is written in binary signals that (generally) may be translated to different processors by changing the target. Any 'letter' and/or combo can be sending all sorts of requests and/or data - like please allocate space for this variable that the programmer used.


问:
What's the best practice for naming uploaded images?
Suppose I have a form in my web application where users can upload a profile picture.

I've got few requirements about file size, dimensions etc, but when the user uploads the image, how should I name them on my system? I suppose it would need to be consistent and also unique.

Maybe a GUID?

```<code>a5c627bedc3c44b7ae7c06a44fb3fcf8.jpg
</code>```

A timestamp?

```<code>129899740140465735.jpg
</code>```

A hash? Ex: md5

```<code>b1a9acaf295cf14ffbc5b6538294562c.jpg
</code>```

Is there a standard or recommended way to do this?

答:
In one of the solutions i worked on years ago we did this:
sub folders for part of user id so if your user id was 232950192

we would have sub folders images/23/29/50/192/232950192

in the final folder have folders for albuns and profile imgs etc

But we save everything in the data base too and keep it in the file system for quick web server access (which has caching too)

Anyway the final image would have the original image name. We did not need to keep versions. But for what can keep more sub folders under the final album names or in the data base with a version id. need to think it thru as once it goes to production would be difficult to change things without time consuming and error prone corrections in current structure

It is very easy to make a sub folder in java and create a file in it:

```<code>    File folder = new File(pathwithslashes);// like "images/23/29/50/192/232950192"
    folder.mkdirs();
    File imgFile = new File(folder, name);
    //Now get output stream etc
</code>```

To get date stamp in subfolders:
        SimpleDateFormat sdf = new SimpleDateFormat ("/yyyy/MM/dd/");
        pathwithslashes = pathwithslashes + sdf.format(now);//now is a util.Date
        File folder = new File(pathwithslashes);

Dot net https://stackoverflow.com/questions/5482230/c-sharp-equivalent-of-javas-mkdirs

Body:
In one of the solutions i worked on years ago we did this:
sub folders for part of user id so if your user id was 232950192

we would have sub folders images/23/29/50/192/232950192

in the final folder have folders for albuns and profile imgs etc

But we save everything in the data base too and keep it in the file system for quick web server access (which has caching too)

Anyway the final image would have the original image name. We did not need to keep versions. But for what can keep more sub folders under the final album names or in the data base with a version id. need to think it thru as once it goes to production would be difficult to change things without time consuming and error prone corrections in current structure

It is very easy to make a sub folder in java and create a file in it:

    File folder = new File(pathwithslashes);// like "images/23/29/50/192/232950192"
    folder.mkdirs();
    File imgFile = new File(folder, name);
    //Now get output stream etc

To get date stamp in subfolders:
        SimpleDateFormat sdf = new SimpleDateFormat ("/yyyy/MM/dd/");
        pathwithslashes = pathwithslashes + sdf.format(now);//now is a util.Date
        File folder = new File(pathwithslashes);

Dot net https://stackoverflow.com/questions/5482230/c-sharp-equivalent-of-javas-mkdirs


答:
I would keep your teams cross-discipline. If one team is too big, I would split the project into separate Scrum teams with each team being cross-disciplined. (At a push, people can split their efforts across two or more teams if necessary; you just need to take this into account when estimating against velocity.) Splitting teams and stories into design/prototyping/dev etc is counter-productive, I think, for reasons I gave in the comment to @nwinkler: you should only ever create stories that deliver value to the customer.

Kanban or Scrumban are good approaches that may help your thinking where dependencies are concerned. If you judiciously control your WIP limits, they would let you create wireframes before the dev takes place, without reducing the total turnaround time for a feature. I have found this especially useful if people ever need to wear different "hats": e.g. if the "test" column reaches its WIP limit, a BA or dev could put on their tester hat for the day.

Title: Do your stories include tasks across disciplines? How do you do capacity planning?

Body: My organization does web projects and employs a handful of disciplines like backend dev, frontend, BA, UX, graphic design, QA. We've been pushing to have tasks for every discipline in our sprints with explicit dependencies (Can't build a page without comps, can't do comps without wires, etc). I've heard some other organizations say that scrum is only for dev tasks. Are we barking up the wrong tree? And, if not, are there any good tools for doing capacity planning when only certain resources can do certain tasks?</p>


问:
Logging to database: Log first or action first?
Long story short, I'm working on a web-based frontend that interacts with a database, and one of the functions is that every action on a particular table gets logged to keep a full history of all changes to that table.

An earlier attempt at using triggers in postgreSQL to handle the logging automatically ran afoul of a couple of other requirements of software that will use said database as a backend, so I'm back to manually creating the log entries and saving them.

My question is, what's best practice? Creating and storing the log first, then making the change, or making the change first, then storing the log? I realize that it's essentially a moot point because I'm wrapping the entire process into a transaction anyway, but I'm suddenly wondering if there are arguments in favor of either methods.

答:
Actually the best practice would be to log the request, then commit, then attempt the update.

That way you have a record of the requested actions even if they failed.

If you are really paranoid you can log "success" or "fail" after you attempt the update.


问:
How to explain to your colleages to stop creating packages and classes named "Utils"?
In most of the projects at work it will eventually show up a package, a class (or multiple packages and classes) named "Utils", where every kind of function is dumped into.

It becomes excruciating harder and harder to navigate the project without a properly named structure. I have tried to ask to stop using "Utils".

When I find it if and the change to the codebase is small I normally refractor it and remove them, but they always end on showing up cluttering the code.

So do you know any strategy to make them stop doing this? Or am I just being a nagger?

答:
Clean code is a valid concern. I like the Guava convention of using the plural form of a type, for example, Strings, Maps, and MoreExecutors. The main problem is that someone needs one or two methods that are related but feels a class needs more than that to warrant a separate class. This is the problematic assumption, and only a culture of frequent code reviews or quick hallway-design will catch it early.

One thing that can help also helps get others to use the utility method: demonstrate it to a few others when it's convenient. It may be enough to mention during a stand-up meeting, "Hey, I created a handy utility class for trimming and standardizing our usage of strings the other day. It's called Strings and is located in package com.example.type."

I will say that I'm less concerned with a package named util as long as there is just one. This is a catch all that should contain other packages that are application agnostic, i.e., a library. Some people call this package lib or tools, but I frown on plural package names (otherwise every package would end up plural).

OwnerDisplayName: fmsf

OwnerDisplayName: David Harkness


问:
Negative test cases confusion
In the Software testing book from Koirala, Sheihk, they say:

A positive test is when you put in a valid input and expect some
  action to be completed in accordance with the specification.

  A
  negative test is when you put in an invalid input and receive errors.

Part of my question:

Let's say there is a requirement: If the customer name=="James Bond", do something.

Is name<>"James Bond" negative or still positive test, verifying the requirement?

Or a login function:

Is correct login positive test case and incorrect negative?

Or Login failed is just confirmation of requirement that a password must be correct ->confirming invalid pass will not work.

For example, if the program is supposed to give an error when the person types in "101" on a field that should be between 1 and 100, then that is positive then if an error shows up. If, however, the application does not give an error when user types 101, then you have a negative test.

答:
"The authors says the field should be between 0-100 and if not, show the error. Then he says showing the error when you type 101 is positive and if the error does not appear, it is negative. Does not make sense IMO."

If a test pass (whatever it test), it is positive (success). If not, its negative (unexpected behavior).

As already said, a test goal is to determine if your code should PASS or FAIL. Failing may be normal.
Personally, I categorize my tests with OK (should pass) and KO (should fail) like that :

```<code>LoginSuccessTestOK()
{
    // Assert that login success in an expected manner
}

LoginFailTestOK()
{
    // Assert that login fail in an expected manner
}

LoginSuccessTestKO()
{
    // Assert that login should success but fail in an expected manner
}

LoginFailTestKO()
{
    // Assert that login should fail but succeeded in an expected manner
    // May be not applicable in this case
}
</code>```

If these tests pass (green), they are positive. If one don't (red), it'll be because of an unexpected behavior.

Title: Negative test cases confusion

Body:
"The authors says the field should be between 0-100 and if not, show the error. Then he says showing the error when you type 101 is positive and if the error does not appear, it is negative. Does not make sense IMO."

If a test pass (whatever it test), it is positive (success). If not, its negative (unexpected behavior).

As already said, a test goal is to determine if your code should PASS or FAIL. Failing may be normal.
Personally, I categorize my tests with OK (should pass) and KO (should fail) like that :

LoginSuccessTestOK()
{
    // Assert that login success in an expected manner
}

LoginFailTestOK()
{
    // Assert that login fail in an expected manner
}

LoginSuccessTestKO()
{
    // Assert that login should success but fail in an expected manner
}

LoginFailTestKO()
{
    // Assert that login should fail but succeeded in an expected manner
    // May be not applicable in this case
}

If these tests pass (green), they are positive. If one don't (red), it'll be because of an unexpected behavior.


问:
Manage feature set of one app on multiple platforms/codebases
So I develop an app that is for both Android and iOS.

From time to time changes occur when working on one version that need to implemented on the other. I find it tedious to keep track of these changes so I don't forget them later.

I'm just curious as to what other workflows you guys use when managing a single feature set to be implemented in various projects.

Thanks

答:
A few thoughts:

Have a Good Specification - I am not doctrinaire about specifications.  I would probably not create a formal written specification when working on a one-person project that is not too big.  However, if you have something that needs to be implemented on two platforms, you absolutely need a specification.  Have a single document that defines exactly what the application does, and use that as the source for both versions.  That way, they will never get out of sync with each other.

Keep the specification up to date.  Avoid making ad hoc changes to one version or the other.  Also make sure the specification is clear about any differences between the two applications.

Maintain One Bug List - Any time you discover a bug, put it in your bug list.  Unless the bug is something very platform-specific (to the point that it doesn't even make sense on the other platform), verify that both platforms are performing correctly before closing a given bug.

Use Common Code if Possible - This is tricky, since iOS development is primarily C/C++, while Android is mainly Java.  However, it is possible to have C/C++ portions of an Android program.  See this StackOverflow question.  It is probably worth considering whether you could put the core functionality in a single C or C++ library.  Obviously, the less work you have to duplicate, the better.

Use a Common Design - Put common functionality in a library that works the same way on both platforms.  Do this even if you can't use a common code base--think of it as a single library that is implemented in two languages.  As far as is practical, use the same objects, functions, interfaces, algorithms, etc.  When iOS and Android do things differently, put the differences behind a layer of abstraction.  The benefit of this is, you only have to figure out one way of doing things when adding a new feature.

Don't force this: if the natural way of doing a certain task differs quite a bit between platforms, then go with what makes most sense.  Just make sure your code has good separation between the similar things and the different things.

Develop in Parallel - Don't let one version get very far ahead of the other.  Make incremental changes in both versions, then build and test both.  If the code in question is similar enough, even try having both versions open side by side.  It will take some discipline to do this, but in doing things this way, I think you will maximize the benefit of having similar code in both apps.


问:
java classes and database queries
Can someone please explain the best way to solve this problem.

Suppose I have three classes

Person

Venue

Vehicle

I have a DAO method that needs to return some or all of these attributes from each of the classes after doing a query.

Please note, by requirements I am using one DAO for all three classes and no frameworks.
Only my own MVC implementation

How do I accomplish this? It seems very wrong to make a class PersonVenueVehicle and return that as an object to get the instance field, values.

I was taught that the database entities must be reflected by classes, if this is case how is it implemented in such a situation?

答:
If you are retrieving an Object or a list of Objects, use one object per query on your controller.
If you want to retrieve a message say in JSON or XML, then you DAO acts like a facade and can query several class attributes.</p>

Title: java classes and database queries


问:
To integrate git versions as build numbers or not?
A colleague and I have been taking turns debating/discussing the issues/merits of integrating a version derived from the current git repository into our code whenever it builds.

We think the merits include:

No need to worry about human error in updating a version number

Traceability between what we find in a device and the source code it was derived from

The issues that have arisen (for us) include:

IDE derived build systems (e.g. MPLABX) can make it hard to figure out where to put these kinds of hooks in (and it can end up pretty cheesy in the end)

More work to actually integrate this into the build scripts/makefiles

Coupling to a particular build approach (e.g. what if one person builds with XCode and the other MPLABX) may create downstream surprises

So we're curious where others have landed on this debate. It's really easy for the discussion to become anecdotal. There are lots of people out there who are insistent on end-to-end automation, hang the amount of up front work and coupling it creates. And there are a lot of others on the other side of the debate, who just do the easiest thing that works and live with the risks.

Is there a reasoned answer to which side is best to land on?

答:
I'm directly linking the output of git status, log and diff into the executable. Then there is an option to print that. The advantage is that you are not only able to figure out which branch your binary was build from, but also which uncommitted source code changes are included. Please see:

https://github.com/colding/MercuryFIX/tree/master/stdlib/scm_state

You should be able to use those 3 files to make your own SCM state lib thing.


问:
What are the practical benefits of LISP like syntax which Clojure uses over Java like syntax of Scala?
I spent couple of months learning Scala and got overwhelmed by number of different constructs it had,
After looking at partial functions, partially-applied functions, pattern matching, actor syntax,
I gave a thought to learning Clojure which doesn't have too much in  terms of syntax but looking at the how Java inter-operability is handled, it looks very difficult to get use to.

for example: things like doto, new and .

Every time I start typing a function, there are times I write (1 + 2) instead of (+ 1 2).

It looks like I will have to completely forget how I write regular programs to get use to this syntax.

Also finding it difficult to deal with side-effects that do and let form have.
Aren't they similar to what functions with void type are ?

Things like registering a callback,things normal I/O, how can such things be side-effects free.

Till now all I really liked about Functional Programming is that,
immutability makes concurrency easier when dealing with shared data,
functions as first class objects and having higher-order functions,
apply,map and reduce with functions and lists
.

I wanted to know, are there practical benefits I will get once I am use to this syntax ?
I f I continue to learn Scala and avoid using var, and always use recursion instead of loops.
I can do all the above things and still write understandable code.

答:
The principles of the functional language like lisp or clojure are very useful for writing self modifing code.

So for adding some values you have only to generate a instruction with a + at the beginning and the numbers after that, in an imperative language you have to add each additional value manually.

The thing is, languages like lisp or clojure don't really have any syntax, ist only a description of a tree structure as text.


问:
How should you deal with a popular project that you no longer want to maintain?
I am the maintainer of a project which has a large non-technical userbase. I've been maintaining it for about 4 years now and adding new features as they've been requested.

I'd like to move on to other projects now and stop developing for this application. Because of the non-technical nature of the users, there have been very few code contributions in the past. I don't believe I will be able to find anyone else to take over the project in my stead.

Bugs, issues, feature requests - these are still coming in. I am still responding to emails for help, as I am not sure if I should ignore them, tell them that I'm not working on the application, or if I should respond to emails in only certain cases.

What is the best way to 'abandon' this project, but still let users use the application?

Update (July 2016) - It didn't go as planned.  I made an announcement in the README and soon after, I started receiving contributions of a more substantial nature.  Pull requests with bug fixes, features, documentation, issue activity.  Since then, the project has felt 'reinvigorated' and I'm now happily maintaining it along with newer projects.  I have collaborators as well.  At a guess, it may have been the kind of contributions which were affecting my view of the project and with the quality of contributions improving, it didn't feel like a chore any more.

答:
It's a tough thing to abandon your fan base, especially when you're different from them.  If there were developers in the user group, it would be an easy problem to solve: just announce your impending exit and suggest that someone else step up, offering to help them get up to speed before you leave.  Since there aren't, the question is really this: Can you (or your users) find someone to replace you in a timeframe that makes sense to you (or your users).

In the past, I've maintained several projects for years longer than I cared to because it was good for my reputation.  My stature, comparatively small though it is, in my field has helped me find jobs when I've needed or wanted them, and that has value to me.  Enough value to make it worth putting my time in when I could.  Eventually, of course, I walked away, but I made sure the full project code was available to any successors.


答:
Lisp syntax is just that:  syntax.  It has nothing to do with semantics.  In other words, the syntax (ideally) shouldn't affect how you write programs; if you feel like you have to "completely forget how you write regular programs", it sounds like you're having difficulty with the semantics, not with the syntax.

Practical benefits of Lisp syntax include:

consistency.  Function/macro/special-form followed by its arguments.  No operator precedence issues.  Grouping is usually explicit.

easy to parse and unparse.  This makes it easier to write source code tools, such as static analyzers and code browsers.

extensibility

user-defined macros.  Users can extend their Lisp system's syntax.

system-defined syntax.  New special forms can be added to a Lisp system without having to worry about how their syntax interferes with existing forms.

You also threw in a couple of questions about side effects and functional programming.  Those aren't related to Lisp syntax and should really be asked in a separate question.

Title: What are the practical benefits of LISP like syntax which Clojure uses over Java like syntax of Scala?

Body:
I spent couple of months learning Scala and got overwhelmed by number of different constructs it had,
After looking at partial functions, partially-applied functions, pattern matching, actor syntax,
I gave a thought to learning Clojure which doesn't have too much in  terms of syntax but looking at the how Java inter-operability is handled, it looks very difficult to get use to.

for example: things like doto, new and .

Every time I start typing a function, there are times I write (1 + 2) instead of (+ 1 2).

It looks like I will have to completely forget how I write regular programs to get use to this syntax.

Also finding it difficult to deal with side-effects that do and let form have.
Aren't they similar to what functions with void type are ?

Things like registering a callback,things normal I/O, how can such things be side-effects free.

Till now all I really liked about Functional Programming is that,
immutability makes concurrency easier when dealing with shared data,
functions as first class objects and having higher-order functions,
apply,map and reduce with functions and lists
.

I wanted to know, are there practical benefits I will get once I am use to this syntax ?
I f I continue to learn Scala and avoid using var, and always use recursion instead of loops.
I can do all the above things and still write understandable code.


答:
Another suggestion for you, which is slightly the opposite of what you're asking but I think should be in your list for consideration. Have you considered not abandoning it? If you have a project that there are people actively using and have increasing requirements for, but are unable to modify it themselves and you are the only expert in the software... then you are in the position to charge them money for it.

If the source is open, you could consider closing it (your choice if you want to stifle competition developing the project further). When the next feature request comes in, say yes for a charge of $xyz.

Just an option to consider.

Title: How should you deal with a popular project that you no longer want to maintain?

Body:
I am the maintainer of a project which has a large non-technical userbase. I've been maintaining it for about 4 years now and adding new features as they've been requested.

I'd like to move on to other projects now and stop developing for this application. Because of the non-technical nature of the users, there have been very few code contributions in the past. I don't believe I will be able to find anyone else to take over the project in my stead.

Bugs, issues, feature requests - these are still coming in. I am still responding to emails for help, as I am not sure if I should ignore them, tell them that I'm not working on the application, or if I should respond to emails in only certain cases.

What is the best way to 'abandon' this project, but still let users use the application?

Update (July 2016) - It didn't go as planned.  I made an announcement in the README and soon after, I started receiving contributions of a more substantial nature.  Pull requests with bug fixes, features, documentation, issue activity.  Since then, the project has felt 'reinvigorated' and I'm now happily maintaining it along with newer projects.  I have collaborators as well.  At a guess, it may have been the kind of contributions which were affecting my view of the project and with the quality of contributions improving, it didn't feel like a chore any more.


答:
I'm guessing this is not a project at a workplace where you are a paid employee and something you do in your spare time for free?

If you are making no money from this, then clearly there is no incentive for you, and no incentive for anyone else to come in fresh to deal with it. (unless maybe it is for a charity or similar voluntary organisation)

As an alternative, why not look at the possibility of adding paid for features.

This way you may have some incentive to continue. You might find people willing to pay, especially when the alternative is for the system to stop being actively developed.
(of course people may abandon your system, but what do you care, you already aren't being paid).

Another option could be to use the project to learn new technologies? Is it a website? Upgrade to the latest technology? Convert from Asp.Net to MVC4 for example? build a mobile version, make it service based and create an iOS app front end for it?


问:
How concerned about load balancing do I need to be?
I'm currently working on a project which will have client applications (desktop & android & web) communicate with varies processes running on a server(s).

My question is how much should I be thinking about load balancing and the like?

All projects which I have worked on before consisted of creating applications for internal use within companies so the number of connections was alwyas very low (probably no more than 50 at a time).

However in my own time I decided to start creating a piece of accounting software, just because. So what I have ended up with is a WPF desktop application, and ASP.NET MVC web site and an Android App which all connect to various processes/data running on my server.

On the server there is an SQL database (MS), various WCF services for communication from client to server and a few services running cleanup stuff.

This works fine when I'm testing and its just me connected. However I have no idea how it will scale if a few people start connecting at once.

I'm not even sure if I will release the software, let alone anyone use it! However as part of a learning exercise how should I be developing the system so that it could take on a large load and not crash/delay.

I'm aware this could be a very open question and could be subjective to a lot of things, but as I say I have no experience in this department and it's something I would like to learn.

答:
However I have no idea how it will scale if a few people start connecting at once.

Premature optimization is the root of all evil. If it works, don't fix it, and if you are curious if it scales then don't lose sleep over it and just test it.

It doesn't matter if you'll ever release the software, there are numerous tools that can help you run automated load and stress tests, simulating thousands or even millions of connections. It really is as simple as that, if your tests show there's a problem, fix it, if not, move on.


答:
Start with methods that run a specific query and return just the data that you need, as opposed to a more complex method that can return many combinations of data.

I'm guessing there's some kind of relationship between the classes you mentioned, such as that a Person has one or more Vehicles, and maybe they commonly travel to one or more Venues, so model your classes to reflect those relationships. In this example, your Person object would contain a List<Vehicle> and a List<Venue>.

So if you need to retrieve one Person and all their associated data, create a DAO method to return a single Person object with its collections loaded.

If you just want the Person with their Vehicles, create a DAO method to return a Person object with their List<Vehicle> loaded and their List<Venue> null.

If you want a list of Persons, and you don't immediately need their Vehicles or Venues, return a List<Person> with null collections.

Title: java classes and database queries

Body:
Can someone please explain the best way to solve this problem.

Suppose I have three classes

Person

Venue

Vehicle

I have a DAO method that needs to return some or all of these attributes from each of the classes after doing a query.

Please note, by requirements I am using one DAO for all three classes and no frameworks.
Only my own MVC implementation

How do I accomplish this? It seems very wrong to make a class PersonVenueVehicle and return that as an object to get the instance field, values.

I was taught that the database entities must be reflected by classes, if this is case how is it implemented in such a situation?


问:
Is there a design pattern or technique in Coldufsion/Java for serializing objects differently depending on customer's desires?
I have data available in the form of Structs and Arrays.

I need some design pattern advice, which I can use to model this situation
into corresponding Coldfusion Components.

Here is the data definition

I have objects like

Hotel

Apartment

Bus

Each object has it's attributes and images. Images have also different types like
thumbnails, gallery etc.

Attributes may be simple or complex

Simple Attributes like: name, code, id etc

And complex attributes are themselves objects which have it's own Attributes and Images.

The second part is Customers. Our customers receive these objects as XML export files. Each customer has it's own requirements. For example some want
one kind of attributes and other want other attributes. Some want that one type of images should be exported and some want all image types should be exported.

答:
Typically what I would do in that situation is to have one XML definition for each of your objects such as Hotels, Apartments and Buses. Choose the simplest possible definition, it will only be known to you. Example:

```<code><hotel id="1">
 <property1></property1>
 <image type="X"></image>
 <image type="Y"></image>
 etc.
</hotel>
</code>```

The objects you would like to export will first be serialized to XML files, given your definitions.

Then, you have to associate for each customer an XSLT file that will be able to transform your private XML file to the XML format desired by the customer. Given a source XML, with XSLT you will able to generate destination XML files with whatever attributes or elements the customer wants.

Basically, here's your process for generating XML files compatible with each customer:

Serialize your objects to one or more XML files

Get the XSLT file associated to your customer

Apply the XSL transformation to your source XML file(s) to get the destination XML file(s)

The main advantage of this technique is that you have your own XML format, no one knows about it except you, and as such, you are not entitled to any specific/proprietary customer XML format.

It's more of a technique than a design pattern, but I guarantee you it's a good one.
Finally, it's been a long time since I've done some XSLT, but if you are not familiar, check the MDN reference website.

Body:
Typically what I would do in that situation is to have one XML definition for each of your objects such as Hotels, Apartments and Buses. Choose the simplest possible definition, it will only be known to you. Example:

<hotel id="1">
 <property1></property1>
 <image type="X"></image>
 <image type="Y"></image>
 etc.
</hotel>

The objects you would like to export will first be serialized to XML files, given your definitions.

Then, you have to associate for each customer an XSLT file that will be able to transform your private XML file to the XML format desired by the customer. Given a source XML, with XSLT you will able to generate destination XML files with whatever attributes or elements the customer wants.

Basically, here's your process for generating XML files compatible with each customer:

Serialize your objects to one or more XML files

Get the XSLT file associated to your customer

Apply the XSL transformation to your source XML file(s) to get the destination XML file(s)

The main advantage of this technique is that you have your own XML format, no one knows about it except you, and as such, you are not entitled to any specific/proprietary customer XML format.

It's more of a technique than a design pattern, but I guarantee you it's a good one.
Finally, it's been a long time since I've done some XSLT, but if you are not familiar, check the MDN reference website.


答:
Scaling a web application is typically a deployment concern, assuming that proper software development practices have been followed in development of the web application (Eg. Not storing user data in statics or application/server contexts.)

Most web servers, like Apache, can be configured to act as a load balancer to multiple application servers by delegating requests for specific contexts.  Web servers can themselves be load balanced by sitting behind a content switch that is configured to delegate incoming requests.

A number of application servers in many different technologies can also be configured to have session sharing, automatic server farm deployment and more.  One hiccup that you might run into could be scheduled tasks as unless you have implemented task scheduling with concurrency in mind then each server will run and do its own thing which could be bad.  Again many application servers have task scheduling features built in so that you won't have to implement that inside of your application directly.

Most major databases have a number of load balancing options and possible configurations.  It could be as simple as configuring one server for a cold failover, or something complex like multiple database server nodes, each handling their own user requests, query plans and database connections in a concurrent way against a common fileshare.

The file share containing the data can also be concurrent and have failover by mounting against something as simple as a RAID array of disk drives or something expensive and complex like a SAN (Storage Area Network).

And if all this isn't enough and you don't have money or access to a data center for the best toys... there is always a cloud service provider that basically gives you infinite scalability.

Title: How concerned about load balancing do I need to be?

Body:
I'm currently working on a project which will have client applications (desktop & android & web) communicate with varies processes running on a server(s).

My question is how much should I be thinking about load balancing and the like?

All projects which I have worked on before consisted of creating applications for internal use within companies so the number of connections was alwyas very low (probably no more than 50 at a time).

However in my own time I decided to start creating a piece of accounting software, just because. So what I have ended up with is a WPF desktop application, and ASP.NET MVC web site and an Android App which all connect to various processes/data running on my server.

On the server there is an SQL database (MS), various WCF services for communication from client to server and a few services running cleanup stuff.

This works fine when I'm testing and its just me connected. However I have no idea how it will scale if a few people start connecting at once.

I'm not even sure if I will release the software, let alone anyone use it! However as part of a learning exercise how should I be developing the system so that it could take on a large load and not crash/delay.

I'm aware this could be a very open question and could be subjective to a lot of things, but as I say I have no experience in this department and it's something I would like to learn.


答:
These are matter of taste. I have converted gradually over the years to preferring Lisp syntax over Java syntax. Why? Good question. Can't really pinpoint a single reason, but here are some thoughts.

Lisp syntax is very simple, almost trivial, albeit maybe bit strange at first (before you unlearn some old habits). Trivial syntax makes it easy to programmatically mangle Lisp code. Code is data is code. Make macros and DSL way more easier and effective. "Lisp is a programmable programming language."

This gets bit philosphical, but I strongly feel that Lisp syntax is closer to "true nature of programs". Structure of programs is not linear -- it's more tree/network like. Java point of view is more linear, line oriented. Lisp POV is hierarcial and tree oriented. Those parenthesis inside paranthesis is just a way to write trees.

Thinking more in tree oriented (rather than line oriented) way enables new ways of thinking, editing and working with code. For example some powerfull tools such as Paredit, which demonstrates some concepts which might not make much sense in Java syntax, such as barf and slurp:

```<code>slurp:
(foo (bar |baz) quux zot) -->  (foo (bar |baz quux) zot)

barf:
(foo (bar |baz quux) zot) -->  (foo (bar |baz) quux zot)
</code>```

Code is a tree! :)

Body:
These are matter of taste. I have converted gradually over the years to preferring Lisp syntax over Java syntax. Why? Good question. Can't really pinpoint a single reason, but here are some thoughts.

Lisp syntax is very simple, almost trivial, albeit maybe bit strange at first (before you unlearn some old habits). Trivial syntax makes it easy to programmatically mangle Lisp code. Code is data is code. Make macros and DSL way more easier and effective. "Lisp is a programmable programming language."

This gets bit philosphical, but I strongly feel that Lisp syntax is closer to "true nature of programs". Structure of programs is not linear -- it's more tree/network like. Java point of view is more linear, line oriented. Lisp POV is hierarcial and tree oriented. Those parenthesis inside paranthesis is just a way to write trees.

Thinking more in tree oriented (rather than line oriented) way enables new ways of thinking, editing and working with code. For example some powerfull tools such as Paredit, which demonstrates some concepts which might not make much sense in Java syntax, such as barf and slurp:

slurp:
(foo (bar |baz) quux zot) -->  (foo (bar |baz quux) zot)

barf:
(foo (bar |baz quux) zot) -->  (foo (bar |baz) quux zot)

Code is a tree! :)


问:
Does this version of insertion sort have O(n) complexity for best case?
```<code>for ( i = 1 ; i <= N ; i++ )
{
  for ( j = 0 ; j < i ; j++ )
  {
    if ( arr[j] > arr[i] )
    {
      temp = arr[j] ;
      arr[j] = arr[i] ;

      for ( k = i ; k > j ; k-- )
        arr[k] = arr[k - 1] ;

      arr[k + 1] = temp ;
    }
  }
}
</code>```

Source: http://programminggeeks.com/c-code-for-insertion-sort/

If not, can it really be called insertion sort? This version of sort is there in a book from reputed author originally.

答:
Assuming it's already sorted, that if statement never gets entered. So you have two loops through everything and it'll execute in n^2 time.

But that's not "Big-O". Big-O cares about the worst time, not the best. I believe this algorithm is O(n^3). The inner loops only execute n/2 and ... I think n/3, but all that division gets thrown away when talking about Big-O.

It's been awhile but I think the best case scenario is called "big omega".


问:
What does a node.js web application's setup look like on a real production server?
Being new to node js magic world, i'm wondering how does a web application's setup look like on a real production server?
So far all tutorials, create the js file that is started from a console...and that's it.
Anyone has created a real world web app that uses node js in the back end? Can you please describe how is it setup, and how reliable this infrastructure is ? I'm coming from the asp.net and php world that require heavy web servers...and can't have a clear idea about node stuff.</p>

答:
Use a Platform as a Service.

I've successfully deployed to Heroku and Jit.su. Nodester seems cool, and I've used Azure for .NET things and if Node.js is equally good then that is a good option as well.

If you want to host a node app on your own server you could just run node app.js on your server.


答:
The best case occurs when the if statement never gets entered.  Then we just have to count the number of times we evaluate the condition of the if statement to determine that we don't want to do it.

The outer loop ranges i from 1 to N and the inner ranges j from 0 to i.  Let's count the number of times we check that if-condition:

```<code>At i = 1  we look at j 1 times  (at j = 0)
At i = 2  we look at j 2 times  (at j = 0, 1)
At i = 3  we look at j 3 times  (at j - 0, 1, 2)
At i = 4  we look at j 4 times  (at j - 0, 1, 2, 3)
At i = 5  we look at j 5 times

At i = N-1  we look at j N times   (at j - 0, 1, 2, ... N-1)
</code>```

This is the classic 1+2+3+4+....+N arithmetic series known to be O(N^2).

It is not insertion sort.  Real insertion sort is O(N) in the best case.

I don't know what this algorithm is.

Title: Does this version of insertion sort have O(n) complexity for best case?

Body:
```<code>for ( i = 1 ; i <= N ; i++ )
{
  for ( j = 0 ; j < i ; j++ )
  {
    if ( arr[j] > arr[i] )
    {
      temp = arr[j] ;
      arr[j] = arr[i] ;

      for ( k = i ; k > j ; k-- )
        arr[k] = arr[k - 1] ;

      arr[k + 1] = temp ;
    }
  }
}
</code>```

Source: http://programminggeeks.com/c-code-for-insertion-sort/

If not, can it really be called insertion sort? This version of sort is there in a book from reputed author originally.

Body:
The best case occurs when the if statement never gets entered.  Then we just have to count the number of times we evaluate the condition of the if statement to determine that we don't want to do it.

The outer loop ranges i from 1 to N and the inner ranges j from 0 to i.  Let's count the number of times we check that if-condition:

At i = 1  we look at j 1 times  (at j = 0)
At i = 2  we look at j 2 times  (at j = 0, 1)
At i = 3  we look at j 3 times  (at j - 0, 1, 2)
At i = 4  we look at j 4 times  (at j - 0, 1, 2, 3)
At i = 5  we look at j 5 times

At i = N-1  we look at j N times   (at j - 0, 1, 2, ... N-1)

This is the classic 1+2+3+4+....+N arithmetic series known to be O(N^2).

It is not insertion sort.  Real insertion sort is O(N) in the best case.

I don't know what this algorithm is.


问:
Does open sourcing your work help you?
Are developers actually likely to receive significant help by open sourcing a work in its unfinished stages, or are open source consumers more likely to want something ready to use?

This is frequently cited as a benefit of open source, but I haven't been able to find evidence of it outside of already established products.

答:
Yes and yes.

Problem is: depending on what your work is, the chances that someone has

exactly the same problem

and the same constraints (including licensing - GPL is a big road block there)

and the time to browse around to find someone having already solved it

and the time to review that solution and figure out if it's an unmaintained piece of questionable code, or if the owner wrote high quality code and will be responsive to pull requests/patches

and the time to contribute (see point above - it they need to contribute, then it's probably not a good solution for them to start with, unless it solves a complex problem, then see first points)

... is pretty slim.
Your best bet is small simple modules (apache commons-* being a excellent example). Too bad that's also the kind of code that any half decent developer can reinvent any time for little additional cost.

Title: Does open sourcing your work help you?


答: It depends on the variable. The OS allocates heap, the program will allocate stack and the compiler will allocate space for globals/statics, i.e. they're built into the exe itself. If you allocate 1MB of global memory your exe size will increase by at least 1MB</p>

Title: Why do books say, "the compiler allocates space for variables in memory"?

Body:
Why do books say,  "the compiler allocates space  for variables in memory". Isn't it the executable which does that? I mean, for example, if I write the following program,

```<code>#include <iostream>
using namespace std;

int main()
{
   int foo;
   return 0;
}
</code>```

and compile it, and get an executable (let it be program.exe), now, if I run program.exe, this executable file will itself command to allocate some space for the variable foo. Won't  it ? Please explain why books keep on saying, "the compiler will do this...do that".


答:
As far as "scaling by load-balancer" goes, make sure you know what properties your load-balancing will need. If your session-management relies on hitting the same application server each time, you need sticky sessions.

If you scale your front-ends, how do your back-ends (storage, databases, ...) scale?

It's hard to give a hard and fast answer, though.


答:
It probably has to be very close to be ready for general use, and already usable by some, in order to get help.  That's the quid pro quo of open source.  You contribute to code that is already more valuable to you than the time it would take you to start from scratch.

For example, my wife used to use Microsoft Money, but we wanted to move our home computers to Linux, so I started evaluating open source alternatives.  One promising alternative could import QIF files from Quicken, but MS Money added some weird proprietary quirk (naturally) that the open source software choked on.  I found the problem.  It was a one-liner fix, which I submitted to the mailing list.

If that software had been unable to import QIF files at all, requiring me to write an entire module just to evaluate it, I would have passed on it without a second glance, unless no other project had that feature.  In other words, you have to pass a certain point of usability if you want to receive help.

Title: Does open sourcing your work help you?

Body:
Are developers actually likely to receive significant help by open sourcing a work in its unfinished stages, or are open source consumers more likely to want something ready to use?

This is frequently cited as a benefit of open source, but I haven't been able to find evidence of it outside of already established products.


问:
Duplicating documentation on interface implementations/overrides good or bad?
So we have an interface like so

```<code>/// <summary>
/// Interface for classes capable of creating foos
/// </summary>
public interface ICreatesFoo
{
  /// <summary>
  /// Creates foos
  /// </summary>
  void Create(Foo foo);
  /// <summary>
  /// Does Bar stuff
  /// </summary>
  void Bar();
}
</code>```

Recently, we played a documentation story which involved generating and ensuring that there is plenty of XML documentation like above. This caused a lot of duplication of documentation though. Example implementation:

```<code>/// <summary>
/// A Foo Creator which is fast
/// </summary>
public class FastFooCreator : ICreatesFoo
{
  /// <summary>
  /// Creates foos
  /// </summary>
  public void Create(Foo foo)
  {
    //insert code here
  }
  /// <summary>
  /// Does Bar stuff
  /// </summary>
  public void Bar()
  {
    //code here
  }
}
</code>```

As you can see the method documentation is a straight rip from the interface.

The big question is, is this a bad thing? My gut tells me yes because of duplication, but then again maybe not?

Also, we have other similar documentation duplication with override functions and virtual functions.

Is this bad and should be avoided, or not? Is it at all worthwhile even?

答:
In general, I'd only add new documentation to the implementation's methods if there's something specific about that implementation that needs to be mentioned.

In javadoc you can link to other methods, which would allow you to just create a link in the implementation to the method documentation in the interface. I think this is how it's supposed to be done in .Net (based on my reading the online documentation, not my own experience):

```<code>/// <summary>
/// Interface for classes capable of creating foos
/// </summary>
public interface ICreatesFoo
{
  /// <summary>
  /// Creates foos
  /// </summary>
  void Create(Foo foo);
  /// <summary>
  /// Does Bar stuff
  /// </summary>
  void Bar();
}

/// <summary>
/// A Foo Creator which is fast
/// </summary>
public class FastFooCreator : ICreatesFoo
{
  /// <summary>
  /// <see cref="ICreatesFoo.Create(Foo)"/>
  /// </summary>
  public void Create(Foo foo)
  {
    //insert code here
  }
  /// <summary>
  /// <see cref="ICreatesFoo.Bar()"/>
  /// Also Note: Implementation of Bar() in FastFooCreator
  /// requires a minimum of 512 MB RAM to Bar the Foo.
  /// </summary>
  public void Bar()
  {
    //code here
  }
}
</code>```

The documentation for the <see/> element: http://msdn.microsoft.com/en-us/library/acd0tfbe.aspx

Body:
In general, I'd only add new documentation to the implementation's methods if there's something specific about that implementation that needs to be mentioned.

In javadoc you can link to other methods, which would allow you to just create a link in the implementation to the method documentation in the interface. I think this is how it's supposed to be done in .Net (based on my reading the online documentation, not my own experience):

/// <summary>
/// Interface for classes capable of creating foos
/// </summary>
public interface ICreatesFoo
{
  /// <summary>
  /// Creates foos
  /// </summary>
  void Create(Foo foo);
  /// <summary>
  /// Does Bar stuff
  /// </summary>
  void Bar();
}

/// <summary>
/// A Foo Creator which is fast
/// </summary>
public class FastFooCreator : ICreatesFoo
{
  /// <summary>
  /// <see cref="ICreatesFoo.Create(Foo)"/>
  /// </summary>
  public void Create(Foo foo)
  {
    //insert code here
  }
  /// <summary>
  /// <see cref="ICreatesFoo.Bar()"/>
  /// Also Note: Implementation of Bar() in FastFooCreator
  /// requires a minimum of 512 MB RAM to Bar the Foo.
  /// </summary>
  public void Bar()
  {
    //code here
  }
}

The documentation for the <see/> element: http://msdn.microsoft.com/en-us/library/acd0tfbe.aspx


答:
You have a couple of options as other have noted.  My option is to put out an end of life notice.  Indicate that the product will be shutting down on such and such a date.

Additionally indicate that since this product is nearing end of life, only critical bugs that impact the ability of the application to function as designed or intended will be addressed.  I.E. if the server is down you will get it up and running again.

If users have data, you may have to add a way for them to export it.

Take a look at what Google recently did with Reader for guidance. They shut it down and it was a very popular service, but it didn't fit their long term goals so the tough decision to shut it down needed to be made.


答:
As Yannis said, premature optimization is the root of all evil.

However, some things like security and scalability can be really hard to fix 'later'.

In your case I think a good compromise is to not build scalability in, but keep it in mind and try to avoid fundamental design decisions which will make it impossible to add later:

statelessness, REST flavors are good

disposable clients and servers are good

long lived job threads can be problematic

anything relying on global synchronization/serialization or only one actor processing something can be problematic

Also generally speaking, app tiers are easier to scale horizontally than a database - so when balancing work between them more work on app server is good.


答:
(Note that this answer applies mostly to game development)

I worked on a non-commercial open-source game development project.

There are many people interested in doing game development as a hobby, but do not yet feel ready for doing it for a living. We noticed that when a project is open source, it makes it a lot more attractive for volunteers who want to contribute to development.

They can actually see the code they will be working with before approaching us and asking if they may take part. This greatly reduces the entry barrier for new developers.

They can fork the code and work on their own. Then we can merge their improvements into our original versions (this only works with a copyleft license like GPL).

They know that an open source game is hard to monetize, so they don't need to worry about being exploited for profit.

When players annoy you with their unrealistic wish lists, you can just tell them go, code it! :)

I believe that doing the project open source was a very good decision. As a closed source project it would have never been as successful as it was.

Title: Does open sourcing your work help you?


问:
where to use web services
I am discovering web services to implement in my ASP.Net website. I visited many sites about Why use webservices and read many articles and found out that web services are good when you have something that is used frequently without loading your page.

I want to know some other example scenarios where web services are used.
Whether i can use web services in sending an order form to database or it is just for textbox box auto completion like google and etc.

Note: I know web services can be used from mobile, web or desktop applications.
But My question is
 When do I use web service in ASP.Net Application?

Some articles I've read so far

Codeplex

How to create a Web service using Visual Studio.net

w3school

答:
Lets go back to basics:

Service: work done for somebody else: work done by somebody for somebody else as a job, duty, punishment, or favor.

As the definition implies, is there anywhere in your application where you need code to perform work for any other piece of code?

"Everywhere" you might say, that's what classes do! ... and at a fundamental level you'd be right. There's an interesting parallel that is made in Programming WCF Services between the structure of ordinary code (with metadata, an interface and an implementation) and web services that also have those properties. So essentially all code can be classified as a service. I think that's a pretty interesting and valuable insight into this class of problems.

If a class is really, functionally equivalent to a service... what questions do you ask yourself when you decide to make a new class? Keep in mind the SOLID principles here.

I posit that you will (or should) ask yourself these same questions when deciding whether or not to make a web service, but only at a higher level of abstraction.

For a class, some such questions would be*:

Is there a set of common functions that the rest of my code needs to consume?

is there a set of common data that the rest of my code will need to know/have access to?

Am I coding the same structure over and over in my project(s)?

Am I coding the same thing/pattern over and over in my project(s)?

Take these kinds of questions to a higher level of abstraction, or a larger logically related set of code, and if you answer "yes", then you have a candidate for a web service.

*not an exhaustive list

Title: where to use web services


答:
I would say that the biggest reasons to use webservices are 1) potential for decoupling and abstracting sections of functionality, and 2) to make more flexible APIs into your system.

If your site is destined to always be in just ASP.NET without worrying about integrating other technologies (maybe some AJAX here or there), then it's a toss-up. You could use webservices or not -- you don't need them.

But if you want to create a website that allows more varied functionality, or if you want to open up APIs for the world (which allows mashups, 3rd party clients, etc.) then webservices are a very good way to accomplish that. They can valuable even if just used internally.

If you do build out services, I'd suggest REST -- it seems to be gaining more steam than SOAP.

Title: where to use web services

Body:
I am discovering web services to implement in my ASP.Net website. I visited many sites about Why use webservices and read many articles and found out that web services are good when you have something that is used frequently without loading your page.

I want to know some other example scenarios where web services are used.
Whether i can use web services in sending an order form to database or it is just for textbox box auto completion like google and etc.

Note: I know web services can be used from mobile, web or desktop applications.
But My question is
 When do I use web service in ASP.Net Application?

Some articles I've read so far

Codeplex

How to create a Web service using Visual Studio.net

w3school


问:
Is it acceptable for child classes to "break" parent class functionality?
One of the devs that works with me is following the Open/Closed Principle to add functionality to a Model by extending from our framework ORM.

```<code>class BaseModel extends ORM {
   ...
}
</code>```

All our models are now inheriting BaseModel, and this model works well in the context of our application.

```<code>class Product extends BaseModel {
  ...
}
</code>```

The problem comes when we tried to use the models as if they where extending directly from the ORM, use some of the most basic functionality:

```<code>$product = Product::factory();
$product->name = 'foo';
$product->price = 9.99;
$product->save();
</code>```

This code should have worked well but it failed because now the factory method requires a list of parameters.

I think that as long as the models works well within the context of our product we are good; but I also have mixed feelings about not supporting some of the basic core functionality of the parent class.

Thoughts?

答:
In general, this really isn't a fundamental issue. Making child classes override functionality from their parents is a common and often-desirable trait of inheritance. It is needed especially if you want to do anything polymorphic.

But this case is a little different -- this is an issue of changing the inheritance chain of your classes. So really, it's the changes to the parent (BaseModel) that are the issue.

It sounds like your BaseModel class has changed (overridden) the static factory() method by adding additional required parameters. Assuming there is some good reason for the new parameter list, I think this is an OK change. It's just that these types of changes can have a real ripple effect to downstream classes.

But here's the real question: why are you relying on Product to inherit a static method? That seems a little strange to me, but it also allows for a potential fix. Just override factory() in your Product class so it doesn't require parameters, if possible. It can then call other factory() methods of the parent classes as needed.

OwnerDisplayName: Onema


问:
Approaches to reduce cyclomatic complexity
I was running our code through JSHint, and decided to switch checks against cyclomatic complexity, and then went on long refactoring sprint. One place though baffled me, here is a code snippet:

```<code>var raf = null //raf stands for requestAnimationFrame

if (window.requestAnimationFrame) {
  raf = window.requestAnimationFrame;
} else if (window.webkitRequestAnimationFrame) {
  raf = window.webkitRequestAnimationFrame;
} else if (window.mozRequestAnimationFrame) {
  raf = window.mozRequestAnimationFrame;
} else if (window.msRequestAnimationFrame) {
  raf = window.msRequestAnimationFrame;
} else {
  raf = polyfillRequestAnimationFrame;
}
</code>```

Not surprisingly, in this implementation CM is 5, first attempt was to use solution from MDN:

```<code>var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
                          window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
window.requestAnimationFrame = requestAnimationFrame;
</code>```

Which simply looks like a hack to me (yes I know, majority of full time javascript programmers won't agree with me, however this is a prevalent opinion within our team). Doodling around my code, I found another hacks I could employ to full code-linter, among ones I was proud for about 5 second was usage of array comprehensions:

```<code>var rafs = [
             window.requestAnimationFrame,
             window.webkitRequestAnimationFrame,
             window.mozRequestAnimationFrame,
             window.msRequestAnimationFrame,
             polyfillRequestAnimationFrame
           ].filter(function (rafClosure) {
             return rafClosure !== null && rafClosure !== undefined;
           });
return rafs[0];
</code>```

However I'm curios whether there is more or less standard practice of refactoring long branching code (that's not trivial to reduce)?

答:
The first sample is just wrong. Not wrong in terms of the result, but the style is terrible. It is repetitive and error prone. The second sample is actually the step to do to obtain the readable, well written code. It's not a hack. It's just badly written code rewritten correctly. The fact that it reduces cyclomatic complexity doesn't surprise me, since there are less operations (at least in source; I'm pretty sure every decent compiler/interpreter will rewrite the first sample into the second one in all cases).

The third sample is more complicated to read for beginners who don't have enough practice with arrays, with filtering, with closures, etc. Personally, given the second sample, I would avoid the third one. Still, reduction in cyclomatic complexity is not surprising neither: you are migrating the complexity from your code to the filter method.


问:
Aspect oriented programming and implicitness
Lets suppose that I have a class which represent an image and has a number of methods.

```<code>class Image
{
    circle(x,y,radius,color);
    square(x,y,w,h,color);
    floodfill(x,y,color)
    clear();
}
</code>```

Furthermore, I want to have undo functionality. A simple way of implementing this is to keep a list of all the actions that have been performed. When I undo, I just re-run all of the actions. One solution would be to implement an aspect, something like this:

```<code>aspect ImageUndo
{
    on Image::circle, Image::square, Image::floodfill
    precall(object, args)
    {
         object.actions_list.add(args)
    }
}
</code>```

Essentially, this aspect has now modified the behavior of Image. That gives me concern. In particular, another programmer unfamiliar with the existence of ImageUndo aspect may run into the following problems:

He adds a method, and it does not work with the undo functionality.

Attempting to debug the undo mechanism, it is not clear where the actions_list get added to.

On the other hand we could have

```<code>class Image
{
    @undoable_action
    circle(x,y,radius,color);

    @undoable_action
    square(x,y,w,h,color);

    @undoable_action
    floodfill(x,y,color)

    @undoable_action
    clear();
}
</code>```

Which does not bother me as much because it gives an idea of where to look for the undo code and makes is so that the new coder will probably notice it an automatically add it to a new method.

To summarize: aspects (at least those like the one I showed) seems to bring "implicit magic" into what code does. It seems to me that the implicitness is dangerous and we should really make it explicit.

Are there good reasons for the implicitness? Do people who actually use AOP write code that does this sort of modification?

Note: this is a reworking of Are certain problems solved more elegantly with AOP? which was closed because my previous version came across, unintentionally, as ranting.

答:
One thing to point ou tis that the code isn't being modified via the aspects, it's being extended. It may be semantic, but the distinction is important, especially when considereing the open/closed principle.

Now, from what I can tell (looks like aspectj maybe?), your first example applies the aspect to the methods at the declaration of the aspect, wherease your second example applies the aspect via attributes on the methods. The problem you seem to have is one where anyone extending your code might not be able to figure out how to include undo into their additions using the first example.

Documentation is there for a reason. So write some for your consumers.

Use a different design to implement the functionality for them.

I believe that something like the following will work:

```<code>public abstract class ImageOperation
{
    @undoable_action
    public abstract void Action(Image img);
}

public class Flood_Fill : ImageOperation
{
    public void Action(Image img)
    {
        // flood-fill
    }
}
</code>```

Now, having abstracted away the image operations, you can supply ImageOperation in a different .dll than your program, and you can use it as the base for ImageOperation plugins, so that others don't need to see your code at all to produce an operation, and you still implicitly provide undo for them.

Body:
One thing to point ou tis that the code isn't being modified via the aspects, it's being extended. It may be semantic, but the distinction is important, especially when considereing the open/closed principle.

Now, from what I can tell (looks like aspectj maybe?), your first example applies the aspect to the methods at the declaration of the aspect, wherease your second example applies the aspect via attributes on the methods. The problem you seem to have is one where anyone extending your code might not be able to figure out how to include undo into their additions using the first example.

Documentation is there for a reason. So write some for your consumers.

Use a different design to implement the functionality for them.

I believe that something like the following will work:

public abstract class ImageOperation
{
    @undoable_action
    public abstract void Action(Image img);
}

public class Flood_Fill : ImageOperation
{
    public void Action(Image img)
    {
        // flood-fill
    }
}

Now, having abstracted away the image operations, you can supply ImageOperation in a different .dll than your program, and you can use it as the base for ImageOperation plugins, so that others don't need to see your code at all to produce an operation, and you still implicitly provide undo for them.

ContentLicense: CC BY-SA 2.5


问:
How do I deal with a MIT project with no included copyright notice?
There's a (possibly abandoned) library I'm using in my project.  Its Google Code project page mentions it's MIT licensed.  Nowhere in the code itself, nor any of the included files, is there a copyright notice or license specified.  The closest thing is the author's name in one of the headers.

Since the sole requirement of the MIT license is its inclusion of the copyright notice, which is non-existant in this libary, what's the best manner to proceed?

答:
The best thing to do is contact the original author and request that he or she update the repository to include a proper license file and copyright notice, along with license headers and copyright notices in each file.

If the author is totally unreachable, then you're on shaky ground, and I'd say the safest thing you can do is not use the code at all. The primary risk, in my view, is the possibility that the code might not actually be MIT-licensed, owing to the absence of a proper license declaration.

However, if you must use this code and you're sure that:

the original author1 did not include a license file with the code, but

the original author claimed that it was MIT-licensed in some authoritative way, and furthermore

the original author is the only author of all the work in the codebase (or you can correctly identify all authors and/or copyright holders)

then your best course of action might be to add those things (license, headers, notices) yourself in your distribution of the code. Your use of the code under an MIT license would be generally defensible under the legal principle of estoppel ("the legal principle that bars a party from denying or alleging a certain fact owing to that party's previous conduct, allegation, or denial"). Because the author made a previous claim that the code was MIT-licensed, the author cannot pursue legal action based on a premise contrary to that claim.

Of course, all this is hardly sound legal advice -- I'm not a lawyer, and I present this information only to demonstrate how one might begin to formulate a proper legal defense for reusing the code. It seems like reasonably strong justification to my layman legal sensibilities, but software is a popular domain for niche regulations, so there may be jurisdictional and international concerns that I have not addressed. As always, your safest course of action is to consult a lawyer.

1 I place emphasis on original author to eliminate from my scope of argument the possibility that this is a re-hosted copy of the code from which the re-hoster lazily dropped the license file.


答:
Is some kind of half way measure a possible solution? Keep the project going but lessen your workload?

For example, you say you are still responding to emails for help. Can you set up a users forum and insist all support queries are done through that so other power-users can help?


问:
Which programming guidelines for a chess network application?
I'd like to implement a simple chess peer to peer network application : one instance of the program may register friends player, and when one friend is "connected" (I mean both available by another program instance and registered as friend), I can ask him to play a game.

As I know J2SE language, as well as Swing framework, I tried to start coding, using Sockets. The problem is that I need a way to

register my friends (or other accounts)

get the friend ip, for creating a socket (it will be the same problem on the other side) : with the problem of dynamic ip adresses.I mean that a serialized adress may not be valid anymore

be informed that the other side has "connected"

I think that first and third point can be resolved if I use a PHP server which will have all informations for all registered users.

This is how the application should work :

First, before trying to connect each other, the users must register an account on a PHP server that I'll have to implement (with MySQL database)

When launching the application, the user logins by giving its username and password. So that the application will be able to retrieve friends (and stats for example) thanks to the server

When two friends are ready to play together, the server give all needed informations (such as ip adress) to both player application instance.

My main difficulties will be for the (de)serialization of dynamic IP Adresses, and for retrieving informations about a user on the PHP server.

What do you suggest ?

答:
Instead of peer to peer, why not have a central server in which connections are handled and the server's responsibility is to connect the peers together.  This also facilitates easier security, acquisition of IP Address and other information that could be kept for storage by the server.

A nice threaded-server in which each connection causes server to spawn a thread and connect that thread to another and thus set up peer to peer would be cool.

This virtualized peer to peer would be simpler and easier to manage in my opinion.


答:
Under the Berne copyright convention, almost every original creation is automatically copyrighted, whether or not a copyright notice is affixed.

Therefore, there should be no issue with adding the author's copyright notice yourself (i.e., explicitly stating the copyright that the Berne convention already says in effect), using the original author's name (which you found in the headers) and the date from Google Code and from version control.  (For projects under development over a multiyear period, the U.S. Copyright Office says to use "the year of first publication", while GNU suggests listing each year with a nontrivial change.

The most polite and safest thing to do is absolutely to contact the original author, but if that fails, then my understanding of copyright law is that there should be no problem with adding the author's copyright notice yourself.

I am not a lawyer, this is not legal advice, etc.

Title: How do I deal with a MIT project with no included copyright notice?

Body:
There's a (possibly abandoned) library I'm using in my project.  Its Google Code project page mentions it's MIT licensed.  Nowhere in the code itself, nor any of the included files, is there a copyright notice or license specified.  The closest thing is the author's name in one of the headers.

Since the sole requirement of the MIT license is its inclusion of the copyright notice, which is non-existant in this libary, what's the best manner to proceed?


问:
Is it a good idea to build a library on top of somebody else's library?
Is it a good idea to use somebody else's library as a base and build your own library over that.

I want to make a JavaScript Canvas framework for a animation player on top of KineticJS. Should I do it? Do I need permission from the author of KineticJS? Do I just say to users to donwload KineticJS before my library, or do I just copy paste the kineticJS code in my library?

答:
Sure you can build your library on top of someone else's. People do that all the time!

You shouldn't need the permission of the author of the base library to do this (because you're just referencing their code), but you might need their permission if you want redistribute their library with yours. This will affect how your users get the base library: if you are allowed to redistribute, then all is well. If not, you will have to direct them to the location where they can download the library they need.


答:
I see two perspectives to this:

Legal: Can you do it?
I see no reason you can't. I know there are some laws/rules about bundling other people's libraries, but that would probably only be for proprietary libraries or with licenses that have very specific rules against including them in other projects (This was the case for a company I worked at). I am not aware of any legal reasons why you can't have your end-user go download it themselves; I believe Ubuntu has gotten around this issue just by having end-users download the drivers manually.

Design: Should you do it?
I once ran into an issue using a library and was getting a very weird error that made no sense to me. It turns out the error was stemming from the fact that the library I was using depended on another library that wasn't referenced properly.

So if you use the KineticJS library just make sure that if they don't include the library that you throw an error that tells them that the KineticJS library is missing.

Title: Is it a good idea to build a library on top of somebody else's library?

Body:
Is it a good idea to use somebody else's library as a base and build your own library over that.

I want to make a JavaScript Canvas framework for a animation player on top of KineticJS. Should I do it? Do I need permission from the author of KineticJS? Do I just say to users to donwload KineticJS before my library, or do I just copy paste the kineticJS code in my library?


问:
"Too object-oriented"
I come from a strong OO background, and I have recently started working in an organization which, although the code is written in Java, has a lot less emphasis on good OO design than what I am used to. I have been told that I introduce "too much abstraction", and that I should instead code the way it has always been done, which is a procedural style in Java.

TDD is also not very much practiced here, but I want to have testable code.  Burying business logic in static private methods in large "God-classes" (which seems to be the norm for this team) is not very testable.

I struggle in clearly communicating my motivation to my co-workers.  Does anyone have some advice on how I can convince my coworkers that using OO and TDD leads to more easily maintained code?

This question about technical debt is related to my question.  However, I am trying to avoid incurring the debt in the first place, as opposed to paying it down after the fact which is what the other question covers.

答:
You didn't complain about it being unmaintainable, just not to your liking.  If it's a deliberate style choice, it may just be a case of irreconcilable creative differences, and you should adjust your style to fit, or find somewhere that fits your preferred style.

People can and do write modular, efficient, well-abstracted, relatively bug-free code in a procedural style all the time.  Java is an odd choice of language for such a shop, but I can see it happening if external factors decided the language, like needing to develop for Android, for example.

Everybody is a genius. But if you judge a fish by its ability to climb
  a tree, it will live its whole life believing that it is stupid.
   — Albert Einstein

If it was a deliberate choice, you can't really judge them by how well they adhere to good object-oriented design principles, you should judge by how well they adhere to good procedural design principles, and also refactor accordingly.  Java doesn't let you write code outside a class, so the mere presence of one doesn't mean they intended a module to be object-oriented.

On the other hand, if the code is a mess in either paradigm, you should probably just cut your losses.

Title: "Too object-oriented"


答:
Syntax

The syntax threw me off too at first, but after working with it and reading about it I realized some things:

1. Lisp doesn't have operators, it only has functions, so stop thinking of +-*/ as operators and that will help with things.

Don't think:

```<code>(1 + 2 + 3 + 4)
</code>```

or, even though it's correct:

```<code>(+  1 2 3 4)
</code>```

but:

```<code>(sum  1 2 3 4)
</code>```

and it will feel more natural.

Likewise with -, think more along the lines of:

```<code>(subtract-from  x  y1 y2 y3)
</code>```

and that should help.

2. Method calls aren't that different!

Functions are the first thing in every Lisp form (the stuff between the ()); since methods are functions, they come first! It's not really that different from Java's syntax though -- all you're doing is moving the starting paren to the front and swapping the positions of the object and method:

Java:

```<code>objectInstance.someMethod(arg1, arg2, arg3);
</code>```

Clojure:

```<code>(.someMethod objectInstance arg1 arg2 arg3)
</code>```

(You also lose the commas and semicolon!)

The (.someMethod objectInstance ...) is a special form that gets expanded out into a form using .: (. objectInstance someMethod ...). The latter feels weird because we're not used to thinking of the . as actually doing something when we're calling a method/property in Java; the former is the idiomatic way of doing things in Clojure anyway (reference).

New is similar:

```<code>new namespace.Object(); // Java

(new namespace.Object)  ; Clojure
</code>```

"Difficult Things"

The "difficult things" you mentioned are actually there to make your life easier!!

You said in a comment that it was annoying to keep track of things when nesting expressions within expressions; the do and let forms are built specifically to help ease that difficulty.

Let's start with do

do lets you call things imperatively, one after another, without nesting:

```<code>(do (.someMethod objectInstance arg1 arg2)
    (.someOtherMethod objectInstance "foo" "bar" "baz")
    (.aMethod anotherObjectInstance 0))
</code>```

The behavior of do is such that each of these method calls will be run in the order in which they're given and the return result of the last expression (in this case the return result of (.aMethod anotherObjectInstance 0)) is what is returned from the do block itself.

Each of these methods may or may not have side effects, and may or may not return a value (all of which but the last will be ignored).

Let

The let form does the same thing as do but it also gives you the ability to add local variables to the mix:

```<code>(let [foo "foo"
      bar "bar"
      arg1 (generateValueFrom foo)
      arg2 (generateValueFrom bar)]
  (.someMethod objectInstance arg1 arg2)
  (.someOtherMethod objectInstance foo bar "baz")
  (.aMethod anotherObjectInstance 0))
</code>```

Again, the method calls will be run step by step in order, only this time they use the local variables defined in the let's bindings (the stuff between the []), and the last call's return value will be returned as the let's return value.

let is handy for breaking a bunch of nested calls down into something more sane; e.g.:

```<code>(reduce someCombiner {} (filter keepXs (map someTransform ys)))
</code>```

becomes:

```<code>(+  1 2 3 4)
</code>```0

Is The Synatx Worth It?

You bet your sweet bippy it is!

The Lisp syntax allows the language to have macros. Macros are functions that run at compile time that rewrite the code. What this means is that you can take code that is repetitititve or complex and write a macro that is simpler to call, and that macro will write the complex version for you.

For example, say we have the following do block:

```<code>(+  1 2 3 4)
</code>```1

We have to repeat the same object instance six times! That's annoying. The doto macro can make things a bit lighter for us typing-wise:

```<code>(+  1 2 3 4)
</code>```2

The doto macro allows us to specify the object instance once, up front, instead of having to repeat ourselves in the code later on -- it rewrites the expressions we give into the do block shown above. (This particular macro is similar to the with syntax some languages support.)

Now, this is a really simple example, but just imagine what sorts of coding tasks you could automate! And that's where the power of Lisp's macros comes in: you can write functions to make the programming language write your code for you!

Side Effects

You can still have side-effects in Clojure code, especially if you're doing interop with Java OOP since that OOP has side-effects. If you use more of the core Clojure code than Java, you'll not have as many side effects because it'll be more purely functional.

A lot of what I've found in my functional programming experience is that it's about partitioning the side-effect causing code from the purely functional code. You can do this in pretty much whatever language you're using (even Java).

Comparison to Scala

I've not used Scala, so I can't help you there. But hopefully the above was informative.

Body:
Syntax

The syntax threw me off too at first, but after working with it and reading about it I realized some things:

1. Lisp doesn't have operators, it only has functions, so stop thinking of +-*/ as operators and that will help with things.

Don't think:

(1 + 2 + 3 + 4)

or, even though it's correct:

(+  1 2 3 4)

but:

(sum  1 2 3 4)

and it will feel more natural.

Likewise with -, think more along the lines of:

(subtract-from  x  y1 y2 y3)

and that should help.

2. Method calls aren't that different!

Functions are the first thing in every Lisp form (the stuff between the ()); since methods are functions, they come first! It's not really that different from Java's syntax though -- all you're doing is moving the starting paren to the front and swapping the positions of the object and method:

Java:

objectInstance.someMethod(arg1, arg2, arg3);

Clojure:

(.someMethod objectInstance arg1 arg2 arg3)

(You also lose the commas and semicolon!)

The (.someMethod objectInstance ...) is a special form that gets expanded out into a form using .: (. objectInstance someMethod ...). The latter feels weird because we're not used to thinking of the . as actually doing something when we're calling a method/property in Java; the former is the idiomatic way of doing things in Clojure anyway (reference).

New is similar:

new namespace.Object(); // Java

(new namespace.Object)  ; Clojure

"Difficult Things"

The "difficult things" you mentioned are actually there to make your life easier!!

You said in a comment that it was annoying to keep track of things when nesting expressions within expressions; the do and let forms are built specifically to help ease that difficulty.

Let's start with do

do lets you call things imperatively, one after another, without nesting:

(do (.someMethod objectInstance arg1 arg2)
    (.someOtherMethod objectInstance "foo" "bar" "baz")
    (.aMethod anotherObjectInstance 0))

The behavior of do is such that each of these method calls will be run in the order in which they're given and the return result of the last expression (in this case the return result of (.aMethod anotherObjectInstance 0)) is what is returned from the do block itself.

Each of these methods may or may not have side effects, and may or may not return a value (all of which but the last will be ignored).

Let

The let form does the same thing as do but it also gives you the ability to add local variables to the mix:

(let [foo "foo"
      bar "bar"
      arg1 (generateValueFrom foo)
      arg2 (generateValueFrom bar)]
  (.someMethod objectInstance arg1 arg2)
  (.someOtherMethod objectInstance foo bar "baz")
  (.aMethod anotherObjectInstance 0))

Again, the method calls will be run step by step in order, only this time they use the local variables defined in the let's bindings (the stuff between the []), and the last call's return value will be returned as the let's return value.

let is handy for breaking a bunch of nested calls down into something more sane; e.g.:

(reduce someCombiner {} (filter keepXs (map someTransform ys)))

becomes:

(let [txd (map someTransform ys)
      xs  (filter keepXs txd)]
  ; do the last call in the let's body so that
  ; its return value is what gets returned
  (reduce someCombiner {} xs))

Is The Synatx Worth It?

You bet your sweet bippy it is!

The Lisp syntax allows the language to have macros. Macros are functions that run at compile time that rewrite the code. What this means is that you can take code that is repetitititve or complex and write a macro that is simpler to call, and that macro will write the complex version for you.

For example, say we have the following do block:

(do (.someMethod      objectInstance arg1 arg2)
    (.aSillyMethod    objectInstance "foo" "bar" "baz")
    (.aSadMethod      objectInstance "alpha")
    (.anHappyMethod   objectInstance 1 2 3)
    (.someOtherMethod objectInstance \a \b \c)
    (.aMethod         objectInstance 0))

We have to repeat the same object instance six times! That's annoying. The doto macro can make things a bit lighter for us typing-wise:

(doto objectInstance
  (.someMethod      arg1 arg2)
  (.aSillyMethod    "foo" "bar" "baz")
  (.aSadMethod      "alpha")
  (.anHappyMethod   1 2 3)
  (.someOtherMethod \a \b \c)
  (.aMethod         0))

The doto macro allows us to specify the object instance once, up front, instead of having to repeat ourselves in the code later on -- it rewrites the expressions we give into the do block shown above. (This particular macro is similar to the with syntax some languages support.)

Now, this is a really simple example, but just imagine what sorts of coding tasks you could automate! And that's where the power of Lisp's macros comes in: you can write functions to make the programming language write your code for you!

Side Effects

You can still have side-effects in Clojure code, especially if you're doing interop with Java OOP since that OOP has side-effects. If you use more of the core Clojure code than Java, you'll not have as many side effects because it'll be more purely functional.

A lot of what I've found in my functional programming experience is that it's about partitioning the side-effect causing code from the purely functional code. You can do this in pretty much whatever language you're using (even Java).

Comparison to Scala

I've not used Scala, so I can't help you there. But hopefully the above was informative.


问:
Non Blocking Sockets vs Blocking sockets - UDP - C&linux
When to use blocking sockets over non blocking sockets on UDP?

Question 1:What's is recommended for the following scenario ?

Multiple clients send data over multiple UDP sockets, i.e. say client1 sends data over sockets 100, 101, 102,..,105 . client2 on sockets 110,111,112...115 etc. Port numbers are fixed for clients. Number of clients are fixed(10).
So totally 10 * 5 sockets.

Data on each sockets(atleast 3 sockets) is sent every few milliseconds.
The other 2 sockets are for sending commands and getting data.

After receiving the data there is some IO involved where i write to disks.
(I cant change any of the above. i.e. number of sockets ,etc )

Question 2:Is it best to use Threads for this scenario (or) Asynchronous IO multiplexing with nonblocking sockets?

答:
The usual way is to use poll() or select(), which ever you find more to your liking, with blocking sockets. Since they accept any file descriptors, same loop can be used for inter-thread or inter-process communication with a socket pair, or reading input from stdin.

A good, quite short and to the point, reading is Beej's Guide to Network Programming
Using Internet Sockets. Check out section about select() for a small example program source. That uses TCP and not UDP, so you'll need to do some adapting, but UDP will probably just make things simpler (unless your use case is re-implementing TCP functionality on top of UDP, which almost never is a good idea).

You may want to do processing in separate threads (or even processes, depending on requirements), or just inside that same loop, depending on how heavy this is: "After receiving the data there is some IO involved where i write to disks." I'd start with a single-threaded implementation and see how it goes, before making it more complex.


问:
How to learn/become capable of thinking out of the box?
In every problem solving there's always people who think differently, who come with a 6th option when only 5 were suggested by others, who think "out of the box". Please tell how one can achieve such ability? And what it takes to achieve it?</p>

答:
I read somewhere that those who consider themselves creative are the ones who are generally more creative in their work or brainstorming.  In other words, it strongly suggests that a creative person is a person who's simply not afraid of thinking differently.

I think a large part of "thinking outside the box" is getting a handle on the problem.  If you understand the problem well, you will see that sometimes the wording of the question is misleading or would lead people to think down a very specific path when in fact there remains an obvious solution standing in front of you.  The other day there was a question on stackoverflow.com in which a person was attempting to convert a input textbox into a textarea once it reached a certain number of characters (I think it was 10).  In his complicated solution, it would carry the 10 characters but nothing that exceeded it, which meant that typing quickly frustratingly removed anything beyond 10 characters.

With his code posted, many people were trying to correct it and provide suggestions to retaining the value.  I suggested he retain textarea and forget the textbox altogether, modifying only the attribute rows.  I saw outside the box not because I'm such a clever guy but because I tried to understand his objective:  make an text input field that grows with increasing text.  When you put it that way, it seems silly to start with a textbox and then replace it.

Just my 10 cents.  ;)