问:
Asynchronously returning a hierarchal data using .NET TPL... what should my return object "look" like?
I want to use the .NET TPL to asynchronously do a DIR /S and search each subdirectory on a hard drive, and want to search for a word in each file... what should my API look like?

In this scenario I know that each sub directory will have 0..10000 files or 0...10000 directories.  I know the tree is unbalanced and want to return data (in relation to its position in the hierarchy) as soon as it's available.  I am interested in getting data as quickly as possible, but also want to update that result if "better" data is found (better means closer to the root of c:)

I may also be interested in finding all matches in relation to its position in the hierarchy. (akin to a report)

Question:

How should I return data to my caller?

My first guess is that I think I need a shared object that will maintain the current "status" of the traversal (started | notstarted | complete ) , and might base it on the System.Collections.Concurrent.

Another idea that I'm considering is the consumer/producer pattern (which ConcurrentCollections can handle) however I'm not sure what the objects "look" like.

Optional Logical Constraint: The API doesn't have to address this, but in my "real world" design, if a directory has files, then only one file will ever contain the word I'm looking for.  If someone were to literally do a DIR /S as described above then they would need to account for more than one matching file per subdirectory.

More information :

I'm using Azure Tables to store a hierarchy of data using these TPL extension methods. A "node" is a table.  Not only does each node in the hierarchy have a relation to any number of nodes, but it's possible for each node to have a reciprocal link back to any other node.  This may have issues with recursion but I'm addressing that with a shared object in my recursion loop.

Note that each "node" also has the ability to store local data unique to that node. It is this information that I'm searching for.  In other words, I'm searching for a specific fixed RowKey  in a hierarchy of nodes.

When I search for the fixed RowKey in the hierarchy I'm interested in getting the results FAST (first node found) but prefer data that is "closer" to the starting point of the hierarchy.

Since many nodes may have the particular RowKey I'm interested in, sometimes I may want to get a report of ALL the nodes that contain this RowKey.

答:
So I would break this out to two stages - the directory listing / traversal and the search function.

The listing / traversal is a classic tree node problem and there's a boodle of examples out there for solving that problem.  What we've done to solve that problem is to ID the upper layers first; retrieve that; then work on retrieves within the lower layers.  The approach lends itself well to recursion and you end up with some tight code.

I would use a skip / take model and pick a smaller amount for each request.  That will help keep the callback open / waiting while the traversal is taking place.

For an API structure... I would expose a single function to retrieve the structure.  That function will provide the callback(s) to the calling function and will essentially act as a buffer for the actual traversal functions.  Depending upon performance of the listing, you can now easily move this to a parallel traversal model and speed things up.  .NET 4 and 4.5 have some pretty slick enhancements for parallelization.

How you want to pass the tree structure back is going to depend upon what you're using for the UI.  Pick a data structure that will play nicely with your UI components.

The search function would be a second call, but it should be able to rely upon | mirror some of the functions you created with the directory listing.  Since you have the liberty of choosing your search order now (ie, you're controlling where it starts from based upon the directory listing) you can preferentially search the closer-to-root locations first.

Here, I would probably create two calls into the API or just overload a single one.  The overload would be the check for getting the first, closet to root instance or get all of them.  As an aside, consider how you want to handle multiple hits at the same depth away from root.

Finally, depending upon how performant the listing is, you may want to consider some form of caching the directory structures.  It shouldn't be that expensive to keep in memory, but should save you some time by avoiding redundant IO.


问:
Compute if a function is pure
As per Wikipedia:

In computer programming, a function may be described as pure if both these statements about the function hold:
  The function always evaluates the same result value given the same argument value(s). The function result value cannot depend on any hidden information or state that may change as program execution proceeds or between different executions of the program, nor can it depend on any external input from I/O devices.
  Evaluation of the result does not cause any semantically observable side effect or output, such as mutation of mutable objects or output to I/O devices.

I am wondering if it is possible to write a function that compute if a function is pure or not. Example code in Javascript:

```<code>function sum(a,b) {
    return a+b;
}

function say(x){
    console.log(x);
}

isPure(sum) // True
isPure(say) // False
</code>```

答:
Great question.

The best you can do in practice, assuming no ability to listen to i/o actions to call the function as many times as feasible. Then see if the return value is consistent.

But you cannot do this in general. Arguably, non-halting programs are non-pure, and we cannot decide the halting problem.

ContentLicense: CC BY-SA 3.0

Title: Compute if a function is pure


问:
Why should a class be anything other than "abstract" or "final/sealed"?
After 10+ years of java/c# programming, I find myself creating either:

abstract classes: contract not meant to be instantiated as-is.

final/sealed classes: implementation not meant to serve as base class to something else.

I can't think of any situation where a simple "class" (i.e. neither abstract nor final/sealed) would be "wise programming".

Why should a class be anything other than "abstract" or "final/sealed" ?

EDIT

This great article explains my concerns far better than I can.

答:
I believe the real reason many people feel classes should be final/sealed is that most non-abstract extendable classes are not properly documented.

Let me elaborate. Starting from afar, there is the view among some programmers that inheritance as a tool in OOP is widely overused and abused. We've all read the Liskov substitution principle, though this didn't stop us from violating it hundreds (maybe even thousands) of times.

The thing is programmers love to reuse code. Even when it's not such a good idea. And inheritance is a key tool in this "reabusing" of code. Back to the final/sealed question.

The proper documentation for a final/sealed class is relatively small: you describe what each method does, what are the arguments, the return value, etc. All the usual stuff.

However, when you are properly documenting an extendable class you must include at least the following:

Dependencies between methods (which method calls which, etc.)

Dependencies on local variables

Internal contracts that the extending class should honor

Call convention for each method (e.g. When you override it, do you call the super implementation? Do you call it in the beginning of the method, or in the end? Think constructor vs destructor)

...

These are just off the top of my head. And I can provide you with an example of why each of these is important and skipping it will screw up an extending class.

Now, consider how much documentation effort should go into properly documenting each of these things. I believe a class with 7-8 methods (which might be too much in an idealized world, but is too little in the real) might as well have a documentation about 5 pages, text-only. So, instead, we duck out halfway and don't seal the class, so that other people can use it, but don't document it properly either, since it will take a giant amount of time (and, you know, it might never be extended anyway, so why bother?).

If you're designing a class, you might feel the temptation to seal it so that people cannot use it in a way you've not foreseen (and prepared for). On the other hand when you're using someone else's code, sometimes from the public API there is no visible reason for the class to be final, and you might think "Damn, this just cost me 30 minutes in search for a workaround".

I think some of the elements of a solution are:

First to make sure extending is a good idea when you're a client of the code, and to really favor composition over inheritance.

Second to read the manual in its entirety (again as a client) to make sure you're not overlooking something that is mentioned.

Third, when you are writing a piece of code the client will use, write proper documentation for the code (yes, the long way). As a positive example, I can give Apple's iOS docs. They're not sufficient for the user to always properly extend their classes, but they at least include some info on inheritance. Which is more than I can say for most APIs.

Fourth, actually try to extend your own class, to make sure it works. I am a big supporter of including many samples and tests in APIs, and when you're making a test, you might as well test inheritance chains: they are a part of your contract after all!

Fifth, in situations when you're in doubt, indicate that the class is not meant to be extended and that doing it is a bad idea (tm). Indicate you should not be held accountable for such unintended use, but still don't seal the class. Obviously, this doesn't cover cases when the class should be 100% sealed.

Finally, when sealing a class, provide an interface as an intermediate hook, so that the client can "rewrite" his own modified version of the class and work around your 'sealed' class. This way, he can replace the sealed class with his implementation. Now, this should be obvious, since it is loose coupling in its simplest form, but it's still worth a mention.

It is also worth to mention the following "philosophical" question: Is whether a class is sealed/final part of the contract for the class, or an implementation detail? Now I don't want to tread there, but an answer to this should also influence your decision whether to seal a class or not.

ContentLicense: CC BY-SA 4.0


问:
Which library/framework did you ditch as being too complex for the problem it is solving?
... and coded the functionality "manually"?

As a rather metaphorical example, you'd hardly need a library for solving quadratic equations, although such libraries do exist and someone takes them seriously.

As a more questionable case, depending on the circumstances I may ditch jQuery (for example when I don't need to support some stone age browsers): it does simplify some things but it adds another layer of complexity and unreliability to DOM. And overusing jQuery leads to absurd problems, such as one seen recently on SO: how do I assign an empty href to an a tag with jQuery? Turned out it was a HTML question, not even JavaScript.

Another absurd case and yet non-obvious for many is using some templating engine/language built on top of another templating system: PHP. Third level of templating anyone?

And another one: sometimes just spitting out XML with (figurally) printf is far easier than doing it with some monstrous XML engine.

Any other cases from your experience?

答: On a particular project I ditched EJB3. It gave me dependency injection and container managed transaction handling. But it introduces huge dependencies (e.g. JBoss) and made the system difficult to write automated tests for. Now I've stripped it down to JPA + constructor dependency injection.</p>

ContentLicense: CC BY-SA 2.5


答:
Yes, it is possible, depending on the language.

In JavaScript, you can tell if a function is pure by the following criteria:

It only reads parameters and locals;

It only writes locals;

On non-locals, it calls only pure functions;

All functions it calls implicitly are pure, e.g., toString; and

It only writes properties of locals if they do not alias non-locals.

Aliasing is not possible to determine in JavaScript in the general case, because you can always look up properties of an object dynamically (object["property"]). Provided you never do that, and you have the source of the whole program, then I think the problem is tractable. You would also need information about which native functions have side-effects, such as console.log or most anything involving the DOM.

The term “pure” could also use some clarification. Even in a strongly, statically typed, purely functional programming language, where all functions are referentially transparent, a function can still fail to terminate. So when we talk about id :: a -> a, what we’re really saying is not:

Given some value of type a, the function id produces a value of type a.

But rather:

Given some value of type a, the function id does not produce a value which is not of type a.

Because a valid implementation of id is error "Not implemented!". As Peteris points out, this nontotality could be seen as a kind of impurity. Koka is a functional programming language—with syntax modelled on JavaScript—which can infer possible effects such as divergence (nontermination), referential transparency, throwing of exceptions, and I/O actions.

Title: Compute if a function is pure

Body:
As per Wikipedia:

In computer programming, a function may be described as pure if both these statements about the function hold:
  The function always evaluates the same result value given the same argument value(s). The function result value cannot depend on any hidden information or state that may change as program execution proceeds or between different executions of the program, nor can it depend on any external input from I/O devices.
  Evaluation of the result does not cause any semantically observable side effect or output, such as mutation of mutable objects or output to I/O devices.

I am wondering if it is possible to write a function that compute if a function is pure or not. Example code in Javascript:

```<code>function sum(a,b) {
    return a+b;
}

function say(x){
    console.log(x);
}

isPure(sum) // True
isPure(say) // False
</code>```


答: I have found abstract classes useful but not always needed, and sealed classes become an issue when applying unit tests. You can't mock or stub a sealed class, unless you use something like Teleriks justmock.</p>

Title: Why should a class be anything other than "abstract" or "final/sealed"?

Body:
After 10+ years of java/c# programming, I find myself creating either:

abstract classes: contract not meant to be instantiated as-is.

final/sealed classes: implementation not meant to serve as base class to something else.

I can't think of any situation where a simple "class" (i.e. neither abstract nor final/sealed) would be "wise programming".

Why should a class be anything other than "abstract" or "final/sealed" ?

EDIT

This great article explains my concerns far better than I can.


问:
Custom .NET apps and clustering
So for a clustered environment - how would this work with your apps?

What about your own custom .NET apps? Would there be a special way to develop them? I know that you could create a simple Hello world app, and cluster that, but that wouldn't be something you could see in terms of the UI or anything. So they would effectively need to be developed as a Windows Service, or even, perhaps, as a standard Console app, which runs and does not wait for user input. But you wouldn't see any output from it (unless you redirect output to somewhere else).

What I'm getting at here is... for those who have experience or developed a cluster application in .NET, how did you do it? What are the things to be aware of?

For example, we have the cloud service, which is fundamentally built on clustering. If there is an outage, another node takes its place, and the service resumes as normal. However, we don't really see much of that downtime.

答:
I've written a lot of .NET clustered applications over the years (exclusively for Active/Passive clusters) and can share what I've learned.

I've always written my apps as Windows Services and include them as clustered resources in the Windows Cluster Administrator.  When the cluster fails over from Node1 to Node2, the Cluster Administrator shuts down the service on Node1 and starts it up on Node2.  That's the simple part and Windows takes care of the heavy lifting.

Aside - There is no technical reason why you couldn't write a console app and have it kicked off by the Scheduled Tasks service (which can also be setup as a clustered resource) or some other means. When I first started writing clustered apps the requirements often required the process to be kicked off by the arrival of a file and that seemed to be a better fit for a service than for a console app. For consistency sake, we just continued to write them as services.

The design of your app is going to depend quite a bit on what exactly its task is. But conceptually, you'll need some way to keep track of what unit of work your app is executing so that if the cluster fails over, your app on Node2 knows where to pick up where the app on Node1 left off.

If your app is file based, meaning it is performing some work on files or the data contained in one or more files, those files will need to be on a drive that either fails over or is visible to both nodes. Your app will need to keep track of what file it was working on and potentially what record within the file as well. How it stores this progress is really up to you and what resources are available, but the important thing is that this progress is stored in a manner that will survive the failover (ie, in a DB table or a file on a drive). Storing this progress on a local drive of Node1 will do you no good when the app starts up on Node2, if Node1 is dead.

While you're designing/coding, keep asking yourself - if the cluster failed over at this exact point in the process,

What data would be lost? (and would it matter?)

Where would the other node deteremine it should start from? (and is it correct?)

There's no magic to it really, just a lot of thought in the details. Should your app do all of the work in transaction (DB or COM+)? That depends on the complexity of the task and requirements. Can you just tag records in a DB as your app completes them and have the other node work on untagged records?  Sure, again it depends on the requirements.

Title: Custom .NET apps and clustering


问:
New "delay" keyword for JavaScript
I had a great idea for a new javascript keyword "delay", but I don't know what I can do to bring it to the new specification. Also I want to know what you guys think about it and if it's even realistic.

What does the delay keyword ?

The delay keyword does nothing more than stop the execution of the current stack and immediately continues to the next "job" in the queue. But that's not all! Instead of discarding the stack, it adds it to the end of the queue. After all "jobs" before it are done, the stack continues to execute.

What is it good for?

delay could help make blocking code non-blocking while it still looks like synchronous code. A short example:

```<code>setTimeout(function(){
    console.log("two");
},0);
console.log("one");
delay; //since there is currently another task in the queue, do this task first before continuing
console.log("three");

//Outputs: one, two, three
</code>```

This simple keyword would allow us to create a synchronous-looking code wich is asynchronous behind the scenes. Using node.js modules, for example, would no longer be impossible to use in the browser without trickery.

There would be so many possibilites with such a keyword!

Is this pattern useful? What can I do to bring this into the new ECMAscript specification?

Note: I asked this previously
on Stack Overflow, where it was closed.

答:
It's funny that your question has been downvoted, since the feature you have described is actually the object of an official strawman1 proposal (but the actual name of the new keyword is await).

If you want to support this proposal, you can suscribe to the es-discuss mailing-list and look for the previous discussions about it.

1 Strawman is the namespace where are keeped the ES6 proposals before validation. The other one is Harmony, where are keeped the ES6 proposals which have been approved but need more work.

Title: New "delay" keyword for JavaScript


答:
This stackoverflow question has an answer by yfeldblum that is relevant here.  (And has a downvote for some reason I can't fathom.  Would it be bad etiquette to upvote something that is 3 years old?)  He gives a proof that whether a function is pure is reducible to the halting problem in a comment.

I think from a practical point of view it wouldn't be too hard for some languages if you let the function return yes, no, or maybe.  I was watching a video about Clojure a couple of days ago, and the speaker had done a count of instances of impurity in a codebase by searching for about 4 different strings (like "ref").  Because of Clojure's emphasis on purity and segregation of impure things, it was trivial, but it wasn't quite exactly what you're looking for.

So, theoretically impossible, practically possible if you tweak the question a bit, and I think how hard it would be would depend greatly on the language.  Simpler/cleaner languages with a focus on immutability and good reflection would be easier.

Title: Compute if a function is pure


问:
How should I compress a file with multiple bytes that are the same with Huffman coding?
On my great quest for compressing/decompressing files with a Java implementation of Huffman coding (http://en.wikipedia.org/wiki/Huffman_coding) for a school assignment, I am now at the point of building a list of prefix codes. Such codes are used when decompressing a file. Basically, the code is made of zeroes and ones, that are used to follow a path in a Huffman tree (left or right) for, ultimately, finding a byte.

In this Wikipedia image, to reach the character m the prefix code would be 0111

The idea is that when you compress the file, you will basically convert all the bytes of the file into prefix codes instead (they tend to be smaller than 8 bits, so there's some gain).

So every time the character m appears in a file (which in binary is actually 1101101), it will be replaced by 0111 (if we used the tree above).

Therefore, 1101101110110111011011101101 becomes 0111011101110111 in the compressed file.

I'm okay with that. But what if the following happens:

In the file to be compressed there exists only one unique byte, say 1101101.

There are 1000 of such byte.

Technically, the prefix code of such byte would be... none, because there is no path to follow, right? I mean, there is only one unique byte anyway, so the tree has just one node.

Therefore, if the prefix code is none, I would not be able to write the prefix code in the compressed file, because, well, there is nothing to write.

Which brings this problem: how would I compress/decompress such file if it is impossible to write a prefix code when compressing? (using Huffman coding, due to the school assignment's rules)

This tutorial seems to explain a bit better about prefix codes: http://www.cprogramming.com/tutorial/computersciencetheory/huffman.html but doesn't seem to address this issue either.

答:
Actually you would use run-length encoding in such a situation. In essence you store the symbol and the number of repeats.

However, if you still insist on using Huffman coding, you could pick either one or zero to represent the symbol in the tree. This causes no problem really. Your tree simply states that symbol x is represented by bit m. Then you have n number of repeats of the encoded m as data. You could even then apply aforementioned RLE on the actual data (which is essentially a run of equal bits of length n) to compress further.


问:
Child to Parent linking - bad idea?
I have a situation where my parent knows about it's child (duh) but I want the child to be able to reference the parent. The reason for this is that I want the child to have the ability to designate itself as most important or least important when it feels like it. When the child does this, it moves it to the top or bottom of the parent's children.

In the past I've used a WeakReference property on the child to refer back tot he parent, but I feel that adds an annoying overhead, but maybe it's just the best way to do it.

Is this just a bad idea? How would you implement this ability differently?

Update 1:
Adding more context. This is a rendering system so the parent container is a list of windows grouped together. The child item (window) that says "I'm most important!" wants to basically be rendered on the top of the rest of the windows.

The parent is just a logical container to group these children together. I can see where adding an event to signal the request to be on the top is a good idea. But implementation (what the child wants to do with the parent) aside, why wouldn't you want to have child->parent linking? Doubly linked lists do this so people can traverse to and from something.

答:
Is this just a bad idea?

Oftentimes.

It breaks encapsulation of the parent.

It increases coupling in both.

It serves as a breakout point for the child to get at the rest of the system, increasing coupling with anything vaguely near it (because people will abuse that reference)

It limits your design if you ever want children without parents.

How do do it better? The child should not know or care that it is in a collection. Instead of deeming itself important, it should signal that some event it knows about has happened so whomever cares (the parent) can increase its priority (or whatever is the rules for the context the child lives in). I'm not thrilled by that, and would perhaps prefer a better separation of concerns between the child's model and the importance behavior, but can't elaborate without more context.

[edit:]

Yeah, rendering systems are one case where parent ownership... well I don't want to say makes sense, but it's one case where it has been done and isn't the end of the world. For giving a control focus, I would still prefer the design where the input handler (or whatever) walks the tree and knows which collection to reorder rather than it finding the child, calling something on it which knows to go to its parent.

Title: Child to Parent linking - bad idea?


问:
Too complex/too many objects?
I know that this will be a difficult question to answer without context, but hopefully there are at least some good guidelines to share on this. The questions are at the bottom if you want to skip the details. Most are about OOP in general.

Begin context. I am a jr dev on a PHP application, and in general the devs I work with consider themselves to use many more OO concepts than most PHP devs. Still, in my research on clean code I have read about so many ways of using OO features to make code flexible, powerful, expressive, testable, etc. that is just plain not in use here.

The current strongly OO API that I've proposed is being called too complex, even though it is trivial to implement. The problem I'm solving is that our permission checks are done via a message object (my API, they wanted to use arrays of constants) and the message object does not hold the validation object accountable for checking all provided data. Metaphorically, if your perm containing 'allowable' and 'rare but disallowed' is sent into a validator, the validator may not know to look for 'rare but disallowed', but approve 'allowable', which will actually approve the whole perm check. We have like 11 validators, too many to easily track at such minute detail.

So I proposed an AtomicPermission class. To fix the previous example, the perm would instead contain two atomic permissions, one wrapping 'allowable' and the other wrapping 'rare but disallowed'. Where previously the validator would say 'the check is OK because it contains allowable,' now it would instead say '"allowable" is ok', at which point the check ends...and the check fails, because 'rare but disallowed' was not specifically okay-ed.

The implementation is just 4 trivial objects, and rewriting a 10 line function into a 15 line function.

```<code>abstract class PermissionAtom {
public function allow(); // maybe deny() as well
public function wasAllowed();
}

class PermissionField extends PermissionAtom {
public function getName();
public function getValue();
}

class PermissionIdentifier extends PermissionAtom {
public function getIdentifier();
}

class PermissionAction extends PermissionAtom {
public function getType();
}
</code>```

They say that this is 'not going to get us anything important' and it is 'too complex' and 'will be difficult for new developers to pick up.' I respectfully disagree, and there I end my context to begin the broader questions.

So the question is about my OOP, are there any guidelines I should know:

is this too complicated/too much OOP? Not that I expect to get more than 'it depends, I'd have to see if...'

when is OO abstraction too much?

when is OO abstraction too little?

how can I determine when I am overthinking a problem vs fixing one?

how can I determine when I am adding bad code to a bad project?

how can I pitch these APIs? I feel the other devs would just rather say 'its too complicated' than ask 'can you explain it?' whenever I suggest a new class.

答:
I quite like this question, but I don't think it is really about OO or APIs. It's about being a junior or a new member of a team and having input (either ideas or past experience) that the other team members aren't agreeing with.

I'll answer your questions:

Doesn't appear to be

When the problem doesn't warrant any more abstraction

When the problem does warrant more abstraction

Experience

Experience

Explain it, demonstrate it, describe the risks and benefits of it.

That is all very deliberately vague. Abstractions add complexity and remove complexity at the same time - just different types of complexity. The correct application depends on your business, product, team, and so on.

Your teammates may not support your idea for a number of reasons:

the idea won't work, is incorrect or bad practice, or is just rubbish (your competence)

there are business or system reasons why the idea won't work (your experience)

they don't see the benefits of the idea or the risks of not adopting the idea (their experience)

they refuse to or cannot understand the idea (their competence)

they are asserting their seniority or position (political)

A political or competence problem falls outside the scope of any technical discussion of the idea, is a management issue, and I hope that's not the problem. It's very likely that this is an experience issue. This doesn't mean that you don't have enough experience, or they don't have enough experience, but there's a disconnect somewhere which causes you to see this as a good idea but others to see it as a bad idea.

What do you do in this situation? You discuss the idea. If they aren't willing to discuss the idea with you (and you should give them the opportunity to dissect it, destroy it for you so you can learn from them) then see above (political or competence reasons). Have a frank and open discussion about the alternatives, particularly with respect to implementation difficulty and future flexibility. It's not your idea vs their idea; there are two approaches on the table and the team must decide between them.

Title: Too complex/too many objects?


问:
doing a full permutation search and replace on a string
I'm writing an app that does something like a custom number (license) plate generator tool where if I ask for the plate "robin" it will suggest I try:

r0bin

rob1n

r0b1n

Are there any published algorithms which can do this? It has to be able to handle replacing single letters with multiples, e.g. m with rn and vise-versa and not fall over if it replaces an i with an l then comes to check the l and replaces it back to an i.

The list of what gets swapped with what is going to be user input but I'm not expecting a huge list, possibly 10 pairs at most.

I'll be implementing this in Ruby or Python but I should be able to convert code from any other language.

答:
Based on my understanding of your requirements, I am not aware of a published algorithm specifically for your case, but you can make one using the following discussion.

I will use an odd example, but you will see why soon.
Let us say you have a string such as

AB1C4D6

Assume that:

Character in position 3 can have values (1,2,3), that is 3 distinct values.

Character in position 5 can have values (4,5), that is 2 distinct values.

Character in position 7 can have values (6,7), that is 2 distinct values.

Possible outcomes of performing various replace operaiotns on the original string are shown below.

The total number of strings we can obtain is 3x2x2 = 12 (including the initial string).

This process is similar to generating Cartesian product of 3 sets (like SELECT * FROM T1, T2, T3).

Given a string length of N letters, if each letter i has at most r_i possible replacement characters, then we'd have a total of (r_0*r_1*r_2*...*r_N) words where r_i=1 if there are no replacements for the letter.

The reason I have choosen this specific example is that there is a description on how to generate the Cartisian product in here that uses similar values, so it would be easy for you to follow (although it is not in either Ruby or Python).

The concept will be the same if you map 1 input character to more than 1 character as long as make a single pass to the string and use the appropriate function to perform the replace.


答: Not possible in the general case. See halting problem. Briefly, it is impossible to write a program that, given an arbitrary function and input, determines whether the program will halt or run forever. If it runs forever, it's not a pure function fitting the definition you gave.

Title: Compute if a function is pure


答:
SharePoint

Don't get me wrong, SharePoint is awesome if you need most of the things it comes with (and it comes with a lot!), but if you don't know what you're doing or only need it for one or two things, it is MASSIVELY not worth the effort and configuration.

Title: Which library/framework did you ditch as being too complex for the problem it is solving?

Body:
... and coded the functionality "manually"?

As a rather metaphorical example, you'd hardly need a library for solving quadratic equations, although such libraries do exist and someone takes them seriously.

As a more questionable case, depending on the circumstances I may ditch jQuery (for example when I don't need to support some stone age browsers): it does simplify some things but it adds another layer of complexity and unreliability to DOM. And overusing jQuery leads to absurd problems, such as one seen recently on SO: how do I assign an empty href to an a tag with jQuery? Turned out it was a HTML question, not even JavaScript.

Another absurd case and yet non-obvious for many is using some templating engine/language built on top of another templating system: PHP. Third level of templating anyone?

And another one: sometimes just spitting out XML with (figurally) printf is far easier than doing it with some monstrous XML engine.

Any other cases from your experience?


问:
When does "proper" programming no longer matter?
I've been building an android game in my spare time. It's using the libgdx library so quite a bit of the heavy lifting is done for me.

While developing, I carelessly selected datatypes for some procedures. I used a hashtable because I wanted something close to an associative array. Human readable key values. In other places to achieve similar things, I use a vector. I know libgdx has vector2 and vector3 classes, but I've never used them.

When I come across weird problems and search Stack Overflow for help, I see a lot of people just reaming the questions that use a certain datatype when another one is technically "proper." Like using an ArrayList because it does not require defined bounds versus re-defining an int[] with new known boundaries. Or even something trivial like this:

```<code>for(int i = 0; i < items.length; i ++)
{
    // do something
}
</code>```

I know it evaluates item.length on every iteration. However, I also know items will never be more than 15 to 20 items. So should I care if I evaluate items.length on every iteration?

I ran some tests to see how the app performs using the method I just described versus the proper, follow the tutorial and use the exact data types suggested by the community. The results: Same thing. Average 45 fps. I opened every app on the phone and galaxy tab. No difference.

So I guess my question to you is this: Is there a threshold when it no longer matters to be proper? Is it ok to say - "so long as it gets the job done, I don't care?"

答:
Is performance your main concern? Is that what you're trying to maximize?

If so, there is a fundamental lesson to learn, and if you do, you'll be one of the few.

Don't try to "think" what you should do to make it faster - that's guessing.
If you're asking "Should I use this container class or that one?", or "Should I put length in the loop condition?", you're like a doctor who sees a patient and tries to decide what treatment to give without actually questioning or examining the patient.

That's guessing. Everybody does it, but it doesn't work.

Instead, let the program itself tell you what its problem is.
Here's a detailed example.

Do you see the difference?


答:
The answer is that it never matters, and it always matters....

It never matters because programming, proper or not, is a way of achieving a goal, not a goal in itself. If that goal is achieved without "proper" programming that's fine (from a business perspective it's often best if the goal can be achieved with no programming).

It always matters because proper programming is a tool that will aid you in achieving your goals.  The proper way of doing things is simply a recognition that doing it another way causes more pain in the long run than it saves.

Which answers the question of when you can ignore it -- when you're sure that another way will be easier in the long run (possibly because there will be no long run).

One off tools are typically done as quick and dirty as you can, with little to no error checking or other validation, no logging of exceptions, cut-n-paste code with minor changes or even no changes instead of generic functions, and so forth.

Just watch out: sometimes those quick and dirty apps take on alife of their own, which means all of the short cuts bite you in the...

Title: When does "proper" programming no longer matter?

Body:
I've been building an android game in my spare time. It's using the libgdx library so quite a bit of the heavy lifting is done for me.

While developing, I carelessly selected datatypes for some procedures. I used a hashtable because I wanted something close to an associative array. Human readable key values. In other places to achieve similar things, I use a vector. I know libgdx has vector2 and vector3 classes, but I've never used them.

When I come across weird problems and search Stack Overflow for help, I see a lot of people just reaming the questions that use a certain datatype when another one is technically "proper." Like using an ArrayList because it does not require defined bounds versus re-defining an int[] with new known boundaries. Or even something trivial like this:

```<code>for(int i = 0; i < items.length; i ++)
{
    // do something
}
</code>```

I know it evaluates item.length on every iteration. However, I also know items will never be more than 15 to 20 items. So should I care if I evaluate items.length on every iteration?

I ran some tests to see how the app performs using the method I just described versus the proper, follow the tutorial and use the exact data types suggested by the community. The results: Same thing. Average 45 fps. I opened every app on the phone and galaxy tab. No difference.

So I guess my question to you is this: Is there a threshold when it no longer matters to be proper? Is it ok to say - "so long as it gets the job done, I don't care?"


问:
Is there an excuse for short variable names?
This has become a large frustration with the codebase I'm currently working in; many of our variable names are short and undescriptive. I'm the only developer left on the project, and there isn't documentation as to what most of them do, so I have to spend extra time tracking down what they represent.

For example, I was reading over some code that updates the definition of an optical surface. The variables set at the start were as follows:

```<code>double dR, dCV, dK, dDin, dDout, dRin, dRout
dR = Convert.ToDouble(_tblAsphere.Rows[0].ItemArray.GetValue(1));
dCV = convert.ToDouble(_tblAsphere.Rows[1].ItemArray.GetValue(1));
... and so on
</code>```

Maybe it's just me, but it told me essentially nothing about what they represented, which made understanding the code further down difficult. All I knew was that it was a variable parsed out specific row from a specific table, somewhere. After some searching, I found out what they meant:

```<code>dR = radius
dCV = curvature
dK = conic constant
dDin = inner aperture
dDout = outer aperture
dRin = inner radius
dRout = outer radius
</code>```

I renamed them to essentially what I have up there. It lengthens some lines, but I feel like that's a fair trade off. This kind of naming scheme is used throughout a lot of the code however. I'm not sure if it's an artifact from developers who learned by working with older systems, or if there's a deeper reason behind it. Is there a good reason to name variables this way, or am I justified in updating them to more descriptive names as I come across them?

答:
There absolutely is; often times a short variable name is all that is necessary.

In my case, I am doing waypoint navigation in my senior Robotics class, and we program our robots in KISS-C. We need variables for current and destination (x, y) co-ordinates, (x, y) distances, current and destination headings, as well as turn angles.

Especially in the case of x and y co-ordinates, a long variable name is completely unnecessary, and names such as xC (current x), yD (destination y), and pD (destination phi), suffice and are the easiest to understand in this case.

You might argue that these aren't 'descriptive variable names' as programmer protocol would dictate, but since the names are based on a simple code (d = destination, c = current), a very simple comment at the outset is all the description they require.


答:
Or even something trivial like this:

```<code>for(int i = 0; i < items.length;i ++) {
     // do something
}
</code>```

I know it evaluates item.length on every iteration. However, I also
  know items will never be more than 15 to 20 items. So should I care if
  I evaluate items.length on every iteration?

Actually in the final code, items.length will not be evaluated in every iteration because the compiler optimizes it. And even if it weren't, length is a public field in the array object; accessing it doesn't cost.

So I guess my question to you is this: Is there a threshold when it no longer >matters to be proper? Is it ok to say - "so long as it gets the job done, I >don't care?"

It really depends on what you expect from your end product; the difference between an average product and a great product relies in details. A car like Tata Nano and a car like Mercedes S "gets the job done" - it takes you from one place to another. The difference  relies in details: engine power, comfort, safety and others. It is the same with any product that exists, including software products; for example why would anyone pay to Oracle, IBM or Microsoft for Oracle database, DB2 or MS SQL Server since MySQL and Postgre are free?

If you want to pay attention to the details and obtain a high quality product you should care about this stuff (and about other stuff, obviously).

Body:
Or even something trivial like this:

for(int i = 0; i < items.length;i ++) {
     // do something
}

I know it evaluates item.length on every iteration. However, I also
  know items will never be more than 15 to 20 items. So should I care if
  I evaluate items.length on every iteration?

Actually in the final code, items.length will not be evaluated in every iteration because the compiler optimizes it. And even if it weren't, length is a public field in the array object; accessing it doesn't cost.

So I guess my question to you is this: Is there a threshold when it no longer >matters to be proper? Is it ok to say - "so long as it gets the job done, I >don't care?"

It really depends on what you expect from your end product; the difference between an average product and a great product relies in details. A car like Tata Nano and a car like Mercedes S "gets the job done" - it takes you from one place to another. The difference  relies in details: engine power, comfort, safety and others. It is the same with any product that exists, including software products; for example why would anyone pay to Oracle, IBM or Microsoft for Oracle database, DB2 or MS SQL Server since MySQL and Postgre are free?

If you want to pay attention to the details and obtain a high quality product you should care about this stuff (and about other stuff, obviously).


问:
How do .so files avoid problems associated with passing header-only templates like MS dll files have?
Based on the discussion around this question. I'd like to know how .so files/the ELF format/the gcc toolchain avoid problems passing classes defined purely in header files (like the std library). According to Jan in that answer, the dynamic linker/loader only picks one version of such a class to load if its defined in two .so files. So if two .so files have two definitions, perhaps with different compiler options/etc, the dynamic linker can pick one to use.

Is this correct? How does this work with inlining? For example, MSVC inlines templates aggressively. This makes the solution I describe above untenable for dlls. Does Gcc never inline header-only templates like the std library as MSVC does? If so wouldn't that make the functionality of ELF described above ineffective in these cases?

答:
What the ELF linker does is that it ensures that static and dynamic linker produce the same result. So using shared objects does not create any new problems. You can create some if you use of non-default visibility or version or linker scripts, but you obviously wouldn't do that if it isn't safe in that particular case.

Now if you use incompatible sets of compiler flags for building different objects, whether shared or static, in one application, you will have problems. You can have two kinds of problems:

The flags are so incompatible that calling convention, structure layout or some other such parameter is different between the modules. Obviously the only solution is to know which compiler options always have to remain set to the platform defaults.

The flags modify content of the headers and thus violate one definition rule. Authors of standard libraries, at least the open-source ones, know well how to avoid breaking compatibility between objects. But if you have some special library who's author were not careful, you can get in trouble and will have to make sure the compilation flags are compatible.

In Linux I've not seen these problems happen. Everybody knows not to touch the compiler flags that could break anything and there are no special incompatible versions for debug or such (gcc can emit debug information in optimizing build, so you normally just get unstripped version of the same object or lately even just the debug information for the normal object split out to separate file).

This is different from Windows, where:

Due to the way shared libraries need explicit export and import there will not merge symbols (like template instances or class impedimenta) generated into different shared libraries.

Have separate debug and release runtimes that differ in both the shared library used and lot of preprocessor magic. It means that you can't link your debug build to libraries built with the release version, so every library needs to ship debug and release variant. And often variant for static and dynamic linking. And despite all this trouble I don't think the debug support on Windows is better; e.g. Linux libc has hooks for replacing allocator (with debug one) which is always gross hack on Windows and Linux has great tools like Valgrind.

Have lots of compiler flags that get flipped for various compatibility reasons, causing more complications. It has to be said that Microsoft is in more difficult position here. Since they cater primarily for the closed-source programmers, they have to assume things can't be recompiled and have to provide various compatibility kludges to keep things working. Linux people just assume things can be recompiled and do a breaking change when things get too complicated, like the switch to ELF format was; The ELF format was created between 1997 and 1999, while Windows objects are still backward compatible to the old Windows 3.1 ones. At the cost of all the mess.


问:
How can I explain the usefulness of Inheritance?
When trying to explain the concept of Inheritance in OOP, the common example is often the mammals example. IMHO, this is really a bad example, because it will lead the newbies to use this concept the wrong way. And moreover, it is not a common design that they will face in their day-to-day design job.

So, what will be a nice, simple and concrete problem that is solved using Inheritance ?

答:
I will use birds as example

like chicken , duck ,eagle

I will explain  both have claws, pecks , and wings but their attributes are different.

Chickens cannot fly, cannot swim, can eat worms , can eat grains

Ducks  cannot fly, can swim , can eat grains, cannot eat worms

Eagle can fly, cannot swim , can eat worms,  cannot eat grains


答:
Is there an excuse for excessively short variable names?

First: Naming a variable for energy e while calculating formulas such as E=MC2 is NOT excessively short naming. Using symbols as an argument for short names is not valid

This question was rather interesting to me, and I can only think of one excuse and that is money.

Say for instance you're wiring javascript for a client which knows that the file is to be downloaded many times a second.
It would be cheaper and make the experience of the users better if the file (in number of bytes) is as small as possible.

(Just to keep the example 'realistic', you were not allowed to use a minifier tool, why? Security issues, no external tools allowed to touch the code base.)

Title: Is there an excuse for short variable names?

Body:
This has become a large frustration with the codebase I'm currently working in; many of our variable names are short and undescriptive. I'm the only developer left on the project, and there isn't documentation as to what most of them do, so I have to spend extra time tracking down what they represent.

For example, I was reading over some code that updates the definition of an optical surface. The variables set at the start were as follows:

```<code>double dR, dCV, dK, dDin, dDout, dRin, dRout
dR = Convert.ToDouble(_tblAsphere.Rows[0].ItemArray.GetValue(1));
dCV = convert.ToDouble(_tblAsphere.Rows[1].ItemArray.GetValue(1));
... and so on
</code>```

Maybe it's just me, but it told me essentially nothing about what they represented, which made understanding the code further down difficult. All I knew was that it was a variable parsed out specific row from a specific table, somewhere. After some searching, I found out what they meant:

```<code>dR = radius
dCV = curvature
dK = conic constant
dDin = inner aperture
dDout = outer aperture
dRin = inner radius
dRout = outer radius
</code>```

I renamed them to essentially what I have up there. It lengthens some lines, but I feel like that's a fair trade off. This kind of naming scheme is used throughout a lot of the code however. I'm not sure if it's an artifact from developers who learned by working with older systems, or if there's a deeper reason behind it. Is there a good reason to name variables this way, or am I justified in updating them to more descriptive names as I come across them?


问:
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>

答: A professional computer programmer who can bend the code to his fiery will.  As a child a hacker found a way to put the square block in the round hole.  Although at times he is proud of a great hack, he is never satisfied with his code. </p>


问:
How can QA prevent defects?
Also according to Software Testing By Srinisvasan Desikan, Gopalaswamy Ramesh or ISTQB text books. Quality assurance is e.g. reviewing products, inspections, walkthroughs to see if all standards are being followed. This is preventive activity. I cannot see how this can be preventive?

For the references:

defect prevention (Quality Assurance)

Software Testing By Srinisvasan Desikan, Gopalaswamy Ramesh

Quality Assurance (QA) tries to go one step further. Instead of concentrating on post- facto defect detection and correction, it focusses on the prevention of defects from the very start.

Managing Global Software Projects - Page 110

QA deals with prevention of defects in the product being developed.

Software Testing and Quality Assurance

答:
QA (Quality Assurance) and the corresponding QEs (Quality Engineers) are supposed to discover defects that have made it in the product before the product is released in production. Ultimately the role of the QA is to make the development team aware of the defects and the development team fixes them. In this sense QA doesn't prevent defects but discovers them.

In another sense QA prevents future defects that would be the product of the initial defect if it is not discovered.

Reviewing specifications or any other research materials that are present before the product starts its development cycle can also help QA discover defects that would be caused by wrongly achieved general architecture of the product.

E.g. We are developing product A because we need to release feature X to the customers. However in future cycles we most certainly would have to develop a feature Y as well. So we need to adjust the architecture to not just support the feature X which we are developing, but also the future features Y and Z.

Title: How can QA prevent defects?


答:
QA checks if predefined procedures are followed during the software development process. It also specifies a framework in which to define these procedures: ISO-9000, CMMi...

Thus QA ensures the quality of the process, not the quality of the product. Quality of the product is assumed to be covered by following the defined procedures.

In practice, QA brings other pairs of eyes to the project with a different point of view, and actually reveals product defects that may remain hidden otherwise.

Title: How can QA prevent defects?

Body:
Also according to Software Testing By Srinisvasan Desikan, Gopalaswamy Ramesh or ISTQB text books. Quality assurance is e.g. reviewing products, inspections, walkthroughs to see if all standards are being followed. This is preventive activity. I cannot see how this can be preventive?

For the references:

defect prevention (Quality Assurance)

Software Testing By Srinisvasan Desikan, Gopalaswamy Ramesh

Quality Assurance (QA) tries to go one step further. Instead of concentrating on post- facto defect detection and correction, it focusses on the prevention of defects from the very start.

Managing Global Software Projects - Page 110

QA deals with prevention of defects in the product being developed.

Software Testing and Quality Assurance


答:
No. You can easily check if a function only does "pure-safe" operations, as described in Jon Purdy's answer, but that is IMO not enough to answer the question.

Consider this function:

```<code>function possiblyPure(x) {
    if (someCheck(x)) {
        return x+1; // pure code path
    }
    else {
        console.log("I'm so unpure..."); // unpure code path
    }
}
</code>```

Obviously, if someCheck is unpure, so is possiblyPure. But, if someCheck is pure and returns true for every possible value of x, possiblyPure is pure, since the unpure code path is unreachable!

And here comes the hard part: determining whether or not someCheck returns true for every possible input. Trying to answering that question immedately leads you into the realm of the halting problem and similar undecidable problems.

EDIT: Proof that it is impossible

There is some uncertainity wether or not a pure function must terminate on every possible input. But in both cases, the halting problem can be used to show that the pureness check is impossible.

Case A) If a pure function is required to terminate on every possible input, you have to solve the halting problem to determine whether or not the function is pure. Since this is known to be impossible, by this definition, pureness cannot be computed.

Case B) If a pure function is allowed to not terminate on some inputs, we can construct something like that:
Let's assume that isPure(f) computes if f is a string defining a pure function.

```<code>function halts(f) {
   var fescaped = f.replace(/\"/g, '\\"');
   var upf = 'function() { '+f+'("'+fescaped+'\); console.log("unpure"); }';
   return isPure(upf);
}
</code>```

Now isPure has to determine whether or not f halts on it's own source as input. If it halts, upf is unpure; if it doesn't terminate, upf is pure iff f is pure.

If isPure worked as expected (returns correct results and terminates on every input), we would have solved the halting problem(*)! Since this is known to be impossible, isPure cannot exist.

(*) for pure JavaScript functions, which is enough to solve it for the turing machine, too.

Title: Compute if a function is pure

Body:
No. You can easily check if a function only does "pure-safe" operations, as described in Jon Purdy's answer, but that is IMO not enough to answer the question.

Consider this function:

function possiblyPure(x) {
    if (someCheck(x)) {
        return x+1; // pure code path
    }
    else {
        console.log("I'm so unpure..."); // unpure code path
    }
}

Obviously, if someCheck is unpure, so is possiblyPure. But, if someCheck is pure and returns true for every possible value of x, possiblyPure is pure, since the unpure code path is unreachable!

And here comes the hard part: determining whether or not someCheck returns true for every possible input. Trying to answering that question immedately leads you into the realm of the halting problem and similar undecidable problems.

EDIT: Proof that it is impossible

There is some uncertainity wether or not a pure function must terminate on every possible input. But in both cases, the halting problem can be used to show that the pureness check is impossible.

Case A) If a pure function is required to terminate on every possible input, you have to solve the halting problem to determine whether or not the function is pure. Since this is known to be impossible, by this definition, pureness cannot be computed.

Case B) If a pure function is allowed to not terminate on some inputs, we can construct something like that:
Let's assume that isPure(f) computes if f is a string defining a pure function.

function halts(f) {
   var fescaped = f.replace(/\"/g, '\\"');
   var upf = 'function() { '+f+'("'+fescaped+'\); console.log("unpure"); }';
   return isPure(upf);
}

Now isPure has to determine whether or not f halts on it's own source as input. If it halts, upf is unpure; if it doesn't terminate, upf is pure iff f is pure.

If isPure worked as expected (returns correct results and terminates on every input), we would have solved the halting problem(*)! Since this is known to be impossible, isPure cannot exist.

(*) for pure JavaScript functions, which is enough to solve it for the turing machine, too.


答:
How execution got to the point where child decides it want to be most important? Did it get there through parent? If yes, you could send reference to parent to that method.

eg. if all nodes have some kind of update() method that does something like

```<code>void update() {
    doSomething()
    for(Node n:childs){
        //do something
        n.update();
    }
}
</code>```

you could change it to

```<code>void update(Node parent) {
    doSomething(parent)
    for(Node n:childs){
        //do something
        n.update(this);
    }
}
</code>```

Title: Child to Parent linking - bad idea?

Body:
I have a situation where my parent knows about it's child (duh) but I want the child to be able to reference the parent. The reason for this is that I want the child to have the ability to designate itself as most important or least important when it feels like it. When the child does this, it moves it to the top or bottom of the parent's children.

In the past I've used a WeakReference property on the child to refer back tot he parent, but I feel that adds an annoying overhead, but maybe it's just the best way to do it.

Is this just a bad idea? How would you implement this ability differently?

Update 1:
Adding more context. This is a rendering system so the parent container is a list of windows grouped together. The child item (window) that says "I'm most important!" wants to basically be rendered on the top of the rest of the windows.

The parent is just a logical container to group these children together. I can see where adding an event to signal the request to be on the top is a good idea. But implementation (what the child wants to do with the parent) aside, why wouldn't you want to have child->parent linking? Doubly linked lists do this so people can traverse to and from something.

Body:
How execution got to the point where child decides it want to be most important? Did it get there through parent? If yes, you could send reference to parent to that method.

eg. if all nodes have some kind of update() method that does something like

void update() {
    doSomething()
    for(Node n:childs){
        //do something
        n.update();
    }
}

you could change it to

void update(Node parent) {
    doSomething(parent)
    for(Node n:childs){
        //do something
        n.update(this);
    }
}


答:
I can think of a reason for variable names to be reasonably short.

The short names are easy to read using shorter eye-span, hence a short attention span.

For example, once I get used to the fact that svdb means "save to the database", the rate of scanning the source code gets better as I only have to quickly scan 4 characters instead of when reading SaveToDatabase (14 characters, things get worse for more complex operation names). I say "scanning" not "reading", because that takes a major part of analyzing source code.

When scanning through large amount of source code, this can provide good performance gains.

Also, it just helps the lazy programmer to type out these short names when writing code.

Of course, all these "shorthands" is expected to be listed in some standard location in the source code.


答:
I think your question boils down to semantics.  The phrase "prevention of defects" doesn't really mean anything.  "Prevention of defects in the product" isn't much more precise.

My guess (and that's just what it is) is that when the authors say "prevention of defects in the product" they are not talking about preventing the creation of defects in any code ever.  They are talking about preventing those defects ever making it into a released product.

QA can definitely aim to prevent defects making it into a released product.  I don't think it could prevent a developer from creating a defect in an internal, interim build.

Title: How can QA prevent defects?


答:
Looks to me that what have been missing in all answers is the main idea of the development process itself. What is a development process about? A development process is mainly about maturity, quality. And quality assurance is nothing but making sure the process is correctly followed. Therefore, its benefits are deeply related to having a development process.

Imagine the following scenarios:

A building is made in an ad-hoc mode.

A building is made by following a process.

Which building is (probably) presenting a better quality? Which one is (probably) presenting more defects?

It is no different for software development. Development process (and quality assurance) have all to do with defects, as it defines how things must be done. And that is critical when you have contributors with different expertise (and daily mood) working together. Imagine the above mentioned scenarios again. Yet this time there are several junior and intern engineers involved. What would be the implications of this in the case where there is no process involved?

From the very beginning, the development process (and quality assurance) assures that the rules are followed. And those rules avoid circumstances that might lead to defects.

Title: How can QA prevent defects?


问:
Are there any reliable solutions for annotations/reflection/code-metadata in C?
Not all languages support java-like annotations or C#-like attributes or code metadata in general, however that doesn't mean it is not possible to have in languages that don't have this.

An example is PHP with Stubbles and the Doctrine annotation library.

My question is, is there anything like this for C?, or are there any reliable ways of doing reflection with extended code metadata in C?

Ideally, I'm looking for something that reads javadoc-like comments.

Edit: The reason for me *needing* as opposed to just wanting, is that I need to generate C code and code-metadata from a database, as well as being able to edit that metadada and update the database. The volume of the work (~15,000 variables/structures/functions to generate from this database) justifies the solution.

答:
The nearest thing I can think of is MetaC:

http://www.maier-komor.de/metac/

(Already mentioned by FrustratedWithFormsDesigner a few days ago)

Put aside this, there are a number of other systems based on the C preprocessor that can be used (or abused) for this task. Have a look at Boost.Preprocessor, for example:

http://www.boost.org/doc/libs/1_52_0/libs/preprocessor/doc/index.html

Or P99 and ABCPP:

http://p99.gforge.inria.fr/

http://code.google.com/p/abcpp/

Despite this, I strongly suggest you to use of some kind of full-blown code-generation tool for this task (as Brian already did).

All of the above-mentioned preprocessor-based tools, at the very end, are just convoluted ways to perform some kind of code generation. You could just implement your own full-blown, well-behaved code-generation tool instead. Ruby, Python and Perl offer a lot of good tools for this. For example, Ruby has its own Modelling and Code Generation framework:

http://ruby-gen.org/

http://rgen.rubyforge.org/

Many other exists for other scripting languages. You could even use a template engine normally used for developing web applications, like Cheetah (Python-based):

http://www.cheetahtemplate.org/

Have a look at the general-purpose Ruby-based WLang framework, as well:

https://www.ruby-toolbox.com/projects/wlang

Using a general-purpose scripting language and a code-generation framework, you will end up developing a real, stand-alone application that will query your DB and generate metadata and code accordingly. It can look like a big and complicated solution but it is actually easier to write and much more maintaineable than a preprocessor-based one (because a full-blown scripting language is much more powerful and flexible than the C preprocessor).

Moreover, from your "feature-requests list" I'm getting the feeling that none of the existing preprocessor-based tools can be used for your task "as is" because the C preprocessor cannot easily deal with a DB and because your task will most likely require a two-pass process (one pass for quering the DB and generate the required metadata and a second one for generating the C code from the metadata).

This can be another reason for using a full-blown scripting language.


答:
QA ideally prevents defects by doing a root cause analysis on defects that have been discovered, and identifies and removes common root causes.

In the context of software development, this would be things like replacing  error-prone technolgies with more mature ones, having new developers by systematically trained, ensuring that there are unit tests for the code (e.g. by tracking code coverage), conducting code reviews, or running static code analysis tools to identify areas of code that may need improvement, and ensuring that developers are given sufficient time to write unit tests and refactor bad code.

Anecdote: I've worked on a workflow application that supported this kind of QA at a large automobile maker. One report was "Units sold in India have the horn break unusally often". The root cause analysis said "The horn is designed for 50,000 cycles of operation. Due to the more intensive usage in India, this is not enough". I don't know whether they started building more sturdy horns into cars sold in India :)

Title: How can QA prevent defects?


问:
In Search of Automatic ORM with REST interface
I have this wish that so far Google hasn't been able to fulfill. I want to find a package (ideally in PHP, because I know PHP, but I guess that's not a hard requirement) that you point at a database, it builds an ORM based on what it finds there, and exposes a REST interface over the web.

Everything I've found in my searches requires a bunch of code--like, it wants you to build the classes for it, but it'll handle the REST request routing. Or it does database and relational stuff just fine, but you have to build your own methods for all the CRUD actions.

That's dumb. REST is well defined. If I wanted to re-invent the wheel, I totally could, but I don't want to. Isn't there somebody who's built a one-shot super-simple auto-RESTing web service package?

答:
The closest thing in PHP (that I know of) to what you describe would be using CAKE. I personally don't like this framework so I'm definitely not an expert but you could build model using bake and add CRUD functionality with bake or using scaffolding so there will be no any codding involved.

And then just setup REST through routing. The main problem would the maintainability of such solution.


答:
I don't think it's a bad idea. You could solve this by adding a sort order value to each child. I'm envisioning something like "z-index" used to display objects ontop-of or behind each other in web pages.

I'm not sure how you would code something like this up, but the concept sounds feasible.

Title: Child to Parent linking - bad idea?


问:
Function names - "standardized" prefixes
Imagine you have such routines

```<code>/*just do X. Fail if any precondition is not met*/
doX()

/*take care of preconditions and then do X*/
takeCareOfPreconditionsCheckIfNeededAtAllAndThenDoX()
</code>```

A little bit more concrete example:

```<code>/*create directory. Most probably fail with error if any precondition is not met (folder already exists, parent does not exists)*/
createDirectory(path_name)

/*take care of preconditions (creates full path till folder if needed, checks if not exists yet) and then creates the directory*/
CheckIfNotExistsYet_CreateDirectory_andFullPathIfNeeded(path_name)
</code>```

How do you name such routines, so it would be clear what does what?

I have come to some my own "convetion" like:

```<code>naiveCreateDirectory, ForceDirectoryExists, ...
</code>```

But I imagine this is very standard situation.

Maybe there already exists some norms/convetions for this?

答:
Usually function names should be longer when the functions' scope is shorter (ie. private methods) and shorter the name when the functions are public with a longer scope.

In your case, I usually do something like this: createDir($path) and fail with ugly error; or tryCreatingDir($path) and catch the error and continue with an internal decision like throw a nice error message or if the directory already exists suppress all errors and get out as normal.

This does not pollute the naming but does a differentiation. Also the explicit nice user friendly exception message is enough for all the exceptional cases.

Sometimes I invert this and use createDir() to check for stuff and than the second method would be doCreateDir() and I would call it ONLY if all conditions are met to create the directory.


答:
The idea is not right. Your database storage is not directly related to the output. For example 2 models could use the same table without any problem. So to relate tables directly to output doesn't feel right to me.

You also miss the part of virtual fields for example. Say you have an invoice total. The model will attach it to the record so you won't find it when you just read the database. That's why there are layers in applications.

Better idea is to use a code generator to make the classes. I notice CakePHP was already mentioned, it's capable of that with scaffolding and bake. Maybe that will save you lots of time.

Title: In Search of Automatic ORM with REST interface

Body:
I have this wish that so far Google hasn't been able to fulfill. I want to find a package (ideally in PHP, because I know PHP, but I guess that's not a hard requirement) that you point at a database, it builds an ORM based on what it finds there, and exposes a REST interface over the web.

Everything I've found in my searches requires a bunch of code--like, it wants you to build the classes for it, but it'll handle the REST request routing. Or it does database and relational stuff just fine, but you have to build your own methods for all the CRUD actions.

That's dumb. REST is well defined. If I wanted to re-invent the wheel, I totally could, but I don't want to. Isn't there somebody who's built a one-shot super-simple auto-RESTing web service package?


问:
Has the term "Service Oriented Architecture" become meaningless jargon?
I was asked today if I had experience with "Service Oriented Architecture" and although I think I do. The concept, to me, seems so muddled I don't know how you could honestly answer that question anymore.

I resorted to Googling the term in an effort to get a concise definition of the concept and how it differs from other architectures. After reading a number of articles on it, the only common thread I seem to be able to find is a system with multiple components that talk to each other over some kind of interface, with perhaps a slight preference for XML/SOAP.

It seems like almost any application could be defined as SOA, especially a web application. Has this term fallen into the "Web 2.0" trap and become a term meaning whatever you want it to mean?

Am I way off base here? When you guys hear the term does it mean anything specific to you? If so I'd love a concise definition that clearly demonstrates what is and what specifically is NOT SOA.

答:
I think it might make sense a bit: one thing is when you have "slave" modules called when needed, and another thing is when you have service/daemon processes running independently and responding to your requests, possibly talking to each other, living their own life in other words. With this approach you can have a huge, scalable, physically distributed system. I've seen some in the area of mobile telephony, for example. But this is just a guess.

(Now let's see what Wikipedia says about SOA... Whoa.)


答:
As you say PHP is not a hard requirement, I hope it's okay to point to a Python solution: Django + django-tastypie will more or less do what you're asking for.

You can autogenerate the Django ORM classes from an existing database, and django-tastypie uses sensible defaults to expose each model using REST, only requiring a few lines of declaration for each ORM class you want to expose.


问:
Can Clojure's thread-based agents handle c10k performance?
I'm writing a c10k-style service and am trying to evaluate Clojure's performance.  Can Clojure agents handle this scale of concurrency with its thread-based agents?  Other high performance systems seem to be moving towards async-IO/events/greenlets, albeit at a seemingly higher complexity cost.

Suppose there are 10,000 clients connected, sending messages that should be appended to 1,000 local files--the Clojure service is trying to write to as many files in parallel as it can, while not letting any two separate requests mangle the same single file by writing at the same time.

Clojure agents are extremely elegant conceptually--they would allow separate files to be written independently and asynchronously, while serializing (in the database sense)  multiple requests to write to the same file.

My understanding is that agents work by starting a thread for each operation (assume we are IO-bound and using send-off)--so in this case is it correct that it would start 1,000+ threads?  Can current-day systems handle this number of threads efficiently?  Most of them should be IO-bound and sleeping most of the time, but I presume there would still be a context-switching penalty that is theoretically higher than async-IO/event-based systems (e.g. Erlang, Go, node.js).

If the Clojure solution can handle the performance, it seems like the most elegant thing to code.  However if it can't handle the performance then something like Erlang or Go's lightweight processes might be preferable, since they are designed to have tens of thousands of them spawned at once, and are only moderately more complex to implement.

Has anyone approached this problem in Clojure or compared to these other platforms?  (Thanks for your thoughts!)

答:
As of the upcoming Clojure 1.5, you can use custom ExecutorServices (through set-agent-send-executor! and set-agent-send-off-executor!).

Doing so you'll be able to cap your number of threads -- if needed, 1k mostly sleeping threads doesn't seem out of reach for the JVM. Beware of the stack size though.


答: There are many possible conventions - I often have to have routines that do something, and other routines that check things and then, eventually, either do it or not. I invariably call these frobWidgets() and maybeFrobWidgets(). There are other prefixes that would fit, e.g. ensure is often used for code that initializes something lazily, but there isn't a universal convention. It's not necessary, though. Far more important than perceived consistency with the "state of the art" is actual consistency within your code base. So go ahead with checkAndFrob() vs. frob() if you've already started doing that.

Title: Function names - "standardized" prefixes

Body:
Imagine you have such routines

```<code>/*just do X. Fail if any precondition is not met*/
doX()

/*take care of preconditions and then do X*/
takeCareOfPreconditionsCheckIfNeededAtAllAndThenDoX()
</code>```

A little bit more concrete example:

```<code>/*create directory. Most probably fail with error if any precondition is not met (folder already exists, parent does not exists)*/
createDirectory(path_name)

/*take care of preconditions (creates full path till folder if needed, checks if not exists yet) and then creates the directory*/
CheckIfNotExistsYet_CreateDirectory_andFullPathIfNeeded(path_name)
</code>```

How do you name such routines, so it would be clear what does what?

I have come to some my own "convetion" like:

```<code>naiveCreateDirectory, ForceDirectoryExists, ...
</code>```

But I imagine this is very standard situation.

Maybe there already exists some norms/convetions for this?


答:
I'ld go with:

```<code>createDirectory(param)
chkDirectoryExists(param)
</code>```

If these are ambiguous ie if there were two different types of directories I'd split the object in two which would both implement an interface called something like DirectoryHandler.

Body:
I'ld go with:

createDirectory(param)
chkDirectoryExists(param)

If these are ambiguous ie if there were two different types of directories I'd split the object in two which would both implement an interface called something like DirectoryHandler.


问:
When should I make the first commit to source control?
I'm never sure when a project is far enough along to first commit to source control. I tend to put off committing until the project is 'framework-complete,' and I primarily commit features from then on. (I haven't done any personal projects large enough to have a core framework too big for this.) I have a feeling this isn't best practice, though I'm not sure what could go wrong.

Let's say, for example, I have a project which consists of a single code file. It will take about 10 lines of boilerplate code, and 100 lines to get the project working with extremely basic functionality (1 or 2 features). Should I first check in:

The empty file?

The boilerplate code?

The first features?

At some other point?

Also, what are the reasons to check in at a specific point?

答:
My rule of thumb is to check in once my solution file (or other build script piece) is done, even if it contains a few files that are empty. It's good practice for when more than one person is working on the project. That file tends to have the worst merge issues initially as people are adding things to the project so needs committed early and often.

Even if you're the only one working on the project and it's only got one file, I find it easier to follow the same workflow and save the thinking for the problem at hand.


答:
If I have a function that may fail - such as creating a directory, writing to a file, etc. - I use the following signature:

bool TryDoSomething(string someParam)

So the method will do something with someParam. If successful, return true; likewise, if unsuccessful, return false.

Method parameters are obviously not always necessary. There is another advantage to this method signature in that you don't have to throw exceptions above this method unless deemed fatal. Note this method can be used to return out values as well. Reference the C# dictionary TryGetValue(...) method.

I also name functions that validate data as SomeParamIsValid(string SomeParam). In this way, I can write something like:

```<code>if (SomeParamIsValid(someParam) {
   if(!TryDoSomething(someParam, out SomeObject someObj) {
      // handle failed operation
   }

   return someObj;
}
</code>```

This makes for some very readable and easily maintained code, in my opinion.

Body:
If I have a function that may fail - such as creating a directory, writing to a file, etc. - I use the following signature:

bool TryDoSomething(string someParam)

So the method will do something with someParam. If successful, return true; likewise, if unsuccessful, return false.

Method parameters are obviously not always necessary. There is another advantage to this method signature in that you don't have to throw exceptions above this method unless deemed fatal. Note this method can be used to return out values as well. Reference the C# dictionary TryGetValue(...) method.

I also name functions that validate data as SomeParamIsValid(string SomeParam). In this way, I can write something like:

if (SomeParamIsValid(someParam) {
   if(!TryDoSomething(someParam, out SomeObject someObj) {
      // handle failed operation
   }

   return someObj;
}

This makes for some very readable and easily maintained code, in my opinion.


问:
What should I study to 'learn' Comp Sci?
[This question was originally asked on Stack Overflow, but recommended to move the question here.]

I can't find anything quite like the question I'm about to ask, so please forgive me if there's something just like it already, please feel free to point me in the right direction. It'll take a bit of background explaining too, please forgive me for that.

[backstory]

Basically, I graduated from University about 18 months ago with a degree in Business Information Systems and Japanese. The Japanese took up half of the degree so the BIS was only joint. I only learned PHP in terms of languages and basically no computing theory - everything was vocational (Networking, programming basics, CMS development, Office and VBA and then loads of Business theory courses).

Since this, I decided to teach myself C# and ASP.Net and try to get a position as a programmer. I created an online shop style website and a small CRM application in Windows Forms to both teach myself and build a portfolio, and luckily I managed to snag a developer position.

Bad side? I'm the only developer at my company. Now don't get me wrong, in the last year I've learned loads and loads, I did some devpt. before Uni so knew the basics anyway, but it was very much a "learning from books" job - every night.

Now then... I am now at a point where I'm building software on a regular basis, making good judgements for time scales, and have even been told my code and methodology are good by other professionals that have been in the game longer than me, and they have offered me jobs.

[/backstory]

What this whole thing boils down to, is that I now want to study up on the topics I'll have missed by not doing CS. More importantly, could you recommend books / free online courses? I want to learn about Computer Science theory, not just better coding.

Thank you!

答:
Read The Structure and Interpretation of Computer Programs, aka SICP

For building up your fundamental knowledge of CS topics, there is probably no better book than SICP.  The acronym alone is almost always recognized by top CS graduates, as a classic they either learned from, or know they need to read. :)  Big names in CS and programming know and recommend the book, e.g. Peter Norvig's praising SICP as the greatest introduction to computer science ever written.

SICP covers the fundamentals of computation in a satisfyingly deep way, raising many perspectives and questions about the nature of computation — quite a few of which remain open issues — while leading the reader to see beyond the superficial aspects of telling the machine what to do, or how to do it.

Click the image to get to the free text online.  You can also readily find the video lectures by the authors, complete with '80s style color and clothing no less.


答: As far as I'm concerned, your source control repo is part of the basic project setup, so I commit right after I generate my empty project.</p>

Title: When should I make the first commit to source control?

Body:
I'm never sure when a project is far enough along to first commit to source control. I tend to put off committing until the project is 'framework-complete,' and I primarily commit features from then on. (I haven't done any personal projects large enough to have a core framework too big for this.) I have a feeling this isn't best practice, though I'm not sure what could go wrong.

Let's say, for example, I have a project which consists of a single code file. It will take about 10 lines of boilerplate code, and 100 lines to get the project working with extremely basic functionality (1 or 2 features). Should I first check in:

The empty file?

The boilerplate code?

The first features?

At some other point?

Also, what are the reasons to check in at a specific point?


答:
You should commit as soon as you have a sensible "unit" complete.

What is a unit? It depends on what you're doing; if you're creating a Visual Studio project, for example, commit the solution right after its creation, even if it doesn't have anything in it.

From there on, keep committing as often as possible, but still commit only completed "units" (e.g. classes, configurations, etc); doing so will make your life easier if something goes wrong (you can revert a small set of changes) and will reduce the likelihood of conflicts.


答:
I would say commit as soon as possible. The main purpose of source control is allowing you to go back in case something goes wrong, and this resonates with "commit early and often" practice.

Personally, my first commit typically contains just the .gitignore file (or equivalent) with few filters I know will be needed, like *.py[co] for Python code. Basic project setup and/or first simplest prototype is what usually follows.


答:
Yesterday

...in alternative, if you're unable to time-travel...

(maybe your car can't get to 88mph, or your flux capacitor just snapped)

Now

New projects should be committed on the bloody spot, it's crazy not to, and contemporary DVCS systems just removed every possibile excuse to avoid commits: git init . ; git add * ; git commit -m initial-commit now, before it's too late, as it might already be.

One more sensible, arguable, question could have been: "When should I merge my commits to a shared source control on a team managed repository on an established project?" (note the adjectives, adjectives are important) And I have the feeling most other answers are actually trying to reply to that.

Your personal branch should be commited to like crazy, at least once each day, before bedtime. You might just wake up the morning after, and find you have no clue of what the hell you were up to, the previous night. The VCS should cover you against that, and having the opportunity to rollback to a very recent sub-version-of-a-sub-version that compiles nicely, runs smoothly, and/or passes tests might be your best option.


答:
This non-mammal, non-bird, non-fish example might help:

```<code>public abstract class Person {

    /* this contains thing all persons have, like name, gender, home addr, etc. */

    public Object getHomeAddr() { ... }

    public Person getName() { ... }

}

public class Employee extends Person{

    /* It adds things like date of contract, salary, position, etc */

    public Object getAccount() { ... }

}

public abstract class Patient extends Person {
    /* It adds things like medical history, etc */
}
</code>```

Then

```<code>public static void main(String[] args) {

    /* you can send Xmas cards to patients and employees home addresses */

    List<Person> employeesAndPatients = Factory.getListOfEmployeesAndPatients();

    for (Person p: employeesAndPatients){
        sendXmasCard(p.getName(),p.getHomeAddr());
    }

    /* or you can proccess payment to employees */

    List<Employee> employees = Factory.getListOfEmployees();

    for (Employee e: employees){
        proccessPayment(e.getName(),e.getAccount());
    }

}
</code>```

NOTE: Just don't tell the secret: Person extends Mammal.

Title: How can I explain the usefulness of Inheritance?

Body:
When trying to explain the concept of Inheritance in OOP, the common example is often the mammals example. IMHO, this is really a bad example, because it will lead the newbies to use this concept the wrong way. And moreover, it is not a common design that they will face in their day-to-day design job.

So, what will be a nice, simple and concrete problem that is solved using Inheritance ?

Body:
This non-mammal, non-bird, non-fish example might help:

public abstract class Person {

    /* this contains thing all persons have, like name, gender, home addr, etc. */

    public Object getHomeAddr() { ... }

    public Person getName() { ... }

}

public class Employee extends Person{

    /* It adds things like date of contract, salary, position, etc */

    public Object getAccount() { ... }

}

public abstract class Patient extends Person {
    /* It adds things like medical history, etc */
}

Then

public static void main(String[] args) {

    /* you can send Xmas cards to patients and employees home addresses */

    List<Person> employeesAndPatients = Factory.getListOfEmployeesAndPatients();

    for (Person p: employeesAndPatients){
        sendXmasCard(p.getName(),p.getHomeAddr());
    }

    /* or you can proccess payment to employees */

    List<Employee> employees = Factory.getListOfEmployees();

    for (Employee e: employees){
        proccessPayment(e.getName(),e.getAccount());
    }

}

NOTE: Just don't tell the secret: Person extends Mammal.


问:
Can a table be both Fact and Dimension
Ok, I am a newbie and don't really think "dimensionally" yet, I have most of my initial schema roughed out but I keep flipping back and forth on one table.

I have a Contract table and it has a quantity column (tonnes), and a net price column,  which need to be summed up a bunch of different ways, and the contract has lots of foreign keys (producer, commodity, futures month etc.) and dates so it appears to be a fact table. Also the contract is never updated, if that makes a difference.

However, we create cash tickets which we use to pay out part or all of the contract and they have a contract ID on them so then the contract looks like a dimension in the cash ticket's star schema.

Is this a problem? Any ideas on the process to resolve this, because people don't seem to like the idea of joining two fact tables.

Should I put producerId and commodityId on the cash ticket? It would seem really weird not to have a contractID on it.

答:
Should I put producerId and commodityId on the cash ticket?

If each cash ticket does directly relate to a contract, and producer and commodity are related to the contract, then it does not make sense to move these from the contract to the cash ticket. This is information about the contract so it should stay with the contract.

I work with a similar system and I think this occurs where you have two distinct groups of facts which are related in a one to many relationship. Here, one contract is related to many cash tickets. That means that the contracts can be used to filter the cash tickets and vice versa despite both tables storing facts.

The only problem I see here is that depending on the tech there may be a limit to the number of records in a table on which a dimension can based; we hit the Analysis Services dimension size limit in this way (with a dimension of many millions of members... I don't know if this changed in SS 2012). So by this I mean, if your tables become very large, you may not be able to use them as dimensions directly.

You can, however, use dimensions related to one fact table to slice a linked fact table. For instance you can apply a dimension filter to the contracts table, and show a count of the connected records in the cash tickets table, etc.

I don't see a problem with this and we have not come across any unexpected issues; some queries can be a bit resource intensive but this has been manageable we have not found a better way to achieve the same results.

Title: Can a table be both Fact and Dimension


答:
With any application, you're going to spend some time designing the components. You should know, roughly or in full detail, your name spaces, projects, external references, 3rd party libraries etc.

If you're on a team, I would suggest your lead, or whoever is chosen, to create the base project, get the dependencies set, and check that skeleton (foundation which your project will be built on) in.

You also want to ensure you have your task, release, trunk, etc. branches spec'd out before checking in so your process is solid.

If you are working on a new "task" for a project that's already under way and you're in your own task branch, do your nightly check-ins so you preserve your work.


答:
The strict definitions of SOA are far past the cost/benefit line as to be theoretical in many cases.

Unless your product is the services themselves you often need a different point of view.

A USABLE definition of SOA means that your overall architecture is service friendly.  A system built completely from atomic services is usually not the right plan, and some services are going to organized functionally while others are going to be single responsibility.  I may have black boxes, I may have offline processes, but if there are a discoverable collection of services through which I can get a meaningful amount of work done that is my minimum definition.

Aside from the debate on what it actually means, the concept (whatever it means) has suffered in many circles by being applied to places it simply does not fit.

For example, If I am building something that is meant to be a black box process and scales through parallelism not segmentation and distribution I may have a service to expose/talk to the black box, but some people keep trying to put the services inside the box.

As a strict technical definition it has always been undefined, but the idea is not without merit where it fits.

Title: Has the term "Service Oriented Architecture" become meaningless jargon?

Body:
I was asked today if I had experience with "Service Oriented Architecture" and although I think I do. The concept, to me, seems so muddled I don't know how you could honestly answer that question anymore.

I resorted to Googling the term in an effort to get a concise definition of the concept and how it differs from other architectures. After reading a number of articles on it, the only common thread I seem to be able to find is a system with multiple components that talk to each other over some kind of interface, with perhaps a slight preference for XML/SOAP.

It seems like almost any application could be defined as SOA, especially a web application. Has this term fallen into the "Web 2.0" trap and become a term meaning whatever you want it to mean?

Am I way off base here? When you guys hear the term does it mean anything specific to you? If so I'd love a concise definition that clearly demonstrates what is and what specifically is NOT SOA.


答:
Real-world examples almost always get it wrong because they give examples where there's always the possibility of something being both TypeA and TypeB but the single inheritance hierarchy of many languages don't allow that.

The more I program the more I get away from inheritance.

Even the word "inherit" is used improperly here.  For instance, you inherit about 50% of your father's traits and 50% of your mother's traits.  Really your DNA is a composition of half your father's DNA and half your mother's DNA.  That's because biology actually favors composition over inheritance, and you should too.

Simply implementing interfaces, or even better, "duck typing", plus dependency injection, is a much better thing to be teaching people who are new to object-oriented programming.


答:
If you've done work that you wouldn't want to lose, it should be in your source control system.

This certainly applies to distributed systems like Git. If you're using a centralized system, and the only way to check something in is to make it visible to everyone, you might want to hold off -- or you might considering setting up your own local git repository, and submitting to the centralized system when you're ready.