答:
People rarely split classes without a good reason.  Where they have trouble is in the details of how.  Before recombining the classes, try reassigning methods between the classes and consider introducing a third class.

If a method calls into another class, try moving the method to that other class.  This is sort of like converting a push into a pull.  It accomplishes the same task, just the other way around.  This exercise can sometimes greatly reduce the coupling.

The other thing that often helps is introducing a third class.  This can be in the layer above, containing instances of both objects and arbitrating between them, in the layer below, like a POD object to share data, or some kind of result object, similar to a database cursor.  A lot of people neglect this approach because it feels like instead of two tightly coupled classes you now have three, but this pattern is often instrumental in making the dependencies only flow one way.


问:
Is a pair of two tightly coupled classes any better than a single, larger class?
I'm rewriting somebody else's code at the minute, and I came across two classes which reference each other directly and call methods on each other. Like so (example in C#):

```<code>class A {
  B otherClass;
  public A() {
    this.otherClass = new B(this);
  }
  // Other methods here call methods on B
}

class B {
  A otherClass;
  public B(A otherClass) {
    this.otherClass = otherClass;
  }
  // Other methods here call methods on A
}
</code>```

Reading through his code and trying to understand it, I'm having to move between the two classes as they call each other.

These classes are not independently reusable without using the other. I'm aware it's considered best practice to avoid circular references (and it's straight up not allowed between C# projects in Visual Studio), but is this, or could this be, in your experience any better than having a single - larger - class?

答:
Class A and B could both derive from other classes, which would not be possible with a single class, since C# does not have multiple inheritance.

Sometimes this kind of mutual dependency seems quite natural. Think of a car/driver relationship. It would not feel natural combine both into one class.

It would however be better not to make both classes directly dependent on each other, but let them know about each other through interfaces. This would enhance modularity and would allow you to provide another implementation for one class, while leaving the other untouched.

ContentLicense: CC BY-SA 3.0


问:
Demonstrate bad code to client?
A client has asked me to do a redesign of their website, an ASP.NET Webforms application that was developed by another consultant. It seemed like a relatively straightforward job, but after looking at the code, it's clear that's not the case.

This application was not written well. At all. It is extremely vulnerable to SQL injection attacks, business logic is spread throughout the entire application, there is a lot of duplication, and dead end code that does nothing. On top of that, it keeps throwing exceptions that are being smothered, so site appears to run smoothly.

My job is to simply update the HTML and CSS, but much of the HTML is being generated in business logic and would be a nightmare to sort out. My estimate on the redesign is longer than the client was aiming for. They are asking why so long.

How can I explain to my client just how bad this code is? In their mind, the application is running great and the redesign should be a quick one-off. It's my word against the previous consultant. How can I give simple, concrete examples that a non-technical client will understand?

Update

Thanks for all the responses.
The SQL injection attack demonstration makes sense and I will demo this in a test environment.
That is just one part of many problems in this application. I was looking for ways to explain why other parts (such as html being generated in the data layer)
would need to be replaced with better practices in order for the html and css update to take place.
There are many good suggestions here which I'll piece together when I talk with my client.

答:
One point not really mentioned yet is that you might simply be overstepping what your client really wants from you in this case.  Overachieving is great and can give you lots of job satisfaction.  But if the client simply doesn't care, thinks current performance is "good enough" and just wants some minor updates, it may be impossible to persuade them to make a large investment in you to overhaul the codebase.

At that point you'll probably need to decide whether to stand on principles and refuse to take a job that would force you to attach your good name to a embarrassing code mess or whether you can hold your nose, get in, get the job done with some duct tape, and get out with your payment.

If you do decide to go ahead with the duct tape job though, make sure to document, document, document and be as transparent as possible.  The last thing you want is to get blamed for something going wrong in the future that is a result of an application flaw you warned the client about but that the client decided wasn't important enough to deal with at the time.

As far as the SQL injection risks go, as others have said you should be able to demonstrate to dangers of that to them in a way that shows the risks without actually doing anything destructive in production.  But again, if they see it and don't care enough to pay you to fix it, you've done your good faith diligence in this case.

Title: Demonstrate bad code to client?


问:
Annexes in Ada95
I want to know the differences between normative and informative annexes in Ada 95.

I am just able to find a list of each of them but not the differences.  What are the differences?

答:
A normative annex specifies what must be true of any Ada implementation providing that Annex.

An informative Annex provides additional description or rationale, but places no requirement on Ada implementations.

This is (roughly) the same distinction as between the Ada Reference Manual and the Ada Rationale.

Title: Annexes in Ada95


问:
Environment Variables and Visual Studio 2012
I have a problem with Visual Studio 2012 and Environment Variables under Windows 7.
I added a variable called {LIBS} with the value C:/libs/.
In C:/libs/ are folders containing C++ libraries.

So far, so good. I added the paths to the project's settings (linker etc.), like {$LIBS}boost to include the boost libraries.

I expected that I would now be able to use something like this

```<code>#include "boost/someboostfile"
</code>```

but this does not work, I have to use the absolute path

```<code>#include "../../boost/someboostfile
</code>```

but this is what I do not want to do.

Is there anything I'm doing wrong?

答: Use angle brackets- #include <boost/someboostfile>.


问:
Senior team members want to move query-relevant persistent data from DB to cache. Does this make sense?
I am a young engineer recently employed at a small company that sells products to the general public. We use Ruby On Rails and MySQL. Our database has a lot of customer data, but a great deal more of "static" persistent data. This data is so rarely changed that some of the more senior engineers have begun to talk about moving it to a cache data store. One of the touted benefits of this plan is that it would make deployments easier, since we would no longer have to bootstrap the database; instead, a lot of data would have permanent IDs, and we could just backup the cache and deploy the backup.

My query is related to the operational aspects of running the site once the change is done, not the change itself. We have persistent data that is used for database queries in response to user activities, which is used on a day basis. Putting it in a cache would remove our abilities to run SQL queries, instead querying the cache from RoR code. I don't have enough experience to judge if this is a good plan or not, but it smells funny to me.

Has anyone ever seen a situation similar to this, or have experience in this area? I'm looking for reassurance that this is not a crazy idea.

答:
I would agree that this does have a strange smell to it.  But as the new guy it's important that you really dig into the deployment process and understand the pain points before you argue against changes proposed by more senior team members, or you risk alienating yourself from your peers.

One question worth asking is why the MySQL deployment is such a burden.  I'm not sure why a production database needs regular re-deployments.  You should only need to deploy it once and populate it with data.  From that day on it should be straightforward to maintain and improve your DB with non-destructive schema modifications and data migrations against a live installation, so your data can live forever.

You'll also want to come from the other side and understand the caching solution being proposed, what the deployment overhead for that will be, and what practical functionality you will lose by switching (if any).  For example, it's straightforward for clients to integrate analytics tools against a DB with an SQL interface which is decoupled from your application logic.  Also, as a developer you will likely find that this decoupling gives you more flexibility to fix problems and improve your app without rolling a new code release.

Another question to ask is how your cache will be populated and how much data will go in it.  Caching implies non-persistent storage, which means you'll still need to populate it on each deployment.  It also means you'll need to have enough RAM in your production environment to store all of this data.  And anyway, caches are typically backed by some sort of persistent storage, such as a MySQL DB...another reason why this smells funny.


问:
"To code quickly, you must quit coding"
First off, not my phrase: http://www.whattofix.com/blog/archives/2010/11/to-code-quickly.php Props to Mr. Markham.

BUT, it got me to thinking about a lot of questions I have seen about being able to get things done.

The approach advocated (setting a timer for a set period, in this case 50 minutes, but I've seen people talk about breaking procrastination by setting times as short as five minutes on tasks that you just cannot bring yourself to do, and then taking a short break) seems to be common sense, but lots of people advocate getting into the "zone" and staying there as long as possible, maybe many hours, rather than break their groove.

I keep trying different approaches and find that each has its own strengths and weaknesses.

What kind of technique do you use to be more EFFECTIVE (i.e., getting work done to the quality level demanded by your client / boss / etc. in the time frame allowed) in your software development and not just to spend more time at the keyboard?

答: Since coding is the problem at hand, in addition to the techniques mentioned by Pierre, I would suggest coding in a dynamic language, if at all possible (Python is a delight to work with, for instance): such languages allow you to be extremely productive (measured coding times show an improvement factor of 2 to 10, compared to C).  They're so nice to work with that you might basically never "just spend time at your keyboard".</p>

ContentLicense: CC BY-SA 2.5

Title: "To code quickly, you must quit coding"


答:
Horrible idea. I have no problem with caching the data and updating it when the database changes but if you remove the data from the database you are likely to remove data integrity and make it impossible for things which do not use the applications, like reporting qeries or dataimprots to find the information they need. Further, ORMs do not write efficient code by and large and you might have to write some complex code in a stored proc to be able to performance tune it later. You are removing the ability to that effectively. </p>

<p>If someone suggested removing the lookup values from my database, I would be most unhappy as it would make it impossible to do my job and impossible to keep the integrity of my data. </p>

Title: Senior team members want to move query-relevant persistent data from DB to cache. Does this make sense?

Body:
I am a young engineer recently employed at a small company that sells products to the general public. We use Ruby On Rails and MySQL. Our database has a lot of customer data, but a great deal more of "static" persistent data. This data is so rarely changed that some of the more senior engineers have begun to talk about moving it to a cache data store. One of the touted benefits of this plan is that it would make deployments easier, since we would no longer have to bootstrap the database; instead, a lot of data would have permanent IDs, and we could just backup the cache and deploy the backup.

My query is related to the operational aspects of running the site once the change is done, not the change itself. We have persistent data that is used for database queries in response to user activities, which is used on a day basis. Putting it in a cache would remove our abilities to run SQL queries, instead querying the cache from RoR code. I don't have enough experience to judge if this is a good plan or not, but it smells funny to me.

Has anyone ever seen a situation similar to this, or have experience in this area? I'm looking for reassurance that this is not a crazy idea.

Body:
Horrible idea. I have no problem with caching the data and updating it when the database changes but if you remove the data from the database you are likely to remove data integrity and make it impossible for things which do not use the applications, like reporting qeries or dataimprots to find the information they need. Further, ORMs do not write efficient code by and large and you might have to write some complex code in a stored proc to be able to performance tune it later. You are removing the ability to that effectively.

If someone suggested removing the lookup values from my database, I would be most unhappy as it would make it impossible to do my job and impossible to keep the integrity of my data.


答: Do A and B have clearly separated concerns? If the answer is yes, it is good when they are kept as two separated classes. And if you want to avoid a circular reference, for example, to create unit tests for testing A and B separately, define interfaces for A, B or both and don't call methods of A in B directly, only by using the interface.</p>

Title: Is a pair of two tightly coupled classes any better than a single, larger class?

Body:
I'm rewriting somebody else's code at the minute, and I came across two classes which reference each other directly and call methods on each other. Like so (example in C#):

```<code>class A {
  B otherClass;
  public A() {
    this.otherClass = new B(this);
  }
  // Other methods here call methods on B
}

class B {
  A otherClass;
  public B(A otherClass) {
    this.otherClass = otherClass;
  }
  // Other methods here call methods on A
}
</code>```

Reading through his code and trying to understand it, I'm having to move between the two classes as they call each other.

These classes are not independently reusable without using the other. I'm aware it's considered best practice to avoid circular references (and it's straight up not allowed between C# projects in Visual Studio), but is this, or could this be, in your experience any better than having a single - larger - class?


答: When you have two classes jumping back and forth between each other, it could mean you didn't hit your abstractions correctly.  Combing that code into one class seems like it would break Single Responsibility(if it's not already broken) when keeping the SOLID principles in mind.  When I am trying to work my way through refactoring legacy code, what seems to work best is getting each class under test.  Your unit tests will help reveal what each class is trying to accomplish.    </p>


问:
What triggered the popularity of lambda functions in modern mainstream programming languages?
In the last few years anonymous functions (AKA lambda functions) have become a very popular language construct and almost every major / mainstream programming language has introduced them or is planned to introduce them in an upcoming revision of the standard.

Yet, anonymous functions are a very old and very well-known concept in Mathematics and Computer Science (invented by the mathematician Alonzo Church around 1936, and used by the Lisp programming language since 1958, see e.g. here).

So why didn't today's mainstream programming languages (many of which originated 15 to 20 years ago) support lambda functions from the very beginning and only introduced them later?

And what triggered the massive adoption of anonymous functions in the last few years? Is there some specific event, new requirement or programming technique that started this phenomenon?

IMPORTANT NOTE

The focus of this question is the introduction of anonymous functions in modern, main-stream (and therefore, maybe with a few exceptions, non functional) languages.
Also, note that anonymous functions (blocks) are present in Smalltalk, which is not a functional language, and that normal named functions have been present even in procedural languages like C and Pascal for a long time.

Please do not overgeneralize your answers by speaking about "the adoption of the functional paradigm and its benefits", because this is not the topic of the question.

答:
This isn't meant to be a serious answer, but the question reminded me of a cool humorous post by James Iry - A Brief, Incomplete, and Mostly Wrong History of Programming Languages which includes the following phrase:</p>

<p>"Lambdas are relegated to relative obscurity until Java makes them popular by not having them." </p>

Body:
This isn't meant to be a serious answer, but the question reminded me of a cool humorous post by James Iry - A Brief, Incomplete, and Mostly Wrong History of Programming Languages which includes the following phrase:

"Lambdas are relegated to relative obscurity until Java makes them popular by not having them."


问:
var args constructors/methods vs lists
In the long debate of using arrays vs lists in the public API of Java classes, I tend to prefer lists in most situations.
However, I also found convenient to use var arguments in many constructors and methods, which require declaring an argument of the method (the last one) as an array (implicitly adding "..." before the parameter name).

Since in many of these methods I do want to provide a programmer the possibility to either explicitly list the arguments (with var args) or use a pre-defined collection when invoking the method, I often end up defining a constructor or method with var arguments, and an overloaded version that accepts a list instead of the var args array. For example:

```<code>public void myMethod(X ...items) {
    myMethod(Arrays.asList(items));
}

private void myMethod(List<X> items) {
    ...
}
</code>```

I know that in theory I do not need to overload the method replacing the var args array with a list if I want the programmer to send a collection of objects. He could just send an array.

The reason I often do this is because most (if not all) of the methods in my API use lists instead of arrays, and it is a bit weird that for one or two methods requirying collection of objects, the programmer needs to work with arrays (in cases when the var args are not convenient).
So I provide an overloaded version working with list for consistency.

However, since this is a recurrent problem, I have the uncomfortable feeling of being writing boilerplate code too often. I would like to receive feedback if my motivation of keeping my interface consistent (accepting var arrays or lists, but not forcing the programmer to work with arrays if not really required) is valid enough to keep writing overloaded versions using lists for most of my methods requirying var arguments.

I would like to highlight that I know that for certain methods arrays could be more convenient than lists. My question concerns situations where the only motivation for declaring the last argument of the method as an array is because in certain scenarios using var arguments can be convinient.

UPDATE

Thanks for your feedback. My conclusions at the moment are the following:

Reduce the usage of var args as much as possible.

Continue adding an overloaded version of the method with var args, such as the array argument is replaced by a list (or an Iterable, as @Kevin pointed out), in cases where it can be useful to have the choice to invoke the method with either var args or with a collection.

Stop using Java as soon as possible :) (I already knew that one)

答: Varargs is a bad idea in modern languages. It was a simplifying assumption in C, but should never have made the jump to Java or C# (C++ can be forgiven because it really wanted to be a superset of C).  Any language that has a first-class List, even before generics and List<Object>, should be able to represent any varargs function much better with a list parameter.  And if you eliminate varargs completely, a lot of method signatures that are ambiguous with varargs cease to be without.

Title: var args constructors/methods vs lists


问:
How to Model a simple file-system by UML class diagram
I want to model a file system which contains both files and directories, and directories can contain either files or other directories.

This is what I have reached so far:

In OOSE book, however, a similar model is presented:

Now I have two questions:

I wonder why the author did not use an Interface to represent the abstract type FileSystemElement? Isn't using an interface for this type correct?

As we know, files and directories must have names with similar constraint (e.g. maximum length of 256 characters). Therefore, it would be nice if I model this in the FileSystemElement. But an interface cannot have a abstract attribute, so I have to repeat name attribute in both Directory and File classes. Is there any better workaround for this problem?

答:
I wonder why the author did not use an Interface to represent the abstract type FileSystemElement? Isn't using an interface for this type correct?

It would be correct, in so far as a valid UML model, as would be using an abstract base class. The design decision depends on other factors, quite often tied to implementation language.

But an interface cannot have a abstract attribute, so I have to repeat name attribute in both Directory and File classes. Is there any better workaround for this problem?

An interface can have attributes, and they are assumed to be abstract. How these abstract attributes are translated to real code will use different idioms for each different implementation language, and often different idioms between different users of the same implementation language. At the UML level, it's not a restriction at all.

As we know, files and directories must have names with similar constraint (e.g. maximum length of 256 characters). Therefore, it would be nice if I model this in the FileSystemElement.

There is no reason why you cannot put a UML constraint on an attribute of the interface. { Name.Length <= 256 } can be put on an attribute owned by an interface just as well as you would an attribute owned by any other classifier. How it would get implemented will differ both in the implementation language and in implementation strategy - perhaps you have a validate function which takes an instance of the interface, asks it for the name and tests the length. Translating UML constraints to code doesn't necessarily follow the 'throw an exception if you try to call the getter' pattern, though it often does.

It is possible that the author of the OOSE book had some implementation strategy in mind, and therefore uses a concrete class. Quite what I'd do depends on what else the classes are for - for example, if they are just placeholders for path fragments, and rely on something else to create a stream which opens the file, they you can test them completely without having an interface to mock, so I'd not bother with the extra layer of abstraction. If they had direct operations to return streams or perform other file system operations, I may well use an interface so they can be mocked for testing. Neither is correct, and which is a better fit for the requirements can't be determined from two very small UML diagrams.

A quick scan through the OOSE book you link to confirms that it is talking about class diagrams much in the same terms as you would ER-Diagrams and considering representing relationships between nouns, not what the objects do. I would caution that if you are considering nouns in static relationship then you are talking procedural rather object oriented code - perhaps that is why you are finding that the model presented in the book is concentrating on concrete types with attributes rather than an interface of operations.  Or perhaps it is just trying to demonstrate different types of associations and it's not worth looking too deeply at it!


问:
Good platform to teach Programming 101?
Years ago, I used to suggest Visual Basic 6 to rank beginners as a way to learn what programming is.  Key point:  This was NOT for career training, but just as a primer to the basic concepts of programming.  I subscribe to the KISS principle (many programmers do not)    Detest Microsoft as we may, the instant graphical nature of VB6 really helped kickstart things for the rank beginner (GUI control methods/events vs, cmdline programming)

VB may have been a "toy", but it allowed real programming concepts to be applied.   One could learn these UNIVERSAL topics in any language, including VB6:

Datatypes, variables and constants

Conditionals (If....Then....Else Blocks, Select Case)

Random number generation / seeding

Introduction to threads/timers

Loops (while loop, for loop)

Functions & procedures (and passing parameters)

Using arrays

GUI controls (properties, methods and events)

GUI animation (manipulating top, left, visible properties)

Creating and adding external modules

Debugging (breakpoints, watches, debug window)

What environment or platform would you suggest to use today?  Is Java/Eclipse making things too complex?  To some extent, I think Java is overkill for this type of goal (OOP, etc).  Would the path of least resistance be Visual Basic Express Edition 2012?  or something else entirely like some sort of smartphone IDE?  Or is that just too distracting, too complex, or too easy?   And what do you lose compared to VB (Think how trivial it is to learn basic animation with the Timer and .top and .left)  The KEY is to keep it EASY while not watering it down.

Again, suggesting some esoteric language just because it's more "elegant" misses the entire point.  What would you tell your neighbor's 15 year old kid to use if he wanted to know what programming is?  (He does not want to become a professional programmer, and is not a good independent learner)

Thank you.

答:
Its the results that matter - the satisfaction that you just made the computer DO something. That's what matters, in my opinion.

In other words, find something the kid wants to do and then use the simplest language to accomplish the task.

That's what basic was good for - it was readable, but it produced results that made you want to explore further.

I'd probably go with python. Maybe make a command line app that plays a wav file. Then as input, use a funny wav file :) You can then extend it to essentially become a sample bank. Kids usually get a kick out of stuff like that.

One reason I suggested python is that if you're successful in whetting an appetite for programming, kids will try and do more using what they already know. Python is a very relevant language and comes with a very rich library, which means what they can do with it, is a lot.

The other reason I suggested python is that with the language, the rule usually is: "The obvious way is the best". This encourages exploration and intuitive discovery, which, when combined with the fact that Python is actually used in production environments today means that it can translate into a real advantage down the line.

Title: Good platform to teach Programming 101?


答: For interactive learning, you might investigate something like Alice or Scratch. Both systems are graphical, designed for learning, free, and supported by large universities.</p>

Title: Good platform to teach Programming 101?

Body:
Years ago, I used to suggest Visual Basic 6 to rank beginners as a way to learn what programming is.  Key point:  This was NOT for career training, but just as a primer to the basic concepts of programming.  I subscribe to the KISS principle (many programmers do not)    Detest Microsoft as we may, the instant graphical nature of VB6 really helped kickstart things for the rank beginner (GUI control methods/events vs, cmdline programming)

VB may have been a "toy", but it allowed real programming concepts to be applied.   One could learn these UNIVERSAL topics in any language, including VB6:

Datatypes, variables and constants

Conditionals (If....Then....Else Blocks, Select Case)

Random number generation / seeding

Introduction to threads/timers

Loops (while loop, for loop)

Functions & procedures (and passing parameters)

Using arrays

GUI controls (properties, methods and events)

GUI animation (manipulating top, left, visible properties)

Creating and adding external modules

Debugging (breakpoints, watches, debug window)

What environment or platform would you suggest to use today?  Is Java/Eclipse making things too complex?  To some extent, I think Java is overkill for this type of goal (OOP, etc).  Would the path of least resistance be Visual Basic Express Edition 2012?  or something else entirely like some sort of smartphone IDE?  Or is that just too distracting, too complex, or too easy?   And what do you lose compared to VB (Think how trivial it is to learn basic animation with the Timer and .top and .left)  The KEY is to keep it EASY while not watering it down.

Again, suggesting some esoteric language just because it's more "elegant" misses the entire point.  What would you tell your neighbor's 15 year old kid to use if he wanted to know what programming is?  (He does not want to become a professional programmer, and is not a good independent learner)

Thank you.


答:
The first 'programming' I did was putting together TTL logic gates. Later, I grew up with BASIC and the BBC micro - a computer was something that sat in the corner and let you play sprite based games or do calculations or print letters on a dot matrix printer ( or generative art ). At university I got a warning from the department that my fractal generator was in the top ten cost items on the mainframe budget - but you needed something costly to do 2D graphics. My MSc was Phong shading surfaces in assembler, and a 386 based computer was just becoming a 3D graphics workstation. By the early '90s the web meant a computer was part of a world-wide research library. By 2000 a computer was starting to become primarily a means of communication, not computation. In 2013, computation has fragmented again - I have a workstation/games machine for 3D graphics, a tablet for reading books and web pages, and a few embedded Arduino and raspberry pi systems which control electronics and provide music. A lot of my current research is based on sensor nets ( formally called 'ubiquitous computing' before computing became ubiquitous ).

So what actually is programming about now?

Apart from C++, I can't think of anything which runs on examples of all those above, but for most tasks there's a more specific language to take away some of the pain.

I wouldn't expect someone who isn't planning to become a programmer to want to learn programming for its own sake. But I would expect anyone to get some satisfaction from taking a topic that they have an interest in and then creating something which relates to that.

If the interest is 'desktop computer', then perhaps Python on Raspberry-Pi - it's a BBC B for 2013.

If the interest is 'tabled computer', Android. The tablet is probably already the default computer for personal stuff. Create a simple game or controller.

If the interest is 'social computer', probably Python again, or Java and Hadoop - either way concentrating on algorithms and parallelism and connecting to web pages. Don't bother with details, but the algorithmic thinking and visualising how data can be correlated is probably going to be more useful than any syntax or type system.

If the interest is '3D workstation', you can do some beautiful things with either processing or cinder. Maybe through in a kinect into the mix. Making something beautiful which 'comes alive' in response to its creator is very satisfying, even if a bit Frankenstein. ( I found the cinder tutorials very good and easy to follow, but I'm not looking at them as a novice )

If the interest is 'sensor nets', then Arduino, which uses a very simple subset of C++ to add behaviour to the real world.

Of course these intersect - it's quite fun to create an Android app which controls a model train via Arduino, or a Processing view of your friendship graph on Facebook. But I'd look at what interests the audience, and focus on algorithmic thinking, privacy and why computers do the silly things we've told them to more than a particular language.

Title: Good platform to teach Programming 101?


答:
It's very hard to suggest something without thinking about the target audience. ie. University students would have a very different set of learning requirements to high school kids.

My suggestion would be to start with something that has a really simple GUI based IDE that lets you quickly and easily assemble a program with a minimum of technical requirements. So VB may still be a good choice in that regard. This lets you teach the basic ideas of coding such as how to make things happen when a button is pressed, basic code statements such as if/then/else and loops, and such things as graphics, i/o and simple networking.

Then I would pose the question of "How would you create a web or data server for the apps you have built?" and lead the students into the concepts of non-GUI based programming. At this point it might be a good idea to switch languages as well to something like Ruby or Node or something that is well suited to server concepts, yet can still keep it simple.

Along side this you can start to look at things like practices and patterns to introduce the concepts of design into the equation as at this point, the students work is likely to start getting complex enough to warrant discussions on these topics.

I guess my goal (and here I'll say I've no teaching experience to draw on) would be to teach the basics, but also give the students a view that covers more than just one language and method of development.

I believe that the most important thing you can teach is not any particular IDE or language, but the ability to analyse problems and determine the best tools to solve them.

Title: Good platform to teach Programming 101?


问:
Source code metrics for measuring code stability?
Considering how software is developed during a release cycle (implementation, testing, bug fixing, release) I was thinking that one should be able to see some pattern in the lines of code that are changed in the code base; e.g. towards the end of a project, if the code becomes more stable, one should see that fewer lines of code are modified per unit of time.

For example, one could see that during the first six months of the project, the average was 200 lines of code per day while during the last month it was 50 lines of code per day, and during the last week (just before the product DVD's were shipped), no lines of code were changed at all (code freeze). This is just an example, and different patterns could emerge according to the development process adopted by a particular team.

Anyway, are there any code metrics (any literature on them?) that use the number of modified lines of code per unit of time to measure the stability of a code base? Are they useful to get a feeling if a project is getting somewhere or if it is still far from being ready to release? Are there any tools that can extract this information from a version control system and produce statistics?

答:
One measure that Michael Feather's has described is, "The Active Set of Classes".

He measures the number of classes added against those "closed". The describes class closure as:

A class is closed on the date at which no further modifications happen to it from that date to the present.

He uses these measures to create charts like this:

The smaller number the gap between the two lines the better.

You may be able to apply a similar measure to your code base. It is likely that the number of classes correlate to the number of lines of code. It may even be possible to extend this to incorporate a lines-of-code per class measure, which might change the shape of the graph if you have some big monolithic classes.


问:
When to import names into the global namespace? (using x::y, from x import y etc.)
I've been programming in various languages for about 10 years now. And I still haven't figured out when it is a good idea to import something into the global namespace (using x::y in C++, from x import y in Python etc.), so I hardly ever do it.

It almost always seems like a bad idea to me, if only because it limits the set of variable names I can use. For example: Where I to use using namespace std; or using std::string;in C++, I couldn't use stringas a variable name anymore, which I occasionally do (e.g. for string utility functions).

But I'm wondering: Are there some situations where importing a name into the global namespace really makes sense? Any rules of thumb?

答:
You should do it when it simplifies your code.  You shouldn't do it when it would cause naming conflicts, or when it could be later brought into scopes where it would cause naming conflicts, such as a header file.

Some people think it should be rare.  I think (outside of header files) not using it should be rare, because the namespace prefix doesn't generally add any useful information, like using someone's full name every single time you address them.

Let me put it this way.  When you see string as a class name, do you automatically think std::string or mycustom::string?  It's like the old adage.  When you hear the sound of hooves, you think horses, not zebras.  In other words, using namespace std is almost always no big deal.  using namespace mycustom is likewise usually not a big deal, unless it contains a conflict with std, in which case your custom namespace is the one you want to always require the prefix for.


答:
As long as there is a relatively consistent mapping of features to classes, or for that matter, file system you could hook something like gource into your version control system and very quickly get a sense on where most of the development is focussed on (and thereby which parts of the code are the most unstable).

This assumes you have a relatively tidy code base. If the code base is a ball of mud, you will essentially see every little portion being worked on because of inter-dependencies. That said, maybe that in itself (the clustering while working on a feature) is good indication of the quality of the code base.

It also assumes that your business and dev team as a whole have some way of separating features in development (be it branches in version control, one feature at a time, whatever). If, for example, you're working on 3 major features on the same branch, then this method produces meaningless results, because you have a bigger problem than code stability on your hands.

Unfortunately, I don't have literature to prove my point. It is solely based on my experience of using gource on good (and not so good) code bases.

If you're using git or svn and your gource version is >= 0.39, its as simple as running gource in the project folder.

Title: Source code metrics for measuring code stability?

Body:
Considering how software is developed during a release cycle (implementation, testing, bug fixing, release) I was thinking that one should be able to see some pattern in the lines of code that are changed in the code base; e.g. towards the end of a project, if the code becomes more stable, one should see that fewer lines of code are modified per unit of time.

For example, one could see that during the first six months of the project, the average was 200 lines of code per day while during the last month it was 50 lines of code per day, and during the last week (just before the product DVD's were shipped), no lines of code were changed at all (code freeze). This is just an example, and different patterns could emerge according to the development process adopted by a particular team.

Anyway, are there any code metrics (any literature on them?) that use the number of modified lines of code per unit of time to measure the stability of a code base? Are they useful to get a feeling if a project is getting somewhere or if it is still far from being ready to release? Are there any tools that can extract this information from a version control system and produce statistics?


答:
The only justification for a client wanting a varargs that I can think of is simply a style argument where it doesn't "feel" right for a client to group things together in a collection on their side.

An example might be when your client has several DAOs which implement a common interface but talk to logically distinct data sources, like a Customer table and an Address table.  Although a client app might use a common interface to access this data, the query terms they use probably won't be the same for both (you might query Customers by last name but you wouldn't query Addresses that way).  Since a client typically wouldn't have a use case to iterate over a List of that interface, they probably won't have naturally stashed those two DAOs in a list.

However, lists are a more useful data structure to work with than arrays.  Dynamic memory allocation, .sublist(x,y), .clear(), iterators, etc are all handy to have which is probably why you are already in the habit of using lists on the backend.  So why not expect the client calling your API feel the same way?  Arrays.asList(item1, item2) is easy for a client to use, so I do not see a reason to provide the varargs API.  Only provide the List API.

In addition, I don't agree with Kevin's comment that you should specify the Iterable interface in your API.  You lose all of the useful APIs in the List interface just to save your client who has a set from calling "new ArrayList(set)" and passing that to your API.  At a minimum your API should take a Collection.

Title: var args constructors/methods vs lists

Body:
In the long debate of using arrays vs lists in the public API of Java classes, I tend to prefer lists in most situations.
However, I also found convenient to use var arguments in many constructors and methods, which require declaring an argument of the method (the last one) as an array (implicitly adding "..." before the parameter name).

Since in many of these methods I do want to provide a programmer the possibility to either explicitly list the arguments (with var args) or use a pre-defined collection when invoking the method, I often end up defining a constructor or method with var arguments, and an overloaded version that accepts a list instead of the var args array. For example:

```<code>public void myMethod(X ...items) {
    myMethod(Arrays.asList(items));
}

private void myMethod(List<X> items) {
    ...
}
</code>```

I know that in theory I do not need to overload the method replacing the var args array with a list if I want the programmer to send a collection of objects. He could just send an array.

The reason I often do this is because most (if not all) of the methods in my API use lists instead of arrays, and it is a bit weird that for one or two methods requirying collection of objects, the programmer needs to work with arrays (in cases when the var args are not convenient).
So I provide an overloaded version working with list for consistency.

However, since this is a recurrent problem, I have the uncomfortable feeling of being writing boilerplate code too often. I would like to receive feedback if my motivation of keeping my interface consistent (accepting var arrays or lists, but not forcing the programmer to work with arrays if not really required) is valid enough to keep writing overloaded versions using lists for most of my methods requirying var arguments.

I would like to highlight that I know that for certain methods arrays could be more convenient than lists. My question concerns situations where the only motivation for declaring the last argument of the method as an array is because in certain scenarios using var arguments can be convinient.

UPDATE

Thanks for your feedback. My conclusions at the moment are the following:

Reduce the usage of var args as much as possible.

Continue adding an overloaded version of the method with var args, such as the array argument is replaced by a list (or an Iterable, as @Kevin pointed out), in cases where it can be useful to have the choice to invoke the method with either var args or with a collection.

Stop using Java as soon as possible :) (I already knew that one)


问:
Migrating from PHP to ASP .NET MVC
I plan on migrating a website from PHP to ASP .NET MVC. However, since the website is large and this migration can't be done in a short time I plan to use both MVC and PHP pages together. So the idea is to replace each PHP page or group of pages with an MVC equivalent.

I have to refactor each page and rewrite it overall anyways so I thought I might as well move to the ASP .NET MVC framework for various reasons.

The question is, does anyone know what are some of the problems I will face while doing this?

Here are some I thought of:
- Logins
  - I plan to overcome this with an ajax request to the ASP .NET website on the background and keeping the login information separately for asp .net.
- Sessions
  - I'm not sure how I can share sessions or if I will even need to.

Other than that, I'm not sure if anything else will arise.

Anyone experienced that have a few things to say?

答:
I'd recommend that you develop the ASP .NET MVP as a sub-service layer to the existing PHP, and then slowly replace all functionality in the ASP. Once that is done you can then build a new top layer in .NET and switch over.

You do this by having the ASP.NET service listen to the localhost on a different port (i.e. 1080). Each time a request comes into the PHP code, you can slowly replace chunks by passing the call to the ASP.NET service as a REST API request.

Over time the majority of the business logic will be moved to the ASP.NET service, and then you can switch over with a new layer that doesn't use the REST API.

Title: Migrating from PHP to ASP .NET MVC


问:
Effective ways to make your OSS project popular?
After writing a few (relatively obscure) OSS frameworks, I've learned the hard way that writing a good framework isn't enough--there has to be some time spent marketing your framework as much as the time you spend coding it. So here's my question: What are some effective ways for making your OSS project become well-known? Aside from blogging, how do I gain the most market attention for my code with the least amount of effort as humanly possible?

(EDIT: I'm a lazy programmer and I hate documentation, but I'm biting the bullet. I want to be famous)

答:
All of the above + read Producing Open Source Software

...a book about the human side of open source development. It describes how successful projects operate, the expectations of users and developers, and the culture of free software. The book is released under an [open copyright](Producing Open Source Software)...

Paper version is available, as well as online at link referred above: html, EPUB, PDF etc.


问:
System requirement specification vs functional one - separate docs?
A lot of sources (e.g. Wikipedia) mentiones System requirement specification and Functional specification as two separate entities.
However, Wiegers in his book writes:

The software requirements specification is sometimes called  a
  functional specification, a product specification...

This is very confusing for me as I thought FS describes just functions while SRS whole system. From this point of view, FS would contain both non functional and functional requirements and everything else.

答:
There are many different ways that things can be structured, but this is one take on it:

System Requirements Specification (SyRS) : This is the high-level engineering document that enumerates the requirements on how the system is to function. It is not a software-only document; if the system involves hardware, or multiple software components, then it describes them as well.

Software Requirements Specification (SwRS) : This is a complete description of the requirements of a single software component.

Either of these two documents could be called a "functional specification". It depends on the scope of what you are talking about.

UPDATE:  Generally, the SyRS should only contain those requirements / functional specifications that apply to the system as a whole. A greenfield SyRS does not decide what the system architecture is; that is for the design document.

The design document (call it System Architecture Document, SyAD) decides what software components are required and how they interface to each other.

The SwRS for each defined component is then a much more detailed functional specification of how each individual component works.

Sometimes, to ensure consistency of UI for example, it makes sense to bundle common requirements into the SyRS.

This can get confusing, but the test plan and test cases for each software component should pull the appropriate specifications from the appropriate place(s).

Requirements management tools like DOORS allow cross-linking between requirements docs (and traceability from product concept to final delivery).

Does Functional Requirement Specification talk about system design?

No, that should be handled by a design document.

should there be a single system requirements document and individual SRS for all the applications?

Yes, that sounds like a good way to proceed.

I also assume that functional requirements strictly deals only with requirements and not the design

Yes, the two are distinct, but people often confuse them.

Could each line of a pseudo code be defined as functional requirement eg: System B must pass emp id , name to System C on receipt of request from System A.

The example you quote certainly sounds like a system-level functional requirement. Just be careful not to include in the SyRS something like "and emp id must be in the form of a GUID".  The only reason to include technical detail like that in an SyRS is if there is some constraint on the system (like all incoming or pre-existing emp ids are GUIDs).

Where I am getting this from is from the approach to Systems Engineering called the "design V" (sometimes the design W). See Wikipedia for more, though in an "Agile" world some of this gets forgotten.


答:
The key thing to remember here is that there is no "one size fits all" solution.

There are lots of techniques for improving your ability to "get things done" and one of the reasons is that different things work for different people.

Some people do very well with this sort of methodology (c.f. Pomodoro Technique) and some people will find it destroys their focus - I really don't like stopping in mid task and that's almost invariably what timer based systems do to me... conceptually good, implementation challenging (true of the majority of structured methodologies for time management and other things)

Title: "To code quickly, you must quit coding"

Body:
First off, not my phrase: http://www.whattofix.com/blog/archives/2010/11/to-code-quickly.php Props to Mr. Markham.

BUT, it got me to thinking about a lot of questions I have seen about being able to get things done.

The approach advocated (setting a timer for a set period, in this case 50 minutes, but I've seen people talk about breaking procrastination by setting times as short as five minutes on tasks that you just cannot bring yourself to do, and then taking a short break) seems to be common sense, but lots of people advocate getting into the "zone" and staying there as long as possible, maybe many hours, rather than break their groove.

I keep trying different approaches and find that each has its own strengths and weaknesses.

What kind of technique do you use to be more EFFECTIVE (i.e., getting work done to the quality level demanded by your client / boss / etc. in the time frame allowed) in your software development and not just to spend more time at the keyboard?


问:
Most secure method of asynchronous exchange of randomized loot in a strictly offline ARPG
I'm interested in the conceptual (programming language agnostic problem) process of sending a game object to another player of the game in exchange for another game object without a face-to-face online presence of both parties. This should be done so that in theory in game exploitation of inherent bugs of the trading system would not be possible to dupe items or steal items from another player. In this case I am not considering cheaters, (I strictly define cheating as manipulating of in game RAM/saves and NOT exploitation of programming/inherent bugs/flaws) only the ability of users to dupe or steal items from strictly within the game itself.

Possible method idea to solve this:

Player 1 (P1) and (P2) meet out of game to arrange a trade of in game loot and come to an agreement amongst themselves.

Both players go in game to set up the trade by giving their item "to the game" to hold and remain inaccessible for the duration of the trade. In exchange they are given a procedurally generated alphanumeric encryption code (such as pokemon mystery dungeon or similar) specific to themselves and the other player's name and ID number (similar to the mainstream pokemon games)

Both players share their codes with each other and enter the opposite code into their game.

a confirmation screen appears for both players showing the other player's offer. if a player accepts the offer they are given another code to give to the other person.

Both players enter in the other's confirmation code to their game and both players receive their item in game.

not sure but may additionally need both players enter in a thank you code to truly confirm both players got their items, but I think that is covered by the confirmation code because if P1 confirms and gets P2's confirm then that means P2 confirmed also. And likewise if P2 confirmed and received P1's confirm then P1 confirmed.

But as I think of it, if P1 accepts and P2 accepts and P1 gives the code but then P2 does not, then P2 is able to get his desired item at the cost of his item and P2 is now a scammer to P1 because P1 was denied his new item, (it vanished) It would cause players to incrementally trade items of lesser worth because they wouldn't stand for losing that great loot they couldn't use but would still be valuable; wasting people's time and discouraging trade. Also a thank you code would add time to the process and not cause any added security. I actually think this is a real world problem of agreements, trading goods, and trust that requires synchronous trade. I think this cannot be solved in a game any more so than in real life. Correct me if I am wrong.

答:
escrow

n. A bond, deed, or other document kept in the custody of a third party, taking effect only when a specified condition has been fulfilled.

Let the system (the third party) administer and fulfil the contract.  The contract is that two players agree on a set of items to trade.  This solution also assume the players are strangers and will never meet in real life.

Alice offers a +1 Sword for sale.

System takes the +1 Sword from Alice.

System advertises the +1 Sword for sale.

Bob makes an offer of 1000 gold.

System takes 1000 gold from Bob.

System alerts Alice of the offer.

Alice counteroffers, requesting 1000 gold and a Healing Potion.

Since the offer was effectively declined, System returns 1000 gold to Bob.

System alerts Bob of the counteroffer.

Bob accepts the counteroffer.

The contract is fulfilled.

System takes 1000 gold and a Healing Potion from Bob.

System closes the advertisement.

System gives Bob the +1 Sword.

System gives Alice the 1000 gold and Healing Potion.

Or, at any time:

Alice retracts the sale.

System closes the advertisement.

System returns the +1 Sword to Alice.

System returns any held items to Bob (and other players who have made offers.)

With concern to cheaters, you will never stop someone from modifying local save files.  The inventory must be replicated on a secure server and validated before any sale takes place.  It should also validate before the player uses items.  If a player hacks their character to have a +58 Sword of Oblivion, they can acquire wealth a lot faster than honest players.  If they sell their ill-gained loot, they can damage the economy.


问:
Which Open Source License is right for my project?
I'm developing a suite of software tools that I need help with which is why I want to release my software open-source. People should be able to use and modify my code as they please while contributing to my project. Ultimately, the tools that I develop will require a paid commercial license, but may be free to those for non-commercial purposes. This software suite will consist mostly of website plug-ins. Other tools I develop open source be used for consulting.

What would you suggest as a license?

答:
Disclaimer: talk to an attorney.  I am not an attorney.

You are contemplating the need to be able to dual-license your software someday down the road.  The authority to licence something is derived (directly or indirectly) through owning the copyright to the materials.

Therefore, you NEED to get copyright assignments from all contributors, or at a minimum, have them sign an agreement which gives you the unlimited right to sublicense/relicense the materials.

As for the open source part of the dual licence, that is your pick.  If you wish to prevent it from becoming part of a closed-source product, then you should pick a viral licence like the GPL.  If you are not so worried about that, then the BSD or Apache license would be quite suitable.

In summary:

If this matters to you, consult an attorney

You need to have the legal authority from the copyright holder to licence the software as closed source.  This means either they transfer the copyright to you or you are granted liberal rights to this.


问:
In Agile development, who owns the software "features" and how to you manage the development?
Some development teams in my company are switching to Agile development practices and their developers' work seem to be diminishing to discuss and program minutia about trivial software features because of two week iteration cycles. And also because of "any developer can fix any bug" mentality. I have recently joined one of those team, transferring from another team in the same company...

I feel strongly that developers should own their software features from start (design) to finish (implementation and unit testing).  Agile seems to be going counter to this thinking. Is there any truth to my perception or am I just living a bad implementation of Agile?

During our two week iterations, people somewhat arbitrarily get assigned new little features and bug fixes, depending on their workload during that cycle. Nobody seems to be owning responsibility of major features of the software. We spend stupid amount of times on trivial things, like adding a single button to a dialog during a two week iteration, complete with a story, daily scrums, code review, etc.

So in Agile projects, how does one manage larger features? Who own the responsibility: individual developers or the whole team?  How does one extract him/herself from minutia and focus on longer term goals?  Any feedback would be valuable.

答:
The way I do it, with a low level of pain, is to have each developer be responsible for a card on the board, from when it is picked up from the TODO list until it has moved to DONE.    The owner of the feature, as far as what functionality goes into the feature are the Team Lead, SME, and BA.  Each team has a Team Lead (the technical expert and advocate), a Subject Matter Expert, and a Business Analyst.

Typically the BA is the guy/gal that fields the questions from the developer currently working on a card.  We all work in the same room, so if either the Team Lead (me), the BA, or the SME hear something that we disagree with, we jump in and take the developer into a breakout room to discuss further.  Typically the three of us will bring the members of the other three in if we feel they can be of value to the discussion.

Admittedly it sometimes leads to some time wasting while we discuss a problem, but generally we get to a good solution quickly.

Ultimately it is the Team Lead that signs off backlog items as being ready for development and it is the team lead that has the final say when a decisions needs to be made and is  responsible if the implementation is "wrong". (Don't ask about the "wrong" blame game :/).

Any other developers hearing the conversation are encouraged to offer input and all team members have input during the showcase at the end of the sprint, when new features are demoed.

tl;dr (for us): The Team Lead owns the features and an individual developer works on a feature card (or bug, improvement, technical debt etc) from start to acceptance by the test team).


答:
In order to answer your question I will try and give a description of how we handle the situations mentioned in your question:

We use the Scrum framework in Agile. Sprint Planning and backlog grooming sessions assist our team to have broken down, relatively-properly defined stories.

All in all a team as a whole is responsible for the outcome of commitments for a sprint (all the stories). They succeeds or fail as a team. Thus the team as a whole would influence how work must be managed to get the job done in the sprint.

Story cards taken by a developer (in the standups) becomes that developer's responsibility to get it done and signed-off, ready for release at the end of the sprint. However the team should use the daily standups to see if anyone seems to be struggling with they story and then proceed to assist the dev to complete his outstanding tasks.

In our case, with Scrum, if anything is given to us which was not part of the original sprint commitment we add it as 'unplanned work' and our product owners know that unplanned effort added may result in our original commitments not being met. We also have a flat structure in the team, so that no one person should play a managing role and everyone is then motivated to not let the team fail as everyone is equally responsible for the work.

Title: In Agile development, who owns the software "features" and how to you manage the development?

Body:
Some development teams in my company are switching to Agile development practices and their developers' work seem to be diminishing to discuss and program minutia about trivial software features because of two week iteration cycles. And also because of "any developer can fix any bug" mentality. I have recently joined one of those team, transferring from another team in the same company...

I feel strongly that developers should own their software features from start (design) to finish (implementation and unit testing).  Agile seems to be going counter to this thinking. Is there any truth to my perception or am I just living a bad implementation of Agile?

During our two week iterations, people somewhat arbitrarily get assigned new little features and bug fixes, depending on their workload during that cycle. Nobody seems to be owning responsibility of major features of the software. We spend stupid amount of times on trivial things, like adding a single button to a dialog during a two week iteration, complete with a story, daily scrums, code review, etc.

So in Agile projects, how does one manage larger features? Who own the responsibility: individual developers or the whole team?  How does one extract him/herself from minutia and focus on longer term goals?  Any feedback would be valuable.


答:
Robustness is a term relating to the correct function of an instruction set, not the quantity, verbosity, terseness, grammatical correctness of the text used to express those instructions.

Indeed syntax is important and must be correct but anything beyond that, as it pertains to the desired function of the instructions by looking at the 'metrics' of the instructions is akin to plotting your future by reading the pattern of tea leaves at the bottom of you tea cup.

Robustness is measured by way of tests. Unit tests, smoke tests, automated regression tests; tests, tests, tests!

My answer to your question is that you are using the wrong approach in seeking an answer to one of robustness. It's a red herring that lines of code means anything more than code occupying lines.  You can only know if code does what you want it to do if you test that it is doing that which you require of it.

Please revisit proper test harnesses and avoid code metric mystisism.

Best wishes.


问:
How is a 256 bin HSV histogram quantised?
I am doing some research on the ScalableColor descriptor in MPEG-7 and I came across this passage:

The descriptor extractions starts with the computation of the colour
  historgam with 25 bins in the HSV colour space with the Hue (H)
  component quantised to 16 bins, and Saturation (S) and Value (V)
  quantised to 4 bins each.

My statistics is a little rusty so could someone please explain (hopefully with an example) how the bins are quantised?

答:
Quantisation is simply a transformation from a large range of possible values into a smaller range of possible values.

In the HSV colour space, Hue takes values from 0 to 360 degrees, while Saturation and Value take values from 0 to 1. I believe (though I'm not positive) that for this process in Mpeg7 the quantisation is uniform, which would mean:

To get our Hue from a range of 0-360 into 16 bins, we would simply divide by 360/16, or 22.5, and then round down. So:

```<code>Hue    Quantised
0      0
22     0
23     1
44     1
45     2
...
337    14
338    15
359    15
</code>```

(One minor quibble: We need to map a hue of 360 to 0 before starting)

For Saturation and Value, we need to get from a range of reals in 0-1 into 4 bins, so we divide by 1/4, or 0.25, and round down:

```<code>Value   Quanitised
0       0
0.24    0
0.25    1
0.49    1
0.5     2
0.74    2
0.75    3
1.0     3
</code>```

(Here we have to make a call on rounding the quarter points)

In general, to quantise uniformly from a range of x-y into n bins, each bin gets a slice of width (y-x) / n in the original range.

You'd need to check the mpeg7 spec for whether this quantisation is to be carried out uniformly, though.

Body:
Quantisation is simply a transformation from a large range of possible values into a smaller range of possible values.

In the HSV colour space, Hue takes values from 0 to 360 degrees, while Saturation and Value take values from 0 to 1. I believe (though I'm not positive) that for this process in Mpeg7 the quantisation is uniform, which would mean:

To get our Hue from a range of 0-360 into 16 bins, we would simply divide by 360/16, or 22.5, and then round down. So:

Hue    Quantised
0      0
22     0
23     1
44     1
45     2
...
337    14
338    15
359    15

(One minor quibble: We need to map a hue of 360 to 0 before starting)

For Saturation and Value, we need to get from a range of reals in 0-1 into 4 bins, so we divide by 1/4, or 0.25, and round down:

Value   Quanitised
0       0
0.24    0
0.25    1
0.49    1
0.5     2
0.74    2
0.75    3
1.0     3

(Here we have to make a call on rounding the quarter points)

In general, to quantise uniformly from a range of x-y into n bins, each bin gets a slice of width (y-x) / n in the original range.

You'd need to check the mpeg7 spec for whether this quantisation is to be carried out uniformly, though.


答:
The Agile process is defined by the team for the team following guidelines and it can differ from team to team. In most cases it does, I haven't seen two different teams that mirror the same process in my professional experience. Basically the idea is to have the most efficient development, which in some cases means that different people work on features in the same code base and in other cases one person is the feature owner from beginning until the feature is complete.

Basically larger features (let's call them user stories) can be broken down in smaller user stories and still one and the same person can be the owner of the feature spreading those user stories across several sprints. Also accordingly the person can be a feature owner and not do all the work for the feature. E.g.

Scenario:

Large feature estimated to take 6 weeks (3 sprints).

The feature is broken down into several user stories each taking up
to two days.

The user stories include feature development, unit tests, interaction
tests, integration (with other features), and integration testing

The team is technically the feature owner but a developer can act like one.

The dev writes the functionality

The dev writes the unit tests

A quality engineer writes the automation

Another dev ensures the integration

In this scenario there are at least 3 people (we may have more than one QE on duty) responsible for the feature delivery but the developer is owning and in a sense driving the feature. This, of course, requires more dedication to this specific feature on the part of the developer but it is in no sense out of the Agile scope and at the same time we have single feature owner.


问:
How long do programmers generally stay in industry?
One thing that I've heard a lot over the years is that those working in the IT world generally don't make life time careers out of it, but tend to "burn out" and start a new career doing something else unrelated (e.g. going from software development to being an accountant).

Have you found this to be generally true in your experience and if so, what is the general impression on how long people work as developers before starting a new career?

答:
Well, personal experience counterpoint.  I'm rapidly approaching 40 (a few months to go) and am looking for a way out of development because ... I've just had enough.  I work in a great place with interesting people, but find programming itself to be frustratingly grey, drudging and uninspiring work for me.  (Other people's experience, thankfully, differs!)

It is really fantastic to read the experiences of people who are lovingly engaged in the crafting of software; people for whom the work is fulfilling and inspiring.  I have friends who just love development, and who relish the challenges it presents.  But I am not one of those people.  It's not that I can't do the work -- hell, I wouldn't have survived a dozen + years in this business if that was the case.  I just don't like it.

As for me, I'm busy trying to navigate my way back into my first career (which I foolishly left when I found that (a) I could program, (b) people would willingly pay me for this, and (c) I needed to pay the rent).  So I'm heading back into research science, and the warm feeling that fills me when I walk into the lab, when I talk with colleagues in that space, and when I apply my mind to the challenge of unraveling how the world works, and where I use reasoning and analytical skills (at least) as challenging as in software, tells me that this really is about different careers appealing to different temperaments.

So this "old" programmer is just busy reinventing himself and moving on :)  (Even though that will mean something of a financial risk)
Pax


答:
From what I see most answers concentrate on explaining why functional programming in general made it's comeback and made it's way into mainstream. I felt this however doesn't really answer the question about anonymous functions in particular, and why they suddenly got so popular.

What has really gained the popularity, are closures. Since in most cases closures are throw-away functions passed variable, it obviously makes sense to use anonymous function syntax for these. And in fact in some languages it's the only way to create closure.

Why have closures gained popularity? Because they are useful in event-driven programming, when creating callback functions. It's currently the way of writing JavaScript client code (in fact it's the way of writing any GUI code). It's currently also the way of writing highly efficient back-end code as well as system code, as code written in event-driven paradigm is usually asynchronous and non-blocking. For back-end this became popular as solution to C10K problem.

Title: What triggered the popularity of lambda functions in modern mainstream programming languages?

Body:
In the last few years anonymous functions (AKA lambda functions) have become a very popular language construct and almost every major / mainstream programming language has introduced them or is planned to introduce them in an upcoming revision of the standard.

Yet, anonymous functions are a very old and very well-known concept in Mathematics and Computer Science (invented by the mathematician Alonzo Church around 1936, and used by the Lisp programming language since 1958, see e.g. here).

So why didn't today's mainstream programming languages (many of which originated 15 to 20 years ago) support lambda functions from the very beginning and only introduced them later?

And what triggered the massive adoption of anonymous functions in the last few years? Is there some specific event, new requirement or programming technique that started this phenomenon?

IMPORTANT NOTE

The focus of this question is the introduction of anonymous functions in modern, main-stream (and therefore, maybe with a few exceptions, non functional) languages.
Also, note that anonymous functions (blocks) are present in Smalltalk, which is not a functional language, and that normal named functions have been present even in procedural languages like C and Pascal for a long time.

Please do not overgeneralize your answers by speaking about "the adoption of the functional paradigm and its benefits", because this is not the topic of the question.


问:
What is a "Business Intelligence" Developer?
What traits / skills does the Business Intelligence Developer role expect over a traditional Web Developer role?</p>

答:
A BI developer may actually not have any web development know-how at all.

Core skills of a BI developer would be in-depth knowledge of databases, data mining, data warehouses, etc. There's probably a bunch of proprietary systems (e.g. Oracle BI Suite) that a BI developer would be expected to know (and have specialized in one or two of them).

Domain knowledge of the business in question would be a big plus as well.


答:
Licensing some part of the code under open-source license means that this part will be always open-source. Then you can't control how the people will use it. If you choose copyleft license, you only can be sure that no one will be allowed to use this code for closed source projects.
If you choose some permissive license - then everyone will be allowed to create whatever projects he wants based on the released code.

If you can keep all copyright for you (and this can be done only by additional agreement with the contributors) then you (and only you) can use this open source cpde for closed source projects. Also, later you can decide to stop releasing the new versions under open source license. (but not the already released versions) - in this case (if your project is really attractive) the project will be forked and all contributors will move to work on the open source fork.

Title: Which Open Source License is right for my project?

Body:
I'm developing a suite of software tools that I need help with which is why I want to release my software open-source. People should be able to use and modify my code as they please while contributing to my project. Ultimately, the tools that I develop will require a paid commercial license, but may be free to those for non-commercial purposes. This software suite will consist mostly of website plug-ins. Other tools I develop open source be used for consulting.

What would you suggest as a license?


问:
Demonstrate bad code to client?
A client has asked me to do a redesign of their website, an ASP.NET Webforms application that was developed by another consultant. It seemed like a relatively straightforward job, but after looking at the code, it's clear that's not the case.

This application was not written well. At all. It is extremely vulnerable to SQL injection attacks, business logic is spread throughout the entire application, there is a lot of duplication, and dead end code that does nothing. On top of that, it keeps throwing exceptions that are being smothered, so site appears to run smoothly.

My job is to simply update the HTML and CSS, but much of the HTML is being generated in business logic and would be a nightmare to sort out. My estimate on the redesign is longer than the client was aiming for. They are asking why so long.

How can I explain to my client just how bad this code is? In their mind, the application is running great and the redesign should be a quick one-off. It's my word against the previous consultant. How can I give simple, concrete examples that a non-technical client will understand?

Update

Thanks for all the responses.
The SQL injection attack demonstration makes sense and I will demo this in a test environment.
That is just one part of many problems in this application. I was looking for ways to explain why other parts (such as html being generated in the data layer)
would need to be replaced with better practices in order for the html and css update to take place.
There are many good suggestions here which I'll piece together when I talk with my client.

答:
I'm going to play devil's advocate here (somewhat along the lines of what @khrome is saying: "you are not paying clients to make your life easier"). I would even go as far as stating that the case you presented is too one-sided because you described the case in a general manner.  Most incoming consultants to a new project would shine a bad light to the previous one...I'm not saying that's what you are doing here, but until we see examples, I cannot simply take your word for it.

That said, I'm going to try to address the issues to you point by point:

SQL Injections.  OK, so I guess the programmer was using string concatenations instead of parameterized queries and/or stored procedure.  This is very easy to fix especially in ADO.NET...I personally would mention it to the client but not make too much of a big deal out of it.

HTML is being generated in business logic and would be a nightmare to sort out. OK, dude, this is one of those where you give me more details.  Unless you're using MVC, this is a tendency to happen...but it's not necessarily a bad thing...it's one of those things where most programmers would say "goto is bad; never use it" but you know what?  I've used goto where it made sense!  So, are you sure they're not using helper classes that happen to be sharing the same namespace as the business code DLL?  Again, it's not that difficult to isolate.

business logic is spread throughout the entire application, there is a lot of duplication, and dead end code that does nothing..  And?  Client is just asking you to change HTML/CSS.  Why would you care about these issues at all?

it keeps throwing exceptions that are being smothered, so site appears to run smoothly.  Again, very vague.  Exceptions are normal in any applications, that's why we have try/catch clauses in our code.  Unless they bubble up in UI and ruin the user experience (like displaying HTTP 500's unnecessarily), I don't think this is something that you should care about, either..

So in short, I would advise you to take the high road. If you think it's not worth your time and you want to rewrite it at the expense of your client, then walk away from the job.  Seriously, at the end, the client pays for your time to make the whole thing work with the least amount of $$$.

In my many years of experience in the field, I always say that the best programmers I've come across are the ones who can make a system stable by writing the least amount of code, not by rewriting the whole thing.

Edit: I already see that my answer is not the most popular one (I already expected this) but I stand by my response.  I edited this to make it less snarky. ;-)

Title: Demonstrate bad code to client?


问:
Usefulness of pre and post order traversal of binary trees
This may be very naive, but I was wondering, it the context of binary trees (plain, sorted and balanced), of all the traversal types:

depth-first pre-order

depth-first in-order

depth-first post-order

breadth-first

what's the actual utility of pre and post-order ones? I mean, is there some type and/or configuration of binary tree in which pre and/or post-order traversal would give an(some) advantage(s) over the other two?

AFAICS, there are certain types and configuration of binary trees for which in-order and breadth-first might give a certain advantage:

for a balanced binary tree any depth-first traversal will use less memory storage space as compared to breadth first (eg. for balanced binary tree of 6 or 7 nodes, height is 2 so any depth-first traversal will need to store a max of 2 nodes at any given time, while last level has 3 or 4 nodes so breadth-first traversal would need to store up to 3 or 4 nodes at some point). In this case using in-order traversal uses the least amount of memory and visits the nodes in their natural order.

for a non-balanced binary tree, if it's close to the worst-case insertion scenario, traversing it breadth-first would use less memory as compared to any of the depth-first traversals. So in this case breadth-first offers an advantage. In-order traversal has the again the advantage of visiting values in their natural order.

However I can't think of a situation where pre and post-traversal would give an advantage over the other two.

答:
The point of having different algorithms to deal with binary trees is not to do things with trees. On this abstract level, one order is largely as good as any other, since you only get abstract symbols out of the procedure.

But trees are typically used to represent interesting stuff, and that can make a big difference in the outcome. For instance, if the nodes represent search states in a complete search through a big domain (maybe even an infinite domain), descending first vs. processing first not only determines in which order the results are found, it can even determine whether you will ever find any solutions at all. The point is easiest to see with infinite domains: if you descend incautiously, you might overlook a solution that lies quite high up in the tree, simply because you took a wrong turn. But in practice, since memory and disks are finite as well, this even applies to domains that are simply very large rather than truly infinite.


问:
Entity Framework as a type checking/verification system for database code
When I read pro and con lists of using Entity Framework (or any modern ORM really), I'm surprised that the following point doesn't arise (self quote):

Using strongly-typed domain entities allows for type checking at
  compile-time which essentially performs a verification of all your
  database operations.  This is something that is not possible with
  ADO.NET (whether using inline SQL or stored procedures).

For me, this is one of the biggest advantages of using an ORM.  An issue that I come across regularly when dealing with ADO.NET based applications are the run-time errors from SQL.  Static checking completely eliminates this.

Could anyone elaborate as to why this isn't hugely relevant to many developers?  It appears that some don't even agree with the above statement.

Example of some pro & con resources:

Entity Framework VS LINQ to SQL VS ADO.NET with stored procedures? (stackoverflow)

Five Reasons for using an ORM Tool

Why use the Entity Framework? Yeah, why exactly?

答:
What you mentioned about Entity Framework happens only if you're model is up to date (in data-driven design). If not, you won't get a compile-time error, and they would definitely defer to become run-time errors.

Consider this scenario. You create a database, with one table called Users which has 3 columns: Username, Password, IsActive.

You create a project, and add an Entity Framework .edmx file to it, updating it with the schema of your database. Great till here.

Now what happens if someone change the data type of the IsActive column from Boolean to int, and you don't know about it?

You simply build your project (which builds successfully) and run it, and then you get some errors.

In model-first and code-first development models, the scenario is even worst, as there is no direct and auto-generated mapping between your domain model and database schema.

Thus by the experience I've got till now, I can't say that Entity Framework definitely helps you get mapping problems at compile time. The only case it can help, is to let it generate the model itself from database, and get updated.


答:
You need to do various things with trees, like translate between the data structure and some serial representation, like on a file or in a language.

So, for example, suppose you have a parse tree like this:

```<code>    *
   / \
  +   \
 / \   \
A   B   C
</code>```

You could serialize it as * + A B C by walking it in prefix order, or as A B + C * by walking it in postfix order. If you work at all with language processors, such things need to be second-nature.

Title: Usefulness of pre and post order traversal of binary trees

Body:
This may be very naive, but I was wondering, it the context of binary trees (plain, sorted and balanced), of all the traversal types:

depth-first pre-order

depth-first in-order

depth-first post-order

breadth-first

what's the actual utility of pre and post-order ones? I mean, is there some type and/or configuration of binary tree in which pre and/or post-order traversal would give an(some) advantage(s) over the other two?

AFAICS, there are certain types and configuration of binary trees for which in-order and breadth-first might give a certain advantage:

for a balanced binary tree any depth-first traversal will use less memory storage space as compared to breadth first (eg. for balanced binary tree of 6 or 7 nodes, height is 2 so any depth-first traversal will need to store a max of 2 nodes at any given time, while last level has 3 or 4 nodes so breadth-first traversal would need to store up to 3 or 4 nodes at some point). In this case using in-order traversal uses the least amount of memory and visits the nodes in their natural order.

for a non-balanced binary tree, if it's close to the worst-case insertion scenario, traversing it breadth-first would use less memory as compared to any of the depth-first traversals. So in this case breadth-first offers an advantage. In-order traversal has the again the advantage of visiting values in their natural order.

However I can't think of a situation where pre and post-traversal would give an advantage over the other two.

Body:
You need to do various things with trees, like translate between the data structure and some serial representation, like on a file or in a language.

So, for example, suppose you have a parse tree like this:

    *
   / \
  +   \
 / \   \
A   B   C

You could serialize it as * + A B C by walking it in prefix order, or as A B + C * by walking it in postfix order. If you work at all with language processors, such things need to be second-nature.


答:
First of all, let's define Business Intelligence. It's simply trying to make sense of the data a business already has.

As an example, consider a company which sells toys, and stores a record for each toy it sells. This record contains the information of the country in which the toy is sold.

Now, the manager of the company wants to see in which country the sales is higher, so that the next year, the distribution plan would be more efficient for that country. He/She needs a report of the sales figures in different countries. This is an example of business intelligence.

Now to get to this report, somebody has to get the data out of the database (storage place, anywhere, even an Excel file). But wait, what if the total records of the data you have in your company exceeds, say for example, 50 million records? Do you want to query over them each time you want to create that report? Even worst than that, what if your database is under a huge amount of transaction and many records are getting inserted into it, while you try to execute a very costly query upon it?

These problems resulted in some science to grew out of the solutions developers proposed. For example, you might create another database, and run a job each night to replicate these databases, so that tomorrow you can execute your query on a database which is not under live transactions.

Some concepts come to mind here, like OLAP (Online Analytical Processing) vs. OLTP (Online Transactional Processing), Data Warehousing, Data Mining, Cubes, Tools for BI like SQL Server Reporting Services and SQL Server Analysis Services, and many other concepts, which are not related to being a web developer at all.

Title: What is a "Business Intelligence" Developer?

Body: What traits / skills does the Business Intelligence Developer role expect over a traditional Web Developer role?</p>


问:
Copying (forking) an open source project to your own repository
I'm currently using an open source project called CodeFirstMembership for one of my projects.  There's a critical issue that I need to get past, and the more I use it, the more I find things I need to modify.  It's extremely useful, except it doesn't look like the developer has much time to update it (totally cool, we've all been there).  I'm wondering about the etiquette and legality and general "hey, you stole my code you jerk" responses I'd get if I copied the source, moved it to github and made my own fork.

On Github, we do this all the time, forking projects, but it FEELs less jerk-ish because there's a connection to the original.  Is there anything wrong with me doing this, whether legal or otherwise since there's no copyright notice or license associated with this library?

答:
You can just fork it, send an email letting the original author know as a kindness. But you have to remember that the author has already told you you can copy it and modify it. No developer truly wants his code to bitrot. If you're lucky your modifications will be pulled back in.

"Grant of Rights

(A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create."


答:
A microsoft BI-developer would know most of these:

sql server

SSIS

SSRS

cubes and so forth.

SQl server 2012 is the latest and the greatest database from Microsoft.

http://www.microsoft.com/en-us/sqlserver/editions/2012-editions/business-intelligence.aspx


答:
Product owner owns the what part. He is in charge of deciding what items of Product Backlog are more prior to other items, and he is responsible to deliver the product based on the overall available resources on time.

Scrum team (including product owner, and scrum master) are responsible for how part. They should decide how to manage the team, share knowledge, be self-organized, meet daily (daily stand-up), revise themselves (retrospective meeting), have cross-functional resources, etc.

This idea is far from owning a feature, as stakeholders own those features, not me and you bro.


问:
What is the most egregious waste of money you have seen, and what did you do about it?
Often we as programmers see large organisations wasting huge sums of money on bloated and inefficient solutions to problems. This pains me greatly because I like organisations to benefit from best of breed solutions. However, my abilities as a programmer are limited when it comes to influencing the key decision makers and often my perspective on the matter is constrained to my own little technical world.

So, my question is this. After encountering an egregious waste of money on some software and/or hardware that really got your goat, what did you do about it to get it fixed or were you doomed to bite the bullet and mutter forever under your breath? I'm interested in hearing your overall experiences and especially what lessons you learned about how to tackle this sort of thing in the future. Let's not name names, the experience of how to tackle the problem is more important than the actual offending product.

答:
Paying for big, bulky, buggy commercial products, in the range of:

Application servers;

Testing tools;

Development environments.

when the open-source or light-weight alternatives are obviously superior.

My steps usually are:

establish an alternative as a reference - e.g. "I will experiment with the app server X instead of app server Y. I had good experience with it, because (...).";

sell this proposition to my colleagues - "I am now developing faster since server X restarts much faster and I don't wast all that time";

sell this to the immediate manager - "Our team now develops faster since we're using server X. It all began as a little experiment but everyone likes it.".


答:
The wikipedia article has a nice concise description of when you would want to use the different types of depth-first search:

Pre-order traversal while duplicating nodes and values can make a complete duplicate of a binary tree. It can also be used to make a prefix expression (Polish notation) from expression trees: traverse the expression tree pre-orderly.

In-order traversal is very commonly used on binary search trees because it returns values from the underlying set in order, according to the comparator that set up the binary search tree (hence the name).

Post-order traversal while deleting or freeing nodes and values can delete or free an entire binary tree. It can also generate a postfix representation of a binary tree.

It boils down to the logistical needs of an algorithm.  For example, if you don't use post-order traversal during deletion, then you lose the references you need for deleting the child trees.


答:
The use of the frequency of the modified lines as an indicator for the code stability is at least questionable.

At first, the distribution over time of the modified lines, highly depends on the software management model of the project. There are great differences in the different management models.

At second, the casualty in this assumption is not clear - is the lower count of modified lines caused by the stability of the software, or simply because the deadline expires and the developers decided to not make some changes now, but to make it after the release?

At third, most of the lines are modified when new features are introduced. But the new feature does not makes the code not stable. It depends on the developer's skill and on the quality of the design. On the other hand, even serious bugs might be fixed with very few line changed - in this case, the stability of the software is increased significantly, but the changed line count is not too big.


问:
JVM vs operating systems
Recently i was re-visiting the basic concepts of operating systems. Since I am a java developer, I have inherently started looking at everything from java point of view. I am also reading 'Inside the JVM fundamentals' from

http://www.artima.com/insidejvm/ed2/jvm.html

so when I see the basics of operating systems and JVM, I have begun to think that there are lot of similarities on an abstract level, i.e. both do the memory management, process scheduling, etc.

So I want to ask SO programmers whether I am correct in my learning or assumptions?

答:
Yes, they are similar. The JVM at a very core level is just a specialized CPU. It requires some bootstrapping and other things similar to a native OS. Where it differs though is that there is no hardware CPU that executes JVM bytecodes. So, this means that you will never be able to boot an actual computer with only Java code. You'll have to have some sort of middle-man to native(which is often much more complex than you'd think)

However, conceptually, they are quite similar. Most modern OSs handle memory management and scheduling. One would argue that the JVM does as well expressly by-design. This is because it was originally written to run on any OS. So naturally, you'd want to rely on the actual OS as little as possible

Title: JVM vs operating systems