答:
I want to say "not gonna happen".  However, that wouldn't be very helpful, and perhaps not entirely accurate, either.

First of all, "security" is rather vague, but I think we can break it down:

Be memory-safe.  Don't allocate buffers that are too small, don't dereference wild pointers, don't overrun buffers, etc.

Have good asymptotic complexity.  Simply having an array of unsorted entries would require O(n) to pull out the item with the highest priority.  Consider using a binary heap instead.

Don't leak memory.  Every call to malloc should have a corresponding call to free.

Second of all, learn enough C to work with data structures.  I'll try to provide a quick overview:

struct

Define compound data types using the struct keyword.  Example:

```<code>struct Foo
{
    int n[10];
};
</code>```

structs are like classes in C++ or Java, but you can't embed methods directly in them.

When you use the type, you have to say struct Foo (C++ lets you leave off the struct, but not C).  To avoid this inconvenience, consider using typedef:

```<code>typedef struct Foo Foo;
</code>```

Pointers

Consider a binary tree node:

```<code>struct Node
{
    int value;
    struct Node *left;
    struct Node *right;
};
</code>```

Here, left and right point to other Node structures.  If we were to take out the asterisks:

```<code>struct Node
{
    int value;
    struct Node left;
    struct Node right;
};
</code>```

Then it would mean left and right exist right here, in this object.  That would require an infinitely large object!  The compiler will refuse this code.

A pointer can be thought of as:

A reference to another data structure

A number representing a location in memory.  Think of memory as a giant array of bytes.  The operating system decides where to put things.  A pointer is an index in that array.

Allocation

So how do we ask the operating system to reserve space for an object?  We call malloc:

```<code>struct Node *node = malloc(sizeof(struct Node));
</code>```

malloc reserves the requested number of bytes of memory, and returns a pointer telling us where those bytes are.  It doesn't initialize the memory to anything, so it currently contains garbage.

sizeof computes the size of a data type (at compile-time).

We can also allocate things directly on the stack:

```<code>struct Node node;
</code>```

As in the case of malloc, node will contain garbage.  Here, node is a value.  We can turn it into a pointer by using C's reference operator &:

```<code>struct Node *node_ptr = &node;
</code>```

The advantages of allocating on the stack are:

It's much faster than malloc

It's freed automatically

The disadvantage is that node_ptr is invalid outside of the current scope.  Thus, we can't return pointers to stack-allocated structures.

Accessing structures

The structure access operator in C is .:

```<code>struct Node node;
node.value = 42;
</code>```

To access a structure value behind a pointer, we can combine the * (dereference pointer) and . (structure member) operators:

```<code>(*node).value = 42; /* . has higher operator precedence */
</code>```

Better yet, use the shorthand -> operator:

```<code>node->value = 42;
</code>```

Simple example

Here's an example program that defines a binary tree node and basic operations on it.

```<code>typedef struct Foo Foo;
</code>```0

Hope this helps.

Title: How should I implement a secure priority queue in C?

Body:
I have an assignment to implement a priority queue in C as well as make an app that uses it. I, however, only know basic-level C (I do know Java). My intuition says that I need to learn pointers.

What other stumbling blocks should I expect or prepare for? How do I go about making this secure?

Body:
I want to say "not gonna happen".  However, that wouldn't be very helpful, and perhaps not entirely accurate, either.

First of all, "security" is rather vague, but I think we can break it down:

Be memory-safe.  Don't allocate buffers that are too small, don't dereference wild pointers, don't overrun buffers, etc.

Have good asymptotic complexity.  Simply having an array of unsorted entries would require O(n) to pull out the item with the highest priority.  Consider using a binary heap instead.

Don't leak memory.  Every call to malloc should have a corresponding call to free.

Second of all, learn enough C to work with data structures.  I'll try to provide a quick overview:

struct

Define compound data types using the struct keyword.  Example:

struct Foo
{
    int n[10];
};

structs are like classes in C++ or Java, but you can't embed methods directly in them.

When you use the type, you have to say struct Foo (C++ lets you leave off the struct, but not C).  To avoid this inconvenience, consider using typedef:

typedef struct Foo Foo;

Pointers

Consider a binary tree node:

struct Node
{
    int value;
    struct Node *left;
    struct Node *right;
};

Here, left and right point to other Node structures.  If we were to take out the asterisks:

struct Node
{
    int value;
    struct Node left;
    struct Node right;
};

Then it would mean left and right exist right here, in this object.  That would require an infinitely large object!  The compiler will refuse this code.

A pointer can be thought of as:

A reference to another data structure

A number representing a location in memory.  Think of memory as a giant array of bytes.  The operating system decides where to put things.  A pointer is an index in that array.

Allocation

So how do we ask the operating system to reserve space for an object?  We call malloc:

struct Node *node = malloc(sizeof(struct Node));

malloc reserves the requested number of bytes of memory, and returns a pointer telling us where those bytes are.  It doesn't initialize the memory to anything, so it currently contains garbage.

sizeof computes the size of a data type (at compile-time).

We can also allocate things directly on the stack:

struct Node node;

As in the case of malloc, node will contain garbage.  Here, node is a value.  We can turn it into a pointer by using C's reference operator &:

struct Node *node_ptr = &node;

The advantages of allocating on the stack are:

It's much faster than malloc

It's freed automatically

The disadvantage is that node_ptr is invalid outside of the current scope.  Thus, we can't return pointers to stack-allocated structures.

Accessing structures

The structure access operator in C is .:

struct Node node;
node.value = 42;

To access a structure value behind a pointer, we can combine the * (dereference pointer) and . (structure member) operators:

(*node).value = 42; /* . has higher operator precedence */

Better yet, use the shorthand -> operator:

node->value = 42;

Simple example

Here's an example program that defines a binary tree node and basic operations on it.

/* Needed for printf and perror */
#include <stdio.h>

/* Needed for malloc, free, and exit */
#include <stdlib.h>

typedef struct Node Node;

struct Node
{
    int value;
    Node *left;
    Node *right;
};

Node *node_new(int value, Node *left, Node *right)
{
    Node *node = malloc(sizeof(Node));

    if (node == NULL) {
        perror("node_new");
        exit(EXIT_FAILURE);
    }

    node->value = value;
    node->left = left;
    node->right = right;
    return node;
}

void node_delete(Node *node)
{
    if (node != NULL) {
        node_delete(node->left);
        node_delete(node->right);
        free(node);
    }
}

void node_dump(Node *node)
{
    if (node != NULL) {
        node_dump(node->left);
        printf("%d\n", node->value);
        node_dump(node->right);
    }
}

int main(void)
{
    Node *node =
        node_new(4,
            node_new(2,
                node_new(1, NULL, NULL),
                node_new(3, NULL, NULL)
            ),
            node_new(6,
                node_new(5, NULL, NULL),
                node_new(7, NULL, NULL)
            )
        );

    node_dump(node);
    node_delete(node);
    return 0;
}

Hope this helps.


问:
Best approach to selecting programming languages and 3D graphics API for simulating physics experiments
I am starting a research project and need to nail down a programming language and 3D graphics API where I will be creating an environment in the field of molecular cell biology where I will be simulating a large range of experiments in silico. This will be an ongoing project which will keep expanding and growing in size. The experiments will be done in discrete time and will encompass a complex physics engine. Pretty graphics are not of importance nor is is audio. I run Ubuntu and this is the environment I will be developing in.

The pairs I have investigated thus far are:

java : flexible,scalable,lib/dependency organization (maven),oo

jogl: full control of graphics

jMonkeyEngine: full game library, includes jBullet, maybe a bit overkill for what I need.

c++ : High speed, low level, oo

opengl:full control of graphics

maya:built in physics engine, infrastructure already in place, proprietary, not free

matlab : Heavily math based, but difficult to maintain and scale

simulink : proprietary, not free

I am least familiar with Maya but it was suggested to me by a friend as a good approach. When would Maya be a good solution and would it be a good selection for this type of case? Just as thinking jMonkey would be overkill this is kinda my feeling on Maya.

Are there any other pairings I should investigate?

Also has anyone had any experience modifying an existing physics library and the flexibility or complexity of doing so (ie Bullet, JBullet, jinngine)? Unsure at this point if I should start from scratch or try and modify/expand an existing one.

Any thoughts, feedback, input or any other suggestions would be greatly appreciated.

Thanks

答:
I am not a regular practitioner on this, but has been involved in development that begins with research (in Image/Video processing and related areas) and goes on towards deployment.

I would suggest don't rush into pro/cons analysis. There are two fundamental questions that will set your priorities straight.

1. How much likely (and you are willing) to throw away code?

If there is a sizable research involved, you will have tough time dealing with lower level language problems just to throw away every Monday morning. However, if there is already is a PoC (proof of concept) or prototypical in fornt, than your path is rather straight forward; you should avoid duplicate work.

2. What other elements you depend on?

You want be developing everything straight forward from scratch. Are there specific tool kits, APIs, frameworks you are going to use as dependency? If so, your choices are limited right here in

ContentLicense: CC BY-SA 3.0


问:
What is the most effective way to add functionality to unfamiliar, structurally unsound code?
This is probably something everyone has to face during the development sooner or later.

You have an existing code written by someone else, and you have to extend it to work under new requirements.

Sometimes it's simple, but sometimes the modules have medium to high coupling and medium to low cohesion, so the moment you start touching anything, everything breaks. And you don't feel that it's fixed correctly when you get the new and old scenarios working again.

One approach would be to write tests, but in reality, in all cases I've seen, that was pretty much impossible (reliance on GUI, missing specifications, threading, complex dependencies and hierarchies, deadlines, etc).

So everything sort of falls back to good ol' cowboy coding approach. But I refuse to believe there is no other systematic way that would make everything easier.

Does anyone know a better approach, or the name of the methodology that should be used in such cases?

答:
First off, it gets a little wearing that everyone on this site thinks anything written by anyone else is rubbish.

Understanding code is difficult, admittedly some poor programming practices make it more difficult, but, for any reasonably complex system understanding the internal structure and idioms used is going to be hard, even if its well written code.

Systems routinely run for more than twenty years. Programming methodologies, best practices, design philosophies and fashions change every couple of years, and, programmers pick up the improved styles at different rates. So what would have been considered a state of the art and excellent example of code in 2007, looks old-fashioned and quirky today. As an exercise I suggest you dig out some code you wrote three years ago, I can almost guarantee you will cringe.

So first of you need to suppress the initial WTF response. Tell yourself that the system has worked well enough and long enough for it to become your problem so there must be something good about it.

Try to get a hang of the original coders style, the idioms used, study the weirder bits of code and see if they fall into a pattern.

If the required changes are small then follow the original coding style, that way someone picking up the code after you only needs to get used to one set idiosyncrasies.

If the required changes are large and the changes are concentrated in a few functions or modules, then, take the opportunity to refactor these modules and clean up the code.

Above all do not re-factor working code which has nothing to do with the immediate change request. It takes too much time, it introduces bugs, and, you may inadvertently stamp on a business rule that has taken years to perfect. Your boss will hate you for being so slow to deliver small changes, and, your users will hate you for crashing a system that ran for years without problems.


问:
Why is DRY important?
Quite simple, why would I want to write code that works for all cases and scalable data when all I need to do is repeat the same process a few times with a few minor tweaks?

I'm unlikely to need to edit this again any time soon.

It looks like a lot of less work to just go...

```<code>function doStuff1(){/*.a.*/}
function doStuff2(){/*.b.*/}
function doStuff3(){/*.c.*/}
</code>```

And if I ever need to add something...

```<code>function doStuff4(){/*.d.*/}
</code>```

And if I need to remove it, I remove it.

It's harder to figure out how to make all of those into one straight-forward pattern that I can just feed data into and deal with all the cases, and make a bunch of changes I don't feel like I'm ever going to have to do.

Why be DRY when it looks like a quick cut+paste is going to be so much less work?

答:
I have an old legacy project, where some of the former developers didn't care about DRY at all. So the whole codebase was cluttered with helper methods like GetSystemTimeAsString(), LogToFile() and lots of other stuff. Some methods were slightly customized to special needs, but most were just copy and paste.

Unfortunately some of the methods had subtle bugs like char array not long enough in some cases, using insecure stuff like strcpy(), etc.

So it was a real PITA to find all the code fragments, harmonize them and fix the bugs. And we are still harmonizing and fixing stuff.

You never know, if you made a mistake in your first method and then have to fix it multiple times, because you just copied it. And if you want to use some of the methods later, how do you know, which of the 5 methods in the codebase is the one for your case now? So you just copy one, customize it and here it starts again...

Title: Why is DRY important?


问:
How to unit test Visual Basic 6 legacy code?
I am doing legacy software programming in Visual Basic 6.0.

How do I unit test it?

答: Googling for "visual basic unit test" lead me to the wikipedia page on unit testing in all kinds of languages. Somewhere down the list is a table with tools for unit testing VB6 code. That should get you started.</p>


问:
How to debug/change Java code while the program is running?
I just saw a video showing how Notch (of Minecraft fame) is debugging and changing Minecraft while it is running. He pauses the game, changes something in the code and then unpauses the game where the change takes immediate effect without the need to restart the program.

How does this work? Which kind of technique is used to achieve this?

答:
Java can do hot-swapping out of the box. If you use an IDE like Eclipse it will work for changing method-bodies. If you want to apply other code changes you might want to use a tool. JRebel is a product that supports more cases.

I don't want to do marketing for that product, but I personally do not know any other alternative. On the JRebel website there's a nice feature-comparison.

Hope that helps.


问:
Algorithm for formating SQL code
I need a tool (for in house usage) that will format SQL code (SQL Server/MySQL).

There are various 3rd party tools and online web sites that do it but no exactly how I need it.

So I want to write my own tool that will fit my needs.

First question is there any standard or a convention for how the SQL code should be formatted? (the tools that I tried format it differently)

The second question, how should I approach this task?
Should at first convert the sql query into some data structure like a Tree?

答:
A little late, only just stumbled across this, sorry.

Poor Man's T-SQL Formatter is an open-source T-SQL formatter (library, ssms plugin, command-line file formatter, etc) - the implementation is reasonably modular and it shouldn't be very hard to implement a MySQL tokenizer and formatter to match the T-SQL ones (I haven't done so primarily because I have no experience of or use for MySQL right now, so it's not a good use of my time).

The library is implemented in C# (2.0) with an AGPL license - that means you can't redistribute it commercially or expose as a public service without publishing any modifications, but for in-house user it should present no issues, whether it's customized or not.

As @Gilbert Le Blank already answered, there is definitely no standard on SQL formatting - even the commercial formatters out there, with the different options they provide, don't converge on the same defaults or even necessarily support the same output formats.

With respect to writing your own tool from scratch, I would advise against it if you need to handle a variety of cases: at least for T-SQL, handling SQL multi-statement batches with CTE WITH clauses, MERGE statements, sub-queries and derived tables, etc turns out to be pretty hard :)

In case it's any help: http://www.architectshack.com/PoorMansTSqlFormatter.ashx

Title: Algorithm for formating SQL code


答:
It's called hot code replace and allows an IDE to change live running code via the debugging interface. It has been supported by the Sun JVM since Java 1.4.1

However, unless you use the (commercial) JRebel JVM extension, it's limited to changes inside method bodies. If you add/remove methods or classes, or change signatures, you have to restart the JVM.

Title: How to debug/change Java code while the program is running?

Body:
I just saw a video showing how Notch (of Minecraft fame) is debugging and changing Minecraft while it is running. He pauses the game, changes something in the code and then unpauses the game where the change takes immediate effect without the need to restart the program.

How does this work? Which kind of technique is used to achieve this?

ContentLicense: CC BY-SA 4.0


问:
Extending Mono's C# compiler with additional custom features (more or less syntactic sugar)
I'm aware that this is a rather broad question, but here it goes anyway...

What is, in your opinion, the most practical way to create own C# implementation with minor additions to the existing 4.0 feature set?

For context: I'm thinking about adding a couple of (mostly syntactic) niceties to the dynamic feature set that would improve the whole duck-typing experience. For example, these would include the idea of a dynamic interface, as proposed in this debate (particularly in the last comment from MiddleTommy).

I'm aware that nothing is stopping me from simply diving into the Mono sources. However, I'm compelled to first ask about potentially similar projects that may already exist in the wild. Any such extension efforts underway?

答: Take a look at the Nemerle programming language - it provides a C# front-end (built upon Nemerle.Peg), which is easily extensible. The only feature missing from its implementation of C# 4.0 is goto.


问:
When is method overloading appropriate?
Suppose I am working on an existing, reasonably large system. I have an object, myObject of class MyClass (for the example's sake, suppose I'm working in Java). myObject is a composition containing a Collection, say, a List and other objects which (I think) are irrelevant. It contains delegate methods which just serve to call upon the methods of the List it is composed of, in order to ensure the List it has is not exposed (sorry if I've got my terminology wrong).

Let's say that this List is a List<String> but, for some reason, the main access method is a mask method for class SomeOtherClass. If I wanted to insert a new value pair into my List, then I'd have an object of SomeOtherClass called someObject. I'd call myObject.insert(someObject) and inside the insert method there would be some magic that would retrieve a String to put into the List<String>.

Supposing now that I've only got a String value, and no SomeOtherClass object to insert. Assuming I can't modify the insert method because it would break everything in this system. Then should I overload the insert method? Or should I create a new object of SomeOtherClass every time I want to call insert?

I guess if I did overload it, it would look something like this...

```<code>public void insert(String s) {
    ...
}

public void insert(SomeOtherObject obj) {
    this.insert(obj.magicStringMethod());
}
</code>```

(This example is a contrived puzzle based upon a similar (slightly more complex) situation regarding overloading that I encountered yesterday. I'll expand it if there's anything that was unclear)

Would this be an appropriate place to overload a method? If not, when should I overload a method?

答:
You overload when you wish to support different types:

```<code>public overload void MyMethod(int value)
{
}

public overload void MyMethod(bool value)
{
}

public overload void MyMethod(string value)
{
}
</code>```

or to support a progressive interface using different parameter lists:

```<code>public overload void MyOtherMethod()
{
    this.MyOtherMethod(DefaultValue);
}

public overload void MyOtherMethod(int value)
{
    this.MyOtherMethod(value, DefaultOtherValue);
}

public overload void MyOtherMethod(int value, bool otherValue)
{
    ...
}
</code>```

You might even get a little crazy and support both different types AND a progressive interface, but you should bear in mind that you need to avoid creating variations in behaviour between overloaded methods.  Each overloaded method should be functionally the same as the others in an overloaded group, otherwise it will be unclear as to how, when or why behaviour is being varied. If you want two functions to do something completely different, then you should name them accordingly.

Title: When is method overloading appropriate?

Body:
You overload when you wish to support different types:

public overload void MyMethod(int value)
{
}

public overload void MyMethod(bool value)
{
}

public overload void MyMethod(string value)
{
}

or to support a progressive interface using different parameter lists:

public overload void MyOtherMethod()
{
    this.MyOtherMethod(DefaultValue);
}

public overload void MyOtherMethod(int value)
{
    this.MyOtherMethod(value, DefaultOtherValue);
}

public overload void MyOtherMethod(int value, bool otherValue)
{
    ...
}

You might even get a little crazy and support both different types AND a progressive interface, but you should bear in mind that you need to avoid creating variations in behaviour between overloaded methods.  Each overloaded method should be functionally the same as the others in an overloaded group, otherwise it will be unclear as to how, when or why behaviour is being varied. If you want two functions to do something completely different, then you should name them accordingly.


问:
How to create an Intelligent Agent
I am currently doing my Honours in Computer Science and taking Artificial Intelligence as a subject. As part of completing the subject I have to develop my own basic intelligent agent.

I have yet to wrap my head around what I actually have to do for this project. I am not the most technically gifted programmer and I have no idea of what to do or where to start

Could someone please point me in the right direction as to where to start learning how to develop an Intelligent Agent as well as any possible idea's of what to actually do for a project? The requirement for the project are very vague as we were not told how technical or big the project should be. (Hopefully not too big as I have another 8 subjects who require projects as well).

Any VB.net references would be appreciated as well. (I know it's not the best language to develop an IA with, but due to my time constraints this is the programming language I 'feel' most comfortable with).

答:
First of all, don't worry about the AI part. A program that uses artificial intelligence is just like any other program. Start thinking in terms of input and output. For an intelligent agent that means that you are perceiving your environment and you can call actions on the environment.
An example could be that you are writing a movie recommandation engine:

What is your input? (or: perception)

A list of movies that your user hasn't seen yet,

A list of movies that your user has already seen together with his rating (could be a simple like/dislike)

A list of all other users, which themselves have a list of rated movies

What is your output? (or: action)

A list of movies ordered by what your program thinks that your user might like.

Your action, will cause the environment to change, e.g. your user will probably watch the movie, though this will not happen immediately nor is it guaranteed.

Internally you can then use the algorithms presented in the class, you could start simple and use a k-nearest neighbors. In this case you want to find users that have similar interests as your current user and then recommend him a movie that he hasn't seen yet but his close neighbors liked.

Now, how do you define close? Well, this is where feature vectors come in and really,  this is the only challenge that you'll face. Once you have the feature vectors it doesn't matter which algorithm you're applying. In our case you could represent a user by his ratings. So if there are only 5 movies in the system, and your user liked Movie A and B, disliked C and hasn't seen D and E his feature vector is [1,1,-1,0,0]. Calculate the distance to all other users and then find a movie he hasn't seen yet (D and E) and calculate the score for those movies amongst his k nearest peers. The recommendation would be the movie that scores highest.

Title: How to create an Intelligent Agent


答:
I don't think you even need to modify the compiler to get very close to dynamic interface.

Just create a wrapper class (possibly autogenerated) that dynamically forwards method invocations to the underlying object.

This has some disadvantages when compared with true dynamic interface, but should be much easier to implement.

Title: Extending Mono's C# compiler with additional custom features (more or less syntactic sugar)

Body:
I'm aware that this is a rather broad question, but here it goes anyway...

What is, in your opinion, the most practical way to create own C# implementation with minor additions to the existing 4.0 feature set?

For context: I'm thinking about adding a couple of (mostly syntactic) niceties to the dynamic feature set that would improve the whole duck-typing experience. For example, these would include the idea of a dynamic interface, as proposed in this debate (particularly in the last comment from MiddleTommy).

I'm aware that nothing is stopping me from simply diving into the Mono sources. However, I'm compelled to first ask about potentially similar projects that may already exist in the wild. Any such extension efforts underway?


答: I had an agents-based course in the academia and "An Introduction to MultiAgent Systems" was my textbook. This is the author's page about the current version of the book, in case you want to have a look.</p>

Title: How to create an Intelligent Agent

Body:
I am currently doing my Honours in Computer Science and taking Artificial Intelligence as a subject. As part of completing the subject I have to develop my own basic intelligent agent.

I have yet to wrap my head around what I actually have to do for this project. I am not the most technically gifted programmer and I have no idea of what to do or where to start

Could someone please point me in the right direction as to where to start learning how to develop an Intelligent Agent as well as any possible idea's of what to actually do for a project? The requirement for the project are very vague as we were not told how technical or big the project should be. (Hopefully not too big as I have another 8 subjects who require projects as well).

Any VB.net references would be appreciated as well. (I know it's not the best language to develop an IA with, but due to my time constraints this is the programming language I 'feel' most comfortable with).


答:
It is possible to do something like what the linked blog post describes with C# 4.0. You can subclass DynamicObject (or even ExpandoObject to have a good starting point) and override TryGetMember and the likes to forward the calls. Then, create a dynamic proxy for the dynamic object. There are several libraries for this purpose, one of them is impromptu-interface. Then you can say something like:

```<code>var obj = Impromptu.ActLike<ISomeInterface>(dyn_obj);
</code>```

And you get a reference with IntelliSense support and ActLike<> will also check the availability of the members of the interface.

Body:
It is possible to do something like what the linked blog post describes with C# 4.0. You can subclass DynamicObject (or even ExpandoObject to have a good starting point) and override TryGetMember and the likes to forward the calls. Then, create a dynamic proxy for the dynamic object. There are several libraries for this purpose, one of them is impromptu-interface. Then you can say something like:

var obj = Impromptu.ActLike<ISomeInterface>(dyn_obj);

And you get a reference with IntelliSense support and ActLike<> will also check the availability of the members of the interface.


问:
Modern Java implementation of Blackboard Pattern?
Is there room for a practical modern application in Java of the Blackboard Pattern detailed in "The Pragmatic Programmer"? Is there any particular library that attempts to assist in the implementation of this concept? What is the general consensus on this pattern in the present software community (especially Java)?

Though the idea is intriguing, I have a feeling that this portion of the book may be outdated.

In case you are not familiar with this concept: http://flylib.com/books/en/1.315.1.55/1/

答:
My opinion is that a lot of the modern Dependency Injection frameworks are more-or-less an implementation of the whiteboard pattern for application architecture. Google Guice in particular allows you to get particular instances of an object from the "Injector" (or whiteboard as you might like to call it) by annotating the objects it creates in a number of ways (including by name using the @Named annotation). It also allows different modules to collaborate in contributing services to the Injector (whiteboard).

Spring is similar, each context XML file (for example) can contribute to and use objects from the Spring context (whiteboard).

OSGi and its service registry is another example of a whiteboard implementation. Here is a description of how OSGi uses and supports the whiteboard pattern for its inversion of control of event handling in OSGi based systems

Here is a tutorial paper on the relationship between Spring dynamic modules, OSGi and the whiteboard pattern (page 51).

My experience is that Guice in particular is also very powerful for supporting your own implementation of the whiteboard pattern. If most of your objects are being injected from the Guice Injector (whiteboard) then its easy to inject them with any other whiteboard a particular class needs. So you can bootstrap a specific white board (e.g. one containing facts about your domain) using the Guice application architecture white board. (You can do similar with Spring, OSGi or many of the others too although maybe not as directly).


答:
When working with Big Ball Of Mud, the only effective approach to me was to get (more) testers and arrange a thorough professional quality assurance in the project.

Thing is, all the approaches applicable with better codebase just don't cut it.

With good code, I study documentation to learn about the principles, read through code (and especially through unit tests) to figure design details, write my own unit tests to cover the changes I do etc. When code is improved, unit tests remain intact or go through minor changes, docs do not need any major rework etc etc.

With bad code, things seem to work exactly opposite way. Information I get from documentation is mostly obscure and outdated waste. Reading through code just melts my brain with convoluted control flow and counter-intuitive patches applied over earlier patches applied over even earlier patches made long time ago to quickly work around design errors.

As for unit tests, these do things opposite to how I use them in good code, like breaking at reasonable changes and failing to catch the real mistakes I make. Which is painful but not surprising - what else would one expect from testing units which have bad design to start with? Instead of helping you improve the design, unit tests often work to preserve bad code - eg in my recent maintenance project I was regularly removing large chunks of code which was only referenced from outdated senseless unit tests. BTW I use that knowledge when writing new code: when I find out that my unit tests tend to get too complicated / fragile, this indicates a need to fix some issue with my own design.

Now, back to what worked for me. First thing is not to let management trick you with you're good developer, you can handle that rhetoric. Think for yourself, think critically and you'll find out that despite good-developer smoke screens, the whole thing is heavily tilted to quality assurance side.

Start by asking yourself - why didn't they just throw away this Big Ball of Mud?

Why did they invest into hiring you to maintain it? Typically, the reason is - the thing works well for the users and you are expected to keep it work well for the users. They perceive it as a black box, they don't look into the (crappy) code, all they see is a useful functionality.

Now, if you ever worked with professional QA, you'll quickly recognize that it's just the way how testers tend to deal with software. Black box, functionality, quality from user perspective - these are all the quality assurance topics and themes.

Okay, if you've read so far you may wonder how exactly that works for me? It is simple really.

First thing is - whenever I finish some feature of bugfix, I just reassign respective item in issue tracker to QA guy to verify my changes. This way, I don't need to waste time on cumbersome functional testing, just make a quick check that candidate code is ready for QA.

If I am really lucky (doesn't happen often), I don't need to worry anymore. As for the worst case scenario, it's not as bad, either. If I did something wrong, tester gets back to me just a day or two later, with clear explanation of what exactly went wrong and how to reproduce the bug, along with their regression test suite extended to easily catch this kind of bugs if they occur again. Not bad really, don't you think?

Next great thing that comes with QA is regular regression test cycles.

Some (lame) managers may try to convince you that you can get this done automagically - don't trust them on that.

Things that work great with good code, just fail to do the trick with Big Ball Of Mud.

Test execution is cumbersome, analyzing test results is effort consuming, maintaining issues and regressions database requires much focus (more focus than you can afford if you plan to also focus on development). Instead of wasting time trying to be jack of all trades, let professional testers do that for you, free your brain and time for design and coding. Just leverage good old division of labour.

Regular test cycles (imNSho weekly are best, although monthly did work well to me, too) let you do the impossible - effective refactoring.

By effective I mean, if the thing needs say one week for coding and one week for fixing regression bugs, you can expect that you'll spend just that - two weeks as you planned - without sinking into extra month wasted on brain-damaging tests execution and complicated failures analysis - because testers will cover that for you.

Besides main benefits mentioned above, there are other, smaller but pleasant bonuses along the way.

With testers, you get someone to discuss design with. As I wrote, docs and code don't help here when you deal with Big Ball of Mud - making kind of vacuum if you work alone. A tester who runs your code and looks at it from different perspective makes a great partner to bounce ideas and explore possible changes.

With testers, you get someone to backup your understanding of design issues. When there are only developers complaining about code quality, this often sounds like subjective WTFs from behind the closed door.

But when this is echoed by QA guy saying something like component A had 100 regression bugs for 10 new features, as opposed to component B which had 10 regression bugs per 20 new features, communication suddenly turns into whole another game.

The last but not the least, professional QA helps to promote your understanding of amount of efforts worth investing into into design improvements. As I already mentioned, management doesn't grok code quality WTFs very well.

But when there is professional QA, with all the data they usually collect, you can come up with stuff that somehow tends to skyrocket through managers brains right into that secret cell with magic stamp I approve

During last year, we wasted about 6 man-months solely on fixing regression bugs in the product. Now, what about giving dev team a week or two to analyze if there's something we can to to get this waste cut by half?

Title: What is the most effective way to add functionality to unfamiliar, structurally unsound code?

Body:
This is probably something everyone has to face during the development sooner or later.

You have an existing code written by someone else, and you have to extend it to work under new requirements.

Sometimes it's simple, but sometimes the modules have medium to high coupling and medium to low cohesion, so the moment you start touching anything, everything breaks. And you don't feel that it's fixed correctly when you get the new and old scenarios working again.

One approach would be to write tests, but in reality, in all cases I've seen, that was pretty much impossible (reliance on GUI, missing specifications, threading, complex dependencies and hierarchies, deadlines, etc).

So everything sort of falls back to good ol' cowboy coding approach. But I refuse to believe there is no other systematic way that would make everything easier.

Does anyone know a better approach, or the name of the methodology that should be used in such cases?


答: Most basic inteligent agent to develop, would be simple BDI (belief-desire-intention) agent. You basically have a set of base beliefs (predicates that might be true or false) which describe observed state of environment, you have inference rules leading to inferred beliefs. You have desires which are description of desired state of beliefs. You have set of actions, which are function transforming one belief set into another, modifying some of them. A plan is a chain of actions. Intention is action (plan) which agent chooses to execute. </p>

Title: How to create an Intelligent Agent


问:
Can Agile be accomplished without client involvement?
I couldn't write a book on Agile.  I have worked in several shops that call their process Agile.  One of the main points of Agile development is regular client involvement.  After a sprint, the work can be demo'd to the client to obtain their feedback.  Rinse and repeat.

The problem I come across is that many clients do not want to be that involved.  They would much prefer a waterfall approach.  Gather the requirements up front, then come back when you are done.  In my experience, waterfall does not work.  Clients do not know what they want until they see it.  The waterfall dilemma is further propagated by a large community of developers that want to have all the requirements up front.  This way they know what they are building, they can architect accordingly, and the client is to blame because they "signed off" on said requirements.

Am I incorrect?  Can Agile work without client involvement?  If so, how and how do you overcome the issues I discussed?

答:
Define the customer.

Is it another company? Another individual?

Is it another team within your company?

Is it a product champion within your company?

Is it you?

All of the above are possible, and quite reasonable depending on the circumstances. You don't want to take a single view down the tunnel about what it is to be Agile, so to say a definitive NO would be incorrect. YES on the other hand requires a little lateral thinking.

Think about the word Agile for a moment. The very clever group of people who coined the term couldn't have picked a better metaphor for the concept they were trying to describe.  When you say Agility, what comes to your mind? Being fleet of foot? Fast to react perhaps? Fast to adapt?

Now think about all of the commonly accepted Agile practices out there, and ask yourself what they really bring to software development methods that are considered to be Agile.

I am the customer to all intents and purposes for my solo projects. I even wear a real hat sometimes, when I really want to make a distinctive mental change in my customer role. This makes me no less Agile than I am when I am at work. For all I care, my cat can be the manager.  He makes sure I take a rest break every once in a while, and reminds me to avoid getting too obsessed with any single task. You may prefer to use your fancy "Pomadoro Technique", but I prefer the "Rascal" Timer!! The thing is, I work in a strictly Agile process whenever I write code for myself.  I'm not the hacker-come-cowboy type, who lives a life of endless development spikes and accomplishing nothing.  I like to craft my software, schedule the development around my work and personal lives, and complete it in a manner that I would expect to do if I were working for a real customer. When things interrupt my schedule, I adjust and prioritize my project work accordingly. I use all of the standard Agile practices and techniques that I can apply solo, and I "deliver" working code to myself (or a friend or colleague to test) as often as I can.  If all of this isn't Agile, I ask you what is?

So my answer is Yes, you can be an Agile Software Developer, and you can apply an Agile methodology, and you don't necessarily need the customer, or even the manager. You can work on a project all by yourself, and wear multiple hats.  It may not necessarily be Ideal to do away with those other roles however, as it is very helpful to cooperate with others to achieve a goal. They act as a sounding board for your ideas, and they feed you requirements that you might otherwise find difficult to generate sensibly on your own.  The other very important role that the customer and manager satisfy is that of keeping you focused on your goals, without endlessly adding features and refining your code beyond what may be strictly necessary.

Still, if you work in a disciplined manner, sticking strictly to your methodology of choice, and apply Agile practices, and if when you get side-tracked, or you change your mind (when wearing your customer hat) and your product design or direction takes a turn, if you can adapt your schedule, and adjust your priorities just as you would imagine your customer would expect you to, then you are being Agile.


问:
Getting users to write decent and useful bug reports
Does anyone know a good way to get users to write a semi-decent (read: useful) bug report?

We wanted to put up something that would make sense to most users (be easy to read and understand), yet give useful information to developers as well.

It does not work when I click the blue button! Ahhh, I just lost a week's work ... make it work.

isn't very useful, as it is.

I started to fix about a list, but thought to check up with you guys, whether a similar method already exists.

答: There is How to Report Bugs Effectively by Simon Tatham. It does explain things nicely, to make it easy to understand for less experienced users. However the downside is that it is quite a bit of text. When you have a user trying to report an issue but failing at explaining it you will usually not be able to convince him to read all this.</p>

OwnerDisplayName: ldigas


问:
Static Analysis tools to detect architectural patterns
Currently for school we are working on a research project. The central question of this project is: Which architectural patterns can be detected using static code analysis? With architectural pattern is meant the architectural patterns from the book: Patterns of Enterprise Application Architecture written by Martin Fowler.

During our literature research we didn't find any studies/articals/journals that adress this problem. So for our approach for this rpoject we where thinking to create a prototype of this kind of tool. But first we have to know if there are any (open-source)tools with the same functionality?(detect architectural patterns with a static code analysis)

So my question is do you know a tool that kind detect architectural patterns? We know of the existence of tools that can detect design patterns of the Gang of Four.
And do you have any suggestions for our approach?

Thanks in advance

答:
A few quick Google searches turned up a paper titled An Eclipse plug-in for the detection of design pattern instances through static and dynamic analysis presented at the 2010 IEEE International Conference on Software Maintenance. Unfortunately, I don't have access to this particular publication with my current IEEE subscription. However, the abstract mentions the name of the project as ePAD. This tool uses both static analysis as well as dynamic monitoring of a running application to detect design patterns. The plugin is available and apparently runs on Eclipse 3.6.0 and better, but I haven't tried it. It might be an interesting start, though, and there is contact information for the creators available.

Searching the Eclipse Marketplace also yielded a tool called Design Pattern Recognizer, which only identifies a handful of Gang of Four patterns. Their hompage indicates that the project is no longer active, but you might be able to look at how they approached the problem as another possible starting point.

Something to keep in mind, though, is that the majority of the patterns defined in Fowler's PoEAA book are not actually architectural patterns. Instead, they are design patterns often found in data-driven "enterprise" applications. It's been a while, but the only two that I can remember as being at the architectural level are Service Layer and Model-View-Controller. The other patterns are defined at the class and method level - the detailed design level - not at the software system architecture level that deals with more abstract modules or packages and nodes.


问:
Using a try-finally (without catch) vs enum-state validation
I have been reading the advice on this question about how an exception should be dealt with as close to where it is raised as possible.

My dilemma on the best practice is whether one should use a try/catch/finally to return an enum (or an int that represents a value, 0 for error, 1 for ok, 2 for warning etc, depending on the case) so that an answer is always in order, or should one let the exception go through so that the calling part would deal with it?

From what I can gather, this might be different depending on the case, so the original advice seems odd.

For example, on a web service, you would always want to return a state of course, so any exception has to be dealt with on the spot, but lets say inside a function that posts/gets some data via http, you would want the exception (for example in case of 404) to just pass through to the one that fired it. If you don't, you would have to create some way to inform the calling part of the quality of the outcome (error:404), as well as the outcome itself.

Though it IS possible to try-catch the 404 exception inside the helper function that gets/posts the data, should you? Is it only I that use a smallint to denote states in the program (and document them appropriately of course), and then use this info for sanity validation purposes (everything ok/error handling) outside?

Update: I was expecting a fatal/non-fatal exception for the main  classification, but I didn't want to include this so as not to prejudice the answers. Let me clarify what the question is about: Handling the exceptions thrown, not throwing exceptions. What the desired effect is: Detect an error, and try to recover from it. If recovery isn't possible, provide the most meaningful feedback.

Again, with the http get/post example, the question is, should you provide a new object that describes what happened to the original caller? If this helper was in a library you are using would you expect it to provide you with a status code for the operation, or would you include it in a try-catch block? If you are designing it, would you provide a status code or throw an exception and let the upper level translate it to a status code/message instead?

Synopsis: How do you chose if a piece of code instead of producing an exception, returns a status code along with any results it may yield?

答:
Exceptions are beautiful things.  They allow you to produce a clear description of a run time problem without resorting to unnecessary ambiguity. Exceptions can be typed, sub-typed, and may be handled by type.  They can be passed around for handling elsewhere, and if they cannot be handled they can be re-raised to be dealt with at a higher layer in your application. They will also automatically return from your method without needing to invoke lots of crazy logic to deal with obfuscated error codes.

You should throw an exception immediately after encountering invalid data in your code. You should wrap calls to other methods in a try..catch..finally to handle any exceptions that might be thrown, and if you don't know how to respond to any given exception, you throw it again to indicate to higher layers that there is something wrong that should be handled elsewhere.

Managing error codes can be very difficult.  You usually end up with lots of unnecessary duplication in your code, and/or lots of messy logic to deal with error states. Being a user and encountering an error code is even worse, as the code itself won't be meanful, and won't provide the user with a context for the error.  An exception on the other hand can tell the user something useful, like "You forgot to enter a value", or "you entered an invalid value, here is the valid range you may use...", or "I don't know what happened, contact tech support and tell them that I just crashed, and give them the following stack trace...".

So my question to the OP is why on Earth would you NOT want to use exceptions over returning error codes?


问:
What is the "architecture" that provides functionality to application-level URI interfaces, like chrome:// and Firefox's about:config, etc?
According to Wikipedia,

about is an internal URI scheme (also known as a "URL scheme" or, erroneously, "protocol") in various web browsers to display certain built-in functions. It is not an officially registered scheme, and has no standard syntax.

my question is...  what "powers" these "interfaces"? there doesn't seem to be any kind of "application server" running - that would conventionally support such a front-end - were it to be running remotely.. i'm sure the reason for the dearth of information out there - is that these all break the psuedo-promise that anything "you do" in the browser - won't "effect" your system.  these interfaces clearly have access to system level resources and permissions, etc..  are they all simply custom, c-coded hooks to the internal code of the parent applications - or are they a more abstract, ui--layer?

i admit to little knowledge of plug-in authoring, but can this type of functionality be achieved via the typical plug-in API's, or are they too limited? i have spent some time in the webkit source code poking around - but it is so massive and convoluted that its hard to deduct much...

it would seem that however these vendors are implementing these features might be an appealing alternative to say, the various language-specific bridges that webkit implements on various platforms.  i personally find the bridges frustrating, which is probably what led me down this train of thought...

any insights appreciated.

答:
A modern browser has to support a number of different URI schemes, e.g. http:, ftp:, file:, data:, mailto:. The handling can be very different depending on the scheme, it isn't always about communicating with a server - data: gets the data from the URI itself while mailto: simply opens an external application (or sometimes a web page). So AFAIK each browser uses different protocol handlers for each URI scheme and these protocol handlers can do just about anything.

The chrome: protocol in Firefox is a way to access the chrome registry. The browser and extensions register the location of their "servers" for their chrome "servers", these locations are either a directory on disk or a directory inside a JAR (technically: ZIP) file. The protocol handler uses the data from the registry to resolve chrome: URIs into the equivalent file: and jar: URIs. There is some additional magic related to considering the current locale/skin but that's about it. The hard work (actually getting the data) is then performed by the handlers of the file: and jar: protocols.

The about: protocol in Firefox also doesn't do any work by itself. The word following about: determines which handler the protocol handler needs to use. It will look up this handler in XPCOM and let it do the work. Most handlers will again defer the work to other protocols - the about: URIs are usually just shortcuts. For example, about:config is simply an alias for chrome://global/content/config.xul.

I hope that this gives you an idea of how this architecture works - there is no big handler for every kind of URI, the work is rather distributed over many components. XPCOM is the glue holding these components together and making sure that components can come and go (e.g. via extensions) without everything breaking apart.


问:
How extensive is the difference between building a WPF app and a Silverlight 5 app?
I have a fair amount of experience with WPF (C#) and XAML. I might soon be asked to create a Silverlight 5 application. I have no experience with any version of SL. What sort of learning curve could I expect in creating a SL 5 app, given that I have some experience with WPF?</p>

答:
Silverlight is a subset of WPF, so it's quite similar...

One big thing to watch out for is that silverlight calls to the serverside have to be done asynchronously because unlike WPF calls cannot be blocked until an answer is returned


答:
Your skills will directly transfer. Be not of concern.

However.

Desktop apps are not browser apps.

Desktop apps have things like menubars and toolbars and statusbars and all the other heavyweight desktop-appy stuff that browser apps tend not to.

The important thing is not simply to port a desktop app to a browser app (which is what it sounds like you will wind up being asked to do), but to rethink it in terms of a browser app.

Title: How extensive is the difference between building a WPF app and a Silverlight 5 app?

Body: I have a fair amount of experience with WPF (C#) and XAML. I might soon be asked to create a Silverlight 5 application. I have no experience with any version of SL. What sort of learning curve could I expect in creating a SL 5 app, given that I have some experience with WPF?</p>


问:
Does the use of debuggers have an effect on the efficiency of programmers?

Possible Duplicate:

  Are debugging skills important to become a good programmer?

I'm a young Java developer and I make a systematic use of the Netbeans debugger. In fact, I often develop my applications when I debug step by step in order to see immediately if my code works.

I feel spending a lot of time programming this way because the use of debugger increase execution time and I often wait for my app to jump from a breakpoint to an other (so much that I've the time to ask this question).

I never learned to use a debugger at school, but at work I've been told immediately to use this functionality. I started teaching myself to use it two years ago, and I've never been told any key tips about it.

I'd like to know if there are some rules to follow in order to use the debugger efficiently.

I'm also wondering if using the debugger is eventually a good practice? Or is it a loss of time and I've to stop now this bad habit?

答:
It affects the efficiency in a very good way.

I feel that it's used too seldom by developers.

Not only is it good for debugging but it can also give you an insight in profiling.

For example when line stepping you can feel "ahh" this line took a little too long time to execute and you get a feeling for where the bottlenecks in your app are.


答:
Just my opinion, but I feel that regular, systematic use of a line-level debugger might be the single greatest productivity enhancement practice that a programmer has available. Whether you are jumping into and trying to learn an existing code base or just trying to get your own code working, get thee into the debugger and start Stepping.

You are fortunate, I think, to work at a place where you are encouraged to learn and use a debugger. I have seen far, far too many working, veteran programmers who just never learned to use an invaluable tool.

Title: Does the use of debuggers have an effect on the efficiency of programmers?

Body:
Possible Duplicate:

  Are debugging skills important to become a good programmer?

I'm a young Java developer and I make a systematic use of the Netbeans debugger. In fact, I often develop my applications when I debug step by step in order to see immediately if my code works.

I feel spending a lot of time programming this way because the use of debugger increase execution time and I often wait for my app to jump from a breakpoint to an other (so much that I've the time to ask this question).

I never learned to use a debugger at school, but at work I've been told immediately to use this functionality. I started teaching myself to use it two years ago, and I've never been told any key tips about it.

I'd like to know if there are some rules to follow in order to use the debugger efficiently.

I'm also wondering if using the debugger is eventually a good practice? Or is it a loss of time and I've to stop now this bad habit?


答:
Debugging eats up time since you are executing code a billion times slower than you would in a unit test.  Often there is a better tool for the job: microbenchmarks, performance profilers, unit tests, logging, or just reading the code.  With a suite of unit tests you can execute dozens of code paths in milliseconds, which would take hours in a debugger.

I rarely debug when I can write a unit test.  That way, you have a record in the form of an executable test of how the code works.  If you simply debug, that knowledge is only in your head until you forget it.

When you have to debug, specific tips would be to learn the step over/into/return hotkeys for your debugger, how to inspect variables, and use conditional break statements.


问:
TTS on App Engine
I have written a small front-end to the Festival TTS system using Python/Django. I wish to deploy it on the Google App Engine cloud. A few questions:

My application uses the Festival app 'text2wave'. Will is work on the cloud?

I have used Python primitives like subprocess.call() to invoke the aforementioned program. Will that work?

If your answer to any or both of (1) and (2) is no, is there a free api on the web that I can use (from the appengine)? I read somewhere about placing calls from Phono to a Voxeo backend, but I'm not sure what that means.

I am aware of the Google Translate extension that allows translation using an HTTP GET (REST) request, but here the text is limited to 100 chars. Bad. Plus, they may take it down any point of time.

答:
1 and 2) I am almost certain subprocess.call() won't work on App Engine for security reasons. Even file system level access is forbidden.

3) If nothing else does the trick, you can build a minimalistic Festival text2wave server that spits out embedable media on Amazon's EC2 or any other VPS-ish platform. You can then embed it in your App Engine application results page.

Title: TTS on App Engine


答:
The differences seem to be minimal until you unpeel the layers to reveal how Silverlight really works.

One person mentioned the inability to perform a synchronous web service call.  Other notable limitations are that Silverlight runs on its own dedicated runtime environment and cannot utilize the core .NET framework libraries.  It is wholly dependent on the limited Silverlight framework libraries, which in fairness is mostly complete however you will run into situations where you will want access to something specifically on the .NET core library that is not available to the Silverlight Runtime.

The other issue I have personally run into is with trying to reuse the same data model classes from my web service project to my Silverlight project.  You can't share the project or the binary assembly directly, as it compiles and runs only on the core .NET framework.  You either duplicate your data model code in both projects (which has its design advantages by the way) or you create a Silverlight project that references resources from your actual data model project.  In this way you have two projects, one that will compile for running on the core framework and the other for Silverlight.  Again, not a big deal, just another wtf realization I had the first time I ran into it.

There are also limitations on XAP file size which third party frameworks are able to deal with quite effectively, but it is something to look out for.


答:
At work, using a debugger increases programmer's efficiency. At school, you can spare it as it is good to dry-run the algorithm of your programming code yourself to get the correct and desired symantics.

Debugger is an efficient and useful tool for programmers. You cannot avoid it at professional level.It is good for you to learn using a debugger yourself for your programming environment as this will greatly help you to save programming time and effort. So using a debugger is a good programming practice at work!


答:
Using the debugger undoubtedly increases your efficiency, since it allows you to do things that would be difficult or impossible to do without it. It is way more efficient to eval expressions on the fly, change local variables etc. than to pre-guess what you might be interested in and write the corresponding printf statements, and to sift through the output for exactly what you want to know.

However, it might indicate that you have other problems - you would normally like to be able write routine code without having to step through it attentively even once, since it's the result that counts rather than the details, and that can be asserted via unit tests. However, that is a matter of personal preference. You may very well be much more productive with your exploratory style than your co-worker with their test-driven style, and vice versa.


答:
I really, really wish our last developer used a debugger. We had a PHP site with a framework with lots of good debugging features, he used none of them. Since the code was PHP and there were no compiler errors, he apparently merrily mutilated his code until it worked at run time.

Every single page output dozens of warnings or errors when in debug mode and if he bothered to read debug output or line-by-line analyze what his code was doing, much of this could have been avoided. Rather than use a debugger he used manual code to write variables to a .log file on the server. He left that code in production; the log files were 8 GB by the time I got to them.

You might spend more time walking through your code, but you'll spend less time trying to fix it. You'll write better code as well, and it will help you understand your own code, making you a better programmer period.


答:
While I rarely write Java code these days, I rely on Python's ipdb library (or Werkzeug HTML/AJAX-based debugger shell) to gain access to an interactive environment where I can manipulate objects in that given stack frame.

It's often an invaluable tool for exploratory programming.

With Java (mostly under Eclipse), I tend to use watches and the debugger more or less the same way, to explore the machine state on any given program point and try to gain some understanding from it. I really thing it helps me being more productive and to understand other people's code better.


问:
Why does Java not permit the use of headers as in C++
I have a question that I did not find an answer for except the following answer that does not meet my requirements:

"Because James Gosling didn't want to"

I know that Java can have interfaces (only pure virtual functions, no attributes), but it is not the exact same thing as class definitions.

答:
One good reason to have includes is to separate code you may want to reuse (such as common definitions) from the code that's specific to a given project. Java wants you to specify only one class or interface per file and that mostly reduces the need for included headers - for you will nave the shared parts already in their own files.

Also, compilers and build systems may want to cache precompiled headers to avoid parsing them more than once.


答:
All good answers.  I would also like to add that returning an error code instead of throwing an exception can make the caller's code more complicated.  Say method A calls method B calls method C and C encounters an error.  If C returns an error code, now B needs to have logic to determine if it can handle that error code.  If it can't then it need to return it to A.  If A can't handle the error then what do you do? Throw an exception? In this example, the code is much cleaner if C simply throws an exception, B doesn't catch the exception so it automatically aborts without any extra code needed to do so and A can catch certain types of exceptions while letting others continue up the call stack.

This brings to mind a good rule to code by:

Lines of code are like golden bullets. You want to use as few as
  possible to get the job done.

Title: Using a try-finally (without catch) vs enum-state validation

Body:
I have been reading the advice on this question about how an exception should be dealt with as close to where it is raised as possible.

My dilemma on the best practice is whether one should use a try/catch/finally to return an enum (or an int that represents a value, 0 for error, 1 for ok, 2 for warning etc, depending on the case) so that an answer is always in order, or should one let the exception go through so that the calling part would deal with it?

From what I can gather, this might be different depending on the case, so the original advice seems odd.

For example, on a web service, you would always want to return a state of course, so any exception has to be dealt with on the spot, but lets say inside a function that posts/gets some data via http, you would want the exception (for example in case of 404) to just pass through to the one that fired it. If you don't, you would have to create some way to inform the calling part of the quality of the outcome (error:404), as well as the outcome itself.

Though it IS possible to try-catch the 404 exception inside the helper function that gets/posts the data, should you? Is it only I that use a smallint to denote states in the program (and document them appropriately of course), and then use this info for sanity validation purposes (everything ok/error handling) outside?

Update: I was expecting a fatal/non-fatal exception for the main  classification, but I didn't want to include this so as not to prejudice the answers. Let me clarify what the question is about: Handling the exceptions thrown, not throwing exceptions. What the desired effect is: Detect an error, and try to recover from it. If recovery isn't possible, provide the most meaningful feedback.

Again, with the http get/post example, the question is, should you provide a new object that describes what happened to the original caller? If this helper was in a library you are using would you expect it to provide you with a status code for the operation, or would you include it in a try-catch block? If you are designing it, would you provide a status code or throw an exception and let the upper level translate it to a status code/message instead?

Synopsis: How do you chose if a piece of code instead of producing an exception, returns a status code along with any results it may yield?


答: Some zealots out there might claim that debuggers make you lazy, or that you should just write a unit test for everything. For those of us that have to actually get stuff done, a debugger is an essential tool in quickly troubleshooting/exploring code. Of course test coverage is great, and will let you know what your code is doing, but sometimes you just need to get into the thick of it and see what's going on.</p>


问:
What are the worst false economies in software development?
What are the worst false economies (that is ways of saving money that ultimately cost more than they save) prevalent in the software industry and how do you combat them?</p>

答:
Making your developers use a 15 inch monitor and low spec PC as it is the corporate standard.

Reasonable sized monitors are cheap, quick to install and make the programmers more productive as well as making your programmers think you care about them.

ContentLicense: CC BY-SA 2.5


问:
How should I add functionality to an object that already exists?
I have an interface that has a certain amount of well-defined functionality. Let's say:

```<code>interface BakeryInterface {
  public function createCookies();
  public function createIceCream();
}
</code>```

This works well for most implementations of the interface, but in a few instances, I need to add some new functionality (like perhaps rolled into a new method, createBrownies()). The obvious/naive approach to doing this would be to extend the interface:

```<code>interface BrownieBakeryInterface extends BakeryInterface {
  public function createBrownies();
}
</code>```

But has a pretty big downside in that I can't add the new functionality without modifying the existing API (like changing the class to use the new interface).

I was thinking about using an adapter to add the functionality after instantiation:

```<code>class BrownieAdapter {
  private brownieBakery;

  public function construct(BakeryInterface bakery) {
    this->brownieBakery = bakery;
  }

  public function createBrownies() {
    /* ... */
  }
}
</code>```

Which would net me something like:

```<code>bakery = new Bakery();
bakery = new BrownieBakery(bakery);
bakery->createBrownies();
</code>```

This seems like a good solution to the problem, but I'm wondering if I'm awakening the old gods by doing it. Is the adapter the way to go? Is there a better pattern to follow? Or should I really just be biting the bullet and just extending the original interface?

答:
If there is a requirement that bakery instance must change its behaviour dynamically (depending on the user actions, etc.) then you should go for the Decorator pattern.

If bakery does not change its behaviour dynamically but you cannot modify the Bakery class (external API, etc.) then you should go for the Adapter pattern.

If bakery does not change its behaviour dynamically and you can modify Bakery class then you should extend existing interface (as you initially proposed) or introduce a new interface BrownieInterface and let Bakery implement two interfaces BakeryInterface and BrownieInterface.

Otherwise you gonna add unnecessary complexity to your code (using the Decorator pattern) for no good reason!


答: A detailed comparison can be found on the following paper. I assume that the paper was prior to Silverlight 5, nevertheless, the paper is very comprehensive. Guidance on difference between Silverlight and WPF. MSDN has released a comparison detailing some features in WPF not in Silverligth and vice verse on this link:MSDN-WPF-Silverlight. Hope this helps.</p>


问:
Is is preferable to design top down or bottom up?
As I understand, top-down design is by refining the abstract high level concept into smaller concrete and comprehensible parts, until the smallest building block is defined. On the other hand, bottom up defines low level parts, then gradually build up higher level blocks until the whole system is formed.

In practice, it is said best to combine the two methods: starts with high level specification to fully specify the domain knowledge, its relationship and constraints. Once the problem is well understood, smallest building blocks are created to build up the system.

The process of:

Creating requirement spec

Create a design spec (with diagrams)

Implement

Deliver

Repeat (in iterative development, rather than doing a whole chunk in each phase, we do a little bit each repeatedly, and got daily meeting to adapt to customer's dynamic requirement)

looks perfectly normal to me (with specs as plans). It has its flaws but that's why we got iterative development: instead of spending time on one phase, says, requirement analysis to study every possible thing in domain knowledge which is subjected to changes (possibly daily), we do a little bit of analysis, a little bit of design and then implement it.

Another way is that each iteration is a mini-waterfall fashion, where analysis is done in a few days (or a week). The same applies for design. The rest of time is spent for implementation. Is there something inherently wrong with top-down approach in combination with iterative development?

In his essay Programming Bottom Up, Paul Graham seems to encourage build from bottom up completely, or program it from bottom up, but not the requirement analysis/design phase:

Experienced Lisp programmers divide up their programs differently. As
  well as top-down design, they follow a principle which could be called
  bottom-up design-- changing the language to suit the problem.

As far as I get, what he meant is that Lisper still performs top-down design, but program bottom up, is that true? Another point he wrote:

It's worth emphasizing that bottom-up design doesn't mean just writing
  the same program in a different order. When you work bottom-up, you
  usually end up with a different program. Instead of a single,
  monolithic program, you will get a larger language with more abstract
  operators, and a smaller program written in it. Instead of a lintel,
  you'll get an arch.

Does this means that during the period of writing a program in Lisp, you end up with a generic tool?

答:
Ideally, writing a program in any language, not just Lisp, lets you write a whole set of generic tools that can speed you along on your next program or speed enhancements to your current one.

In practice, keeping track of these tools can be difficult.  Documentation is poor and disorganized and people who know about them leave.  In practice, reusing code is often more trouble than it's worth.  But if the code is documented and organized properly, and programmers stick around (or keep their own supply of useful code) a vast amount of work can be saved by grabbing code from the warehouse rather than rebuilding it.

All design has to be top down or you wouldn't know what you were doing.  Are you building a shed or a car?  You can't figure out that one with bottom-up design.  But if you are going to build a left front wheel, you might think that you might need more wheels later, both for this project and for others.  And if you build a reusable wheel you'll have four for the price of one.  (And 18 for that tractor-trailer you're building next, all for free.)

Note that unlike with real cars and real wheels, if you've built one software "wheel" you've built an infinite number of them.

More on top-down design:  while you have to start out with this, I feel obligated to point out that if you cannot build a wheel, you need to find that out before you do much work on your car.  So you do need to work bottom-up almost in parallel with working top-down.  Also, knowing you can build a wheel might suggest a lot of projects you would not have thought of before, like the tractor-trailer.  I do think the top-down approach has to dominate, but with a very light touch.

So, to continue paraphrasing Paul Graham, ideally when you write a program you end up with lots of reusable parts that can save lots of time on both the original program and in others.  To distance myself slightly from Paul Graham, this works in any language (though some encourage the process more than others).

The enemy of this almost magical process are programmers with very short-term outlooks.  This may result from personality defects, but more commonly from switching jobs and responsibilies too quickly, both inside and between employing companies.


答:
I think that it is a very good practice and somewhat a replicate of the test-driven approach. By way of immediately stepping through the code, the programmer is unit-testing it himself.

However, I also think that the programmer should have confidence in the code that he has written and should not write code that he does not trust to see how it behaves within the debugging environment. That, for sure, will lead to inefficiency.

Moreover, do not forget that there can be environments where you might not have the capability to run the debugger. I had an issue where I had to work on a code base that I did not have the luxury and time to set-up the debugger for. The code just had to work. Thankfully it was a small area for the modification and thankfully it worked.


答: Using a debugger is fine when something fails, or when you don't understand what some legacy code does. Using a debugger when nothing fails, just because you don't understand what your own code does (the lines you have written the last 10 minutes), is IMHO a very bad practice. In this case you could improve your productivity much more by investing time in writing your code in a more readable or understandable manner instead of debugging, or by writing some automatic tests.</p>


答:
Obviously a debugger is invaluable for understanding your own and other developers code. However, don't lean on it! For bottom-up approaches, you generally should try to find a proof that your code is doing what it should do. Multi-threaded code generally is hard to debug, especially when you have problems with deadlocks/lifelocks/starvation. I feel it is one of the prime reasons why many die-hard programmers find it so hard to write multi-threaded code, as they don't have their most 'valuable' tool to their disposal.

I use a debugger as a last resort and generally only in unstructured code, when a proof is hard to find.

The things you should lean on are:

Prevent state (the prime reason why you need a debugger)

Prevent complex code paths (another reason)

Use unit-tests (find bugs earlier)

Try to find a proof that your algorithms are working the way the do

Document the pre- and post-conditions of your methods (

Peer-review your code

These should give you trust in the things you're writing.


问:
Should a view and a model communicate or not?
According to the wikipedia page for the MVC architecture, the view is free to be notified by the model, and is also free to query the model about its current state. However, according to Paul Hegarty's course on iOS 5 at Stanford, lecture 1, page 18 all interaction must go through the controller, with Model and View that are never supposed to know each other. It is not clear to me if Hegarty's statement must be intended as a simplification for the course, but I am tempted to say that he intends the design as such.

How do you explain these two opposite points of view ?

答:
This is a controversial topic in MVC/MVVM.  Some say it is OK for the View to access the Models directly, other say you should wrap the Models in ViewModels in order to abstract them away from the View.  I'm personally not a fan of either approach.

The one of the primary goals of MVC/MVVM is to decouple the UI, business logic and data.  So with that concept in mind, allowing the View to directly access the Models creates a dependency that you might not want to have.  On the other hand, wrapping the Models in ViewModels is often tedious and not very useful as the ViewModels tend to act simply as a pass-through to the Models.

I like the approach of having your Models implement a particular interface, lets call it IModel.  Your ViewModel class can then offer instances of objects that implement IModel for View consumption.  The View simply knows it works with IModel objects that it gets from the ViewModel.  This removes the extraneous ViewModel wrapper code as well as hides the concrete implementation of IModel from the View.  You can later swap out one implementation of IModel for another without affecting the View one bit.


答:
Debuggers are just another tool.  It can really help your understanding of programming when you are starting out, and it can simplify hard problems at times.

There is also a logic portion to solving problems--many problems involving threading or the interactions of systems can be difficult or impossible to trace with a debugger--for those you may need different tools--working on your problem solving skills NEVER hurts.

You know one thing I've learned over the years is that everyone who is proficient in a skill thinks they know 90% of what they need to know--the problem is that people typically can't know what they don't know (if they saw something they didn't know, they would go and learn it!)

Why do I add that?  Well I've seen developers who can solve most problems without a debugger much quicker than it would have taken to bring the debugger up.  Over-reliance can slow you down if that's the very first thing you do every time.

It's like learning on the keyboard--if a beginning typist had to type on a keyboard without letters he'd think it was obvious that having letters was better--but then you reach a point where having the letters removed can make you significantly faster (By teaching you not to look at your hands), and finally you reach the point where it's completely irrelevant if the letters are on the keys or not.

In programming some people reach that last stage where the debugger just slows you down, but there are probably more at a point where having it taken away might boost their analysis skills significantly--yet most people are probably in the first stage where you just flounder without it.


答: You should be able to reason through the code without the use of a debugger. It's good that you're using it though and yes it does have an effect. Sometimes it's faster and more efficient to run through the code and see how it changes things rather than to puzzle it out just by reading the code.</p>


问:
How do I learn algorithms and data structures?
This is in continuation to my previous question where I asked is it necessary to learn algorithms and data structures. I feel yes it is.

Now I work in an environment where I won't ever get the chance to learn it by experimenting or practically or in any assignment. What is the right approach like the right books, right kind of problems, right kind of resources that I can go through to give six months or a year or two to learn algorithms and data structures?  And also mold my mind in a way that it can relate problems to data structures and algorithms.

答:
here the following link redirects you to one of the most successful DS and Algorithms classes by MIT I've ever followed.

http://academicearth.org/courses/introduction-to-algorithms

Hope you'll enjoy this video series. Good luck !!!


答: Too many Bachelors of Business Administration (or the like), hierarchically organized, that try to apply what they think modern management is about: Bothering people with "KPI"s, "SLA"s and what not, requiring "reports" (without, of course, caring about the infrastructure to generate them), so that programmers waste their days filling in fancy EXCEL sheets, Q4 reports and what not and copy from one great new management tool and paste into another one (it seems to be the rule that these tools are never inegrated nor integratable with each other), and attend meetings where the reports and figures are presented (and everybody is made feeling guilty about having failed to fullfil this or that KPI).</p>

Title: What are the worst false economies in software development?

Body: What are the worst false economies (that is ways of saving money that ultimately cost more than they save) prevalent in the software industry and how do you combat them?</p>


问:
Where can I obtain the specification for Distributed Relational Database Architecture?
I'm developing a DBMS that should be able to connect to IBM DB2 via the DRDA protocol. I found a DRDA reference manual that mentions "DRDA Implementation Programmer's Guide, SC21-9529" as a publication about DRDA, and seems that this manual is exactly what I was looking for. The problem is, I am unable to find it on the net.

Where can I obtain this document or another comparable document that explains implementing DRDA?

答:
The Distributed Relational Database Architecture (DRDA) Version 5 standard  is available online as a free PDF download from The Open Group's Publications Catalog.  It comprises 3 volumes:

C112 DRDA V5 Vol. 1: Distributed Relational Database Architecture
(806 pages)
https://www2.opengroup.org/ogsys/jsp/publications/PublicationDetails.jsp?publicationid=12360

C113 DRDA V5 Vol. 2: Formatted Data Object Content Architecture (110
pages)
https://www2.opengroup.org/ogsys/jsp/publications/PublicationDetails.jsp?publicationid=12361

C114 DRDA V5 Vol. 3: Distributed Data Management Architecture (1176
pages)
https://www2.opengroup.org/ogsys/jsp/publications/PublicationDetails.jsp?publicationid=12362

The current version (as of this writing) was published in August 2011.  It supersedes DRDA v4 (C066, C067, C068) published in April 2007, which in turn superseded DRDA V3 (C043, C044, C045) published in January 2004.


问:
How should I implement a secure priority queue in C?
I have an assignment to implement a priority queue in C as well as make an app that uses it. I, however, only know basic-level C (I do know Java). My intuition says that I need to learn pointers.

What other stumbling blocks should I expect or prepare for? How do I go about making this secure?

答:
If the set of priorities is small and virtual memory plentiful, it's a reasonable approach to use an array of queue structs, indexed by priority, where the consumer iterates the array from the high-priority end looking for a non-zero queue count.  If the items queued are pointers, then a queue struct based on a 'classic' circular buffer with in/out indexes should be fine.  If the priority queue is to be producer/consumer, then you need the usual pair of semaphores and a critical section, (or some other appropriate signaling/protection mechanism).

The advantages of this appoach is that it is not necessary to iterate a list, (or navigate a tree), of queued items on push/pop and also there is, in general, no malloc/free/realloc per push/pop, (ie. no contention on memory-manager either).

The memory-use issue can be mitigated by some extra code to malloc/realloc/free queue buffer space as necessary, but this obviously requires more code inside the queues lock, (especially if it is found that a queue needs to be realloced larger), impacting contention :(


问:
If ASP.NET MVC 4 supports RPC style communication what does that mean for WCF?
From http://www.microsoft.com/download/en/details.aspx?id=28942

ASP.NET MVC 4 also includes ASP.NET Web API, a framework for building
  and consuming HTTP services that can reach a broad range of clients
  including browsers, phones, and tablets. ASP.NET Web API is great for
  building services that follow the REST architectural style, plus it
  supports RPC patterns.

If ASP.NET MVC 4 supports RPC style communication what does that mean for WCF?

On what basis should we chose to use WCF or ASP.NET MVC Web API's RPC mechanism?

答:
Nothing.  You're still free to use WCF where it is most suitable, or at your own discretion.

ASP.NET MVC has supported a RESTful communication style since its inception, and many people use it as a thin veneer for RESTful services.  That doesn't automatically cause WCF to go obsolete, or make ASP.NET MVC the One Tool to Rule Them All™.

This is why carpenters and other craftsmen don't just have one type of hammer.  They have several different types, each optimized for a particular type of hammering.

To help you decide which to use, listen to this Hanselman podcast:

This is not your father's WCF - All about the WebAPI with Glenn Block

How does WCF fit into a world of Web 2.0 lightweight APIs? What's the
  WCF WebAPI and how does compare to services in ASP.NET MVC?

I haven't personally looked at it yet, but it wouldn't surprise me if the Web API you refer to in ASP.NET MVC 4, and the new WebAPI in WCF, turn out to be the same thing. Phil Haack is probably using WCF to implement WebAPI internally in ASP.NET MVC 4, or they both resolve to the same internal mechanism.

See Also

http://wcf.codeplex.com/wikipage?title=WCF%20HTTP


问:
Learning Zend Framework 1 or 2?
I have programmed for a few years in php and now I'm going to learn zend framwork.
Zend is very popular and there are a lot of tutorials, books and documentation out there. But I saw in the last months that there is a second version of Zend, but it's not so used and popular, not yet.

I think it is better to start with a new version, but I don't know what to do now, as when I see job offers many people require the first version.
Which version do you suggest me?

答:
ZF2 appears to be in beta; this will add additional overhead to your daily routine, as you might often have to update previously written code with each subsequent beta release (which could be often).

With that said, if you're looking at starting a long term project, that overhead may be worth it.  I ran into this dilemma a while ago with Symfony2, and decided I did not want to start a new project with a framework that will have no LTS.

If you simply want to learn this to increase your employability, you won't likely see any benefits for a year or more.  As it stands, no companies will be running ZF2 for a production application, and it is unlikely that many will want to migrate their ZF1 application immediately (or at all) after the release of ZF2.

Title: Learning Zend Framework 1 or 2?


问:
Is there a typical way of having a view that is a dependent on another?
I am working on a program with two views, html and ajax (which will be html transmitted via json).

The HTML view is the standard, and by default the ajax should look the same. However, the ajax view is also meant to have options configurable on the client side for which components of the page should be displayed.

I'm having trouble wrapping my head around making an elegant way to handle this requirement. Is there a standard way to handle related views like this?

答: Isn't the HTML view just a degenerate case of the "ajax" view -  equivalent to the ajax view with all configurable components turned on? If so, doesn't that simplify the dependency?</p>


问:
Which one of these implementations is more appropriate for my REST api?

Background

So I have a REST API that allows for client applications to access and manipulate users' data.

I'm in the process of writing an Objective-C class for simple utilization of this REST API, but I'm stuck between two methods of implementation.

Method 1

```<code>class MYClient
    string username
    string password
    methods for using GET, PUT, POST, DELETE on questions
    // questions are dictionaries with 'title' and 'body' strings
</code>```

Method 2

```<code>class MYUser
    string username
    string password
    array  tokens
class MYToken
    string title
    string body

// classes inherently sync themselves to the server in their initializers, setters, and getters
</code>```

Questions

Is there one that is more appropriate for use in (for example) iOS apps?

Is there one that is more appropriate in general?

What are the distinct benefits of Method 1 over Method 2 and vice versa?

答:
The difference is going to be the number and granularity of HTTP requests that go over the network.

Method 1 is going to send fewer, larger requests that perform operations on a batch operations.  Method 2 is going to send more, smaller requests every time an object's property is modified.

Method 1 is also going to give you the ability to queue up a bunch of changes client-side then give the user the option to cancel or commit the changes.  Method 2 is going to commit each change individually and immediately.  If the user cancels or undoes an operation then a second request will be needed to undo the changes server side.

Based purely on their own merits, I prefer Method 1.  However, which one is more appropriate for your app depends on the functionality you are looking for.

UPDATE: In Method 1, MyClient.DoSomething() does not have to "do something" to one object at a time.  Say you want to create 5 new MyUser objects.  You don't have to call MyClient.Create(newMyUser) 5 times, once for each new MyUser object.  Your Create() method can take an array of objects and all 5 new MyUser objects can be sent to the server in the body of a single POST.  Similarly, say you want to update the UserName and Password properties on the same MyUser object.  Method 2 would result in 2 requests, each sending a copy of the whole MyUser object for each property change.  Method 1 would allow you to make the changes to both properties client side then send the MyUser object with both property changes to the server in a single PUT.  In both scenarios, Method 1 gives you the option to delay pushing changes to the server until you call the appropriate method in MyClient and pass in the changed objects.  In Method 2, changes to each object are pushed to the server immediately and individually.


问:
Are utility classes with nothing but static members an anti-pattern in C++?
The question Where should I put functions that are not related to a class has sparked some debate over whether it makes sense in C++ to combine utility functions in a class or just have them exist as free functions in a namespace.

I come from a C# background where the latter option does not exist and thus naturally trend toward using static classes in the little C++ code I write. The highest voted answer on that question as well as several comments however say that free functions are to be preferred, even suggesting static classes were an anti-pattern. Why is that so in C++? At least on the surface, static methods on a class seem indistinguishable from free functions in a namespace. Why thus the preference for the latter?

Would things be different, if the collection of utility functions needed some shared data, e.g. a cache one could store in a private static field?

答: If a function maintains no state and is reentrant, there doesn't seem to be much point in shoving it inside a class, (unless forced to by the language).  If the function maintains some state, (eg. it can only be made thread-safe by means of a static mutex), then static methods on a class seem appropriate.  </p>


答:
Limited or no internet access

Because obviously your employees will use use the internet to play facebook games not too research answers to technical questions on Stackoverflow.

In reality of course the internet is a huge productivity boost, and while it may be appropriate to use some sort of site filter for genuinely dodgy sites there is something wrong if it is blocking the visual studio readme file or blocking telford local goverment pages for reason "sex tourism"