问:
Validation and authorization in layered architecture
I know you are thinking (or maybe yelling), "not another question asking where validation belongs in a layered architecture?!?"  Well, yes, but hopefully this will be a little bit of a different take on the subject.

I am a firm believer that validation takes many forms, is context-based and varies at each level of the architecture.  That is the basis for the post - helping to identify what type of validation should be performed in each layer.  In addition, a question that often comes up is where authorization checks belong.

The example scenario comes from an application for a catering business. Periodically during the day, a driver may turn in to the office any excess cash they've accumulated while taking the truck from site to site.  The application allows a user to record the 'cash drop' by collecting the driver's ID, and the amount.  Here's some skeleton code to illustrate the layers involved:

```<code>public class CashDropApi  // This is in the Service Facade Layer
{
    [WebInvoke(Method = "POST")]
    public void AddCashDrop(NewCashDropContract contract)
    {
        // 1
        Service.AddCashDrop(contract.Amount, contract.DriverId);
    }
}

public class CashDropService  // This is the Application Service in the Domain Layer
{
    public void AddCashDrop(Decimal amount, Int32 driverId)
    {
        // 2
        CommandBus.Send(new AddCashDropCommand(amount, driverId));
    }
}

internal class AddCashDropCommand  // This is a command object in Domain Layer
{
    public AddCashDropCommand(Decimal amount, Int32 driverId)
    {
        // 3
        Amount = amount;
        DriverId = driverId;
    }

    public Decimal Amount { get; private set; }
    public Int32 DriverId { get; private set; }
}

internal class AddCashDropCommandHandler : IHandle<AddCashDropCommand>
{
    internal ICashDropFactory Factory { get; set; }       // Set by IoC container
    internal ICashDropRepository CashDrops { get; set; }  // Set by IoC container
    internal IEmployeeRepository Employees { get; set; }  // Set by IoC container

    public void Handle(AddCashDropCommand command)
    {
        // 4
        var driver = Employees.GetById(command.DriverId);
        // 5
        var authorizedBy = CurrentUser as Employee;
        // 6
        var cashDrop = Factory.CreateCashDrop(command.Amount, driver, authorizedBy);
        // 7
        CashDrops.Add(cashDrop);
    }
}

public class CashDropFactory
{
    public CashDrop CreateCashDrop(Decimal amount, Employee driver, Employee authorizedBy)
    {
        // 8
        return new CashDrop(amount, driver, authorizedBy, DateTime.Now);
    }
}

public class CashDrop  // The domain object (entity)
{
    public CashDrop(Decimal amount, Employee driver, Employee authorizedBy, DateTime at)
    {
        // 9
        ...
    }
}

public class CashDropRepository // The implementation is in the Data Access Layer
{
    public void Add(CashDrop item)
    {
        // 10
        ...
    }
}
</code>```

I've indicated 10 locations where I've seen validation checks placed in code.  My question is what checks you would, if any, be performing at each given the following business rules (along with standard checks for length, range, format, type, etc):

The amount of the cash drop must be greater than zero.

The cash drop must have a valid Driver.

The current user must be authorized to add cash drops (current user is not the driver).

Please share your thoughts, how you have or would approach this scenario and the reasons for your choices.

答:
For the rules:

1-    The amount of the cash drop must be greater than zero.

2-    The cash drop must have a valid Driver.

3-    The current user must be authorized to add cash drops (current user is not the driver).

I would do validation in location (1) for business rule (1) and make sure the Id is not null or negative (assuming zero is valid) as pre-check for rule (2). The reasons is my rule of "Don't cross a layer boundary with wrong data that you can check with available information".
An exception to this would be if the service does the validation as part of its duty to other callers. In which case, it will be sufficient to have the validation only there.

For rules (2) and (3), this must be done at the database access layer (or db layer itself)  only since it involves db access. No need to travel between layers intentionally.

In particular rule (3) can be avoided if we let the GUI prevent unauthorized users from pushing the button enabling this scenario. While this is harder to code, it is better.

Good question!


问:
Is it a security flaw to log the class and method name when an exception occurs?
I have the following :

```<code>public class doCheck(){

    public void performCheck(){
        try {
            perform all checks......
        }
        catch(Exception e){
            logger.error("Exception occured in class doCheck in method performCheck");
            thrown new MyNewException(e.getMessage());
        }
    }
}
</code>```

Is it safe to log the class and method name?

答:
It's not particularly unsafe, so unless there's anything critical that you'd want to hide in this class or if the class is part of a critical path (like a secure handshake or "hidden" feature), I wouldn't consider this an issue at all.

Furthermore, we're talking about Java here. So if we're talking about a client-side app running Java on the client, they can always modify their JRE to use add their own debugging routines and/or use a custom classloader and access your classes pretty much any way they want to. Making it harder for them (by way of hiding stuff deeper, or even obfuscating code) is always a possibility, but it usually isn't cost-effective when you consider the time and effort needed to achieve this against the loss caused by statistically improbable malicious users.

If we're talking about a server-side piece of software that may output logs to clients (say, to the user's browser), then it probably isn't too big a deal, but it's already more straightforward to fix: configure your container accordingly, and use a logging framework or multiplexer to output to appropriate files on the server for debugging purposes instead. This way you retain useful records for debugging but don't compromise potentially useful information.

But in general, this probably wouldn't be a problem. it's more what you put in the debug message that could be an issue, as we often tend as developers to output things we work on (you don't want to leave these debug outputs for usernames, passwords, salts and security tokens in clear view).

ContentLicense: CC BY-SA 3.0


问:
What's your favourite quote about programming?
What's your favourite quote about programming?

One quote per answer, and please check for duplicates before posting!

答: To understand recursion, you first need to understand recursion</p>

LastEditorDisplayName: Roger Pate

ContentLicense: CC BY-SA 2.5


问:
Are proofs worth the effort?
I bought the de-facto book for learning about data structures and algorithms (CLRS). The book is though quite good but the singularity is in the proofs. The book is filled with Lemmas, theorems, peculiar symbols and unimaginable recurrence relations which are very hard to understand. I am able to somehow get the algorithms but the discrete mathematics just not for me.

So should I leave them out and just concentrate on algorithims?

答:
If you look for a practical way to understand and/or implement the algorithms, I would suggest a different book - Practical Algorithms for Programmers .

However, if you are looking at academics and theory part to build your own customized algorithm and base it on some other existing once, you may probably continue with what you have.

Title: Are proofs worth the effort?


答:
Usually looking through the proof helps to understand the algorithm better. It shows why the algorithm works and what facts it is based on. Sometimes it even helps to see what the author was thinking about, or gives a clue how to edit and/or optimize the algorithm for special needs.

If later you'll need to make your own algorithm, these proofs will really help. On the other hand, if you just need to use some famous algorithms, it's ok to miss the proofs. But I'd still recommend you take a look at them. Even if you don't understand everything in details, at least try to take your time and grasp the general idea.

Title: Are proofs worth the effort?

Body:
I bought the de-facto book for learning about data structures and algorithms (CLRS). The book is though quite good but the singularity is in the proofs. The book is filled with Lemmas, theorems, peculiar symbols and unimaginable recurrence relations which are very hard to understand. I am able to somehow get the algorithms but the discrete mathematics just not for me.

So should I leave them out and just concentrate on algorithims?


问:
What's the point of passing a parameter by reference in C#?

Possible Duplicate:

  Why are objects passed by reference?

Doesn't C# send the objects themselves? So unless it's some kind of swap function for primitive typed variables - why would I send an object by reference?

答:
C# doesn't pass the objects themselves. C# passes whatever's in the stack. For value types that are locally-scoped and thus live on the stack, the value is passed down to the next level of the call stack. For all other objects, the data is on the heap and a reference to the heap address is stored on the stack, and is passed around.

In either case, the data that resides on the stack, whether that's the data you care about or a reference "pointer" to the data you care about, is not changed, because when it is passed, it is copied to a new location on the stack and that value is what is manipulated (and then discarded when the method exits and that frame pops off the call stack). If you pass a value type to a method that changes the value, when that method returns to its caller the value will be unchanged, because that copy of the data was never touched by the method.

If you pass a reference type, it is the reference that is copied. This means that the data on the heap, pointed to by the reference, can be altered and that will change the data for the caller. BUT, if the passed parameter is reinitialized or otherwise assigned to a different reference, that change will be reverted when the method returns, because that is a change to the reference to the object, which was passed "by value" and doesn't affect the caller's copy of that reference.

For proof, run this test in NUnit:

```<code>    [Test]
    public void TestPassObject()
    {
        //instantiate a new instance of some reference type
        var myObj = new object();

        //make a "shallow" copy. This copy will never be touched.
        var myLocalCopy = myObj;

        //Pass the original copy by reference to a method that will alter it.
        var result = TestMethod(myObj);

        //Our original reference value did not change even though
        //the passed reference was reinstantiated.
        //myObj and myLocalCopy are still the same object...
        Assert.AreEqual(myObj, myLocalCopy);
        //and are different from result, even though TestMethod
        //assigned the reference in result to its passed myObj parameter.
        Assert.AreNotEqual(myObj, result);
    }

    private object TestMethod(object myObj)
    {
        //myObj is a local "copy" of the reference passed by the caller.
        //if you changed myObj's children, the caller would see that,
        //but reinitializing it points the copy to new data on the heap,
        //and does not affect the caller.
        return myObj = new object();
    }
</code>```

So given that default behavior when not using ref, the answer to your question is that the ref keyword changes what is passed. Instead of passing a copy of the value that resides on the stack, a parameter with the ref keyword is given a "pointer" to the data residing on the stack, whether that's a data value itself or a reference to a data value on the heap. I put "pointer" in quotes because the term is anathema to most .NET coders, but dig down deep enough and that's pretty much what's going on; you're given an immutable pointer to that element of the caller's stack frame.

Behind the scenes, when you use or alter the passed ref parameter, you are using or changing the value of the caller's copy, as pointed to by the ref parameter. This is true regardless of what was passed (data, or a reference to data). This means that you can change a value type's data, or reinitialize/reassign a reference type's reference, and that will affect the caller. However, the syntax remains the same, because the C# spec says it must be so to avoid the confusion that C++ has; in C++, when dealing with a child of your passed parameter, you have to know whether you were given a pointer to an object and must use ., or a pointer to a pointer to an object and must use -> (or a pointer to a pointer to a pointer to an object and must double-dereference, etc etc).

Body:
C# doesn't pass the objects themselves. C# passes whatever's in the stack. For value types that are locally-scoped and thus live on the stack, the value is passed down to the next level of the call stack. For all other objects, the data is on the heap and a reference to the heap address is stored on the stack, and is passed around.

In either case, the data that resides on the stack, whether that's the data you care about or a reference "pointer" to the data you care about, is not changed, because when it is passed, it is copied to a new location on the stack and that value is what is manipulated (and then discarded when the method exits and that frame pops off the call stack). If you pass a value type to a method that changes the value, when that method returns to its caller the value will be unchanged, because that copy of the data was never touched by the method.

If you pass a reference type, it is the reference that is copied. This means that the data on the heap, pointed to by the reference, can be altered and that will change the data for the caller. BUT, if the passed parameter is reinitialized or otherwise assigned to a different reference, that change will be reverted when the method returns, because that is a change to the reference to the object, which was passed "by value" and doesn't affect the caller's copy of that reference.

For proof, run this test in NUnit:

    [Test]
    public void TestPassObject()
    {
        //instantiate a new instance of some reference type
        var myObj = new object();

        //make a "shallow" copy. This copy will never be touched.
        var myLocalCopy = myObj;

        //Pass the original copy by reference to a method that will alter it.
        var result = TestMethod(myObj);

        //Our original reference value did not change even though
        //the passed reference was reinstantiated.
        //myObj and myLocalCopy are still the same object...
        Assert.AreEqual(myObj, myLocalCopy);
        //and are different from result, even though TestMethod
        //assigned the reference in result to its passed myObj parameter.
        Assert.AreNotEqual(myObj, result);
    }

    private object TestMethod(object myObj)
    {
        //myObj is a local "copy" of the reference passed by the caller.
        //if you changed myObj's children, the caller would see that,
        //but reinitializing it points the copy to new data on the heap,
        //and does not affect the caller.
        return myObj = new object();
    }

So given that default behavior when not using ref, the answer to your question is that the ref keyword changes what is passed. Instead of passing a copy of the value that resides on the stack, a parameter with the ref keyword is given a "pointer" to the data residing on the stack, whether that's a data value itself or a reference to a data value on the heap. I put "pointer" in quotes because the term is anathema to most .NET coders, but dig down deep enough and that's pretty much what's going on; you're given an immutable pointer to that element of the caller's stack frame.

Behind the scenes, when you use or alter the passed ref parameter, you are using or changing the value of the caller's copy, as pointed to by the ref parameter. This is true regardless of what was passed (data, or a reference to data). This means that you can change a value type's data, or reinitialize/reassign a reference type's reference, and that will affect the caller. However, the syntax remains the same, because the C# spec says it must be so to avoid the confusion that C++ has; in C++, when dealing with a child of your passed parameter, you have to know whether you were given a pointer to an object and must use ., or a pointer to a pointer to an object and must use -> (or a pointer to a pointer to a pointer to an object and must double-dereference, etc etc).


问:
Is this a decent use-case for goto in C?
I really hesitate to ask this, because I don't want to "solicit debate, arguments, polling, or extended discussion" but I'm new to C and want to gain more insight into common patterns used in the language.

I recently heard some distaste for the goto command, but I've also recently found a decent use-case for it.

Code like this:

```<code>error = function_that_could_fail_1();
if (!error) {
    error = function_that_could_fail_2();
    if (!error) {
        error = function_that_could_fail_3();
        ...to the n-th tab level!
    } else {
        // deal with error, clean up, and return error code
    }
} else {
    // deal with error, clean up, and return error code
}
</code>```

If the clean-up part is all very similar, could be written a little prettier (my opinion?) like this:

```<code>error = function_that_could_fail_1();
if(error) {
    goto cleanup;
}
error = function_that_could_fail_2();
if(error) {
    goto cleanup;
}
error = function_that_could_fail_3();
if(error) {
    goto cleanup;
}
...
cleanup:
// deal with error if it exists, clean up
// return error code
</code>```

Is this a common or acceptable use-case of goto in C? Is there a different/better way to do this?

答:
In Java you'd do it like this:

```<code>makeCalls:  {
    error = function_that_could_fail_1();
    if (error) {
        break makeCalls;
    }
    error = function_that_could_fail_2();
    if (error) {
        break makeCalls;
    }
    error = function_that_could_fail_3();
    if (error) {
        break makeCalls;
    }
    ...
    return 0;  // No error code.
}
// deal with error if it exists, clean up
// return error code
</code>```

I use this a lot.  Much as I dislike goto's, in most other C-style languages I use your code; there's no other good way to do it.  (Jumping out of nested loops is a similar case; in Java I use a labeled break and everywhere else I use a goto.)

Body:
In Java you'd do it like this:

makeCalls:  {
    error = function_that_could_fail_1();
    if (error) {
        break makeCalls;
    }
    error = function_that_could_fail_2();
    if (error) {
        break makeCalls;
    }
    error = function_that_could_fail_3();
    if (error) {
        break makeCalls;
    }
    ...
    return 0;  // No error code.
}
// deal with error if it exists, clean up
// return error code

I use this a lot.  Much as I dislike goto's, in most other C-style languages I use your code; there's no other good way to do it.  (Jumping out of nested loops is a similar case; in Java I use a labeled break and everywhere else I use a goto.)


答:
To judge whether something is 'worth the effort' you must consider the value to you of what you get for your effort. In this case, learning to understand the proofs would mean, well, that you understand the proofs. We can't decide for you how much you consider that worth.

If you are happy to look up a list of algorithms and costs, then by all means do so.

Mind you, there is the nagging worry that if you do skip the proofs, if you ever find yourself in a situation where you come across (or even think up for yourself) a method you can't find documented anywhere, you won't know what to do...

Title: Are proofs worth the effort?


答: In my opinion, proofs are not really terrifically useful, unless you're inventing the algorithm in question, or looking to work in theoretical CS. If you're just implementing the algorithm, what's important is that you can understand the description, and that you know it has been proved to be correct.</p>

Title: Are proofs worth the effort?


问:
Minimizing use of paper
I've recently faced this problem in a dynamic programming curriculum, and I honestly have no idea about how to determine the appropriate state.

You're given N (1 <= N <= 70) paragraphs and M (1 <= M <= N) figures. Each paragraph i requires PL_i (1 <= PL_i <= 100) lines and references at most one figure. Each figure is referenced exactly once (i.e., no two paragraphs can reference the same figure, and for each figure there's a paragraph that references it.) Each figure requires PF_i (1 <= PF_i <= 100) lines.

The task is to distribute those figures and paragraphs on paper in the order they're given, where one paper fits for L lines at most. No paragraph or figure is too large to fit on one paper. If a paragraph x placed on paper x_p references a figure y then y must be placed on either the paper x_p - 1 or x_p or x_p + 1.

We have to find the minimum number of lines (and thus pages) to allocate in order to distribute all the figures and paragraphs. Any help would be extremely appreciated. Thanks in advance!

答:
Have a 2d matrix.  Row is number of number of paragraphs you can fit, column is number of figures you can fit, cell value is the minimum number of lines possible.  Cell[0,0] = 0.  Cell[1,0] and Cell[0,1] can be calculated trivially.  Cell[1,1] can be calculated by finding a minimum based on Cell[1,0] and Cell[0,1].  The bottom right cell is your answer.  There's a step missing in this explanation related to "x_p - 1 or x_p or x_p + 1," but I think this is probably the right direction for using dynamic programming to solve this problem.

More detail:

You can calculate Cell[X,Y] by finding the most efficient way to reach it (i.e., check the minimum cost of reaching it from Cell[X-1,Y] and from Cell[X,Y-1]).  In the case of a figure, the cost to jump one cell won't necessarily be equal to the number of lines in the figure, since you may be forced to move the figure to the next page.  What this explanation is missing is how to cut off cells where the figures are to far behind or in front of the paragraphs.

Title: Minimizing use of paper


问:
Do your managers prefer to create proof of concept (POC) before working prototype?
At last team meeting I heard from managers that we need to create proof of concept (POC) before main prototype and integrate this concept with the main system for proving a new feature.

Could you explain me the main features or this method?

Do you use the POC in your projects before implementation?

What is the main advantages and disadvantages of this method?

答: Where I work, we typically use proofs of concept to verify that a given technology can actually be used to perform a particular task (e.g., we can write a connector that permits us to write callback routines in a DSL).  PoCs are always disposable and are almost never used as a basis for a prototype.  Prototypes are more formal and typically either implement only one of the functions of the complete system or are more of a shell with a mostly-complete UI and stubbed-out functionality that simply logs operations.  Prototypes follow coding and documentation standards, and often evolve into the final application, whereas PoCs are typically hacks or cut-n-paste mashups.


问:
Is there any well-known commercial project which is currently an open source ?
I mean is there some open sourced projects that were started as closed source and were commercially successful also? I am also interested in any story behind open sourcing them.</p>

答:
IIRC, Sun's Glassfish server was originally the Sun Java System Application Server, which was originally the SunONE Application Server, which started out as the iPlanet Application Server, which had been created by merging the code bases of the Netscape Enterprise Server and the NetDynamics Application Server.

Likewise, the EclipseLink project started out as a Smalltalk product (TopLink) which was ported to Java and eventually donated to Sun to be used as part of the Glassfish project, before finally finding its way to the Eclipse project.


问:
SQLite resources or any other storage concept for mobile applications?
I would like to know what storage concepts are used for mobile or handheld devices, where an app is operated on?. AFAIK one of them is SQlite.

Can anyone shed a light on this concept? perhaps links and resources will be much useful to many of new developers. Thanks a ton.:)

EDIT: My target would be Android and ios OS.

答:
SQLite is part of Android, it's a really good example about a simple and effective way to store data when you want to use resources as less as possible.

Regarding iOS, it basically adopt the same software https://developer.apple.com/technologies/ios/data-management.html .

You can also find many questions with at least 1 good answer here on stackexchange https://stackoverflow.com/questions/6344715/how-to-embed-sql-in-ios-app .

In this case the most popular structure is an Hash Table http://en.wikipedia.org/wiki/Hash_table but you don't have to care about that when programming.


问:
Should I use a relational datamodel or Cassandra with ColumnFamily based indexes?
Currently we are working on some storage problems for log data from various servers and communication message logs (HTTP(S), XMPP). There will be many write operations and for read operations we will use search queries with filters.

Should we stick with the classic relation database schema solution or concentrate on Cassandra with ColumnFamily based indexes?

答:
If you are only going to store logs, you've strayed into one of the few places were relational databases do not make much sense.

SQL is surely not going to be the ideal medium to perform your work- no joins, not many different tables, etc. Transactions and UPDATEs probably won't be necessary.

I would choose something that let me run map-reduce jobs easily- it might well be the case that a single-threaded algorithm be all you need, but if it ever becomes too slow for your purposes, being able to throw cores at the problem will come in handy.

If you are going to be searching a lot (i.e. perform calculations on small subsets of data), indexing is going to be another defining factor- having a store which supports indexing which handles your searches well will save plenty of time.

On the other hand, depending on what you do, it might make sense to "summarize" your logs using a non-relational data store, but put in the massaged data in a RDBMS. If there's structured/relational data hidden in your logs, the ability to perform ad-hoc queries using SQL is invaluable- aggregates, window functions, etc. can be made to run pretty quickly in a decent RDBMS, perhaps even more efficiently than with map-reduce and highly-parallel algorithms; definitely, if you know your SQL, implementation is usually much quicker.

For instance, say the logs you are really interested all look like:

```<code>[timestamp] add student xxxxx
[timestamp] create class yyyy at [date-time] with professor zzzz
[timestamp] student xxxx books class yyyy
[timestamp] student xxxx cancels class yyyy
</code>```

then dumping them into student, class, student_booking and performing aggregates on them makes plenty of sense.

(of course, I would contend that you are not parsing logs then...)

Body:
If you are only going to store logs, you've strayed into one of the few places were relational databases do not make much sense.

SQL is surely not going to be the ideal medium to perform your work- no joins, not many different tables, etc. Transactions and UPDATEs probably won't be necessary.

I would choose something that let me run map-reduce jobs easily- it might well be the case that a single-threaded algorithm be all you need, but if it ever becomes too slow for your purposes, being able to throw cores at the problem will come in handy.

If you are going to be searching a lot (i.e. perform calculations on small subsets of data), indexing is going to be another defining factor- having a store which supports indexing which handles your searches well will save plenty of time.

On the other hand, depending on what you do, it might make sense to "summarize" your logs using a non-relational data store, but put in the massaged data in a RDBMS. If there's structured/relational data hidden in your logs, the ability to perform ad-hoc queries using SQL is invaluable- aggregates, window functions, etc. can be made to run pretty quickly in a decent RDBMS, perhaps even more efficiently than with map-reduce and highly-parallel algorithms; definitely, if you know your SQL, implementation is usually much quicker.

For instance, say the logs you are really interested all look like:

[timestamp] add student xxxxx
[timestamp] create class yyyy at [date-time] with professor zzzz
[timestamp] student xxxx books class yyyy
[timestamp] student xxxx cancels class yyyy

then dumping them into student, class, student_booking and performing aggregates on them makes plenty of sense.

(of course, I would contend that you are not parsing logs then...)


问:
Is there a single book that covers the breadth of computer science fundamentals?
When I did my undergraduate studies in elecrical engineering, there was this book called "Basic Electricity" by Van Valkenburgh. If you read that book cover to cover, your fundamentals in electrical engineering would be bulletproof. I would recommend it all my juniors and I absolutely loved it.

Is there such a book in the field of computer science? I am not so concerned about the algorithms. I am looking more into something that tells me how does everything work beneath the covers. TCPIP, memory management, DNS, routing, SSL, buffer, queuing etc.

答:
It is a very broad topic. I wold suggest to look at Wikipedia - Computer Science .

Here you are structured paper on tis topic: Fundamental Computer Science Concepts


问:
Design Pattern for Complex Data Modeling
I'm developing a program that has a SQL database as a backing store.  As a very broad description, the program itself allows a user to generate records in any number of user-defined tables and make connections between them.  As for specs:

Any record generated must be able to be connected to any other record in any other user table (excluding itself...the record, not the table).  Yes, this creates a arbitrary user-generated relational map.

These "connections" are directional: Incoming, outgoing, and bi-directional.

The list of connections a record has is user ordered.

A record must "know" of connections made from it to others as well as connections made to it from others.

A record's field can also include aggregate information from it's connections (like obtaining average, sum, etc) that must be updated on change from another record it's connected to.

To conserve memory, only relevant information must be loaded at any one time (can't load the entire database in memory at load and go from there).

I cannot assume the backing store is local.  Right now it is, but eventually this program will include syncing to a remote db.

I cannot depend on a specific implementation of a backing store.  This means I cannot be certain the backing store is, in fact, relational.  Thus all relational data is stored explicitly.

The connections are kind of the point of this program, so there is a strong possibility that the number of connections made is very high, especially if the user is using the software as intended.  Neither the user tables, connections or records are known at design time as they are user generated.

I've spent a lot of time trying to figure out how to design the backing store and the object model to best fit these specs.  In my first design attempt on this, I had one object managing all a table's records and connections.  I attempted this first because it kept the memory footprint smaller (records and connections were simple dicts), but maintaining aggregate and link information between tables became....onerous (ie...a huge spaghettified mess).  Tracing dependencies using this method almost became impossible.  Instead, I've settled on a distributed smart graph where each record and connection is 'aware' of what's around it by managing it own data and connections to other records.  Doing this increases my memory footprint but also let me create a faulting system so connections/records aren't loaded into memory until they're needed.  It's also much easier to code: trace dependencies, eliminate cycling recursive updates, etc.  My biggest problem is storing/loading the connections.  I'm not happy with any of my current solutions/ideas so I wanted to ask and see if anybody else has any ideas of how this should be structured.  Connections are fairly simple.  They contain: fromRecordID, fromTableID, fromRecordOrder, toRecordID, toTableID, toRecordOrder.    Here's what I've come up with so far:

Store all the connections in one big table. If I do this, either I load all connections at once (one big db call) or make a call every time a user table is loaded.  The big issue here: the size of the connections table has the potential to be huge, and I'm afraid it would slow things down.

Store in separate tables all the outgoing connections for each user table.    This is probably the worst idea I've had.  Now my connections are 'spread out' over multiple tables (one for each user table), which means I have to load each table just to find all the incoming connections for a particular user table.  I've avoided making "one big ass table", but I'm not sure the cost is worth it.

Store in separate tables all outgoing AND incoming connections for each user table (using a flag to distinguish between incoming vs outgoing).  This is the idea I'm leaning towards, but it will essentially double the total storage for all the connections (as each connection will be stored in two tables).  It also means I have to make sure connection information is kept in sync in both places (each 'from' connection has a corresponding 'to' connection in the appropriate table.  This is obviously not ideal but it does mean that when I load a user table, I only need to load one 'connection' table and have all the information I need.  This also presents a separate problem, that of connection object creation.  Since each user table has a list of all connections, there are two opportunities for a connection object to be made.  However, connections objects (designed to facilitate communication between records) should only be created once.  This means I'll have to devise a common caching/factory object to make sure only one connection object is made per connection.

Does anybody have any ideas of a better way to do this?  Once I've committed to a particular design pattern I'm pretty much stuck with it, so I want to make sure I've come up with the best one possible.

I'll also note that my current backing store is SQLite.  I've written the program to not depend on a specific backing store, though, by introducing an adapter layer to disassociate the data retrieval from the the rest of the program.  So the backing store could be anything, even a simple text file.  I use the backing store exclusively for storage and data retrieval, nothing else.  I don't use any specific database/SQL relational features and I don't use the database to perform calculations (aggregate or otherwise).  All of that is handled in program logic.

答:
All your requirements, save for #8, are implemented by relational databases (consider INFORMATION_SCHEMA, which is a standard relational database feature- the information schema contains views which describe the tables in the database, which columns they have, etc.- your app would work a lot with the INFORMATION_SCHEMA data).

Thanks to #8, you have basically cornered yourself into writing your own relational database engine.

It sounds like you are implementing Access which... implements its own relational database (Jet); it also sucks because implementing a relational engine is quite hard (more if you are subject to the constraints that Access has), and in the end, Access doesn't really make hard things easy.

Implementing a relational database engine on top of another datastore might simplify things, of course (i.e. Berkeley DB is useful for implementing an RDBMS, and Berkeley DB is everywhere. See a related answer I gave recently), but I would think hard about requirement #8 and the viability of your project.


答:
In the softwaredevelopment company where i work for, we use the term "prototype" for "Gui-prototypes" where the screen-maskes are painted so the customer will see, how his app might look like.

Instead of the term "technical prototype" or "prove of concept" we have "spikes" that show that some technical interop is possible (i.e. that an android app can talk to a sap-system")

Title: Do your managers prefer to create proof of concept (POC) before working prototype?

Body:
At last team meeting I heard from managers that we need to create proof of concept (POC) before main prototype and integrate this concept with the main system for proving a new feature.

Could you explain me the main features or this method?

Do you use the POC in your projects before implementation?

What is the main advantages and disadvantages of this method?


答: Sounds like you're looking for the "Computer Science Body of Knowledge". There's a Software Engineering BoK, but I'm not sure such a thing exists for CS. You may want to start with the undergraduate curricula at various universities. Computer Science Curricula 2013 looks like a good start.</p>

Title: Is there a single book that covers the breadth of computer science fundamentals?

Body:
When I did my undergraduate studies in elecrical engineering, there was this book called "Basic Electricity" by Van Valkenburgh. If you read that book cover to cover, your fundamentals in electrical engineering would be bulletproof. I would recommend it all my juniors and I absolutely loved it.

Is there such a book in the field of computer science? I am not so concerned about the algorithms. I am looking more into something that tells me how does everything work beneath the covers. TCPIP, memory management, DNS, routing, SSL, buffer, queuing etc.


答:
Conceptually Computer Science is a fairly narrow topic

Computer science or computing science (abbreviated CS or CompSci) is
  the scientific and mathematical approach to computation, and
  specifically to the design of computing machines and processes. A
  computer scientist is a scientist who specialises in the theory of
  computation and the design of computers.

Pure Computer Science isn't about most of the things you list that you want a comprehensive book about. There are many sub-genres that are part of Computer Science but they diverge very quickly from the definition above.

DNS, TCP/IP, routing, etc are about Networking and Network Management. This easily a multi-tome subject.

SSL is about encryption and secure transmission of data. Multi-tome subject as well.

buffering, queuing, memory management are about time and space algorithms are a crossover. Multi-tome subject on theory and history as well multiple tomes on implementations.

Strictly speaking Computer Science is a not really about the things above; it is about what makes those things possible.


问:
Why is it good to split a program into multiple classes?
I'm still a student in high school (entering 10th grade), and I have yet to take an actual computer course in school. Everything I've done so far is through books. Those books have taught me concepts such as inheritance, but how does splitting a program into multiple classes help? The books never told me.

I'm asking this mainly because of a recent project. It's an arcade video game, sort of like a Flash game as some people have said (although I have no idea what a Flash game is). The thing is, it's only one class. It works perfectly fine (a little occasional lag however) with just one class. So, I'm just asking how splitting it into multiple classes would help it.

This project was in Java and I am the only person working on it, for the record.

答:
The whole idea is based on a general rule named divide and conquer .

This paradigm can be used almost every where; you divide a problem into smaller problems and then you solve these little, simple and well-known problems .

Dividing your program into classes is one of the types of division which started to become common in last decade . In this programming paradigm we model our problem by some objects and try to solve the problem by sending messages between these objects .

Some people might say that this approach is easier to comprehend, expand and debug .

Although some people disagree :)


问:
How do you call the process of taking a part of a function and making an individual function of it?
I know there was a technical term for this. I'm just can't remember what it was.

If the title needs clarification, here is what I mean; If this is the old code:

```<code>Result foobar(Param1,Param2,Param3) {
  code that does abc
  code that does xyz
  code that does asdf
  more code that does something
}
</code>```

and it's changed into:

```<code>SomeResult do_xyz(SomeParams) {
  code that does xyz
}
Result foobar() {
  code that does abc
  do_xyz(args);
  code that does asdf
  more code that does something
}
</code>```

答:
Technical term for this is Extract Method

See http://www.refactoring.com/catalog/extractMethod.html

Turn the fragment into a method whose name explains the purpose of the method.

```<code>void printOwing() {
    printBanner();

    //print details
    System.out.println ("name:    " + _name);
    System.out.println ("amount    " + getOutstanding());
}
</code>```

```<code>void printOwing() {
    printBanner();
    printDetails(getOutstanding());
}

void printDetails (double outstanding) {
    System.out.println ("name:    " + _name);
    System.out.println ("amount    " + outstanding);
}
</code>```

Body:
Technical term for this is Extract Method

See http://www.refactoring.com/catalog/extractMethod.html

Turn the fragment into a method whose name explains the purpose of the method.

void printOwing() {
    printBanner();

    //print details
    System.out.println ("name:    " + _name);
    System.out.println ("amount    " + getOutstanding());
}

void printOwing() {
    printBanner();
    printDetails(getOutstanding());
}

void printDetails (double outstanding) {
    System.out.println ("name:    " + _name);
    System.out.println ("amount    " + outstanding);
}


答:
Personally I'd refactor it more like this:

```<code>int DoLotsOfStuffThatCouldFail (paramstruct *params)
{
    int errcode = EC_NOERROR;

    if ((errcode = FunctionThatCouldFail1 (params)) != EC_NOERROR) return errcode;
    if ((errcode = FunctionThatCouldFail2 (params)) != EC_NOERROR) return errcode;
    if ((errcode = FunctionThatCouldFail3 (params)) != EC_NOERROR) return errcode;
    if ((errcode = FunctionThatCouldFail4 (params)) != EC_NOERROR) return errcode;

    return EC_NOERROR;
}

void DoStuff (paramstruct *params)
{
    int errcode = EC_NOERROR;

    InitStuffThatMayNeedToBeCleaned (params);

    if ((errcode = DoLotsOfStuffThatCouldFail (params)) != EC_NOERROR)
    {
         CleanupAfterError (params, errcode);
    }
}
</code>```

That would be more motivated by avoiding the deep nesting than avoiding the goto however (IMO a worse problem with the first code sample), and would of course be dependent on CleanupAfterError being possible out-of-scope (in this case "params" could be a struct containing some allocated memory that you need to free, a FILE * that you need to close or whatever).

One major advantage I see with this approach is that it's both easier and cleaner to slot a hypothetical future extra step between, say, FTCF2 and FTCF3 (or remove an existing current step), so it lends itself better to maintainability (and the person who inherits my code not wanting to lynch me!) - goto aside, the nested version lacks that.

Title: Is this a decent use-case for goto in C?

Body:
I really hesitate to ask this, because I don't want to "solicit debate, arguments, polling, or extended discussion" but I'm new to C and want to gain more insight into common patterns used in the language.

I recently heard some distaste for the goto command, but I've also recently found a decent use-case for it.

Code like this:

```<code>error = function_that_could_fail_1();
if (!error) {
    error = function_that_could_fail_2();
    if (!error) {
        error = function_that_could_fail_3();
        ...to the n-th tab level!
    } else {
        // deal with error, clean up, and return error code
    }
} else {
    // deal with error, clean up, and return error code
}
</code>```

If the clean-up part is all very similar, could be written a little prettier (my opinion?) like this:

```<code>error = function_that_could_fail_1();
if(error) {
    goto cleanup;
}
error = function_that_could_fail_2();
if(error) {
    goto cleanup;
}
error = function_that_could_fail_3();
if(error) {
    goto cleanup;
}
...
cleanup:
// deal with error if it exists, clean up
// return error code
</code>```

Is this a common or acceptable use-case of goto in C? Is there a different/better way to do this?

Body:
Personally I'd refactor it more like this:

int DoLotsOfStuffThatCouldFail (paramstruct *params)
{
    int errcode = EC_NOERROR;

    if ((errcode = FunctionThatCouldFail1 (params)) != EC_NOERROR) return errcode;
    if ((errcode = FunctionThatCouldFail2 (params)) != EC_NOERROR) return errcode;
    if ((errcode = FunctionThatCouldFail3 (params)) != EC_NOERROR) return errcode;
    if ((errcode = FunctionThatCouldFail4 (params)) != EC_NOERROR) return errcode;

    return EC_NOERROR;
}

void DoStuff (paramstruct *params)
{
    int errcode = EC_NOERROR;

    InitStuffThatMayNeedToBeCleaned (params);

    if ((errcode = DoLotsOfStuffThatCouldFail (params)) != EC_NOERROR)
    {
         CleanupAfterError (params, errcode);
    }
}

That would be more motivated by avoiding the deep nesting than avoiding the goto however (IMO a worse problem with the first code sample), and would of course be dependent on CleanupAfterError being possible out-of-scope (in this case "params" could be a struct containing some allocated memory that you need to free, a FILE * that you need to close or whatever).

One major advantage I see with this approach is that it's both easier and cleaner to slot a hypothetical future extra step between, say, FTCF2 and FTCF3 (or remove an existing current step), so it lends itself better to maintainability (and the person who inherits my code not wanting to lynch me!) - goto aside, the nested version lacks that.


答: I recommend Computer Organization and Design by Patterson and Hennessy. It covers a lot of the fundamentals of computer architecture very thoroughly.</p>


问:
A solution for a PHP website without a framework
One of our customers asked us to add some dynamic functionality to an existent website, made of several static HTML pages.

We normally work with an MVC framework (mostly CodeIgniter), but in this case moving everything to a framework would require too much time.

Since it is not a big project, not having the full functionality of a framework is not a problem. But the question is how to keep code clean.

The solution I came up with is to divide code in libraries (the application's API) and models. So inside HTML there will only be API calls, and readability will not be sacrificed.

I implemented this with a sort of static Registry (sorry if I'm wrong, I am not a design pattern expert):

```<code><?php
class Custom_framework {

    //Global database instance
    private static $db;

    //Registered models
    private static $models = array();

    //Registered libraries
    private static $libraries = array();

    //Returns a database class instance
    static public function get_db(){

        if(isset(self::$db)){
            //If instance exists, returns it
            return self::$db;
        } else {
            //If instance doesn't exists, creates it
            self::$db = new DB;
            return self::$db;
        }
    }

    //Returns a model instance
    static public function get_model($model_name){

        if(isset(self::$models[$model_name])){
            //If instance exists, returns it
            return self::$models[$model_name];
        } else {
            //If instance doesn't exists, creates it
            if(is_file(ROOT_DIR . 'application/models/' . $model_name . '.php')){
                include_once ROOT_DIR . 'application/models/' . $model_name . '.php';
                self::$models[$model_name] = new $model_name;
                return self::$models[$model_name];
            } else {
                return FALSE;
            }
        }
    }

    //Returns a library instance
    static public function get_library($library_name){

        if(isset(self::$libraries[$library_name])){
            //If instance exists, returns it
            return self::$libraries[$library_name];
        } else {
            //If instance doesn't exists, creates it
            if(is_file(ROOT_DIR . 'application/libraries/' . $library_name . '.php')){
                include_once ROOT_DIR . 'application/libraries/' . $library_name . '.php';
                self::$libraries[$library_name] = new $library_name;
                return self::$libraries[$library_name];
            } else {
                return FALSE;
            }

        }
    }

}
</code>```

Inside HTML, API methods are accessed like this:

```<code><?php echo Custom_framework::get_library('My_library')->my_method(); ?>
</code>```

It looks to me as a practical solution. But I wonder what its drawbacks are, and what the possible alternatives.

答:
Your method is overcomplicated if you are only going to implement authentication/authorization to access some static pages;

```<code><?php include "check_access.php" ?>
</code>```

at the top of the protected pages would be all you need, plus a login form and form handler.

You might want to use PHP simply as an SSI mechanism to remove HTML duplication boilerplate (i.e. headers, footers, etc.)- includes might be all you need, although you might want to introduce a better templating mechanism.

The big decision is, are you going to adapt the existing parts of the website to be dynamic? How much more will you need to implement after you deliver this functionality?

If you're not going to do much work on the existing site, and it is big, it might makes sense to do everything new using your preferred framework/methodology. OTOH, framework-less PHP sucks, so redoing everything with your framework of choice might make sense.

In any case, unless what you need to implement is very simple, I would suggest doing it with a framework, even if you don't touch the old pages.

Body:
Your method is overcomplicated if you are only going to implement authentication/authorization to access some static pages;

<?php include "check_access.php" ?>

at the top of the protected pages would be all you need, plus a login form and form handler.

You might want to use PHP simply as an SSI mechanism to remove HTML duplication boilerplate (i.e. headers, footers, etc.)- includes might be all you need, although you might want to introduce a better templating mechanism.

The big decision is, are you going to adapt the existing parts of the website to be dynamic? How much more will you need to implement after you deliver this functionality?

If you're not going to do much work on the existing site, and it is big, it might makes sense to do everything new using your preferred framework/methodology. OTOH, framework-less PHP sucks, so redoing everything with your framework of choice might make sense.

In any case, unless what you need to implement is very simple, I would suggest doing it with a framework, even if you don't touch the old pages.


答:
Since the field of Computer Science is extremely wide, you wouldn't find everything that you are looking for in a single book. However, you could get almost all your fundamentals in order by reading at least one book from the topics below:

Computer Architecture (e.g. Computer Architecture: A Quantitative Approach)

Operating Systems (e.g. Modern Operating Systems)

Networking (e.g. Computer Networking: A Top-Down Approach)

Programming Languages (e.g. Programming Language Pragmatics)

Database Management Systems (e.g. Database Design and Relational Theory)

If you add an introduction to algorithms and a course or two on specific programming languages to this list, you would get your run-of-the-mill basic CS curriculum.


问:
How do I handle a user story that I complete, but with compromise and need to revisit?
I have just fulfilled (is that a good term?) two user stories out of a new project backlog I have just built. These are user registration and password reset, both requiring mail. I need to implement a substitute mail component because my initial choice, and a normally reliable one, wasn't working. Because I was focused on delivering the user stories, not debugging the mail component, I swapped it out to deliver working code at sprint end. Do I now log a new support issue for the mailer, or 're-insert' these stories into the backlog? If I do the latter, am I not introducing too much tech detail into user stories?</p>

答:
According to your question and additional comments to @Klee's answer I think the problem is little bit different.

You completed a story. It should mean you passed all definitions of done - otherwise the user story cannot be considered as completed. But if you completed the story and passed all definitions of done it should mean that your current solution is satisfying. Otherwise the customer / product owner must rise the reason why it is not satisfying (not you) and either reject your completion or define another user story extending this one with new definition of done which are not satisfied by your current solution.

Technical debt is raised only when your current solution doesn't satisfy some requirement or constraint. Is there any constraint you have violated by using a workaround? If yes you should not mark your user story as completed in the first place.

Is there any code duplication or another bad practice introduced by your workaround? Then you have created technical debt and you should solve it ASAP. You can either be fair to product owner and simply tell him that during next sprint you must spend same time to fixing your technical issues which will result in less planed user stories. Or if your relation with product owner is not very good simply plan less user stories because of "newly" discovered complexities in any of them and fix your technical debt.

If there is no code duplication or any real reason why your code should be improved simply don't touch it. By the real reason I mean no customer / product owner defined constraint (for example company policy, performance, predefined time for creating a new email template which cannot be achieved with your current solution, etc.). There is no technical debt in your code. What you are trying to do is called golden plating - delivering features which were not required = wasting customers resources.

If your solution will not satisfy any future user story simply move your refactoring and code improving to that user story. It doesn't have to be solved now because it passed current definition of done. Deal with improvements when they have to be done to pass definition of done for newly implemented stories and to avoid bad practices.


答:
The process itself is called Refactoring the code, and method is called  Extract Method , and it is a good match for applying SRP (single responsibility principle) to the code.

Refactoring to SOLID - Part 2: The Single Responsibility Principle

Refactoring Exercise: The Single Responsibility Principle vs Needless Complexity

Title: How do you call the process of taking a part of a function and making an individual function of it?

Body:
I know there was a technical term for this. I'm just can't remember what it was.

If the title needs clarification, here is what I mean; If this is the old code:

```<code>Result foobar(Param1,Param2,Param3) {
  code that does abc
  code that does xyz
  code that does asdf
  more code that does something
}
</code>```

and it's changed into:

```<code>SomeResult do_xyz(SomeParams) {
  code that does xyz
}
Result foobar() {
  code that does abc
  do_xyz(args);
  code that does asdf
  more code that does something
}
</code>```


问:
how to change the sequence used in planning poker
Is it possible to change the used sequence in Planning Poker, for some stories, it is thought that when the stories gets larger it contains more uncertainty but stories have nearly exact time estimations and these estimations don't drop into two bounds defined by Fibonacci series.</p>

答:
No you should not change sequence for some user stories. Use the same sequence for the whole project. Fibonacci sequence is used because it describes growing uncertainty with complexity of stories.

The sequence doesn't have anything to do with time estimation! It is complexity / sizing estimation. We don't estimate time for stories. We only measure how many story points we completed in previous sprints and use that measurement for computation of our expected velocity.

If you feel that your user story is not a lower bound you should always choose the upper bound because you have already showed uncertainty with lower bound. If you feel that size estimation results in big user stories with a lot of uncertainty its time to talk with product owner (he should actually initiate this because he sees that his user stories are not specific enough from your estimations) and split those stories into smaller and better defined.

OwnerDisplayName: yesildal


问:
Herding your users to your bugtracker
I have a fully configured mantis bug tracker for tracking issues in apps that I create.  When an user is disciplined and goes straight to mantis to write a issue report, he/she will have fastest response and everything regarding the issue will be very easy to track.

However, not everyone is keen to do so.  They report their problems via phone, e-mail, don't report them at all.

What would be the best way to nudge them towards the using a bugtracker system?  Clearly, they HAVE to see some immediate benefits so they can return and look for more benefits.

EDIT:

I am talking about support for the products that I sell as an ISV.

答:
A user who complains is better than one that doesn't, gives up, and calls your competitor. For this reason, I would make it as easy as possible to send a complaint. I would let them continue to call and/or send emails and not ask them to file bugs.

Look at it from their point of view -- If you had to not just take the time to call/write an email but also be forced to learn someone's wonky bug tracking system-- odds are you're just not going to complain.

If need be, hire a customer service person so developers don't get interrupted. They can take the complaints from the customers and make bugs for the dev team.

Title: Herding your users to your bugtracker


问:
Scrum and Google Docs burndown chart
There is a tutorial on how to create a burndown chart for Scrum in the Google Docs application:

http://www.scrumology.net/2011/05/03/how-to-create-a-burndown-chart-in-google-docs/

The problem with it though is, it has only a place to update progress once per sprint but the burndown is supposed to be updated with daily progress, right? How can one modify this chart to be able to put daily progress on it?

I mean to be able to plot two lines (ideal and actual) with data such as (story points 255, velocity 24):

Actual Google Docs document (free to edit):
https://docs.google.com/spreadsheet/ccc?key=0AuPWErnOiLTUdElJVzJZaE5EWEZ2S2xCelF6Z2lzaUE

答:
The tutorial you are referencing is very basic and meant to be customized :)

When I coach Scrum teams, I generally (not always) advise within the Sprint to:

Burn down on task hours

Burn up on story points

That way you can see how you are burning down on hours but balance that with actually completing stories.

Title: Scrum and Google Docs burndown chart


答:
Prevent Anchoring

Fibonacci Sequence is chosen because there is does not represent a linear extrapolation between the increments in the sequence, and help stop psychological anchoring on numbers based on the values on either side.

Back to the Future

The estimation isn't solely about time.

It is a composite of Time/Complexity/Risk as understood by the team. Yes it might be 30 minutes worth of effort for one team member, but 3 hours for anyone else on the team. Majority of the time it is going to be one of the 3 hour people working on the task.

Its all Relative

Stories should be rated relative to each other. The numbers in the Fibonacci Sequence discourages saying things like "Story A is twice Story B" and encourages "Story A is more like Story X" or "Story A is more than Story B but less than Story X" since the numbers get bigger and smaller very quickly on a non-linear scale.

Human Nature

Certain team members will gravitate to everything they estimate being a 3, 5 or 20 and will never budge from those numbers because they get anchored to the 3 and the 20 as upper and lower bounds in their head. The 5 is their compromise number when they are forced to do so, because everyone is usually overly optimistic. Giving realistic or pessimistic estimates; they think makes them look bad in some undefinable way. What really makes them look bad is being wrong on the low side constantly and missing commitments and deadlines constantly because of it.

Refresh Understanding

Sounds like you need to get the team to read up on how Planning Poker is really supposed to work, what the numbers actually mean in context of estimation.

Title: how to change the sequence used in planning poker

Body: Is it possible to change the used sequence in Planning Poker, for some stories, it is thought that when the stories gets larger it contains more uncertainty but stories have nearly exact time estimations and these estimations don't drop into two bounds defined by Fibonacci series.</p>


答:
"Please report this on the bug tracker at http://your/url/. I cannot keep track of bugs if you don't report them there."

Perhaps it's possible for you to write a plugin for your mail client to turn an email into a bug report, or to use a dedicated mailbox - bugs@foo - for taking bug reports. (But the latter of course requires training your users...)

Title: Herding your users to your bugtracker

Body:
I have a fully configured mantis bug tracker for tracking issues in apps that I create.  When an user is disciplined and goes straight to mantis to write a issue report, he/she will have fastest response and everything regarding the issue will be very easy to track.

However, not everyone is keen to do so.  They report their problems via phone, e-mail, don't report them at all.

What would be the best way to nudge them towards the using a bugtracker system?  Clearly, they HAVE to see some immediate benefits so they can return and look for more benefits.

EDIT:

I am talking about support for the products that I sell as an ISV.


问:
Why does Scheme r5rs have no module system
With all the controversy surrounding scheme r6rs, I stuck with r5rs and I am wondering why the designers decided to not implement a module system. How does one organize code in this?</p>

答:
It seems that your concerns are addressed in the following post R6RS vs. R5RS scheme.
In another words, there was no standardized modules in place till r6rs version.</p>


问:
What are the commonly confused encodings that may result in identical test data?
I'm fixing code that is using ASCIIEncoding in some places and UTF-8 encoding in other functions.

Since we aren't using the UTF-8 features, all of our unit tests passed, but I want to create a heightened awareness of encodings that produce similar results and may not be fully tested.

I don't want to limit this to just UTF-8 vs ASCII, since I think issue with code that handles ASN.1 fields and other code working with Base64.

So, what are the commonly confused encodings that may result in identical test data?

答:
For MIME the following headers may produce similar results:

Content-type: text/plain; charset=us-ascii (Plain text)

Content-type: text/plain; charset=UTF-8 (a superset of ASCII)

Content-type: text/plain; charset="ISO-8859-2" (another superset of ASCII)

Content-type: text/enriched; charset="windows-1252" (if there are no enriched codes)


答:
The short answer is "because they didn't standardize a module system until R6RS."

At least based on my recollection from the time, there were several reasons a module system wasn't dealt with before that. First of all, although it wasn't standardized, nearly every implementation included some sort of module system before that, so the group of people who cared was restricted to those who wanted modules to be portable, not just everybody who wanted modules at all.

Second, a module system is a lot of work with very few unequivocally "right" answers -- nearly every decision you make is a compromise. Many earlier changes (not all, of course, but many nonetheless) were clear corrections of earlier mistakes.

Third, (related to the first one) nearly every implementation had some sort of module system in place, which created a bit of contention -- most of them saw their own design as good (that's generally why they picked that design after all) and in most cases they'd gone through several iterations of improvements on their basic design as well. As I already said, most of the decisions are compromises, so advocates of each could point to problems with every other design extant, and most theoretical ones as well.

So, few people, lots of work, and quite a bit of disagreement. Pretty much a recipe for slow development (at best).

Title: Why does Scheme r5rs have no module system

Body: With all the controversy surrounding scheme r6rs, I stuck with r5rs and I am wondering why the designers decided to not implement a module system. How does one organize code in this?</p>


问:
How to model the components of a non Information System?
I am working on a kernel-related project (specifically related to the TCP/IP stack of the kernel).

I need to build some models to describe the functionality and components of my system.
Initially I thought about using a Class Diagram, as it can describe the general architecture of my system. But it doesn't make sense since my code is VERY structured (written in standard C).

I also thought about DFDs: they'd describe the processes of my system, and how the data is flowing. But they contain something which doesn't really fit in: data-storages.
I have no databases here (at all).

For the functionality, other team members suggested using Activity and Sequence diagrams, which is kinda okay with me, but what about the system components?

So basically my question is: If I want to describe the components of my system, what do you suggest as a meaningful diagram ?

Again, the project is a research low-level systems-oriented project with almost no user-interface at all.

答:
Then, why don't you use UML to build a Component diagram or even a Package diagram? If I understood correctly, you want a bird's eye view of your whole architecture and that's why you don't need a class diagram, right?

I guess you could even look at SysML which can provide a more systems-oriented approach.


问:
Is it worth to learn Experimental Languages?
I'm a young programmer who desires to work in the field someday as a programmer.  I know Java, VB.NET and C#.  I want to learn a new language (as I programmer, I know that it is valuable to extend what I know - to learn languages that make you think differently).  I took a look online to see what languages were common.  Everybody knows C and C++ (even those muggles who know so little about computers in general), so I thought, maybe I should push for C.

C and C++ are nice but they are old.  Things like Haskell and Forth (etc. etc. etc.) are old and have lost their popularity.  I'm scared of learning C (or even C++) for this same reason.  Java is pretty old as well and is slow because it's run by the JVM and not compiled to native code.

I've been a Windows developer for quite a while.  I recently started using Java - but only because it was more versatile and spreadable to other places.  The problem is that it doesn't look like a very usable language for these reasons:

It's most used purpose is for web application and cellphone apps (specifically Android)

As far as actual products made with it, the only things that come to mind are Netbeans, Eclipse (hurrah for making and IDE with the language the IDE is for - it's like making a webpage for writing HTML/CSS/Javascript), and Minecraft which happens to be fun but laggy and bipolar as far as computer spec. support.

Other than that it's used for servers but heck - I don't only want to make/configure servers.

The .NET languages are nice, however:

People laugh if I even mention VB.NET or C# in a serious conversation.

It isn't cross-platform unless you use MONO (which is still in development and has some improvements to be made).

Lacks low level stuff because, like Java with the JVM, it is run/managed by the CLR.

My first thought was learning something like C and then using it to springboard into C++ (just to make sure I would have a strong understanding/base), but like I said earlier, it's getting older and older by the minute.

What I've Looked Into

Fantom looks nice.  It's like a nice middleman between my two favorite languages and even lets me publish between the two interchangeably, but, unlike what I want, it compiles to the CLR or JVM (depending on what you publish it to) instead of it being a complete compile.

D also looks nice.  It seems like a very usable language and from multiple sources it appears to actually be better than C/C++.  I would jump right with it, but I'm still unsure of its success because it obviously isn't very mainstream at this point.

There are a couple others that looked pretty nice that focused on other things such as Opa with web development and Go by GOOGLE.

My Question

Is it worth learning these "experimental" languages?  I've read other questions that say that if you aren't constantly learning languages and open to all languages that you aren't in the right mindset for programming.  I understand this and I still might not quite be getting it, but in truth, if a language isn't going to become mainstream, should I spend my time learning something else?  I don't want to learn old (or any going to soon be old) programming languages.  I know that many people see this as something important, *but would any of you ever actually consider (assuming you didn't already know) FORTRAN?  My goal is to stay current to make sure I'm successful in the future.

Disclaimer

Yes, I am a young programmer, so I probably made a lot of naive statements in my question.  Feel free to correct me on ANYTHING!  I have to start learning somewhere so I'm sure a lot of my knowledge is sketchy enough to have caused to incorrect statements or flaws in my thinking.  Please leave any feelings you have in the comments.

The Results...

I'm truly amazed by the amazing responses, most of them so nicely pointing out my misunderstandings and misjudgments.  I've learned quite a lot from this and I'm excited to hopefully utilize everything I've learned!  I'll probably start learning Haskell next (the not so old language, albeit over 20 years old - hahaha) and then start looking at some other options around me.

Thanks

答:
Pick ones with different types.  Group them by features, and pick one in each group.  If you want to do this professionally, pick one that is used (so C++ over D for statically typed compiled language with template metaprogramming).

Poor D, it's a good language, but it lacks the killer app which C++ had: almost full backwards compatibility with the #1 language of the time (C for C++'s case).  It's nice, but that important little fact will probably relegate D to sideshow status in the history books.


问:
When to skip solving the general problem and settling for the specific problem?
I've been working hard on trying to develop a general solution to my problem, but I cannot seem to formulate a proper algorithm for it, at least one that doesn't take a ton of inaccurate grunt work building a lookup table.

I have a solution already for the specific requirement, but it requires the software's configuration to be changed every time the software is loaded with a different geographic area's datasets.

So is it better to be finished and move on for now, or to keep attempting to solve the general problem knowing that the specific problems will keep popping up?

答:
I've been in this situation before, and it's really just a special case of YAGNI (you ain't gonna need it).

Implement the solution based upon the current requirements (which you say you've solved).  When the next round of requirements come in that require a modification, handle it then.  You'll either A) discover the general solution that you couldn't find now, B) come up with an elegant / tolerable way of extending for each new case, or C) find that you don't need to make those modifications after all.

From what you've described, it sounds like the modifications can be easily scripted if nothing else.  Sometimes, a second app is the solution to the intractable problems in the first app.

Code to meet your contract, and accommodate expected future growth only inasmuch as is obviously necessary.  Coding for every what-if (or the full expression of the problem set) isn't what's required at the moment.  (caveat: that advice is intended for this particular issue and in other cases more future-proofing could be warranted.)


问:
How do you manage your javascript unit tests?
When you are writing JavaScript unit tests, where do you put all the test code?

I see two potential approaches:

Leave all your test code with your regular web project and explictly don't release the code to production.

Maintain a separate project that runs all your tests.

I see pros and cons for both. I'm curious what more experienced JavaScript developers have ended up using.

答:
We organize and run our unit tests separately :

Must be able to run tests from the commend-line

Tests should be relatively easy to write

Unit tests are the design specs of the module’s behavior, they are not an observation of everything the code does. Unit tests query how the module does its job, rather than what it does.

After some re-search we ended up with rhinounit - Ant Based Javascript Testing Framework.
However, there might be some other new frameworks that i would be glad to hear about.

There is also a comparison of RhinoUnit vs JSUnit net that might be interesting to look.


问:
How common is meta-programming?
How often do you or have you seen meta-programming be used in projects? In uni I've never seen this be applied, but I've seen this on my previous job (when I saw it I was blown away of how effective it was).

But how common is it? Is it used all the time, or just occasionally?

答: I think it depends strongly on what language you use. Common Lisp people probably make a fair use of it - the Meta-Object Protocol allows for neat things transparent/orthogonal persistence, for instance - and Smalltalkers use it frequently.</p>

Title: How common is meta-programming?


问:
"Guiding" a Domain Expert to Retire from Programming
I've got a friend who does IT at a local non-profit where they're using a custom web application which is no longer supported by the company who built it.  (out of business, support was too expensive, I'm not sure...)  Development on this app started around 10+ years ago so the technologies being harnessed are pretty out of date now - classic asp using vbscript and SQL Server 2000.  The application domain is in the realm of government bookkeeping - so even though the development team is long gone, there are often new requirements of this software.  Enter the...

The domain expert.  This is an middle aged accounting whiz without much (or any?) prior development experience.  He studied the pages, code and queries and learned how to ape the style  of the original team which, believe me, is mediocre at best.  He's very clever and very tenacious but has no experience in software beyond what he's picked up from this app.  Otherwise, he's a pleasant guy to talk to and definitely knows his domain.

My friend in IT, and probably his superiors in the company, want him out of the code.  They view him as wasting his expertise on coding tasks he shouldn't be doing.  My friend got me involved with a few small contracts which I handled without much problem - other than somewhat of a communication barrier with the domain expert.  He explained the requirements very quickly, assuming prior knowledge of the domain which I do not have.  This is partially his normal style, and I think maybe a bit of resentment from my involvement.  So, I think he feels like the owner of the code and has entrenched himself in a development position.

So... his coding technique.  One of his latest endeavors was to make a page that only he could reach (theoretically - the security model for the system is wretched) where he can enter a raw SQL query, run it, and save the query to run again later.  A report that I worked on had been originally implemented by him using 6 distinct queries, 3 or 4 temp tables to coordinate the data between the queries, and the final result obtained by importing the data from the final query into Access and doing a pivot and some formatting.  It worked - well, some of the results were incorrect - but at what a cost! (I implemented the report in a single query with at least 1/10th the amount of code.) He edits code in notepad.  He doesn't seem to know about online reference material for the languages.    I recently read an article on Dr. Dobbs titled "What Makes Bad Programmers Different" - and instantly thought of our domain expert.  From the article:

Their code is large, messy, and bug laden.

They have very superficial knowledge of their problem domain and their tools.

Their code has a lot of copy/paste and they have very little interest in techniques that reduce it.

The fail to account for edge cases, while inefficiently dealing with the general case.

They never have time to comment their code or break it into smaller pieces.

Empirical evidence plays no little role in their decisions.

5.5 out of 6.

My friend is wanting me to argue the case to their management - specifically, I got this email from their manager to respond to:

...Also, I need to talk to you about what effect there is from Domain
  Expert continuing to make edits to the live environment.  If that is
  a problem for you I need to know so I can have his access blocked.
  Some examples would help.

In my opinion, from a technical standpoint, it's dangerous to have him making changes without any oversight.

On the other hand, I'm just doing one-off contracts at this point and don't have much desire to get involved deeply enough that I'm essentially arguing as one of the Bobs from Office Space.  I'd like to help my friend out - but I feel like I'm getting in the middle of a political battle.

More importantly - if I do get involved and suggest that his editing privileges be removed, it needs to be handled carefully so that doesn't feel belittled.  He is beyond a doubt the foremost expert on this system.

I'm hoping this is familiar territory for some other stackechangers, because I'm feeling a little bewildered.  How should I respond?  Should I argue that he shouldn't be allowed to touch the code?  Should I phrase it as "no single developer, no matter how experienced, should be working on production code unchecked"?  Should I argue to keep him involved with the code, but with a review process?  Should I say "glad I could help, but uh, I'm busy now!"  Other options?

Thanks a bunch!

答:
Take the long term perspective on this issue.  A lot of the items you mentioned wash away when you place a lens of objectivity over the situation.

You've got minimal skin in this game and no real desire / prospects for significant contract work from the NFP.  Ultimately, what benefit is there to you to answer one way or the other to the management request?

You are well within decorum to simply state "I don't have enough of the history about this project to make a statement like that."  And then you can follow that up with "A good practice is to have a test system to make and test changes against prior to making those changes in production.  No one, including myself, should make changes directly to production in a non-emergency situation."  And yes, even in most emergency situations you should hit Test before Prod.

The NFP is asking a technical person to make a personnel judgement, which is really outside the realm of your role, especially as a part-time / ad-hoc contractor.  There is no gain for you or benefit to your professional reputation by becoming involved in their internal matter.

Update:

This wasn't directly in your question, but it relates to the more technical aspects of it.  And it provides more concrete steps of what you can actually do to help this situation.  It doesn't affect my original answer to stay out of the personnel issue.  It's always worth remembering that code is the product of the circumstances that created it.  I try not to be too quick to judge any set of code that I didn't personally write because I don't know all of the circumstances.  I've written some crap code under pressure, and I remind myself of that whenever I see new examples.  Keep it real.  Keep it humble.

Some people simply don't know that what they are doing is wrong.  On your next contract, you can offer to show him some techniques to improve his coding skills.  Start with a compliment and / or acknowledge his domain expertise.  Then show him an easy simplification and point out why it will make his life easier.  Start small and always frame it towards his benefit, not as one-upping him.  You especially don't want to advertise that you are trying to "train" him; frame it as just offering up simple tricks and tips.  Despite his brusque personality, everyone appreciates learning the tricks of the trade that make their lives easier.


答:
Unit Tests

For real JavaScript unit tests, usually I'd recommend that they can be executed by a command-line tool, or by a browser-based tool but where the unit-tests are still separate from the main code base.

Lately, the frameworks I've found to be the most practical to use where Jasmine and JsTestDriver, both in terms of API design and tooling (for instance, to integrate with a Maven build, which already enforces the separation of source code and test code in general). Some other automated and head-less tools offer some level of support of JavaScript as well (like HtmlUnit), but unfortunately it's usually the browser-based ones that provide the best results (but are also the hardest to integrate and maintain).
So, usually, the test-code is part of the same project, but clearly separated and not part of the generated output.

Integration Tests

On top of that, obviously some JavaScript aspects rely heavily on the UI, and you may want to have more complete integration tests (using something like Seleniun, for instance). For these, it's not uncommon to have them in separate projects, especially as integration tests may rely on multiple modules.

Title: How do you manage your javascript unit tests?

Body:
When you are writing JavaScript unit tests, where do you put all the test code?

I see two potential approaches:

Leave all your test code with your regular web project and explictly don't release the code to production.

Maintain a separate project that runs all your tests.

I see pros and cons for both. I'm curious what more experienced JavaScript developers have ended up using.


问:
concurrency semantics reading a file being written (ext)
In Ext 3/4 filesystem, if I have a log file open and being appended to, if another process tries to read it (e.g. with cat), what happens?

Can the reading process read part of / an incomplete write?

Is reading-during-writing safe and won't disrupt the writing process?  Or is there a chance the logs can be corrupted by doing this?

Where should one read more?

答:
1. Can the reading process read part of / an incomplete write?
The reading process will only be able to read the data that has been written, but to answer the question, yes it could read part of the data if the write has not yet completed.

2. Is reading-during-writing safe and won't disrupt the writing process? Or is there a chance the logs can be corrupted by doing this?

Reading during writing, although not entirely safe, should not disrupt the writing process. Neither will it necessarily corrupt the logs, but any data that is does manage to read will likely be incomplete.

Ultimately I wouldn't recommend it.


答: As @Astyanax said, UML Component and Package diagrams are generally-useful even in non-OO systems. State-Transition Diagrams are another form that are commonly seen at the system level. I actually like the idea of DFDs, too, even if you don't have datastores: I've always found them to be pretty accessible for both technical and non-technical users (you don't have to know all the semantics of "filled diamonds" vs "unfilled diamonds" etc.)  </p>

Title: How to model the components of a non Information System?

Body:
I am working on a kernel-related project (specifically related to the TCP/IP stack of the kernel).

I need to build some models to describe the functionality and components of my system.
Initially I thought about using a Class Diagram, as it can describe the general architecture of my system. But it doesn't make sense since my code is VERY structured (written in standard C).

I also thought about DFDs: they'd describe the processes of my system, and how the data is flowing. But they contain something which doesn't really fit in: data-storages.
I have no databases here (at all).

For the functionality, other team members suggested using Activity and Sequence diagrams, which is kinda okay with me, but what about the system components?

So basically my question is: If I want to describe the components of my system, what do you suggest as a meaningful diagram ?

Again, the project is a research low-level systems-oriented project with almost no user-interface at all.


问:
Best Architecture for ASP.NET WebForms Application
I have written an ASP.NET WebForms portal for a client.  The project has kind of evolved rather than being properly planned and structured from the beginning.  Consequently, all the code is mashed together within the same project and without any layers.  The client is now happy with the functionality, so I would like to refactor the code such that I will be confident about releasing the project.  As there seems to be many differing ways to design the architecture, I would like some opinions about the best approach to take.

FUNCTIONALITY

The portal allows administrators to configure HTML templates.   Other associated "partners" will be able to display these templates by adding IFrame code to their site.  Within these templates, customers can register and purchase products.  An API has been implemented using WCF allowing external companies to interface with the system also.  An Admin section allows Administrators to configure various functionality and view reports for each partner. The system sends out invoices and email notifications to customers.

CURRENT ARCHITECTURE

It is currently using EF4 to read/write to the database.  The EF objects are used directly within the aspx files.  This has facilitated rapid development while I have been writing the site but it is probably unacceptable to keep it like that as it is tightly coupling the db with the UI.  Specific business logic has been added to partial classes of the EF objects.

QUESTIONS

The goal of refactoring will be to make the site scalable, easily maintainable and secure.

What kind of architecture would be best for this?  Please describe what should be in each layer, whether I should use DTO's / POCO / Active Record pattern etc.

Is there a robust way to auto-generate DTO's / BOs so that any future enhancements will be simple to implement despite the extra layers?

Would it be beneficial to convert the project from WebForms to MVC?

答:
ASP.NET MVP pattern is the best architecture for a long term ASP.NET webforms application. It is coming into play with "separation of concerns" concept, which is de-facto a trend behind the MV* patterns.

The question on Why to use it? - addressed in details in this post - ASP.NET MVP

Getting started with testing an ASP.NET Webforms Application

Trade-offs between MVP vs MVC

End of Confusion: MVP vs MVC


答:
I don't know Mantis specifically, but can it be configured to monitor an e-mail address and automatically generate reports from them? I know other systems (like JIRA for example can).

The problem then becomes it getting them to use the right e-mail address!

Title: Herding your users to your bugtracker


答:
Paraphrasing your question "My mate works for a company that want to fire someone who they don't think is doing a good enough job, they have asked me to help, and I am happy to because I agree, Can I have some advise on how to really twist the knife on this guy?"

All I can add to the superb answer by @GlenH7 is that this is a serious employment issue. Apart from the ethics of it, discussing it openly on the internet could put a number of people in deep ..... Glen indicated you have nothing to gain.... I would go as far as you have a lot to lose.

My advise is stay out of it, it's not your battle.

Title: "Guiding" a Domain Expert to Retire from Programming

Body:
I've got a friend who does IT at a local non-profit where they're using a custom web application which is no longer supported by the company who built it.  (out of business, support was too expensive, I'm not sure...)  Development on this app started around 10+ years ago so the technologies being harnessed are pretty out of date now - classic asp using vbscript and SQL Server 2000.  The application domain is in the realm of government bookkeeping - so even though the development team is long gone, there are often new requirements of this software.  Enter the...

The domain expert.  This is an middle aged accounting whiz without much (or any?) prior development experience.  He studied the pages, code and queries and learned how to ape the style  of the original team which, believe me, is mediocre at best.  He's very clever and very tenacious but has no experience in software beyond what he's picked up from this app.  Otherwise, he's a pleasant guy to talk to and definitely knows his domain.

My friend in IT, and probably his superiors in the company, want him out of the code.  They view him as wasting his expertise on coding tasks he shouldn't be doing.  My friend got me involved with a few small contracts which I handled without much problem - other than somewhat of a communication barrier with the domain expert.  He explained the requirements very quickly, assuming prior knowledge of the domain which I do not have.  This is partially his normal style, and I think maybe a bit of resentment from my involvement.  So, I think he feels like the owner of the code and has entrenched himself in a development position.

So... his coding technique.  One of his latest endeavors was to make a page that only he could reach (theoretically - the security model for the system is wretched) where he can enter a raw SQL query, run it, and save the query to run again later.  A report that I worked on had been originally implemented by him using 6 distinct queries, 3 or 4 temp tables to coordinate the data between the queries, and the final result obtained by importing the data from the final query into Access and doing a pivot and some formatting.  It worked - well, some of the results were incorrect - but at what a cost! (I implemented the report in a single query with at least 1/10th the amount of code.) He edits code in notepad.  He doesn't seem to know about online reference material for the languages.    I recently read an article on Dr. Dobbs titled "What Makes Bad Programmers Different" - and instantly thought of our domain expert.  From the article:

Their code is large, messy, and bug laden.

They have very superficial knowledge of their problem domain and their tools.

Their code has a lot of copy/paste and they have very little interest in techniques that reduce it.

The fail to account for edge cases, while inefficiently dealing with the general case.

They never have time to comment their code or break it into smaller pieces.

Empirical evidence plays no little role in their decisions.

5.5 out of 6.

My friend is wanting me to argue the case to their management - specifically, I got this email from their manager to respond to:

...Also, I need to talk to you about what effect there is from Domain
  Expert continuing to make edits to the live environment.  If that is
  a problem for you I need to know so I can have his access blocked.
  Some examples would help.

In my opinion, from a technical standpoint, it's dangerous to have him making changes without any oversight.

On the other hand, I'm just doing one-off contracts at this point and don't have much desire to get involved deeply enough that I'm essentially arguing as one of the Bobs from Office Space.  I'd like to help my friend out - but I feel like I'm getting in the middle of a political battle.

More importantly - if I do get involved and suggest that his editing privileges be removed, it needs to be handled carefully so that doesn't feel belittled.  He is beyond a doubt the foremost expert on this system.

I'm hoping this is familiar territory for some other stackechangers, because I'm feeling a little bewildered.  How should I respond?  Should I argue that he shouldn't be allowed to touch the code?  Should I phrase it as "no single developer, no matter how experienced, should be working on production code unchecked"?  Should I argue to keep him involved with the code, but with a review process?  Should I say "glad I could help, but uh, I'm busy now!"  Other options?

Thanks a bunch!


问:
Is a Metro application installation restricted through Windows Store only?
I found that Windows 8 allows packaging and deploying of Metro applications and it can be installed by clicking on a ".bat" file. How will it technically be ensured that the applications can be installed through Windows Store only?

Can't the developers just host the package at a different location from where users can install it?

答:
It looks like you will need a developer license or a special product key to enable 'side-loading' which is what you are describing.

Have a look at:

Will Metro-style applications be able to be installed outside the market frame? (Stack Overflow) and

How to Add and Remove Apps (MSDN)


问:
How to find a programming mentor?
I decided to learn programming. I've been reading SO for few days, and I think I will start with C++, as I read some articles. I am aware of loops, arrays, program logic and objects a little and I need someone to look me over and help me with small questions I get when doing my first projects.

So here is the question - where do I find such guy? I don't got any friends who program and all.

EDIT: 2 years later, I am still looking for mentor. I did not actively code just started 3 months again. I work on Objective-C and iOS programming and game programming with Cocos2d. If you want to become my mentor, drop me a or comment.

答:
"How do I find a programming prodigee? It's all I want. I just want to build a massive robot army to take over the world with. I'm clever and I've written the AI. I have the money, the influence, the facilities. I just can't be bothered to deal with that loathsome .NET or JVM foolishness... Hmm... How.. How!? Damnit!"

Normally I wouldn't explain this, but we're on Stack. Some folks like it literal. You find one (a mentor), by being useful. You can be useful, by solving the problems the kids with the experience (or - maybe - brains - or (heh) money) don't want to solve.

Solve those problems grasshopper.

Or don't. It's the information age. DIY my friend. Look to communities like Stack to tell you when you're being stupid or wise about something code-related or something we don't get as easily like the machinations of that that investor who is all set to screw you over and then some.

And share what you know. Participate a bit in the collective once you've found your groove. This is not blacksmithing in the 1700s. Your parents didn't have to know anybody (although certainly everybody appreciates when you don't hog craft-knowledge to yourself and share with the guild).

You just decide you're interested and you go. Pretty freakin' empowering when it sinks in. It takes a while (I know) but trust me (if only on this one seemingly absurd point - it took me over ten years to realize that yes, I was a freaking programmer), all that really matters is that you have the base level of talent and that you actually are interested. If you're not, kindly !@#$ off and find something that you are interested in.

Because programming/scripting/coding is a horrible choice otherwise. But I don't want to leave that on a negative, nasty point. If you are interested, don't worry about how good you are. Ask questions. Demand answers. Put up with total long-winded gas/douche-bags like myself. You'll get there if you want to.

Do you like puzzles? Do you like random arbitrary problems to solve? Do you like gladiator movies? Unequivocally on the first two points, yes? Don't look for a mentor. Learn one language really well, learn one or two others that aren't overly similar to your first language to the point of entry-skill-level-well, read some books, and have some opinions. Enjoy having them challenged and alter them occasionally even if only to see whether you weren't just totally wrong. You might be surprised how often your instincts weren't actually all that bad. Ask people to come out and slap you in the face for asking the wrong question and you might find you know better than most who rise to that occasion. But mostly, it's a problem to solve. Solve it.

Title: How to find a programming mentor?