问:
About insertion sort and especially why it's said that copy is much faster than swap?
From Lafore's "Data Structures and Algorithms in Java":
(about insertion sort (which uses copy + shift instead of swap (used in bubble and selection sort)))

However, a copy isn’t as time-consuming as a swap, so for random data
  this algo- rithm runs twice as fast as the bubble sort and faster than
  the selectionsort.

Additionally, the author doesn't mention how time consuming shift is.

It seems that copying is the simplest pointer assignment operation. While swap is 3 pointer assignment operations, which don't take much time. Further, shift of N elements is N pointer assignment operations.

Can someone explain this seeming inconsistency?

答:
a copy isn’t as time-consuming as a swap

Let's compare a copy to a swap:

```<code>int[] a = ...
int idx = ...

// copy:
a[idx] = a[idx + 1];

// swap:
int temp = a[idx];
a[idx] = a[idx + 1];
a[idx + 1] = temp;
</code>```

Swap allocates a temporary variable performs and three copies - one from the array to the temporary variable, one from one index at the array to another, and one from the temporary variable back to the array.  Therefore a swap is at least 3 times as expensive as a copy.

Shifting elements in an array (as opposed to shifting bits in a primitive integer type) is expensive because it is repeated copying:

```<code>for (int i = shiftEnd - 1; i >= shiftStart; i--) {
  a[i + 1] = a[i];
}
</code>```

You can see here that when (shiftEnd - shiftStart) > 3 a shift will perform more copy operations than a swap.

Let's look at the same example with an array of pointers to objects instead of primitive ints:

```<code>Object[] a = ...

// copy the pointer to an object from one array element to another
a[idx] = a[idx + 1];

// swap the pointer to an object between array elements
Object temp = a[idx];
a[idx] = a[idx + 1];
a[idx + 1] = temp;
</code>```

You will notice that these operations are exactly the same whether dealing with primitives or objects.  The List version is more expensive due to the method-call overhead of accessing the list.  Most List implementations use multiple arrays to allow resizing of the list which is more expensive than using a single, fixed-length primitive array.

Body:
a copy isn’t as time-consuming as a swap

Let's compare a copy to a swap:

int[] a = ...
int idx = ...

// copy:
a[idx] = a[idx + 1];

// swap:
int temp = a[idx];
a[idx] = a[idx + 1];
a[idx + 1] = temp;

Swap allocates a temporary variable performs and three copies - one from the array to the temporary variable, one from one index at the array to another, and one from the temporary variable back to the array.  Therefore a swap is at least 3 times as expensive as a copy.

Shifting elements in an array (as opposed to shifting bits in a primitive integer type) is expensive because it is repeated copying:

for (int i = shiftEnd - 1; i >= shiftStart; i--) {
  a[i + 1] = a[i];
}

You can see here that when (shiftEnd - shiftStart) > 3 a shift will perform more copy operations than a swap.

Let's look at the same example with an array of pointers to objects instead of primitive ints:

Object[] a = ...

// copy the pointer to an object from one array element to another
a[idx] = a[idx + 1];

// swap the pointer to an object between array elements
Object temp = a[idx];
a[idx] = a[idx + 1];
a[idx + 1] = temp;

You will notice that these operations are exactly the same whether dealing with primitives or objects.  The List version is more expensive due to the method-call overhead of accessing the list.  Most List implementations use multiple arrays to allow resizing of the list which is more expensive than using a single, fixed-length primitive array.


问:
Software design for non object oriented paradigm
I'm currently working on a project where I'm writing the firmware for an electronic system in C, and have been asked to produce documentation on the development/evolution of the software for the embedded devices. Having developed software in the object oriented paradigm I know to use UML to document the software such as class diagrams with objects, however this does not work for documenting the development of my embedded system. So what should I produce to document the development of my firmware?</p>

答:
You can make an object-oriented design and implement it in C, even though C does not directly support object-oriented concepts.

See for example Rumbaugh et al., "Object-Oriented Modeling and Design", Chapter 16, Prentice-Hall 1991, ISBN 0-13-629841-9.

ContentLicense: CC BY-SA 3.0


答: You do the same design only with conceptual modules (like you really should've done in OO design) rather than explicit classes. In C, those modules tend to be functions, structures, or some bundle of functions, structures or both.</p>

Title: Software design for non object oriented paradigm

Body: I'm currently working on a project where I'm writing the firmware for an electronic system in C, and have been asked to produce documentation on the development/evolution of the software for the embedded devices. Having developed software in the object oriented paradigm I know to use UML to document the software such as class diagrams with objects, however this does not work for documenting the development of my embedded system. So what should I produce to document the development of my firmware?</p>


答:
Even for a system that is not designed according to the OO paradigm, you can still use UML notation to document the system, possibly extended with some Data Flow Diagrams (as I can't immediately find a corresponding diagram in UML).
Diagrams worth looking into, even for non-OO systems are:

State (Transition) Diagrams

Use Case Diagrams

Sequence Diagrams

When modeling a non-OO system, you may have to be a bit flexible as to what you model as a 'class'.

For example, if you have a header file stack.h like this

```<code>struct stack;
struct stack* stack_create(void);
void stack_destroy(struct stack*);
void stack_push(struct stack*, void*);
void stack_pop(struct stack*);
void* stack_top(struct stack*);
</code>```

with corresponding implementation, there is nothing to stop you from presenting that as a 'class' stack in your models.

Body:
Even for a system that is not designed according to the OO paradigm, you can still use UML notation to document the system, possibly extended with some Data Flow Diagrams (as I can't immediately find a corresponding diagram in UML).
Diagrams worth looking into, even for non-OO systems are:

State (Transition) Diagrams

Use Case Diagrams

Sequence Diagrams

When modeling a non-OO system, you may have to be a bit flexible as to what you model as a 'class'.

For example, if you have a header file stack.h like this

struct stack;
struct stack* stack_create(void);
void stack_destroy(struct stack*);
void stack_push(struct stack*, void*);
void stack_pop(struct stack*);
void* stack_top(struct stack*);

with corresponding implementation, there is nothing to stop you from presenting that as a 'class' stack in your models.


问:
When is a 'core' library a bad idea?
When developing software, I often have a centralised 'core' library containing handy code that can be shared and referenced by different projects.

Examples:

a set of functions to manipulate strings

commonly used regular expressions

common deployment code

However some of my colleagues seem to be turning away from this approach. They have concerns such as the maintenance overhead of retesting code used by many projects once a bug is fixed. Now I'm reconsidering when I should be doing this.

What are the issues that make using a 'core' library a bad idea?

答:
One point not yet mentioned is that any code is going to have dependencies on something, even if it's literally the only thing running in the ROM of an embedded microcontroller; if the manufacturer of the controller changes some behavior which the code relied upon, the code will either have to be modified to work on chips manufactured after the change, or else manufacturers of the device which uses the code will have to somehow acquire chips which do not incorporate the change--possibly paying a price premium for them.

Using a library to perform various hardware functions may mean that code is now dependent upon a library whereas it hadn't been previously, but it may also eliminate dependencies between the code and the hardware.  For example, a chip manufacturer might promise to supply a library for all present and future chips which will always perform certain I/O functions a certain way.  Code which uses that library to perform those I/O functions would become reliant upon the manufacturer to supply appropriate versions of that library, but would no longer be dependent upon the manufacturer to use the same hardware implementation of those functions.

Unfortunately, it's often hard to know which is the correct approach for future-proofing code.  I've seen cases where a chip vendor changed the way a library worked (so as to accommodate new chips), even when it was being used to access a chip which had changed.  I've also seen cases where a chip manufacturer changed the way its hardware worked, but supplied libraries were adjusted appropriately, so code which used a library routines would continue to work without change, while code which accessed hardware directly had to be adjusted.

Similar situations exist with Windows applications.  Microsoft sometimes loves to change the way applications are required to do things; code which uses certain libraries for such things may be upgraded simply by updating the library, while code which does not use libraries that get updated for them must be updated manually.

Title: When is a 'core' library a bad idea?


答:
Writing libraries for basic things like strings and linked lists is quite silly in this millennium. Use a batteries-included programming language which has the core functionality already in it.

If you like writing core run-time support libraries just for fun, then design a new programming language. If you do that in an application, then essentially you're growing a language out of its side.

Besides, hasn't someone already written N different core libraries in the language you're using? Researching existing frameworks and picking the best-suited one may be better use of time than doing it from scratch.

Title: When is a 'core' library a bad idea?

Body:
When developing software, I often have a centralised 'core' library containing handy code that can be shared and referenced by different projects.

Examples:

a set of functions to manipulate strings

commonly used regular expressions

common deployment code

However some of my colleagues seem to be turning away from this approach. They have concerns such as the maintenance overhead of retesting code used by many projects once a bug is fixed. Now I'm reconsidering when I should be doing this.

What are the issues that make using a 'core' library a bad idea?


问:
How would you react if someone told you your code is a mess?
I am a good programmer, or so I thought before. I always love to program. And I want to learn many things about programming to make me a better programmer. I studied programming for 1 year and now I am working as a programmer for almost 2 years. So in short, I have almost 3 years programming experience.

Our team is composed of 5 programmers, and 4 of us are new, 1 has more than 3 year experience. We've been working for a program for almost a year now and nobody ever review my code and I was given a page to work with. We never had a code review and we are all new so we don't know what is a clean code looks like. I think programmers learn by themselves?

We deployed our program to the program without thorough testing. Now it is tight and we need an approval and code review first before we make changes with the code. For the first time, someone reviews my code and he says it is a mess.

I feel so sad and hurt. I really love programming and making them say something like that really hurts me. I really want to improve myself. But it seems like I'm not a genius programmer like in the movies. Can you give me advise on how to be better? Have you ever experience something criticizing your code and you feel really hurt? What do you do on those events.

答:
While it is important to recognize when your own code is a mess (very typical feeling among programmers, especially as they become more experienced and their earlier code ages) it is even more important to listen when other people tell you so.

There are only so many issues you can recognize in your own code, since it was produced in constraints of your current programming knowledge.

Code review is essential learning opportunity because it likely exposes you to new knowledge that you didn't have while working on the code (otherwise you would use it and there would be no mess).

I think there are two parts to processing negative feedback.

1. Determine nature of raised issue(s) and what you should learn from it

When I review or have my code reviewed I sort information about code issues in roughly such buckets:

violates hard technological requirements

plain wrong (does not function or perform to requirements)

will fail in other circumstances (environment/configuration change)

uses deprecated functionality and will break in foreseeable future

violates industry best practice, lacking in things such as

using proven approach to specific problem

performance

backwards compatibility

ease of maintenance

coding style

documentation

violates workplace best practice

same as industry, but more specific to company/colleagues and can differ from industry in details

not in line with personal expertise

can be improved in some way, in opinion of person reviewing

Note that this ranges from very objective things ("this will break when deployed to our production server") to very subjective things ("I don't like how you named variables").

2. Determine which (if any) changes to the code will be made as outcome of review

After information is processed there comes decision if it is actionable and if code should be changed. This is not necessarily your decision, your opinion might or might not matter depending on parties involved and specifics of your situation (seniority, etc). But possible outcomes roughly are:

address issue in full

fix broken

format to required coding style

and so on

come to compromise if issue should be addressed at all or partially, since there might be

no resources (such as time or budget)

no need (will only achieve insignificant improvement, compromise stability, etc)

come to understanding that raised issue is invalid

feedback (especially from subjective opinion category) can very well be outright harmful and should not be acted on blindly

You've learned that it feels painful to get negative feedback and it very well might be painful every time in the future. However you have left learn how it is important learning opportunity and how the process helps you to improve professionally and your workplace to achieve better code base.


问:
need explanation on amortization in algorithm
I am a learning algorithm analysis and came across a analysis tool for understanding the running time of an algorithm with widely varying performance which is called as amortization.

The autor quotes

An array with upper bound of n elements, with a fixed bound N, on it size. Operation clear takes O(n) time, since we should dereference all the elements in the array in order to really empty it.

The above statement is clear and valid. Now consider the next content:

Now consider a series of n operations on an initially empty array. if we take the worst case viewpoint, the running time is O(n^2), since the worst case of a sigle clear operation in the series is O(n) and there may be as many as O(n) clear operations in the series.

From the above statement how is the time complexity O(n^2)? I did not understand the logic behind it. if 'n' operations are performed how is it O(n ^2)? Please explain what the autor is trying to convey..

答:
In your case, n is the size of the array. And the algorithm is running at most once over the array. Each time it runs, it performs an operation (or calls another function) that itself runs at most once over the array. Thus, if you assume that the worst cost of running the clear() algorithm is O(n) and that the outer algorithm does nothing more expensive or proportional to that algorithm, you will run an O(n) clear() function n times.

This means that the overall cost of the function will be n * O(n) or O(n^2).

One important thing to note is that your operation is not a constant operation. When one says that running an operation n times costs O(n) she simply means that that operation is a constant operation or O(1) --meaning one that does not increase in cost with increase in size. The clear() function does not fit this description and hence you cannot say that running the clear() function n times is an O(n) operation.

Post script:

O(n^2) means that the run time complexity of the examined function will not exceed square growth for sufficiently large values of n.

In simpler words, for large values of n, O(n^2) means that the time to execute the examined algorithm over an input of size n will not increase by more than four times when n is doubled. The keyword here is large because for smaller values of n, constant factors (even when they exist as coefficients) may be significant. Theoretically, large values of n mean approaching infinity.


问:
GPL question : web application using Imagick and GhostScript => Which would be the final licence?
I am a bit confusing and I need your help to undertand my problem.

I have developed a web application (PHP, JQuery) for one of my customer.

Recently, my customer ask me to add a new feature permitting PDF to JPG conversion.

After web browsing, I have discovered that iMagick (Apache licence) PHP extension with GhostScript (GPL licence) is the only solution.

But, as my customer want to sell the web application to others companies, I have to use non-GPL licences.

By the way, this feature is OPTIONAL and the final user must download and install manually iMagick and GhostScript if he his interesting by using the PDF conversion.

Is there someone to tell me if the fact to use Imagick to convert PDF to JPG (and therefore use GhostScript) turns my current proprietary licence to GPL?

And what about if I don't use Imagick but call GhostScript using PHP exec() function?

Is there others non-GPL projects to convert PDF to JPG that I could use with PHP?

Any help would be greatly appreciated.

答: Run Ghostsript as a separate process either reading/writing files or directly streaming stdin-stdout.   Then your app isn't a derived work of ghostscript which can be freely distributed alongside your app.</p>


答:
"Now consider a series of n operations on an initially empty array. if we take the worst case viewpoint, the running time is O(n^2), since the worst case of a single clear operation in the series is O(n) and there may be as many as O(n) clear operations in the series."

if you perform n operations on an array with n elements (assuming that each operation is of order 1), you get n X O(n) --> O(n^2).

Example:

Say n=3, you want to perform 3 clears on the array.
first clear process takes 3 operations
second clear process takes 3 operations.
third clear process takes 3 operations.
total = 3x3=9=O(3^2).

The tricky part I can't justify though is the one in italics!

Title: need explanation on amortization in algorithm

Body:
I am a learning algorithm analysis and came across a analysis tool for understanding the running time of an algorithm with widely varying performance which is called as amortization.

The autor quotes

An array with upper bound of n elements, with a fixed bound N, on it size. Operation clear takes O(n) time, since we should dereference all the elements in the array in order to really empty it.

The above statement is clear and valid. Now consider the next content:

Now consider a series of n operations on an initially empty array. if we take the worst case viewpoint, the running time is O(n^2), since the worst case of a sigle clear operation in the series is O(n) and there may be as many as O(n) clear operations in the series.

From the above statement how is the time complexity O(n^2)? I did not understand the logic behind it. if 'n' operations are performed how is it O(n ^2)? Please explain what the autor is trying to convey..


问:
As a programmer, are you required to do timesheets?
Timesheets are something that I've never been fond of, but none the less something that is a requirement within my company. They don't bother me so much, but they seem to really grind some other people's gears. I suppose I have a few questions, and feedback would be great.

Are you required to do timesheets, assuming you aren't a contractor? (That is understandable to me).

What is the granularity of timesheets that you would be comfortable with or that you use? (ex: all entries must be under two hours).

Would timesheets ever factor into your reasons for not accepting a job or leaving a current one?

How has management within your organization justified timesheets if you aren't billing to a client?

答:
Unless you are charging clients by the hour, or unless you are a contractor paid by the hour, I wouldn't expect to be filling in timesheets. In my experience, they are counter-productive - yes, you need to generally keep track of the amount of resource going into projects, but that can be approximated monthly ("10 days on Project X and 9 days on Project Y etc"). The benefits of anything more granular are often outweighed by the cost of recording them, and if they can be used as a stick to beat the staff with, the staff will simply record what is acceptable rather than what is accurate.

The other unanticipated downside to businesses is that if you start monitoring staff, you might find that you start recording just how much extra the staff are doing! If you are paid for 40 hrs and are tracked for 40hrs, come 40hrs there is an incredible incentive to just go home. Staff will often stop doing that little bit extra that can so often make the difference.

ContentLicense: CC BY-SA 2.5


问:
Immutable design with an ORM: How are sessions managed?
If I were to make a site with a mutable language like C# and use NHibernate, I would normally approach sessions with the idea of making them as create only when needed and dispose at request end.  This has helped with keeping a session for multiple transactions by a user but keep it from staying open too long where the state might be corrupted.

In an immutable system, like F#, I would think I shouldn't do this because it supposes that a single session could be updated constantly by any number of inserts/updates/deletes/ect...   I'm not against the "using" solution since I would think that connecting pooling will help cut down on the cost of connecting every time, but I don't know if all database systems do connection pooling.  It just seems like there should be a better way that doesn't compromise the immutability goal.

Should I just do a simple "using" block per transaction or is there a better pattern for this?

答:
To be language agnostic the issue you are talking about is binding a connection/transaction to some "context" and then doing some very stateful and procedural communication to the connection and then disposing/closing/committing the connection/transaction and then finally removing the connection/transaction from the "context".

Worse in most languages this "context" is maintained in a ThreadLocal which is sort of equivalent to a global variable.

My guess is F# probably does what C# does but if you did want to do this in a more  FP way I would look at implementing it as a Monad and see how Haskell manages database stuff.


问:
Would it be a good idea to work on letting people add arrays of numbers in javascript?
I am a very mathematically oriented programmer, and I happen to be doing a lot of java script these days.  I am really disappointed in the math aspects of javascript:

the Math object is almost a joke because it has so few methods

you can't use ^ for exponentiation

the + operator is very limited, you cant add array's of numbers or do scalar multiplication on arrays

Now I have written some pretty basic extensions to the Math object and have considered writing a library of advanced Math features, amazingly there doesn't seem to be any sort of standard library already out even for calculus, although there is one for vectors and matricies I was able find.

The notation for working with vectors and matricies is really bad when you can't use the + operator on arrays, and you cant do scalar multiplication.  For example, here is a hideous expression for subtracting two vectors, A - B:

```<code>Math.vectorAddition(A,Math.scalarMultiplication(-1,B));
</code>```

I have been looking for some kind of open-source project to contribute to for awhile, and even though my C++ is a bit rusty I would very much like to get into the code for V8 engine and extend the + operator to work on arrays, to get scalar multiplication to work, and possibly to get the ^ operator to work for exponentiation.  These things would greatly enhance the utility of any mathematical javascript framework.

I really don't know how to get involved in something like the V8 engine other than download the code and start working on it.  Of course I'm afraid that since V8 is chrome specific, that without browser cross-compatibility a fundamental change of this type is likely to be rejected for V8.  I was hoping someone could either tell me why this is a bad idea, or else give me some pointers about how to proceed at this point to get some kind of approval to add these features.

Thanks!

答:
Your code isn't too likely to find its way into V8.  It's a language change, and language changes happen only rarely, and if they do, it's usually because a company, rather than a person or even a community, is pushing for them.

So ... unless you want to train your VM muscles, I'd try and stay within the language.


问:
Annotate source code with diagrams as comments
I write a lot of (primarily c++ and javascript) code that touches upon computational geometry and graphics and those kinds of topics, so I have found that visual diagrams have been an indispensable part of the process of solving problems.

I have determined just now that "oh, wouldn't it just be fantastic if I could somehow attach a hand-drawn diagram to a piece of code as a comment", and this would allow me to come back to something I worked on, days, weeks, months earlier and far more quickly re-grok my algorithms.

As a visual learner, I feel like this has the potential to improve my productivity with almost every type of programming because simple diagrams can help with understanding and reasoning about any type of non-trivial data structure. Graphs for example. During graph theory class at university I had only ever been able to truly comprehend the graph relationships that I could actually draw diagrammatical representations of.

So...

No IDE to my knowledge lets you save a picture as a comment to code.

My thinking was that I or someone else could come up with some reasonably easy-to-use tool that can convert an image into a base64 binary string which I can then insert into my code.

If the conversion/insertion process can be streamlined enough it would allow a far better connection between the diagram and the actual code, so I no longer need to chronographically search through my notebooks. Even more awesome: plugins for the IDEs to automatically parse out and display the image. There is absolutely nothing difficult about this from a theoretical point of view.

My guess is that it would take some extra time for me to actually figure out how to extend my favorite IDEs and maintain these plugins, so I'd be totally happy with a sort of code post-processor which would do the same parsing out and rendering of the images and show them side by side with the code, inside of a browser or something. Since I'm a javascript programmer by trade.

What do people think? Would anyone pay for this? I would. But I would perhaps also point out that regardless of whether I or some significant number of my peers would pay for such a thing, the only way such a thing is likely to succeed would be through an open source release.

答:
What about Image Insertion plugin for Visual Studio?

If you're using a different IDE and either it doesn't support embedded images or you don't have time to extend it, then what about putting a link to an image in the comments, while the image would reside somewhere in the repository?


问:
Morse Code - Binary Tree
How is the Morse Code representation of a letter determined?

"E" = "."
"T" = "-"

Why is it not alphabetic? As in let "A" = ".", "B" = "-", "C" =".-", etc.

I'm trying to develop an algorithm for a traversing Binary Tree filled with these letter.

My main aim is to search for a letter, like "A", but I don't know what conditions to use that determines when to branch to the right or left node.

答: The representation of the letters is determined (roughly) by "the frequency of use of letters in the English language . . ., and the letters most commonly used were assigned the shorter sequences of dots and dashes." You could build a tree with traversing to the left means adding a '.' and traversing to the right means adding a '-' to the previous code. You may want to also look at Huffman coding as this is very similar.</p>

Title: Morse Code - Binary Tree


问:
Serializing Data Structures in C
I've recently read three separate books on algorithms and data structures, tcp/ip socket programming, and programming with memory. The book about memory briefly discussed the topic of serializing data structures for the purposes of storing it to disk, or sending it across a network. I can't help but wonder why the the other two books didn't discuss serialization at all.

After an unsuccessful web/book search I'm left wondering where I can find a good book/paper/tutorial on serializing data structures in C? Where or how did you learn it?

答:
The Wikipedia article Serialization covers the topic fairly well, though oddly it does not mention ASN.1 which is a widely hated, but extremely well defined and well known standard for describing efficient data serialization protocols.  ASN compilers typically generate code (e.g. C code) for encoding and decoding the described data structures in a canonical way.

BTW, the endian issue can be trivially dealt with in C, as Rob Pike has shown nicely in his article The Byte Order Fallacy, though some C compilers don't yet always generate the most optimal object code when using this technique.

Title: Serializing Data Structures in C


答:
You could try the emacs artist mode.  It would do ascii art rather than images per se, so it may or may not be what you're looking for.  In particular, if your IDE doesn't do fixed-width fonts, it wouldn't be useful.  Being plain text, it would play very nicely with version control.

Here's a screencast of artist mode being used, so you can get an idea if you're interested or not.

To start up artist mode in emacs, do Alt-x, type artist-mode, and hit return.  The middle mouse button brings up the menu.  The keybindings for cut and paste aren't the normal windows ones by default, but you can turn on CUA mode to change that.

Title: Annotate source code with diagrams as comments

Body:
I write a lot of (primarily c++ and javascript) code that touches upon computational geometry and graphics and those kinds of topics, so I have found that visual diagrams have been an indispensable part of the process of solving problems.

I have determined just now that "oh, wouldn't it just be fantastic if I could somehow attach a hand-drawn diagram to a piece of code as a comment", and this would allow me to come back to something I worked on, days, weeks, months earlier and far more quickly re-grok my algorithms.

As a visual learner, I feel like this has the potential to improve my productivity with almost every type of programming because simple diagrams can help with understanding and reasoning about any type of non-trivial data structure. Graphs for example. During graph theory class at university I had only ever been able to truly comprehend the graph relationships that I could actually draw diagrammatical representations of.

So...

No IDE to my knowledge lets you save a picture as a comment to code.

My thinking was that I or someone else could come up with some reasonably easy-to-use tool that can convert an image into a base64 binary string which I can then insert into my code.

If the conversion/insertion process can be streamlined enough it would allow a far better connection between the diagram and the actual code, so I no longer need to chronographically search through my notebooks. Even more awesome: plugins for the IDEs to automatically parse out and display the image. There is absolutely nothing difficult about this from a theoretical point of view.

My guess is that it would take some extra time for me to actually figure out how to extend my favorite IDEs and maintain these plugins, so I'd be totally happy with a sort of code post-processor which would do the same parsing out and rendering of the images and show them side by side with the code, inside of a browser or something. Since I'm a javascript programmer by trade.

What do people think? Would anyone pay for this? I would. But I would perhaps also point out that regardless of whether I or some significant number of my peers would pay for such a thing, the only way such a thing is likely to succeed would be through an open source release.


问:
What is the common definition of a Hacker?
I'm wondering if the term Hacker means different things to different people.  When most people hear the word hacker what are the first things that come to mind?</p>

答: Someone who has the ability to change the functionality of a program, device, or methodology to perform a task or function that is different than it's original design in the effort to improve the program, device, or methodology, or to solve a problem with what is available.</p>


问:
Anti Cloud Open Source License
I'm working on a browser based open source monitoring project that I want to be free to the community.

What I'm worried about is someone taking the project, renaming it, deploying it in the cloud and start charging people who don't even know my project exists. I know I maybe shouldn't mind, but it just sticks in my throat a bit if someone took a free ride like that and contributed nothing back.

Is there any common open source license that can prevent this. I know GPL or AGPL don't.

答: The Affero GPL is an extention/alternative GPL that forbids the "service loophole" where it is perfectly OK to use GPL code behind some network service without acknowledging it since you never distribute the code to the users, only the results.

Title: Anti Cloud Open Source License


答: Creative Commons have a few licences you can choose from, plus a small tool to help you choose.</p>

Title: Anti Cloud Open Source License

Body:
I'm working on a browser based open source monitoring project that I want to be free to the community.

What I'm worried about is someone taking the project, renaming it, deploying it in the cloud and start charging people who don't even know my project exists. I know I maybe shouldn't mind, but it just sticks in my throat a bit if someone took a free ride like that and contributed nothing back.

Is there any common open source license that can prevent this. I know GPL or AGPL don't.


答:
A tree is suitable for decoding Morse code, that is converting from dots and dashes to letters. As long as you know where the breaks are between letters, this is entirely feasible.

To go the other way, from letters to dots and dashes, there's no need to use a tree. Finding a letter in such a tree would be annoying. Just make a simple lookup table:

```<code>a => ".-"
b => "-..."
c => "-.-."
</code>```

Title: Morse Code - Binary Tree

Body:
How is the Morse Code representation of a letter determined?

"E" = "."
"T" = "-"

Why is it not alphabetic? As in let "A" = ".", "B" = "-", "C" =".-", etc.

I'm trying to develop an algorithm for a traversing Binary Tree filled with these letter.

My main aim is to search for a letter, like "A", but I don't know what conditions to use that determines when to branch to the right or left node.

Body:
A tree is suitable for decoding Morse code, that is converting from dots and dashes to letters. As long as you know where the breaks are between letters, this is entirely feasible.

To go the other way, from letters to dots and dashes, there's no need to use a tree. Finding a letter in such a tree would be annoying. Just make a simple lookup table:

a => ".-"
b => "-..."
c => "-.-."


问:
When do you typically write a software module yourself vs. buying an existing product?
I'm trying to find out your decision rationale of when to do what. I'm happy to provide more context, but I want to make it general for now.</p>

答:
It's overly simplified I guess, but that sort of holds true as a general guideline:

In a Personal Environment

Do I have fun coding it?

OR do I learn something from coding it?

AND:

Do I have enough time to code it?

If yes, then I prefer to write it than to buy it.

In a Professional Environment

If the total cost of ownership of the product (including development, testing, maintenance, support or any related expenses) is higher than the cost of the product, and that the calculated return on investment won't offset this cost, then you're better off buying it and moving on.


答:
For me it's the attitude.

The yearning to learn more. The openness to help others. And being passionate about what they love.

He/She doesn't need to be a guru yet. But we are sure with the above attitude soon they would be attaining that status.

Title: What is the common definition of a Hacker?

Body: I'm wondering if the term Hacker means different things to different people.  When most people hear the word hacker what are the first things that come to mind?</p>


答:
high time effort, existing fitting product  >> buy product

personal interest in technique or no product existing fitting all requirements >>

develop on my own

Title: When do you typically write a software module yourself vs. buying an existing product?

Body: I'm trying to find out your decision rationale of when to do what. I'm happy to provide more context, but I want to make it general for now.</p>


答:
Things to consider for a make-or-buy decision

cost of development / cost for maintenance vs. cost of product / cost for maintenance contract: of course, that's the obvious thing, but that's actually not the only thing. For example, if I am going to use the software not only for my own company, but also want to sell it to others, then the calculation looks quite differently

Availability of a suitable product. For a lot of business processes, there is just no standard of-the-shelve software available. Or there is something available, but it is not suitable, because it contains 100 features from which you need just 3 in a slightly different manner, while 2 other important features are missing.

Risk in getting dependend from a third-party vendor. Especially for smaller vendors you never know how long they will survice in the market, or if the further development of the product will stay in the direction you need. For a product you have under your own control, you can steer the direction of development much better.

When do I need a specific software, and what will be quicker: develop it on my own, or buying something, learn it, adapt it until it fit's to my processes and roll it out? Buying something from the shelve may seem the quicker and sometimes cheaper alternative, but I personally have seen also scenarios where developing a software exactly for the needs of a company, fitting to existing business processes, saved so much time compared to buy something and teaching several hundreds of users to do their work in a new and different way, that the cost of development were negligable.

ContentLicense: CC BY-SA 4.0


问:
Should adapters or wrappers be unit tested?
Suppose that I have a class that implements some logic:

```<code>public MyLogicImpl implements MyLogic {
    public void myLogicMethod() {
        //my logic here
    }
}
</code>```

and somewhere else a test class:

```<code>public MyLogicImplTest {
    @Test
    public void testMyLogicMethod() {
        /test my logic
    }
}
</code>```

I also have:

```<code>@WebService
public MyWebServices class {
    @Inject
    private MyLogic myLogic;

    @WebMethod
    public void myLogicWebMethod() {
        myLogic.myLogicMethod();
    }
}
</code>```

Should there be a test unit for myLogicWebMethod or should the testing for it be handled in integration testing.

答:
Consider the different pressures involved. 100% Code coverage in your unit tests is a valid goal, since it protects you from regressions happening through casual changes, through requirements changes, environment changes, etc. On the other hand, writing regression tests in itself consumes valuable time. If you have completely regular or even automatically generated accessors or wrappers, those are probably the least likely to introduce subtle errors through later changes, so writing tests against these should be the lowest priority. In practice, you often don't have enough time to achieve 100% code coverage (let alone 100% state coverage), but the very act of thinking about your system and deciding which parts to test preferably is already much, much better than not having regression tests.

So my answer would be: you should, but if that is not feasible in your work environment, it's not as bad as lacking unit tests against more complicated parts of the code base.


答: Anything that has to do with cryptography. There are a 100.000 ways to do it wrong and expose your software to serious security vulnerabilities and just a few ways to do it right. High expertise is needed for this.</p>


问:
Tried teaching myself to program before college, accidently overwhelmed myself, tips?
I'm sixteen, I'm overly interested in programming, and I'm currently taking IT classes during my mornings in high school. Last year, I tried teaching myself to code. It was quite exciting, but all I did was watch TheNewBoston's videos on YouTube for Python.

After his tutorials, I just did research, made some CMD programs, and that's it. After that, I got cocky and got my feet wet in many other languages. Java, C++, C#, Perl, Ruby... and it overwhelmed me. Which made it less fun to code. I want to go to college for a 2 year programming course. And I want to make writing code my profession.

But how do you recommend I attack re-learning it all again? Start with Python? Don't even try? Also, I'm not 100% in math, but I'm good friends with a lot of programmers, who say they suck at math, but manage to code just fine.

I'm not looking for negative feedback. I just want the proper head-start on things before college.

答:
I suck at math, but I manage to code just fine (I think?).

Now that that's out of the way, you've already identified the root cause of your problems, you got cocky. A better description might be over enthusiastic, and it's quite common mistake, we've all done it in the past. Coding is exciting, and programming in general is a unique blend of art, science, engineering and... magic ;) But you really need to slow your pace and come up with a solid learning path. Don't code just for the fun of it, the boring parts are important as well.

One tip would be to focus your learning in creating small (but non trivial) projects. If, for example, you're interested in web development, build yourself a simple blog engine. Yes, it's the most trite example there is, but do it anyway, the reason everybody does it it's because it combines all the basics you'll find in almost any web application (basic CRUD: users, posts, comments).

Python is good enough as a first language, as is Java, Ruby, C, C#, C++, Haskell, PHP, Visual Basic,  etc1. Just pick one and stick with it, at least until you can honestly say that you are being productive with it. It really doesn't matter which language you'll pick, and beware than when asking chances are people will (perhaps unwittingly) direct you to their favourite language instead of a language that's suitable for beginners. I'd also advice against trying to learn two languages at the same time, you need to get a solid foundation first, and learning two languages in parallel might do more to confuse you than teach you.

There are several Coursera courses you could follow, and learn in a more structured way. There's also a ton of free resources for every popular language, if you go with Python I'd recommend Learn Python The Hard Way. It might seem extremely boring (it's a very basic book), but you really should go through all it's exercises, I did, regardless of my 10+ years in the field (crap, I'm old). Same with any other resource you might choose to learn from, just don't be hasty, you're sixteen, you have time. Right now your "job" is to learn, and learn well.

Programmers is also a great resource, and so are the rest of the programming friendly sites of the network:

Stack Overflow,

Code Review,

Computer Science,

Database Administrators,

Game Development.

Familiarize yourself with the sites, and use them to your benefit. We are all here to help, all we ask is that you show us a little bit of effort (and reach each site's FAQ thoroughly before you ask your questions).

Further reading:

Teach Yourself Programming in Ten Years

No Silver Bullets?

Help, I just graduated but I don’t feel like I know how to program!

What have you tried?

Which computer science / programming Stack Exchange do I post in?

List of freely available programming books

Related questions:

On developing deep programming knowledge

How do I improve my coding skills?

My Dad is impatient with the pace of my learning to program. What do I do?

Could spending time on Programmers.SE or Stack Overflow be substitute of good programming books for a non-beginner?

How can I find a good open source project to join?

Learn programming backwards, or "so I failed the FizzBuzz test. Now what?"

https://softwareengineering.stackexchange.com/questions/165918/way-in-over-my-head-dealing-with-better-programmers

How important is self-teaching in the programming field?

What differentiates the exceptional programmers from the really good ones?

Recommendations for teaching junior programmers good coding style

https://softwareengineering.stackexchange.com/questions/108578/is-it-true-that-once-you-learn-one-language-most-of-the-rest-come-easy

Is there a canonical book on mathematics for programmers?

Where do you draw the line for your perfectionism?

Is perfectionism a newbie's friend or enemy?

1 I'd avoid Perl right now, only because Perl 6 will bring some major changes to the language. Still one of my favourite languages, just not a good time to learn it if you are a complete beginner.


答:
What would you like to code or what would you like to develop using your compiled code.

You can develop Softwares or Chips or Web.

When I first started learning programming, I took the fun road. Developing Static HTML Pages. It will introduce you to basic syntax.

Then make your way using C++. By producing: Hello World!, Input number: Output Word of that number, Fibonacci.

Then I am guessing after that you will be more interested in your school projects that is: Developing Systems or games.

My suggestion is to start off using C++ then move to Visual Basic.

Title: Tried teaching myself to program before college, accidently overwhelmed myself, tips?

Body:
I'm sixteen, I'm overly interested in programming, and I'm currently taking IT classes during my mornings in high school. Last year, I tried teaching myself to code. It was quite exciting, but all I did was watch TheNewBoston's videos on YouTube for Python.

After his tutorials, I just did research, made some CMD programs, and that's it. After that, I got cocky and got my feet wet in many other languages. Java, C++, C#, Perl, Ruby... and it overwhelmed me. Which made it less fun to code. I want to go to college for a 2 year programming course. And I want to make writing code my profession.

But how do you recommend I attack re-learning it all again? Start with Python? Don't even try? Also, I'm not 100% in math, but I'm good friends with a lot of programmers, who say they suck at math, but manage to code just fine.

I'm not looking for negative feedback. I just want the proper head-start on things before college.


问:
Practical size limits of a DataTable in c#
I have to query a large data-set (~500 MB) using a sqlDataReader but I have to save the data in three different formats. Instead of querying the database 3 times I'm thinking about saving the data to an in-memory table and then save the data from there.

Is there a practical limit to a table size in memory? Any ideas for a better approach?

答: SQL Server 2005 has 1024 columns limit per base table. A data table should be able to take at least 1024 data columns.</p>


答: Sounds like a use-case for Literate Programming where you could add diagrams and whatever to your documentation.</p>


问:
Android Card Game Database for Deck Building
I am making a card game for Android where a player can choose from a selection of cards to build a deck that would contain around 60 cards. Currently, I have the entire database of cards created that the user can browse.

The next step is allowing the user to select cards and create a deck with whatever cards they would like. I have a form where the user can search for specific cards based off a few different attributes. The search results are displayed in a List Activity. My thought about deck creation is to add the primary key of each card the user selects to a SQLite Database table with the amount they would like in the deck.

This way as the user performs searches for cards they can see the state of the deck. Once the user decides to save the deck. I'll export the card list to XML and wipe the contents of the table. If the user wanted to make changes to the deck, they would load it, it would be parsed back into the table so they could make the changes. A similar situation would occur when the eventually load the deck to play a game.

I'm just curious what the rest of you may think of this method. Currently, this is a personal project and I am the only one working on it. If I can figure out the best implementation before I even begin coding I'm hoping to save myself some time and trouble.

答:
The database seems a bit pointless to me, if you don't need the data to be persistent you shouldn't be using a database, just an an array of structs instead.

The cards however should be stored as a database to allow the system to be easily expanded, just remember to keep SQL injection in mind.


答:
Unless the XML is given to you, I would probably just keep the deck stored in the database. But I suspect it's there for interoperability with some other application, so it has to be there.

If loading the data in the database makes it easier for you to manipulate them, go ahead. But to limit amount of writes to the non-volatile storage, you should take advantage of the memory tables support in SQLite. In-memory tables can be created in two ways:

CREATE TEMP TABLE ... with PRAGMA temp_store = MEMORY in effect.

ATTACH ':memory:' AS mem and CREATE TABLE mem.....

Advantage of memory table compared to on-disk table that you drop before exiting is that it will not stay around if your application is forcibly closed. So you don't have to drop it in onStop and it still won't stay around when your application is killed, which Android does without further warning (of course you still need to write the XML in onStop).

Title: Android Card Game Database for Deck Building

Body:
I am making a card game for Android where a player can choose from a selection of cards to build a deck that would contain around 60 cards. Currently, I have the entire database of cards created that the user can browse.

The next step is allowing the user to select cards and create a deck with whatever cards they would like. I have a form where the user can search for specific cards based off a few different attributes. The search results are displayed in a List Activity. My thought about deck creation is to add the primary key of each card the user selects to a SQLite Database table with the amount they would like in the deck.

This way as the user performs searches for cards they can see the state of the deck. Once the user decides to save the deck. I'll export the card list to XML and wipe the contents of the table. If the user wanted to make changes to the deck, they would load it, it would be parsed back into the table so they could make the changes. A similar situation would occur when the eventually load the deck to play a game.

I'm just curious what the rest of you may think of this method. Currently, this is a personal project and I am the only one working on it. If I can figure out the best implementation before I even begin coding I'm hoping to save myself some time and trouble.


答: The glider and thereifixedit. It's people who're playing the actual game of life in any possible way except by the book :)</p>


问:
What does it mean to write "good code"?
In this question I asked whether being a bad writer hinders you from writing good code. Many of the answers started of with "it depends on what you mean by good code".

It appears that the term "good code" and "bad code" are very subjective. Since I have one view, it may be very different from others' view of them.

So what does it mean to write "good code"? What is "good code"?

答:
There are lots of features of 'good' code, but the most important, IMHO, are readability and maintainability.

Your code will contain bugs, will probably be extended and re-used, and ought to be re-factored at some point - even if it is you re-visiting it, the chances are that you won't have a clue what the hell you did in the first place, to do yourself a favour and don't put any barriers in the way.

Sure, use that complex-yet-uber-efficient algorithm,  but make sure you spend a little extra time documenting it, but otherwise make your code clear and consistent.

Title: What does it mean to write "good code"?


问:
"Programming error" exceptions - Is my approach sound?
I am currently trying to improve my use of exceptions, and found the important distinction between exceptions that signify programming errors (e.g. someone passed null as argument, or called a method on an object after it was disposed) and those that signify a failure in the operation that is not the caller's fault (e.g. an I/O exception).

How should these two kinds of exceptions be treated differently? Do you think that error exceptions need to be explicitly documented, or is it enough to document the relevant preconditions? And can you leave out the documentation of a precondition or error exception if it should be obvious (for example, ObjectDisposedException when calling a method on a disposed object)

答:
Here are my own thoughts. Note that I am not too certain this is the best way to go, which is why I created this question in the first place.

As far as I understand, it makes little sense for an immediate caller to actually handle programming error exceptions, he should instead assure that the preconditions are met. Only "outer" exception handlers at task boundaries should catch them, so they can keep the system running if a task fails.

In order to ensure that client code can cleanly catch "failure" exceptions without catching error exceptions by mistake, I create my own exception classes for all failure exceptions now, and document them in the methods that throw them. I would make them checked exceptions in Java.

Until recently, I tried to document all exceptions that a method could throw, but that sometimes creates an unwiedly list that needs to be documented in every method up the call chain until you can show that the error won't happen. Instead, I now document the preconditions in the summary / parameter descriptions and don't even mention what happens if they are not met. The idea is that people should not try to catch these exceptions explicitly anyway, so there is no need to document their types.

For documenting the preconditions, stating the obvious just creates needless clutter - if passing null to a method makes no obvious sense, the caller has to expect an exception if he passes null anyway, even if that is not documented. The same is true for the case of ObjectDisposedException - this interface is so widely used that someone calling Dispose would be aware of the responsibility to ensure nobody will continue using the object.


问:
What level/format of access should be given to a client to the issue tracking system?
So, I used to think that it would be a good idea to give the customer access to the issue tracking system, but now I've seen that it creates less than ideal situations, like:

Customer judging progress solely on ticket count

Developers denied to add issues to avoid customer thinking that there is less progress

Customer appointing people on their side to add issues who don't always do a good job (lots of duplicate issues, insufficient information to reproduce, and other things that distract people from doing their real job)

However, I think customers should have access to some indicators or proof that there is progress being done, as well as a right to report bugs.

So, what would be the ideal solution to this situation?, specially, getting out of or improving the first situation described?

答:
It's hard to say. To use an analogy some restaurants allow you to see into the kitchen so you can see how hard the chefs are working. Some don't.

However, we're programmers not chefs. I would say you need a forum where developers can be honest so as work can get done. The solution is either to adjust the security settings so some things stay private (we have this at my current place of work) or to see if it is possible to better educate your customers.

Judging productivity on ticket count is a bit like judging a horse's performance in a race on the amount of hay it's been eating.

The system we use is ZenDesk. This allows our customers to submit tickets but we use permissions to keep some things private.


答:
I think you are on the right track.  Neither throwing, catching, nor documenting all potentially throwable exceptions makes much sense.  There are times where the product stringency requires a higher degree of exception employment and documentation (e.g. certain safety critical aspects of a systems).

The strategy of being more defensive, using contract concepts to identify preconditions (and postconditions) on especially downstream callers (e.g. anything that resembles a public or protected member) will often be more effective and more flexible.  This applies not only to the implementation, but to the documentation.  If developers know what is expected, they are more likely to follow the rules and less likely to be confused or misuse the code you have written.

Some of the common things that should be documented include the case of null parameters.  Often there is a consequence for their use that drives the result to something that wouldn't normally be expected, but are allowed and used for a variety of reasons, sometimes for flexibility.  As a consumer of a member that has parameters that allow null, or other special, non rational values (like negative time, or negative quantities), I expect to see them identified and explained.

For non null parameters, as a consumer of a public or protected member, I want to know that null is not allowed.  I want to know what the valid range of values in the given context is.  I want to know the consequences  of using values that are outside the normal range, but are otherwise valid in a different calling context (eg the value of the type is generally valid for any operation, but not here  -- like a boolean parameter that doesn't expect false as a valid value.

As far as platform, or otherwise well known interfaces, I don't think you have to go to extremes in documenting it.  However, because you have an opportunity as a developer to vary the implementation from whatever platform guidance, making note of how it follows that guidance may be of value.

Specific to IDisposable, often implementations of this interface offers an alternative method that is preferred over the explicit disposal process.  In these cases,  highlight the preferred method, and note that the explicit disposal is not preferred.

Title: "Programming error" exceptions - Is my approach sound?

Body:
I am currently trying to improve my use of exceptions, and found the important distinction between exceptions that signify programming errors (e.g. someone passed null as argument, or called a method on an object after it was disposed) and those that signify a failure in the operation that is not the caller's fault (e.g. an I/O exception).

How should these two kinds of exceptions be treated differently? Do you think that error exceptions need to be explicitly documented, or is it enough to document the relevant preconditions? And can you leave out the documentation of a precondition or error exception if it should be obvious (for example, ObjectDisposedException when calling a method on a disposed object)


问:
License for library developed with commercial program
I'm developing a commercial application that largely depends on the functionality of a library that will be developed with it. I'd like to open-source this library, because it offers functionality that is not found elsewhere and can be useful in other applications.

However, I will also use it in my own commercial application. I don't want to publish the source of the main application, but it is definitely not a derived work (think of calculator app using GPL licensed library to calculate sine). And if someone else commercially uses the library, I want to require them to publish any changes made.

Is the GPL license suitable for this or is LGPL perhaps what I need?

答:
I'm not a lawyer, but

AFAIK, the definition of derived work is more extensive than you think and your program will be a derived work of your library

as long as you are the copyright holder, nothing prevent you to publish derived work in closed source.  It's when you accept contribution of others than things become complex as you aren't the only copyright holders and the others may have objection. There are solutions -- you may for instance accept contribution only if they come along with a copyright assignation to yourself, that's what the FSF does -- but you need a layer to put them in place.  As a kind of possible complication, some intellectual property rights aren't transferable in some countries.


答:
Since you are the author, you can give yourself the library under different terms from what you give the library to others (and you can give it under different terms to various others). As long as you are the only author or get all contributors agree to the special terms for you (you'd need good lawyer to write the agreement so that it's valid across the world though), you can give the library out under any terms you want.

This is what Trolltech has been doing for long years with Qt. It was GPL or commercial, so GPL applications like KDE could use it free, but if you wanted to write commercial application, you had to pay for it.

So if you want to get some advantage of the library, you can use that model too. Otherwise  you have to use LGPL; A calculator using GPL library to calculate sine definitely and unambiguously is a derived work of the library and must be shipped under GPL.

Also don't forget that LGPL only excludes dynamically linked objects. If you don't like that, either use Mozilla Public License or GPL with library use exception like libgcc has, or one of the yet more permissive ones, i.e. MIT/X, new BSD or (as mentioned in comments) Apache License or Eclipse Public License (the later two are lately popular because they cover patent grants).

Derived work note: Everything that links to a GPL library has to be covered by it. Even things that don't directly depend on it. E.g. if you have GPL library "g" and another library "h" and link them both to application "i", you have to provide source not just for application "i", but also for library "h" that does not depend on "g"! That's because the linked binary is a derived work of the library "g" (for the binary it's obvious) and GPL requires that if you give that derived work to somebody, you have to give everything it contains under GPL except vaguely defined "system libraries". So it includes library "h" that itself knows nothing about "g"!

MPL note: Looking at Mozilla Public License I am not really sure what it covers. I think it does not cover larger software that includes the derived work, but I am not sure.

Title: License for library developed with commercial program

Body:
I'm developing a commercial application that largely depends on the functionality of a library that will be developed with it. I'd like to open-source this library, because it offers functionality that is not found elsewhere and can be useful in other applications.

However, I will also use it in my own commercial application. I don't want to publish the source of the main application, but it is definitely not a derived work (think of calculator app using GPL licensed library to calculate sine). And if someone else commercially uses the library, I want to require them to publish any changes made.

Is the GPL license suitable for this or is LGPL perhaps what I need?


答:
You tagged this with "Agile", so I'd suggest that one of the "agile" tools might be a good option--use a Product Backlog, containing a list of what needs to be done, and have a Product Owner manage it.  The Product Owner should share what's in the backlog with all stakeholders and be able to explain why issues appear (or not).  This gives visibility into the progress being made, which is a good thing, but limits the amount of confusion that it might create. </p>

<p>Basically, you've identified an area where trust and visibility are at risk in your organization--so you need somebody to manage it. </p>

Title: What level/format of access should be given to a client to the issue tracking system?

Body:
So, I used to think that it would be a good idea to give the customer access to the issue tracking system, but now I've seen that it creates less than ideal situations, like:

Customer judging progress solely on ticket count

Developers denied to add issues to avoid customer thinking that there is less progress

Customer appointing people on their side to add issues who don't always do a good job (lots of duplicate issues, insufficient information to reproduce, and other things that distract people from doing their real job)

However, I think customers should have access to some indicators or proof that there is progress being done, as well as a right to report bugs.

So, what would be the ideal solution to this situation?, specially, getting out of or improving the first situation described?

Body:
You tagged this with "Agile", so I'd suggest that one of the "agile" tools might be a good option--use a Product Backlog, containing a list of what needs to be done, and have a Product Owner manage it.  The Product Owner should share what's in the backlog with all stakeholders and be able to explain why issues appear (or not).  This gives visibility into the progress being made, which is a good thing, but limits the amount of confusion that it might create.

Basically, you've identified an area where trust and visibility are at risk in your organization--so you need somebody to manage it.


问:
Why do node packages put a comma on a newline?
I'm learning node.js and am trying out Express.  My first app had this code:

```<code>var express = require('express')
  , routes = require('./routes')
  , user = require('./routes/user')
  , http = require('http')
  , path = require('path');
</code>```

Reading through the mongoose tutorial gives me this:

```<code>var mongoose = require('mongoose')
  , db = mongoose.createConnection('localhost', 'test');
</code>```

On strict mode, JSHint gives me

app.js: line 6, col 32, Bad line breaking before ','.

Which shows that I'm not the only one out there who's bugged by this syntax.

Is there any reason to declare vars this way instead of adding the comma at the end of the line?

答:
I think that the main reason is so that if you add an extra item, you create an "add new line" change in your version control system, rather than a "Replace line with 2 new lines" change, with the only change to the first line being addition of a comma.

Tools like git-blame will then report the commit where you added parts relevant to the new item, rather than the item after it.


答:
If you are not an ASCII artist, you can use doxygen as documentation tool together with dot/graphviz integrated to it.

This allows for writing textual description of graphs and rendering them in documentation.

For instance, this description:

```<code>digraph finite_state_machine {
    rankdir=LR;
    size="8,5"
    node [shape = doublecircle]; LR_0 LR_3 LR_4 LR_8;
    node [shape = circle];
    LR_0 -> LR_2 [ label = "SS(B)" ];
    LR_0 -> LR_1 [ label = "SS(S)" ];
    LR_1 -> LR_3 [ label = "S($end)" ];
    LR_2 -> LR_6 [ label = "SS(b)" ];
    LR_2 -> LR_5 [ label = "SS(a)" ];
    LR_2 -> LR_4 [ label = "S(A)" ];
    LR_5 -> LR_7 [ label = "S(b)" ];
    LR_5 -> LR_5 [ label = "S(a)" ];
    LR_6 -> LR_6 [ label = "S(b)" ];
    LR_6 -> LR_5 [ label = "S(a)" ];
    LR_7 -> LR_8 [ label = "S(b)" ];
    LR_7 -> LR_5 [ label = "S(a)" ];
    LR_8 -> LR_6 [ label = "S(b)" ];
    LR_8 -> LR_5 [ label = "S(a)" ];
}
</code>```

renders as:

Body:
If you are not an ASCII artist, you can use doxygen as documentation tool together with dot/graphviz integrated to it.

This allows for writing textual description of graphs and rendering them in documentation.

For instance, this description:

digraph finite_state_machine {
    rankdir=LR;
    size="8,5"
    node [shape = doublecircle]; LR_0 LR_3 LR_4 LR_8;
    node [shape = circle];
    LR_0 -> LR_2 [ label = "SS(B)" ];
    LR_0 -> LR_1 [ label = "SS(S)" ];
    LR_1 -> LR_3 [ label = "S($end)" ];
    LR_2 -> LR_6 [ label = "SS(b)" ];
    LR_2 -> LR_5 [ label = "SS(a)" ];
    LR_2 -> LR_4 [ label = "S(A)" ];
    LR_5 -> LR_7 [ label = "S(b)" ];
    LR_5 -> LR_5 [ label = "S(a)" ];
    LR_6 -> LR_6 [ label = "S(b)" ];
    LR_6 -> LR_5 [ label = "S(a)" ];
    LR_7 -> LR_8 [ label = "S(b)" ];
    LR_7 -> LR_5 [ label = "S(a)" ];
    LR_8 -> LR_6 [ label = "S(b)" ];
    LR_8 -> LR_5 [ label = "S(a)" ];
}

renders as:


问:
How to do dependency Injection and conditional object creation based on type?
I have a service endpoint initialized using DI. It is of the following style. This end point is used across the app.

```<code> public class CustomerService : ICustomerService
{
    private IValidationService ValidationService { get; set; }
    private ICustomerRepository Repository { get; set; }

    public CustomerService(IValidationService validationService,ICustomerRepository repository)
    {
        ValidationService = validationService;
        Repository = repository;
    }

    public void Save(CustomerDTO customer)
    {
        if (ValidationService.Valid(customer))
            Repository.Save(customer);
    }
</code>```

Now, With the changing requirements, there are going to be different types of customers (Legacy/Regular). The requirement is based on the type of the customer I have to validate and persist the customer in a different way (e.g. if Legacy customer persist to LegacyRepository).

The wrong way to do this will be to break DI and do somthing like

```<code>  public void Save(CustomerDTO customer)
    {
        if(customer.Type == CustomerTypes.Legacy)
        {
            if (LegacyValidationService.Valid(customer))
                LegacyRepository.Save(customer);
        }
        else
        {
            if (ValidationService.Valid(customer))
                Repository.Save(customer);
        }
    }
</code>```

My options to me seems like

DI all possible IValidationService and ICustomerRepository and switch based on type, which seems wrong.

The other is to change the service signature to Save(IValidationService validation, ICustomerRepository repository, CustomerDTO customer) which is an invasive change.

Break DI. Use the Strategy pattern approach for each type and do something like:

```<code>validation= CustomerValidationServiceFactory.GetStratedgy(customer.Type);
validation.Valid(customer)
</code>```

but now I have a static method which needs to know how to initialize different services.

I am sure this is a very common problem, What is the right way to solve this without changing service signatures or breaking DI?

答: Inject your IValidationServices into your CustomerValidationServiceFactory. GetStrategy should not be static. Inject CustomerValidationServiceFactory into your CustomerService. Use as approproiate.</p>


答:
I wouldn't use a static method, but it seems like an IoC container (or simple DI depending on usage pattern) for your ICustomerService is appropriate. After all, if the customer dictates that the validation and repo both change together, that is the axis of change, not each of the members independently.

It should also hopefully cut down on number of combinations, making the code less complex.

Title: How to do dependency Injection and conditional object creation based on type?

Body:
I have a service endpoint initialized using DI. It is of the following style. This end point is used across the app.

```<code> public class CustomerService : ICustomerService
{
    private IValidationService ValidationService { get; set; }
    private ICustomerRepository Repository { get; set; }

    public CustomerService(IValidationService validationService,ICustomerRepository repository)
    {
        ValidationService = validationService;
        Repository = repository;
    }

    public void Save(CustomerDTO customer)
    {
        if (ValidationService.Valid(customer))
            Repository.Save(customer);
    }
</code>```

Now, With the changing requirements, there are going to be different types of customers (Legacy/Regular). The requirement is based on the type of the customer I have to validate and persist the customer in a different way (e.g. if Legacy customer persist to LegacyRepository).

The wrong way to do this will be to break DI and do somthing like

```<code>  public void Save(CustomerDTO customer)
    {
        if(customer.Type == CustomerTypes.Legacy)
        {
            if (LegacyValidationService.Valid(customer))
                LegacyRepository.Save(customer);
        }
        else
        {
            if (ValidationService.Valid(customer))
                Repository.Save(customer);
        }
    }
</code>```

My options to me seems like

DI all possible IValidationService and ICustomerRepository and switch based on type, which seems wrong.

The other is to change the service signature to Save(IValidationService validation, ICustomerRepository repository, CustomerDTO customer) which is an invasive change.

Break DI. Use the Strategy pattern approach for each type and do something like:

```<code>validation= CustomerValidationServiceFactory.GetStratedgy(customer.Type);
validation.Valid(customer)
</code>```

but now I have a static method which needs to know how to initialize different services.

I am sure this is a very common problem, What is the right way to solve this without changing service signatures or breaking DI?


答:
If they're private and there's no logic behind the getters/setters (as it appears in your code example), there should be no reason for your class members to be properties:

```<code>private IValidationService ValidationService { get; set; }
private ICustomerRepository Repository { get; set; }
</code>```

would be better served as:

```<code>private IValidationService ValidationService;
private ICustomerRepository Repository;
</code>```

or even better yet, if they're only set in the constructor (again, as the code shows), make them readonly to declare intent and keep them invariant throughout the lifetime of the class:

```<code>private readonly IValidationService ValidationService;
private readonly ICustomerRepository Repository;
</code>```

Body:
If they're private and there's no logic behind the getters/setters (as it appears in your code example), there should be no reason for your class members to be properties:

private IValidationService ValidationService { get; set; }
private ICustomerRepository Repository { get; set; }

would be better served as:

private IValidationService ValidationService;
private ICustomerRepository Repository;

or even better yet, if they're only set in the constructor (again, as the code shows), make them readonly to declare intent and keep them invariant throughout the lifetime of the class:

private readonly IValidationService ValidationService;
private readonly ICustomerRepository Repository;


问:
Do people in non-English-speaking countries code in English?
I've heard it said (by coworkers) that everyone "codes in English" regardless of where they're from. I find that difficult to believe, however I wouldn't be surprised if, for most programming languages, the supported character set is relatively narrow.

Have you ever worked in a country where English is not the primary language?

If so, what did their code look like?

答:
I'm French. As has been pointed out in comments, my countrymen tend to exhibit an above-average pride in the national language :-). I take a pragmatic position on the issue myself:

I speak the language that the target audience will most likely understand.  When coding open-source software with a global ambition, I use English. For less widely useful stuff (for instance, my Emacs configuration file), I might use French.

I acknowledge the fact that not everyone will master English.  In that perspective, using my mother tongue might actually make my code more accessible instead of less (in the example above, nobody cares about an umpteenth .emacs, except if it happens to be written in a language that they understand).

Better to write good French than bad English. I actively discourage my subordinates from writing half-assed English especially where concision matters, eg in docstrings and version control commit messages.


问:
What core principles would you want in a library?
Theres talk about what syntax and feature you like in a programming language; i'll now ask what core principles or feature would you like in a library in your favorite (or any) language?

An example is having adding list += anotherList valid as oppose to only allowing list += listElement (although some may see this as a bad idea)

答:
I'm more concerned about the soft features of an API.  That is:

Simplicity

Consistency

Elegance

Intuitive

It just works

I could right a book on how those apply or would get implemented, but suffice to say unless a user of the API can wrap their head around how to use it effectively, it's of limited use.  Simplicity does not mean simplisticness, just as elegance does not mean onate.  It simply means that it is just perfect for the job.  The less someone has to think about how to use the API, the more they can just use it.

How these look depend on the lnaguage, purpose and target audience of the API.  The very last criteria boils down to the principle of least surprise.  No errors where you didn't expect them.  Any reasonable interpretation of the API will get you the results you want.


问:
Mocking concrete class - Not recommended
I've just read an excerpt of "Growing Object-Oriented Software" book which explains some reasons why mocking concrete class is not recommended.

Here some sample code of a unit-test for the MusicCentre class:

```<code>public class MusicCentreTest {
  @Test public void startsCdPlayerAtTimeRequested() {
    final MutableTime scheduledTime = new MutableTime();
    CdPlayer player = new CdPlayer() {
      @Override
      public void scheduleToStartAt(Time startTime) {
        scheduledTime.set(startTime);
      }
    }

    MusicCentre centre = new MusicCentre(player);
    centre.startMediaAt(LATER);

    assertEquals(LATER, scheduledTime.get());
  }
}
</code>```

And his first explanation:

The problem with this approach is that it leaves the relationship
  between the objects implicit. I hope we've made clear by now that the
  intention of Test-Driven Development with Mock Objects is to discover
  relationships between objects. If I subclass, there's nothing in the
  domain code to make such a relationship visible, just methods on an
  object. This makes it harder to see if the service that supports this
  relationship might be relevant elsewhere and I'll have to do the
  analysis again next time I work with the class.

I can't figure out exactly what he means when he says:

This makes it harder to see if the service that supports this
  relationship might be relevant elsewhere and I'll have to do the
  analysis again next time I work with the class.

I understand that the service corresponds to MusicCentre's method called startMediaAt.

What does he mean by "elsewhere"?

The complete excerpt is here:
http://www.mockobjects.com/2007/04/test-smell-mocking-concrete-classes.html

答:
This makes it harder to see if the service that supports this
  relationship might be relevant elsewhere and I'll have to do the
  analysis again next time I work with the class.

After thinking a lot about it, I get a possible interpretation of this quote:

The quoted "service" corresponds to the "fact of scheduling". This could be expressed by a well-named and "focused-on-one-role" interface named "ScheduledDevice" or expressed implicitly by a concrete method implementation not depending upon any interfaces.

In the sample above, scheduling is expressed by the whole full-featured object named CDPlayer. Thus, it still leads to implicit relationship between MusicCentre and "fact of scheduling".

So if we start injecting concrete classes and mocking them into high-level objects; when we want to test these ones, we have to analyse each injected "concrete" objects to see whether it presents a specific relationship that we HAVE TO MOCK because they are HIDDEN (implicit).
On the contrary, coding ALWAYS over interface allows developer to figure out directly what kind of relationship is about to be served by the high-level object and therefore detect features that have to be mocked in order to isolate the unit-test.


答:
If you have only two types of customers i would use the ugly version to let CustomerService.Save(CustomerDTO customer) decide which repository to use. Of course this violates the open-closed-priciple but obeys the keepItSimpleStupid (kiss).

If you really have several types of customers I would implement one customerservice for every type of customer and one customerservice on top that decides which spezialized service to use using a strategy pattern.

```<code> > but now I have a static method which needs to know how to initialize different services.
</code>```

It is not necessary that the strategy is a static method.

Instead of letting the strategy know every service you can reverse the dependency and let every spezialized service register at the stragey like this

```<code> public class LegacyCustomerService : ICustomerService
 {
    LegacyCustomerService(IStrategy strategy)
    {
       strategy.register(this, typeof(LegacyCustomer));
    }
 }
</code>```

The strategy uses a hash/dictionary from customer-type to service.

This is an open-closed-priciple solution that violates the keepItSimpleStupid (kiss) principle.

Body:
If you have only two types of customers i would use the ugly version to let CustomerService.Save(CustomerDTO customer) decide which repository to use. Of course this violates the open-closed-priciple but obeys the keepItSimpleStupid (kiss).

If you really have several types of customers I would implement one customerservice for every type of customer and one customerservice on top that decides which spezialized service to use using a strategy pattern.

 > but now I have a static method which needs to know how to initialize different services.

It is not necessary that the strategy is a static method.

Instead of letting the strategy know every service you can reverse the dependency and let every spezialized service register at the stragey like this

 public class LegacyCustomerService : ICustomerService
 {
    LegacyCustomerService(IStrategy strategy)
    {
       strategy.register(this, typeof(LegacyCustomer));
    }
 }

The strategy uses a hash/dictionary from customer-type to service.

This is an open-closed-priciple solution that violates the keepItSimpleStupid (kiss) principle.


答:
The author of that post is promoting the use of Interfaces over the use of member classes.

It turns out that my MusicCentre object only uses the starting and stopping methods on the CdPlayer, the rest are used by some other part of the system. I'm over-specifying my MediaCentre by requiring it to talk to a CdPlayer, what it actually needs is a ScheduledDevice.

The relationship that he's worried about re-discovering later is the fact that the MediaCentre class doesn't need all of the CdPlayer object.  His claim is that by using an Interface (presumably limited to just start | stop) that it's easier to understand what the interaction really is.

"elsewhere" simply means that other objects may have similarly limited relationships, and the full member object is not required - a subset of the functionality wrapped through an Interface should be sufficient.

The claim starts to make more sense when you explode out all the potential functionality:

start

stop

pause

record

random play order

sample tracks, beginning of song

sample tracks, random sample of song

provide media information

...

Now his claim of "I just need start & stop" makes more sense.  Using the concrete member object instead of an Interface makes it less clear to future developers as to what is really required.  Running unit tests from MediaCentre on all the other functions within CdPlayer is a waste of testing effort since they belong to the "don't care" state.  If the Record function wasn't working in this case, we truly don't care since it isn't required.  But a future maintainer wouldn't necessarily know that based upon the code, as written.

Ultimately, the author's premise is to use only what is needed and make it clear to future maintainers what was required before.  The goal is to minimize rework / reanalyzing the module of code during subsequent maintenance.

Title: Mocking concrete class - Not recommended

Body:
I've just read an excerpt of "Growing Object-Oriented Software" book which explains some reasons why mocking concrete class is not recommended.

Here some sample code of a unit-test for the MusicCentre class:

```<code>public class MusicCentreTest {
  @Test public void startsCdPlayerAtTimeRequested() {
    final MutableTime scheduledTime = new MutableTime();
    CdPlayer player = new CdPlayer() {
      @Override
      public void scheduleToStartAt(Time startTime) {
        scheduledTime.set(startTime);
      }
    }

    MusicCentre centre = new MusicCentre(player);
    centre.startMediaAt(LATER);

    assertEquals(LATER, scheduledTime.get());
  }
}
</code>```

And his first explanation:

The problem with this approach is that it leaves the relationship
  between the objects implicit. I hope we've made clear by now that the
  intention of Test-Driven Development with Mock Objects is to discover
  relationships between objects. If I subclass, there's nothing in the
  domain code to make such a relationship visible, just methods on an
  object. This makes it harder to see if the service that supports this
  relationship might be relevant elsewhere and I'll have to do the
  analysis again next time I work with the class.

I can't figure out exactly what he means when he says:

This makes it harder to see if the service that supports this
  relationship might be relevant elsewhere and I'll have to do the
  analysis again next time I work with the class.

I understand that the service corresponds to MusicCentre's method called startMediaAt.

What does he mean by "elsewhere"?

The complete excerpt is here:
http://www.mockobjects.com/2007/04/test-smell-mocking-concrete-classes.html


问:
Random List of numbers in C
I have just started a C programming course and so far have only done the basics like printf, read a little on variables etc on the course book.  The teacher has tasked us with writing a program that will take a value entered by the user, this will be the number of students in the class (25 at the moment but can be variable).  It will then list the number of students randomly and place them in 3 columns.  The purpose is to sort students into groups of 3 randomly, then display on the screen in columns.

Now my question is not for the code that defeats the object of me attempting the exercise, but how to structure it.  I can see that using an array can be used to display the list, but really after some pointers on how best to approach the problem in blocks, then I can attempt to program each block.

答:
Perhaps the most instructive thing to do for yourself is to try to implement it in various ways, and you'll see by yourself what are the advantages and disadvantages of each.

...I mean, this is obviously a "learning by doing" exercise.

Title: Random List of numbers in C


答:
The biggest challenge you face is the fact that the number of entries to randomize is variable.  C requires more effort with managing variable structures, and that's probably the real intent of the exercise.

You should also consider the input structure as well as an output structure.

One approach to solving this is to take in all the inputs, placing them in an array or similar structure while they are read in.  You can then randomly select entries from that input array and either push them to the output structure or push them to the output device.  This gives a randomization of the input values along with a potential randomization of their output location.

Another approach would be to push the input values to their randomly selected output structure as they are provided.  This only provides a randomization of their output location, and a modest appearance of randomization to their input.

A 25+ entry array would be just as good of a place to start with on the input structure.  It's also pretty easy to tap based upon the index.

A simply 3x9 array would be a good starting point to consider for storing the results.  You could also use 3 separate arrays for storing the results.  Honestly, I'm not sure there's an advantage either way.  If you had additional requirements on the output, that might affect the structures.

A final aspect to consider is input array overflow (ie too many values being provided) as well as handling too many entries into a given "column" of the output structure.  It's possible that one column will fill up before the others.  What limits do you want to place on how many entries each column can have?

Title: Random List of numbers in C

Body:
I have just started a C programming course and so far have only done the basics like printf, read a little on variables etc on the course book.  The teacher has tasked us with writing a program that will take a value entered by the user, this will be the number of students in the class (25 at the moment but can be variable).  It will then list the number of students randomly and place them in 3 columns.  The purpose is to sort students into groups of 3 randomly, then display on the screen in columns.

Now my question is not for the code that defeats the object of me attempting the exercise, but how to structure it.  I can see that using an array can be used to display the list, but really after some pointers on how best to approach the problem in blocks, then I can attempt to program each block.


答:
The service I meant here was CDPlayer.scheduleToStartAt(). That's what the MediaCentre calls--the collaborator it needs to function. The MediaCentre is the object under test.

The idea is that if I make explicit just what the MediaCentre depends on, not an implementation class, I can give that dependency role a name and talk about it. All the MediaCentre needs to know is that it talks to ScheduledDevices. As rest of the system changes, I won't need to alter the MediaCentre unless its features change.

Does that help?


问:
What is the common definition of a Hacker?
I'm wondering if the term Hacker means different things to different people.  When most people hear the word hacker what are the first things that come to mind?</p>

答: Someone who is considered hacker by other hackers.</p>


答:
Assuming creating your own random number generator isn't supposed to be part of the assignment, then you have three parts to the assignment.

Create structure with the proper size to hold the number of students input.

Use a random number generator to assign positions.

Output the randomized groups in the correct format.

The two main hangups I can see is creating a properly sized structure based on dynamic input is a bit more difficult in C than more modern languages, and handling collisions when randomly assigning spots.

How to hold the data is really a question of how much you need to do with it, if only printing is required a single array will work fine, if more is required to be done based on groups it may be beneficial to use a 2 dimensional array so individual groups are easier to access.

Title: Random List of numbers in C


答:
On a personal level, I develop on a weird combination of what I want and what would be interesting to write.

On a professional level, @haylem makes a good overall point about when to buy versus when to write. I will say that there is a huge element that is overlooked: opportunity. For larger companies it often makes sense, in my opinion, to custom write core line of business apps (not all line of business apps) when doing so makes the enterprise more nimble. There is an opportunity cost associated with buying software because then your enterprise (not just your IT) are locked into the vendor's way of looking at your domain.

For most things, it doesn't matter. Your accounting system had better not be creative. Your word processor will be just the same as anyone else's. But the things that make you you might be better written in house so that it can adapt to what it is that your business is trying to accomplish.


答:
It is, as pretty much every other answer has said, a cost-benefits decision:

What will it cost me in man-hours, materials, etc to give this project to a developer in-house, or an external contractor, to custom-develop? (usually high; counting their portion of overhead, plus salary and benefits, an experienced developer will cost you about a grand a day; maybe a bit more or less depending on the finances involved)

What will it cost me to buy the known product off the shelf? (Depends on the product; general-use programs like text editors are typically cheap, even free, while specialized programs like circuit path design products can cost millions)

What benefits will I get from a custom-developed solution? (Typically a custom solution is a closer fit to your business and thus can automate or at least digitize more of it)

It comes down to whether the cost, offset by benefits, of a custom-developed solution is less than the cost of the off-the-shelf product.

There are also opportunity costs to consider. Understand that these are not to be included in the real costs of developing vs buying, but in the wider world, you have to consider them. If your in-house development staff is working on this one project, they are not working on any other project; that means if there's another project on the list that is costing you money every day it's not done, it may well be a higher priority causing you to shelve or even cancel custom development and go with the off-the-shelf package. However, if not doing this project means your in-house staff is sitting on their hands, the developer cost is sunk; you're paying your development staff whether they're working or not, so it will cost you less overall if you're using them to their potential.


问:
Looking for terminology for the relation of a subject and a predicate
While writing some predicates for collection filtering I have stumbled over the choice of the right words for the relation of the subject and the predicate (English is a foreign language for me). What I ended up writing was "Subjects matching this predicate..."

This seems to be incorrect, since predicates are functions and not regular expressions. But saying "Subjects for which this predicate returns true..." sounds awkward to me as well..

So what would be the correct term?

答:
I would use "Subjects satisfying this predicate".

Matches implies a pattern, rather than a condition. And "for which this predicate returns true," although the most accurate, sounds more technical than I think you intend.

Edit: Mike makes a good point that predicate is also very technical. Perhaps "Subjects satisfying this condition" is a better option.


答:
I think the terminology really depends on your intended audience.

If we're talking about code comments and API documentation then I would say your suggestion would be very accurate and understandable.

```<code>"For which this predicate returns true."
</code>```

If we're writing end user documentation I would avoid the word predicate all together and stick with "filter" and "match".

```<code>"Subjects matching your filter."
</code>```

Title: Looking for terminology for the relation of a subject and a predicate

Body:
While writing some predicates for collection filtering I have stumbled over the choice of the right words for the relation of the subject and the predicate (English is a foreign language for me). What I ended up writing was "Subjects matching this predicate..."

This seems to be incorrect, since predicates are functions and not regular expressions. But saying "Subjects for which this predicate returns true..." sounds awkward to me as well..

So what would be the correct term?

Body:
I think the terminology really depends on your intended audience.

If we're talking about code comments and API documentation then I would say your suggestion would be very accurate and understandable.

"For which this predicate returns true."

If we're writing end user documentation I would avoid the word predicate all together and stick with "filter" and "match".

"Subjects matching your filter."