问:
Is it still worth learning desktop gui development?
For the last couple of years, all of the serious projects I have worked on have been either web based, or had a non graphical user interface (services, command line scripts etc...).  I can throw together a WinForms app or do some simple WPF when needed, but I've never really delved into some of the lower level API's like MFC or QT.

I understand that this depends on the situation but in general is it still worth taking the time to learn desktop development well or are applications moving to the web and mobile devices at a pace which makes this knowledge less relevant?  Also, do you expect developers you work with to have desktop gui expertise?

答:
According to the IE9 team:

There shouldn’t be a gap between native and web apps. HW acceleration, fast JS and site pinning starts it off

I think it's a safe bet that these technologies will grow closer together. If you're a java developer, there's very little difference between developing desktop apps and web apps (using GWT). It's not unreasonable to expect more and more "desktop" development platforms to be able to target the browser engine. It's also not unreasonable to expect more and more desktop apps to have a web-like distribution model (auto-updating in the background, sandboxed execution, like chrome).


问:
Strengthening code with possibly useless exception handling
Is it a good practice to implement useless exception handling, just in case another part of the code is not coded correctly?

Basic example

A simple one, so I don't loose everybody :).

Let's say I'm writing an app that will display a person's information (name, address, etc.), the data being extracted from a database. Let's say I'm the one coding the UI part, and someone else is writing the DB query code.

Now imagine that the specifications of your app say that if the person's information is incomplete (let's say, the name is missing in the database), the person coding the query should handle this by returning "NA" for the missing field.

What if the query is poorly coded and doesn't handle this case? What if the guy who wrote the query handles you an incomplete result, and when you try to display the informations, everything crashes, because your code isn't prepared to display empty stuff?

This example is very basic. I believe most of you will say "it's not your problem, you're not responsible for this crash". But, it's still your part of the code which is crashing.

Another example

Let's say now I'm the one writing the query. The specifications don't say the same as above, but that the guy writing the "insert" query should make sure all the fields are complete when adding a person to the database to avoid inserting incomplete information. Should I protect my "select" query to make sure I give the UI guy complete informations?

The questions

What if the specifications don't explicitly say "this guy is the one in charge of handling this situation"? What if a third person implements another query (similar to the first one, but on another DB) and uses your UI code to display it, but doesn't handle this case in his code?

Should I do what's necessary to prevent a possible crash, even if I'm not the one supposed to handle the bad case?

I'm not looking for an answer like "(s)he's the one responsible for the crash", as I'm not solving a conflict here, I'd like to know, should I protect my code against situations it's not my responsibility to handle? Here, a simple "if empty do something" would suffice.

In general, this question tackles redundant exception handling. I'm asking it because when I work alone on a project, I may code 2-3 times a similar exception handling in successive functions, "just in case" I did something wrong and let a bad case come through.

答:
What you're talking about here is trust boundaries. Do you trust the boundary between your application and the database? Does the database trust that the data from the application is always pre-validated?

That's a decision that has to be made in every application and there are no right and wrong answers. I tend to err on the side of calling too many boundaries a trust boundary, other developers will happily trust third-party APIs to do what you expect them to do, all the time, every time.

ContentLicense: CC BY-SA 3.0


问:
Designing a SQL-like encapsulation object for programmatic use
In the last few weeks, I have been working on a Data Mapping Library, which has involved lots of research, experimentation, crying, blaming the whiteboard for not being big enough, and more research. But now I have a full idea of what I'm trying to do.

I have decided that before working on any data source adapters, I need to build a SQL expression library. The queries are not assembled with a string of text, but in the form of an instantiated object, containing multiple other objects associated with which part of the query it pertains to.

As such, a SELECT query object will have objects for the columns, table from, joins, where clause, group bys, having clause, order bys, and limit. These objects are then passed to the data source adapter, which will take the input and turn it into a query (or use it in other ways) so that it can fetch the data in a common fashion.

Although this is good enough for simple queries, when it comes to more complex queries, where the join reference, or a condition within the where clause is a nested select query (i.e. SELECT * FROM tblA INNER JOIN (SELECT * FROM tblB WHERE foo = 'bar'), or SELECT * FROM tblA WHERE alice IN (SELECT * FROM tblB WHERE foo = 'bar')), I am having trouble designing an interface where such a thing could be defined, which would later be passed to the adapter that could use it in whatever way it needs to.

So, can anyone propose a design that would allow for such queries to be defined in abstract which could be interpreted into a sql query, or into a nosql programmatic interface function call?

EDIT

The design of the system is such that all the tables and columns are defined as objects (separately, but with named associations for linking). Here is an example of the coding I am hoping to be able to execute:

```<code>tblA::select()
    ->where(new inCondition(
                           'tblAfooCol',
                            tblB::select()->where(new isNullCondition('tblBbarCol'))
                           )
           )
    ->fetch();
</code>```

Now, instead of this being directly translated into SQL (which is very easy), I am trying to plan a way that this can be returned to the data source adapter (internally through the fetch function). So far, the system I have built can handle the commands for a single SELECT query being parsed, but it is when sub queries are used in conjunction with the query that will be passed to the adapter. I am having problems determining how to encapsulate the sub query so the adapter can process it itself. As said before, converting it directly into SQL works great, but if I want to use it with a special adapter that does not use SQL (i.e. an XML or MongoDB adapter), without a function to convert the SQL into commands (or if it is SQL, converting some of the syntax to a valid specification for that rmdbs) that can be used may become very processor intensive (only for certain queries) and cost quite a lot of performance.

答:
What you currently have looks very much like an ORM. You might look at how ORM's in the established frameworks are implemented.

On the other hand, the existing ORM implementations all (to my knowledge) target databases that support SQL interfaces. If it is your intention to target also NoSQL databases, it might be better to re-think your approach and not start from an SQL-like syntax.

You could start with having a DataCollection (table or join), on which you apply Filters (where), Ordering (order by) and an OutputSpecification (select columns), which then results in a new DataCollection.

This approach can still be converted to SQL without too much trouble (although it will be harder than with your current approach), but it might lend itself better for processing in contexts that don't use SQL (directly).


答: The robustness principle "Be conservative in what you send, be liberal in what you accept" is what you are after. It is a good principle - EDIT: as long as its application does not hide any serious errors - but I agree with @pdr that it always depends on the situation if you should apply it or not. </p>

Title: Strengthening code with possibly useless exception handling

Body:
Is it a good practice to implement useless exception handling, just in case another part of the code is not coded correctly?

Basic example

A simple one, so I don't loose everybody :).

Let's say I'm writing an app that will display a person's information (name, address, etc.), the data being extracted from a database. Let's say I'm the one coding the UI part, and someone else is writing the DB query code.

Now imagine that the specifications of your app say that if the person's information is incomplete (let's say, the name is missing in the database), the person coding the query should handle this by returning "NA" for the missing field.

What if the query is poorly coded and doesn't handle this case? What if the guy who wrote the query handles you an incomplete result, and when you try to display the informations, everything crashes, because your code isn't prepared to display empty stuff?

This example is very basic. I believe most of you will say "it's not your problem, you're not responsible for this crash". But, it's still your part of the code which is crashing.

Another example

Let's say now I'm the one writing the query. The specifications don't say the same as above, but that the guy writing the "insert" query should make sure all the fields are complete when adding a person to the database to avoid inserting incomplete information. Should I protect my "select" query to make sure I give the UI guy complete informations?

The questions

What if the specifications don't explicitly say "this guy is the one in charge of handling this situation"? What if a third person implements another query (similar to the first one, but on another DB) and uses your UI code to display it, but doesn't handle this case in his code?

Should I do what's necessary to prevent a possible crash, even if I'm not the one supposed to handle the bad case?

I'm not looking for an answer like "(s)he's the one responsible for the crash", as I'm not solving a conflict here, I'd like to know, should I protect my code against situations it's not my responsibility to handle? Here, a simple "if empty do something" would suffice.

In general, this question tackles redundant exception handling. I'm asking it because when I work alone on a project, I may code 2-3 times a similar exception handling in successive functions, "just in case" I did something wrong and let a bad case come through.


答:
It depends on what it is you're testing; but let's assume the scope of your test is your own code only. In that case, you should test:

The "happy case": feed your application valid input and make sure it produces correct output.

The failure cases: feed your application invalid inputs and make sure it handles them correctly.

In order to do this, you cannot use your colleague's component: instead, use mocking, that is, replace the rest of the application with "fake" modules that you can control from the testing framework. How exactly you do this depends on the way the modules interface; it can be enough to just call your module's methods with hard-coded arguments, and it can become as complex as writing a whole framework that connects the other modules' public interfaces with the testing environment.

That's just the unit test case, though. You also want integration tests, where you test all the modules in concert. Again, you want to test both the happy case and the failures.

In your "Basic Example" case, to unit-test your code, write a mock class that simulates the database layer. Your mock class doesn't really go to the database though: you just pre-load it with expected inputs and fixed outputs. In pseudocode:

```<code>function test_ValidUser() {
    // set up mocking and fixtures
    userid = 23;
    db = new MockDB();
    db.fixedResult = { firstName: "John", lastName: "Doe" };
    db.expectedCall = { method: 'getUser', params: { userid: userid } };
    userController = new UserController(db);
    expectedResult = "John Doe";

    // run the actual test
    actualResult = userController.displayUserAsString(userid);

    // check assertions
    assertEquals(expectedResult, actualResult);
    db.assertExpectedCall();
}
</code>```

And here's how you'd test for missing fields that are reported correctly:

```<code>function test_IncompleteUser() {
    // set up mocking and fixtures
    userid = 57;
    db = new MockDB();
    db.fixedResult = { firstName: "John", lastName: "NA" };
    db.expectedCall = { method: 'getUser', params: { userid: userid } };
    userController = new UserController(db);

    // let's say the user controller is specified to leave "NA" fields
    // blank
    expectedResult = "John";

    // run the actual test
    actualResult = userController.displayUserAsString(userid);

    // check assertions
    assertEquals(expectedResult, actualResult);
    db.assertExpectedCall();
}
</code>```

Now things become interesting. What if the real DB class misbehaves? For example, it could throw an exception for unclear reasons. We don't know if it does, but we want our own code to handle it gracefully. No problem, we just need to make our MockDB throw an exception, e.g. by adding a method like this:

```<code>class MockDB {
    // ... snip
    function getUser(userid) {
        if (this.fixedException) {
            throw this.fixedException;
        }
        else {
            return this.fixedResult;
        }
    }
}
</code>```

And then our test case looks like this:

```<code>function test_MisbehavingUser() {
    // set up mocking and fixtures
    userid = 57;
    db = new MockDB();
    db.fixedException = new SQLException("You have an error in your SQL syntax");
    db.expectedCall = { method: 'getUser', params: { userid: userid } };
    userController = new UserController(db);

    // run the actual test
    try {
        userController.displayUserAsString(userid);
    }
    catch (DatabaseException ex) {
        // This is good: our userController has caught the raw exception
        // from the database layer and wrapped it in a DatabaseException.
        return TEST_PASSED;
    }
    catch (Exception ex) {
        // This is not good: we have an exception, but it's the wrong kind.
        testLog.log("Found the wrong exception: " + ex);
        return TEST_FAILED;
    }
    // This is bad, too: either our mocking class didn't throw even when it
    // should have, or our userController swallowed the exception and
    // discarded it
    testLog.log("Expected an exception to be thrown, but nothing happened.");
    return TEST_FAILED;
}
</code>```

These are your unit tests. For the integration test, you don't use the MockDB class; instead, you chain both the actual classes together. You still need fixtures; for example, you should initialize the test database to a known state before running the test.

Now, as far as responsibilities go: Your code should expect the rest of the codebase to be implemented per the specification, but it should also be prepared to handle things gracefully when the rest screws up. You are not responsible for testing other code than your own, but you are responsible for making your code resilient to misbehaving code on the other end, and you are also responsible for testing your code's resilience. That's what the third test above does.

Body:
It depends on what it is you're testing; but let's assume the scope of your test is your own code only. In that case, you should test:

The "happy case": feed your application valid input and make sure it produces correct output.

The failure cases: feed your application invalid inputs and make sure it handles them correctly.

In order to do this, you cannot use your colleague's component: instead, use mocking, that is, replace the rest of the application with "fake" modules that you can control from the testing framework. How exactly you do this depends on the way the modules interface; it can be enough to just call your module's methods with hard-coded arguments, and it can become as complex as writing a whole framework that connects the other modules' public interfaces with the testing environment.

That's just the unit test case, though. You also want integration tests, where you test all the modules in concert. Again, you want to test both the happy case and the failures.

In your "Basic Example" case, to unit-test your code, write a mock class that simulates the database layer. Your mock class doesn't really go to the database though: you just pre-load it with expected inputs and fixed outputs. In pseudocode:

function test_ValidUser() {
    // set up mocking and fixtures
    userid = 23;
    db = new MockDB();
    db.fixedResult = { firstName: "John", lastName: "Doe" };
    db.expectedCall = { method: 'getUser', params: { userid: userid } };
    userController = new UserController(db);
    expectedResult = "John Doe";

    // run the actual test
    actualResult = userController.displayUserAsString(userid);

    // check assertions
    assertEquals(expectedResult, actualResult);
    db.assertExpectedCall();
}

And here's how you'd test for missing fields that are reported correctly:

function test_IncompleteUser() {
    // set up mocking and fixtures
    userid = 57;
    db = new MockDB();
    db.fixedResult = { firstName: "John", lastName: "NA" };
    db.expectedCall = { method: 'getUser', params: { userid: userid } };
    userController = new UserController(db);

    // let's say the user controller is specified to leave "NA" fields
    // blank
    expectedResult = "John";

    // run the actual test
    actualResult = userController.displayUserAsString(userid);

    // check assertions
    assertEquals(expectedResult, actualResult);
    db.assertExpectedCall();
}

Now things become interesting. What if the real DB class misbehaves? For example, it could throw an exception for unclear reasons. We don't know if it does, but we want our own code to handle it gracefully. No problem, we just need to make our MockDB throw an exception, e.g. by adding a method like this:

class MockDB {
    // ... snip
    function getUser(userid) {
        if (this.fixedException) {
            throw this.fixedException;
        }
        else {
            return this.fixedResult;
        }
    }
}

And then our test case looks like this:

function test_MisbehavingUser() {
    // set up mocking and fixtures
    userid = 57;
    db = new MockDB();
    db.fixedException = new SQLException("You have an error in your SQL syntax");
    db.expectedCall = { method: 'getUser', params: { userid: userid } };
    userController = new UserController(db);

    // run the actual test
    try {
        userController.displayUserAsString(userid);
    }
    catch (DatabaseException ex) {
        // This is good: our userController has caught the raw exception
        // from the database layer and wrapped it in a DatabaseException.
        return TEST_PASSED;
    }
    catch (Exception ex) {
        // This is not good: we have an exception, but it's the wrong kind.
        testLog.log("Found the wrong exception: " + ex);
        return TEST_FAILED;
    }
    // This is bad, too: either our mocking class didn't throw even when it
    // should have, or our userController swallowed the exception and
    // discarded it
    testLog.log("Expected an exception to be thrown, but nothing happened.");
    return TEST_FAILED;
}

These are your unit tests. For the integration test, you don't use the MockDB class; instead, you chain both the actual classes together. You still need fixtures; for example, you should initialize the test database to a known state before running the test.

Now, as far as responsibilities go: Your code should expect the rest of the codebase to be implemented per the specification, but it should also be prepared to handle things gracefully when the rest screws up. You are not responsible for testing other code than your own, but you are responsible for making your code resilient to misbehaving code on the other end, and you are also responsible for testing your code's resilience. That's what the third test above does.


问:
UML modelling semantics
In today's lecture about Modelling techniques with respect to MDD using UML the lecturer stated that it's absolutely necessary to give a (possibly) textual description about the semantics of each diagram you produce.

In my opinion it's not necessary to describe semantics of diagram elements which are already standardized by UML. I can see that it's completely appropriate if you extend the standard UML by stereotypes/tagged values for any reason.

In contrast, I think that standardization has in the ordinary case the intention to let people reason and talk about diagrams without the need to explain semantics every time. The only precondition is of course that they all rely on the same UML specification.

Another point regarding MDD is that using different semantics from time to time for the same diagram kind makes code generation and automatic model transformation difficult in the end.

Am I right with this notion?

Are there some inherent interpretation ambiguities in UML to make it more general usable?

答:
In my opinion it's not necessary to describe semantics of diagram elements which are already standardized by UML.

Yes, there would be no need to describe the semantics of diagram elements when that semantics would be properly defined somewhere in the UML standard. The problem is that, especially with MDD, the full semantics depends on the code generation for those elements, and since there is no widely accepted standard for the UML-to-code-mapping, the UML standard does simply not define the whole semantics for it's elements. In fact, even the "UML semantics" paragraphs in the standard deals primarily with UML syntax and gives only a very informal notion about the semantics.

Of course, when doing MDD, and you have your code generators in place, you can create a meta-description just once, telling which semantics applies to you/your team/your project/your company, instead of deploying the same description with each diagram again-and-again.

Here is a scientific paper dealing with the problem that UML semantics is mostly informal. A google search for "uml semantic rules" will bring you more papers discussing that topic in-depth.

Title: UML modelling semantics


问:
Agile MVP (Most Valuable Player/Programmer)
Recently I've been involved in an agile project (using scrum) where management came up with the idea that the team would nominate a developer 'MVP' as well as a QA 'MVP' at the end of each sprint, voted on by the team.  The MVP then gets a small monetary reward and free lunch as well as a trophy to display on his desk.  We've had two sprints so far with this reward system in place.

The good I see from this is the following:

More bugs have been fixed (which is what upper management wants to see, a number change in the direction they want)

The MVP from each 'team' gets recognized and gets a self esteem boost (or is it an ego boost?)

I've noticed a few what I would consider bad sides to doing such a thing (at least from a developer standpoint):

There are a few developers who are so concerned with the number that the quality of bug fixes has gone down. Fixes in one area are causing regressions in another.

There are a few developers who are cherry picking 'easier/quicker' bugs to boost their bug count.  Could be good of bad here I guess.

Higher priority (which a lot of the time correlates to 'harder/longer to fix') defects actually become lower priority.

Blocking defects are not addressed in a timely manner, as usually they take longer and require more coordination with QA.

The team aspect within the Dev team has been lost.  The team aspect of Dev and QA working together as one hasn't improved either, but hasn't really changed too much from before.

Work beyond bug fixes, or working towards THAT number, isn't easily recognizable/tracked.

I do believe that each of the 'bad' above can be addressed to some degree, depending on how the team handles each.

My question is, then, has anyone successfully pulled anything like this off, where you recognize an MVP per sprint?  If so, what do you think contributed to that success?

答:
Some sort of group recognition of the efforts of a team member can be a valuable motivator, but in this case it sounds like it's being misapplied. You state that the MVP is chosen by vote, but there's a lot of mentions of numbers of bugs fixed per sprint. It sounds like your time has a funny definition of MVP - I would assume that the person who deserves the title of "most valuable" is the person who added most value to the software in that sprint. If a team member is picking out bugs that can be fixed quickly, blasting through them as fast as possible, and causing regression bugs and other problems in their wake, then they're not adding value, they're creating more work for whoever has to follow them around identifying and fixing those problems.

My suggestion would be to try to start a proper discussion the next time your team has one of these votes. Don't just make it a show of hands; talk it through first. If someone seems to be gaining votes based on the sheer number of "fixes" they've made, point out (tactfully) where those fixes caused regressions, and suggest that perhaps the person who fixed those regressions should be nominated for cleaning up other people's mess. If someone spent the whole sprint slaving away on one nasty issue, point that out to the team, highlighting the fact that although this person's fix count is one, they've single-handedly solved a major problem with your software - a problem that was so nasty that nobody else wanted to touch it.

Picking out easy fixes and doing them in a rushed or haphazard manner isn't valuable, so developers who just do that probably shouldn't qualify as MVP candidates. When selecting the new MVP, forget all about the team and the people on it, and look at the software. Pick out the single most important change in that software since the last time. I mean single here; "not as many tiny bugs" is not a major change. Has a particularly glaring bug been fixed? Has a great new feature been added? Once you've identified what this one big change is, ask who was responsible for it. One of those people is probably your actual MVP. If "not as many tiny bugs" is the only difference, then and only then is bug count a valid measure of MVP - and even then, I'd look at ratio of bugs fixed to regression bugs caused. Every bug someone causes deducts at least 1 from their count. In fact, I'd say more than 1, because a bad fix will cause an unknown bug that you then have to find, which is worse than a known bug that's been found already. A known bug takes developer effort to fix; an unknown bug takes QA effort to find, and developer effort to fix, and then there's the risk that QA will miss it.

In theory, if developers realise that the way to the prize is to fix fewer, bigger problems, they'll aim for the tough ones, the complex ones, the blocking defects. This will require them to band together sometimes, either because there aren't enough meaty problems to go around, or because the problem is tricky enough to require more sets of eyes. Perhaps suggest that in cases like this, the award could be shared if it's not immediately clear which of a set of people did more work towards fixing a bug - and remember, work done != lines of code written. The developers will probably know that, but you said management is involved, and management don't always understand that point.

And hey, if all else fails, forget the MVP program. Talk to your fellow developers outside of the scrums, and point out the negative impact that the MVP awards are having on the software. See if you can get them to ignore it, or not make it such a big deal. Leave the trophy in a drawer, spend the cash prize on a round of drinks for the team after work, use the free lunch to get something you can share, like a bunch of cupcakes. Agile is a team system; highlighting individual performance risks pitting the team against each other. United you stand, divided you ship bug-filled software, after the deadline, over-budget.


问:
Recompiling dll's and adding more during run time - what are my options?
I want to compile custom functions during run time based on user written scripts. I'll give a hypothetical example that should demonstrate exactly what I need to do. This is the best way for me to describe the problem. I'd like a little input/ideas in how I can solve this. At the bottom I give you my ideas.

I have 2 classes, one with public int x and y. Another with public int x,y,z. There can be more than one instance of each class running.

The thing with these classes though (and here comes my problem) is that they need to be updatable via a user written and then compiled function during run time, that then gets added to a list of update functions that gets run once per cycle/event. Which could be at the touch of some button or something.

Example: The user has written a script to update the public members of Class A. He has written A.X = B.Y + C.Z. The variables here are public, never private. This method needs to be compiled, and added to some list of functions to call each cycle. Obviously this method needs access to class B and C, as well as A. So pointers to those need to be passed in. The function returns nothing.

When I say class A, B, and C. I mean these as some instances of any classes. 'A' could be class Q, while both B and C could be from class T. Or any other variation. These classes do not need recompilation/user written or anything like that.

I just need help with coming up with options and how to compile a function that gets passed in some pointers and does something with them. But with all of that defined run time, what the function does, what gets passed into it, ect.

---- What I think I can do ---

I'm jumping extremely far in knowledge but it is what I always do. So I am just switching from C# to C++ and have little to go on for now while I know little. So all i can do is guess solutions and research them. I'm guessing I could compile a late loading dll for each function, and I'm guessing the dll has to know something about the data structures passed into it so I think it could work to have them in a separate normal dll usable by any program. (The A,B, and C class thingies, or rather Q, and T classes which A,B,and C were instances of in my little demo). So now both the normal program and the dll functions knows all about the classes, and all I have to do is compile the dlls during runtime, load them, and somehow get a pointer to them that my main application has and can call with the appropriate arguments. Then if the user changes the script, the dll unloads, recompiles, loads again, and a new pointer is gotten?

Any help is greatly appreciated. If you can help direct my learning/research I'll learn a lot faster and be able to implement this. Thank you so much!

答: Leverage an existing compiler, like LLVM. This can be embedded into your application to compile custom code at runtime using the JIT feature of LLVM - see the cpp example that appears to do exactly what you need - compile a user-supplied function at runtime and then call it!</p>


问:
3D tiled space viewed one plane at a time; general concepts to understand while programming this?
I am not asking for someone to program this for me, I still would like to do all the programming, however I need some additional mathematical programming background for this kind of stuff because I haven't really dabbled into 3D spaces much and I am thinking lots of potential if-thens and switches could be simplified way down if I think of this concept the right way. I will be using a programming language that supports 2D tiled or text screen  output (think Java). I want to know if there are simple ways to program in the viewing, orienting and moving about this virtual space I am about to describe without resorting to lots of switch statements to control i.e. what the screen will be displaying depending on the PC's location, facing direction and rotation.

Okay so far I am working out concepts of a way to explore a 3D top-down maze type environment with a procedurally generated voxel landscape and a 1x1x1 player character which can view only the eye level plane and the plane 1 unit below it. the PC can move in the following ways; Please note I intend whichever way the PC considers down to be which direction gravity is acting upon it, (unrealistic):

Walk forward to another square unobstructed by a wall or cliff

Turn the face another direction, in which case a different direction becomes the PC's forward face (visually). The PC will always appear to be facing up for the user.

Start scaling a wall, in which case the previously upward direction (out of the screen, towards the user) becomes forward.

Climb down and scale the wall of a pit below, in which case the previously down direction become forward.

Flip upside down and tether off the now ceiling, scaling up or down the tether until the PC hits a floor. in which case it can choose other transportation modes again.

Each time the PC moves, all other entities get their chance to move in a turn based fashion.

This won't be like a Minecraft-esque sandbox, so editing the landscape after generation won't be likely necessary. I will have a screen that views 16x16x2 voxels at a time. I do however like the idea of dynamically allocated chunks. I plan on generating or loading previously generated 16x16x16 chunks of voxels and the adjacent 26 chunks as needed. while unloading out of range chunks and saving them to a file. I want to know the mathematical/conceptual ideas behind generating these chunks and loading already generated chunks. Note I still use the term voxel even though I will only view them as squares on a text screen, because the game space is a 3D grid.

答:
There will be 24 different orientations for your character. So you definitely don't want to go with if/then/else statements.

If you describe your character orientation as a 3x3 matrix (consisting of 0, 1 and -1) then each type of turn is achieved by multiplying that matrix by a rotation matrix (also 0,1&-1).

The orientation matrix

Consider a positive orthonormal axis system X'Y'Z', describing the orientation of your character in your 3D world. Typically, X' would point to the characters right. Y' would point upwards (from the characters perspective) and Z' would point backwards. (forward would seem more logical, but that would not be a right-handed system.)

These 3 vectors make up the columns of the 3x3 orientation matrix.

Note that you still have to keep track of the characters position separately.

Rotations

Whenever the character makes a turn, its orientation matrix changes. This can be achieved through rotation matrices. To perform the rotation, you multiply the rotation matrix it with a vector, or in this case with the entire orientation matrix:

```<code>NewOrientationMatrix = RotationMatrix * OldOrientationMatrix
</code>```

To describe all possible 90 degree rotations around main axes X, Y and Z, you need 6 rotation matrices.

eg. A 90 degree rotation around the Z axis, clockwise when looking against the positive Z direction, would be:

```<code>0 -1  0
1  0  0
0  0  1
</code>```

Note that these rotation matrices are specified in absolute space (XYZ), not in X'Y'Z'.

Transform to the Characters Viewpoint

Suppose you have a point in 3D space, and you want to know where this point lies, relative to your character:

First you subtract the characters position:

```<code>point - charactersPosition
</code>```

Now, you want to decompose this vector to X', Y' and Z' components. For that you multiply with the inverse (which is in this case the transpose) of your orientation matrix:

```<code>relativePoint = Transpose(OrientationMatrix) * (point - charactersPosition)
</code>```

Eg. If the result is (3,0,-1) then this point lies 3 units to the characters right, one unit forward and same height.

Body:
There will be 24 different orientations for your character. So you definitely don't want to go with if/then/else statements.

If you describe your character orientation as a 3x3 matrix (consisting of 0, 1 and -1) then each type of turn is achieved by multiplying that matrix by a rotation matrix (also 0,1&-1).

The orientation matrix

Consider a positive orthonormal axis system X'Y'Z', describing the orientation of your character in your 3D world. Typically, X' would point to the characters right. Y' would point upwards (from the characters perspective) and Z' would point backwards. (forward would seem more logical, but that would not be a right-handed system.)

These 3 vectors make up the columns of the 3x3 orientation matrix.

Note that you still have to keep track of the characters position separately.

Rotations

Whenever the character makes a turn, its orientation matrix changes. This can be achieved through rotation matrices. To perform the rotation, you multiply the rotation matrix it with a vector, or in this case with the entire orientation matrix:

NewOrientationMatrix = RotationMatrix * OldOrientationMatrix

To describe all possible 90 degree rotations around main axes X, Y and Z, you need 6 rotation matrices.

eg. A 90 degree rotation around the Z axis, clockwise when looking against the positive Z direction, would be:

0 -1  0
1  0  0
0  0  1

Note that these rotation matrices are specified in absolute space (XYZ), not in X'Y'Z'.

Transform to the Characters Viewpoint

Suppose you have a point in 3D space, and you want to know where this point lies, relative to your character:

First you subtract the characters position:

point - charactersPosition

Now, you want to decompose this vector to X', Y' and Z' components. For that you multiply with the inverse (which is in this case the transpose) of your orientation matrix:

relativePoint = Transpose(OrientationMatrix) * (point - charactersPosition)

Eg. If the result is (3,0,-1) then this point lies 3 units to the characters right, one unit forward and same height.


问:
Binary Search Programming implementation
Binary Search, as we all know requires the elements to be sorted. But we have to take care of unsorted elements too, in the worst case. If the input size is very large, is it a good idea to sort the elements everytime? Can we not just check the elements that they are not sorted or not and proceed to sorting and proceed to sorting only if they are unsorted?</p>

答:
checking if a list is sorted defeats the purpose of the binary search (using less comparisons for a O(log n) running time instead of a O(n))

you are better of doing a linear search if you can't be sure the list is already sorted


问:
Ship Early, Ship Never
This started as a "Note to Self," so please excuse me if the frustration is all too evident and the writing is less than stellar...

Three major subjects I've had at the forefront of my mind lately:

Motivation

Learning (Curiosity)

Doing (Making)

I've been studying motivation and incentives for months now. It seems there are an infinite number of different motivations that people might have for doing things (I realize that sounds trite but bear with me). I've been really drawn to it because I'm desperate to find out why I do the things I do and why I don't do the things that I want to do but don't do.

I'm in the midst of reading Paul Graham's excellent Hackers and Painters book. In it, he makes the case that hackers and painters are very similar because they are both "makers." Painters make paintings. Hackers make software. Painters don't necessarily need to understand the chemical composition of paint to make beautiful paintings. And hackers don't necessarily need to know 1's and 0's to make beautiful software.

Graham then draws the distinction between disparate computer science fields:

some people seem to be studying mathematics

some people seem to be studying the computers themselves

the hackers are making software.

The difference is incredibly important. It seems the motivation for some is to make beautiful things. And the motivation for the others is to learn out of curiosity. Certain motivations seem obvious to me, but curiosity seems a bit less obvious. I would certainly consider myself as a curious person with a seemingly unquenchable thirst to learn just about everything I can. But this is exactly where the problem comes up.

The thing that scares me so much is that I desperately want to make things. I desperately want to do things. I want to write a book. I want to paint a painting. I want to compose a song. I want to do things like travel. But the strangeness is that I also want to learn things. I want to learn to play guitar. I want to learn about art history. I want to learn more about philosophy and literature.

The key seems to be the balance between learning and doing... between studying and making.

While I'm not sure how much one should learn about a given thing before doing it, I know for certain that I find myself constantly on one side rather than the other. As it stands now (and as far as I can tell I've always been this way), I am a learner and not a doer. I've read great books. I've practiced guitar for years. I've spent countless hours studying programming.

But I've written 0 books. I've composed 0 songs. I've coded 0 beautiful programs. I've painted 0 beautiful paintings. I've started 0 viable businesses.

The scary part of all this is that there are probably countless unfinished works of art in the world. Is this my misanthropic revenge against society and culture to never produce or finish any of the works of art that I start? Perhaps the worst part (aside from this being my natural inclination), is the fact that I f***ing know better. I just finished books like "Getting Things Done" and "Making Ideas Happen." I've aggregated and synthesized countless words of wisdom on how to do things and how to make things.

Imagine the horror of going through life without being able to do the things you want to do. If this is something you've struggled with (and hopefully overcome), please share. If not... perhaps some delicious pity would make me feel better.

[UPDATE: Just wanted to send a quick thanks to everyone that shared their thoughts. I deliberately left the question somewhat open-ended in hopes of encouraging discussion and having others refashion the central problem around their similar experience, and I think it worked out great... there's a lot of amazing insight here to work with and it was really helpful. Thanks again.]

答:
why I do the things I do and why I don't do the things that I want to do but don't do.

That is the definition of "you".

the brain

For an oversimplified view1, imagine: a lizard core, crying for food, reproduction and torpidity. Around: a shell of mammal brain - barely aware of itself, able to manipulate its environment to get high on the lizard's kicks. Riding on to of it, a giant programmable gate array, finally finding purpose in itself, for which the rest of the body is just a vessel. That's what we call "human" - but it's the youngest and weakest part; when it lets slip control, the mammal, the lizard take over. Control works like a muscle: it can be tired, and it can be trained.

"You" is the fight between the three (or - if you prefer a more poetic wording - their dance.)

A reason for the dissonance

The rider yearns for the late gratification of having written a novel, the mammal for the kick it gets out of another round of Starcraft.

On Trying, and Doing

Ray Bradbury2 once said: when he was twenty, he decided to write the amount of a short story every week. He forced himseld to sit down, and do that - no matter what comes out. Because when he does that much,  at least some of it must be great.

Hearing that shook me, because I highly adore a lot of his works, and - probably like you - whatever I do I want to do it right.

But in my opinion, he succeeded.

Do Do Do Do Do

Jonah Lehrer (unfortunately, can't find the post nor any link anymore) cited a comparative study that showed that world-class excellence in music doesn't correlate with social or political background or education, but with one thing: the endurance to practice 5 or more hours nearly every day for years. Now you might claim that they were just lucky: their brain was wired to get addicted to practice.

But hey, monkey brain can be trained.

1 with apologies to William Gibson and Jonah Lehrer

2 Yes, that one (NRSFW)

ContentLicense: CC BY-SA 2.5

Title: Ship Early, Ship Never


答:
I don't think that the point of the lecturer is that the comments should teach over and over what UML represents. Instead, I interpret your question as a special case of: Do I need to comment my code? If yes, how?.

The usual controversy is around whether your production (being code or UML) is self documenting thus needing no comments, or whether comments actually add some value to your production, or whether comments stay consistent with your production.

Title: UML modelling semantics

Body:
In today's lecture about Modelling techniques with respect to MDD using UML the lecturer stated that it's absolutely necessary to give a (possibly) textual description about the semantics of each diagram you produce.

In my opinion it's not necessary to describe semantics of diagram elements which are already standardized by UML. I can see that it's completely appropriate if you extend the standard UML by stereotypes/tagged values for any reason.

In contrast, I think that standardization has in the ordinary case the intention to let people reason and talk about diagrams without the need to explain semantics every time. The only precondition is of course that they all rely on the same UML specification.

Another point regarding MDD is that using different semantics from time to time for the same diagram kind makes code generation and automatic model transformation difficult in the end.

Am I right with this notion?

Are there some inherent interpretation ambiguities in UML to make it more general usable?


答:
There are 3 main principles I try to code by:

DRY

KISS

YAGNI

The rub off all these is that you risk writing validation code that is duplicated elsewhere. If the validation rules change, these would need to be updated in multiple places.

Of course, at some point in the future, you might replatform your database (it happens) in which case you might think having the code in more than one place would be advantageous. But...you're coding for something that may not happen.

Any additional code (even if it never changes) is overhead as it will need to be written, read, stored and tested.

All the above being true, it would be remiss of you to do no validation at all. To display a full name in the application, you would need some basic data - even if you don't validate the data itself.


问:
What can I use to keep track of the status of 60 programs, some of which are obsolete?
I've taken a software development role in an engineering company(all software developed is for internal use only). The company has about 60 individual programs from past developers.  The problem is that all past developers are gone and no one knows why about half of the software was built, who uses it, or even what some of it does.  We use SVN, but no past developers wrote comments or did any sort of documentation.

Assuming I figure all of this out, is there some program/system/method that could be used to keep track of all this information?  The company is leaning toward Excel, I'm assuming there's something better.  Would it just be better to write up documentation in a Word Doc and commit it to svn so it's right next to the code?

答:
I use text files inside the project for that sort of thing.  They're easy to maintain, easy to find and tough to misplace.  Word or Excel would probably work just as well if you need to share but you'll need more discipline to write in some sort of log format so you can easily tell what changed when.

On a side note, I'd aggressively attempt to retire as many of those projects as possible - it's a lot easier to manage 20 projects than 60.


答:
From what you're describing, it is inevitable that some work will have to be done to get a good idea of what you're dealing with here.

SVN is just the repository. It is meant to store your work in a way that enables you to make mistakes without that leading to big problems. It shouldn't be used to take care of project management!

If you can get some kind of funds for a cheap server running some software development project management/ALM software, it could help you out in terms of tracking development and user queries, all linked to your repo! I'm a big fan of using ALM software. It can help you communicate and plan your development in a way that makes the human link less of a dependency. If used properly, it can really help you structure your process. (It requires some discipline)

If you have the funds to run a windows server, go TFS. It seems a good fit to what you're describing, but costs more money compared to FOSS tools. On the other hand, it is a very nicely integrated set of tools, so it'll let you manage your projects in a nicely integrated environment with a shallow learning curve. (Assuming you don't want anything special. TFS is highly configurable, but a PITA to configure if you haven't worked with the techs involved before.)

FOSS alternatives that I like are: trac, redmine or chilliproject. Except for redmine, I've only used those as a user, so I can't really tell you how easy it is to set them up.

If management won't go any further than Excel, you're out of luck. It's down to common sense in that case. I'd suggest having some kind of overview sheet and one workbook per project with one page for bug tracking, one page for release planning, and one page for documenting releases. (Just made that up now, but seems a start if you're unable to get hold of proper tools to do your job)

In terms of who's using that softare? That's anyone's guess. The only way to tell is by polling potential users, unless they have connections over the network that you could scan for with the help of a/the network administrator. As far as telling what software does, you're going to have to analyse it if no docs are available and noone is able to provide you that info. The fast but inaccurate way would be to run it in some kind of sandbox and take a look. The slow but complete way would be to review the code. (Maybe reverse engineer it with the help of an UML tool with round trip capabilties for a quick overview of the structure)

As for as the no documentation part. This looks like a good time to point out the necessity of documentation. Docs have two sides: commenting code and creating overview/usage docs.

Title: What can I use to keep track of the status of 60 programs, some of which are obsolete?

Body:
I've taken a software development role in an engineering company(all software developed is for internal use only). The company has about 60 individual programs from past developers.  The problem is that all past developers are gone and no one knows why about half of the software was built, who uses it, or even what some of it does.  We use SVN, but no past developers wrote comments or did any sort of documentation.

Assuming I figure all of this out, is there some program/system/method that could be used to keep track of all this information?  The company is leaning toward Excel, I'm assuming there's something better.  Would it just be better to write up documentation in a Word Doc and commit it to svn so it's right next to the code?


答:
Of course you will need to document as much as possible each project but you will also need a centralized "place" where you have your catalog of services/products, describing the "metadata" of the project as you pointed out: What department is using it? Who is responsible of maintaining it? What is it used for? What dependencies with other projects are there?

That "place" can be anything that works out for you and your company, like a document or an excel sheet. But of course you can use more "complex" tools or products like a wiki, a document management system, or specialized products on the matter.

I recommend you to take a look at ITIL, where they define what they call the ITIL Service Catalog: https://www.google.com/search?q=itil+service+catalog, just to have an idea.


答:
As Dan points out, having a readme.txt in the project is cruical -- it doesn't need to be thick but it should cover enough to get a trained person building and debugging the code. The key things to cover are external configurations and dependencies and other landmine sort of things.

I would also advise using a project tracking tool with SCM integration. Personally I'm partial to redmine these days. If used properly they tend to be nice, easy, self-feeding documentation stores over time. I find our redmine is especially invaluable for occasions when one has to dive into a project that has been dormant for a long time as there are things one can learn from redmine that one can't learn from other project tools.


答:
One of the easiest adjustments to make to ensure something like an MVP program works is to reward team members for being the most valuable to the team's success, not being the hardest worker.

We've done this successfully by recognizing people who didn't even work on bugs, or features, but did something awesome that made everybody on the team succeed better.  For example, we had one developer who took on the task of mentoring a bunch of new members to the team so they could learn the architecture and how we worked.  Our velocity jumped up because we had these new recruits able to deliver results quickly and efficiently, even though individually that one developer's velocity went down because he was spending more time on helping the rest of the team.

Reward teamwork, and the team will notice that it's the TEAM that matters, not their own personal success.

Title: Agile MVP (Most Valuable Player/Programmer)

Body:
Recently I've been involved in an agile project (using scrum) where management came up with the idea that the team would nominate a developer 'MVP' as well as a QA 'MVP' at the end of each sprint, voted on by the team.  The MVP then gets a small monetary reward and free lunch as well as a trophy to display on his desk.  We've had two sprints so far with this reward system in place.

The good I see from this is the following:

More bugs have been fixed (which is what upper management wants to see, a number change in the direction they want)

The MVP from each 'team' gets recognized and gets a self esteem boost (or is it an ego boost?)

I've noticed a few what I would consider bad sides to doing such a thing (at least from a developer standpoint):

There are a few developers who are so concerned with the number that the quality of bug fixes has gone down. Fixes in one area are causing regressions in another.

There are a few developers who are cherry picking 'easier/quicker' bugs to boost their bug count.  Could be good of bad here I guess.

Higher priority (which a lot of the time correlates to 'harder/longer to fix') defects actually become lower priority.

Blocking defects are not addressed in a timely manner, as usually they take longer and require more coordination with QA.

The team aspect within the Dev team has been lost.  The team aspect of Dev and QA working together as one hasn't improved either, but hasn't really changed too much from before.

Work beyond bug fixes, or working towards THAT number, isn't easily recognizable/tracked.

I do believe that each of the 'bad' above can be addressed to some degree, depending on how the team handles each.

My question is, then, has anyone successfully pulled anything like this off, where you recognize an MVP per sprint?  If so, what do you think contributed to that success?


答:
I think it's a good example of -bad- gamification being applied. The problem is that your programmers potentially had intrinsic motivation in solving problems and winning though challenges (finding and fixing hard bugs) AND, since you've implemented Scrum, in working as a TEAM. In other words, they potentially wanted to do a good job.

Now, at least for some of them, this intrinsic motivation or part of it has been replaced with extrinsinc motivation consisting in titles ("MVP of the week") and rewards (monetary amount, and free lunch), which are game mechanics often part of a gamified process.

Gamification can be applied successfully at work but you have to be very careful in leveraging intrinsic/extrinsic motivation. Extrinsic motivation has to power to fuel self-determination in order for the motivation to become intrinsic. However what happened here is the reverse, programmers are "gaming the game" in order to win.

What you could do to fix this is to ask the management to change the rules a bit:

give points matching the difficulty and priority of the tickets. Make it so that it is much more interesting, points-wise, to fix a hard to find/reproduce bug.

give points for solving problems cooperatively (again, the TEAM). This is where you could get more programmers to interact with the QA. Give points for a problem being solved cooperatively by a programmer AND a QA for example.

give different titles, one for the most points, and one for the most tickets. This should satisfy the competitive instincts of the programmers.

possibily establish a friendly competition between the Dev and the QA by summing up points of every member of a team

Reducing the possibility of regression bugs appearing however is another problem. You could for example apply negative points, but I'm sure it's not a good idea since it would be a form of punishment. What would be better perhaps is to automatically start a sprint with a few points if no regression bug has been detected in the past week. If regression bugs have been detected, the programmer starts with 0.

Also, in "gamification" there is "game". And the fundamental aspect of a game is that you play/participate voluntarily. In the context of work, it may be imposed by the management which is the case here, but normally no one should be forced into this.

To conclude, this MVP thing is not necessarily a bad idea, but the approach could be changed a little bit to make business (solving important bugs) come first, and emphasize teamwork rather than individuals.


问:
Is it a bad practice to modify code strictly for testing purposes
I have a debate with a programmer colleague about whether it is a good or bad practice to modify a working piece of code only to make it testable (via unit tests for example).

My opinion is that it is OK, within the limits of maintaining good object oriented and software engineering practices of course (not "making everything public", etc).

My colleague's opinion is that modifying code (which works) only for testing purposes is wrong.

Just a simple example, think of this piece of code that is used by some component (written in C#):

```<code>public void DoSomethingOnAllTypes()
{
    var types = Assembly.GetExecutingAssembly().GetTypes();

    foreach (var currentType in types)
    {
        // do something with this type (e.g: read it's attributes, process, etc).
    }
}
</code>```

I have suggested that this code can be modified to call out another method that will do the actual work:

```<code>public void DoSomething(Assembly asm)
{
    // not relying on Assembly.GetExecutingAssembly() anymore...
}
</code>```

This method takes in an Assembly object to work on, making it possible to pass your own Assembly to do the testing on. My colleague didn't think this is a good practice.

What is considered a good and common practice ?

答:
I've used code coverage tools as part of unit testing in checking whether all paths through the code are exercised. As a pretty good coder/tester on my own, I usually cover 80-90% of the code paths.

When I study the uncovered paths and make an effort for some of them, that's when I discover bugs such as error cases that will "never happen". So yes, modifying code and checking for test coverage makes for better code.


问:
Worst coding standard you've ever had to follow?
Have you ever had to work to coding standards that:

Greatly decreased your productivity?

Were originally included for good reasons but were kept long after the original concern became irrelevant?

Were in a list so long that it was impossible to remember them all?

Made you think the author was just trying to leave their mark rather than encouraging good coding practice?

You had no idea why they were included?

If so, what is your least favorite rule and why?

Some examples here

答:
Local variable names are all lowercase with no underscores

Real examples: paymentmethodtotalshtml, contracttypechangecontexts, customsegmentspectexts, potentialmsceventref

The New York Times weighs in:

“Word spaces should not be taken for granted. Ancient Greek, the first alphabet to feature vowels, could be deciphered without word spaces if you sounded it out, and did without them. […] Latin, too, ceased to separate words by the second century. The loss is puzzling, because the eye has to work much harder to read unseparated text. But as the paleographer Paul Saenger has explained, the ancient world did not desire ‘to make reading easier and swifter.’”


答:
This is a classic example of how a specific practice (public recognition as MVP) can have a significant yet indirect impact in how your team behaves.  This goes beyond incentives, motivations, and rewards and actually touches on ideas in environmental/behavioral psychology and decision architecture.  Cool stuff.

The question is -- how can you design a process so that your team just seems to do all the right things naturally, without having to put in place rigid policies or forcing people to do something?

I've written about using affordances (in the tradition of Donald Norman's Design of Everyday Things) for processes as a mechanism for designing a process that works for your team.  The basic idea is that the practices in a process directly influence a person's behavior.  As such, problems arise when the affordances in your process are not fully aligned with your team's values.

I've run several workshops on this topic and this particular issue comes up as an example in groups from time to time.  Applying the theory of affordances to the case you shared in your question might look something like this.....

Assume your team values consistency, predictability, and high quality code.

You've got a laundry list of negative behaviors that you have observed and they all seem to stem from using defect metrics to pick a team MVP.  For example, teammates seem to naturally want to haphazardly pick and fix bugs, negatively impacting all three of your values.  (I'm assuming that there was a problem before too, and this is what led to the MVP idea).

Rather than having a single MVP based on defect metrics, we will try to change team behavior by making some small, but significant changes.

Let anyone give a "team kudo" to any (and all, not just one) individuals who demonstrably embrace your team values.  This will promote predictability be democratizing the team value system through examples.  (We actually do this on our team..)

Start pair programming (or assign "bug buddies") for all bug fixing.  This will promote quality by discouraging hasty or half-assed programming decisions and encourage consistency because buddies will temper erratic behavior.  (This idea is commonly suggested during the workshops, seems intuitive..)

And these are just some examples to demonstrate the approach and get you started...

What's great about this approach is that you are actively designing your process changes and have justifiable reasons for the process changes you make.  Just like in object or UI design, you can even measure outcomes to understand if things are working or not.


答:
I think your colleague is wrong.

Others have mentioned the reasons why this is a good thing already, but so long as you are given the go ahead to do this, you should be fine.

The reason for this caveat is that making any change to code comes at the cost of the code having to be re-tested. Depending what you do, this test work may actually be a large effort by itself.

It is not necessarily your place to make the decision of refactoring versus working on new features which will benefit your company/customer.

Title: Is it a bad practice to modify code strictly for testing purposes

Body:
I have a debate with a programmer colleague about whether it is a good or bad practice to modify a working piece of code only to make it testable (via unit tests for example).

My opinion is that it is OK, within the limits of maintaining good object oriented and software engineering practices of course (not "making everything public", etc).

My colleague's opinion is that modifying code (which works) only for testing purposes is wrong.

Just a simple example, think of this piece of code that is used by some component (written in C#):

```<code>public void DoSomethingOnAllTypes()
{
    var types = Assembly.GetExecutingAssembly().GetTypes();

    foreach (var currentType in types)
    {
        // do something with this type (e.g: read it's attributes, process, etc).
    }
}
</code>```

I have suggested that this code can be modified to call out another method that will do the actual work:

```<code>public void DoSomething(Assembly asm)
{
    // not relying on Assembly.GetExecutingAssembly() anymore...
}
</code>```

This method takes in an Assembly object to work on, making it possible to pass your own Assembly to do the testing on. My colleague didn't think this is a good practice.

What is considered a good and common practice ?


答:
I had to deal with something similar a long time ago.

Maintain a large sorted file and a small unsorted file.  The small one contains items that haven't been merged in yet.  Search the small one first, and, if that fails, then search the large one.  "Every so often", like when the small file gets to be a certain fraction of the size of the large file, sort the small file and then merge it with the large one.

Title: Binary Search Programming implementation

Body: Binary Search, as we all know requires the elements to be sorted. But we have to take care of unsorted elements too, in the worst case. If the input size is very large, is it a good idea to sort the elements everytime? Can we not just check the elements that they are not sorted or not and proceed to sorting and proceed to sorting only if they are unsorted?</p>


答:
I was facing this problem just yesterday. Here are three bits of info I can offer that may help:

Try to keep a database view of the data you need to query that is always sorted.  For example, I had a huge (500k records), unsorted data table that contained, among other things, a column for CompanyName.  In my application, I needed to search these records based on a given company name, which is ripe for a binary search.  I simply created a sorted SQL view that contains only the CompanyName and the id (which is the primary key in the original table`.  Now I query that directly from the application and get the result in under 10ms.

If you can't ensure ahead of time that your data set is sorted, then make good use of hashtables and look into the "Quick Sort" algorithm.  This is a O(log n) algorithm so if you run it first and then a binary search against your data it is surely faster than a linear search.

Also, try to make good use of caching--if you have already sorted a given dataset, there is no reason to do it again for the next query against it.

Good luck!


问:
Software Architecture Modelling
I am a little confused at how best to visually model a space-based architecture (SBA)  for presenting the system/software architecture design to a client.

The goal of this modelling is to show:

The major components of the system (e.g.: databases, server exposed API, client, server workers, client exposed API)

Interactions between these major components

Primary end-to-end workflows

Currently I am thinking to use BPMN2 notation with swimlanes; and sequence & use-case diagrams in UML2 notation.

Not sure if this approach is best, would be great to get some feedback :)

答:
With any architectural modelling and representation you have to consider your audience and what notations will most easily and accurately communicate the designed structures as well as rationale for those decisions.

Two good things --

Using a documented and "standard" architectural style (SBA) helps with communication by way of pattern recognition.  If someone knows the style, knowing that you are using it will help that person understand more easily.

Using a documented and "standard" notation for diagramming will assist with readability in that individuals who know the notation will be able to infer structures and meaning more easily.

The caveat, of course, is that you cannot assume that everyone will already know the styles and notation conventions so you must still use standard diagramming best practices (e.g. legends, clear labels, not mixing perspectives, multiple views and viewpoints, etc.)

The only other catch regarding UML notations for architecture representation is that it can sometimes be challenging to diagram architecture-level concepts using notations designed for object-oriented design.  I don't see how either of the notations you've mentioned will help you model the architecture.  Use cases aren't just pictures.  And business process modelling has nothing to do with structures -- dynamic, static, or physical.

Title: Software Architecture Modelling


问:
Best resource for developing JavaScript curriculum?
At the risk of being downvoted, I really need the community's input - I am helping put together a post-secondary quality curriculum (vocational school, not university) around open-source languages, specifically JavaScript and maybe some Ruby or PHP. There are some great trade books out there, but things get a little more limited when you need a text book with quizzes and an answer key, for example.

I believe this material exists somewhere - is there an online resource or any sort of accreditation body around JavaScript?

I realize this may be considered too 'subjective', but I am having a hard time sifting through the mountains of online JavaScript tutorials and trade books.

答:
I can't speak for their PHP content as I've never used it, but W3Schools have a fantastic javascript section here:

http://www.w3schools.com/js/default.asp

The reason I like this and what would make it good for classes is that they have a "try it yourself" section on every page. This shows you the code, allows you to run it and see the result. You can then play with it and modify as you want and run again.

On its own it might not be enough, but if there will be someone to answer questions and lead the class I think this would be at least a great place to start. You could use the "try it yourself" sections as places to set assignments. E.g. this shows how to change the style of a div, now make it change the div to look like this ...


问:
What concept am I missing with private methods and testing?
I've read a lot o blogs arguing about private methods and testing. Some people say you should not test private methods, they say you should make them public or put those methods in a new class.

But then, what about encapsulation? let's say:

I have this method which is simple enough for not being part of a new class, and

It can be useful only for internal stuff, so there's not a good reason to make it public.

My general rule about methods being public or private is simple, if it's useful outside it's public, if it's useful just inside then it's private. Am I missing something with this logic?

答:
No I would completely agree with you and a similar logic was thought to me in college. We were thought basically, make it private in all cases unless you need to access it from somewhere else.

Many Times I would make a private method as a way to cut down code duplication. Say I have 3 public methods that all at some point need to run similar code. I'm not going to make another public method that is not necessary and possibly dangerous if its a group project, I'm not going to have the code there 3 times making it unmanageable, I'm going to make a private method and call it 3 times, thats basic programming knowledge.

As for not testing it? never in my life would I finish a project without testing a method ... deliberately of course.

I find the statements you've read on blogs to be completely ridiculous, you should stay away from these blogs or authors as they are not programmers.


问:
In languages that don't allow underscores in integer constants, is it a good practice to create a constant for 1 billion?
In languages that don't allow underscores in integer literals, is it a good idea to create a constant for 1 billion?  e.g. in C++:

```<code>size_t ONE_BILLION = 1000000000;
</code>```

Certainly, we shouldn't create constants for small numbers like 100.  But with 9 zeros, it's arguably easy to leave off a zero or add an extra one in code like this:

```<code>tv_sec = timeInNanosec / 1000000000;
tv_nsec = timeInNanosec % 1000000000;
</code>```

答:
I personally wouldn't consider it good practice to create a constant unless it needs to be a constant. If its going to be in multiple places and having it defined at the top of the file for modification / or testing is going to be useful then absolutely.

If its just because its awkward to type ? then no.

Personally if I got someone else's code that had a constant defined, I generally consider this to be an important aspect of the code. E.g. tcp keep alive timers, maximum number of connections allowed. If I had to debug it I would probably pay a lot of unneeded attention to it trying to figure out why / where its being used.


答:
In a case like you describe, I would keep the method private. Testing (especially unit tests) should give you good coverage of your class without needing to know the implementation. If the tests are too coupled to the implementation (rather than desired behavior) then the class will feel brittle and hard to work with.

If you do your job correctly, your private method should be thoroughly tested (code coverage) indirectly by testing the behavior of your class.

Title: What concept am I missing with private methods and testing?

Body:
I've read a lot o blogs arguing about private methods and testing. Some people say you should not test private methods, they say you should make them public or put those methods in a new class.

But then, what about encapsulation? let's say:

I have this method which is simple enough for not being part of a new class, and

It can be useful only for internal stuff, so there's not a good reason to make it public.

My general rule about methods being public or private is simple, if it's useful outside it's public, if it's useful just inside then it's private. Am I missing something with this logic?


问:
Most human-friendly way to order class method definitions?
In any given class definition, I've seen the method definitions ordered in various ways: alphabetical, chronological based on most common usage, alphabetical grouped by visibility, alphabetical with getters and setters grouped together, etc. When I start writing a new class, I tend to just type everything in, then reorder when I'm done writing the entire class. On that note, I've got three questions:

Does order matter?

Is there a "best" order?

I'm guessing there's not, so what are the pros and cons of the different ordering strategies?

答:
tl;dr

Only if the language you're working in requires a specific ordering. Other than that, the ordering is up to you. Pick a system which is consistent and makes sense, and try to stick with it as much as possible.

1 . Does order matter?

Only if the language you are working needs to have a function defined earlier in the file than where it is called, such as in this example:

```<code>void funcA()
{
   funcB();
}

void funcB()
{
   //do something interesting...
}
</code>```

you will get an error because you call funcB() before you use it. I think this is an issue in PL/SQL and possibly in C as well, but you can have forward declarations such as:

```<code>void funcB();

void funcA()
{
   funcB();
}

void funcB()
{
   //do something interesting...
}
</code>```

This the only situation I can think of where if the ordering is "wrong", you won't even be able to compile.

Otherwise, you can always re-order them however you want. You could probably even write a tool to do that for you (if you can't find one out there).

2 . Is there a "best" order?

If the language/environment doesn't have ordering requirements, then the "best" order is the one that works best for you. For me, I like to have all getters/setters together, usually at the beginning of the class (but after constructors/static initializers), and then the private methods, then protected, then public. In each scope-based group there is usually no ordering, though overloaded methods I try to keep together, in order of number of parameters. I also try to keep methods with related functionality together, though sometimes I have to break my scope-based ordering to do so; and sometimes trying to maintain scope-based ordering breaks group-by-functionality. And my IDE can give me an alphabetic outline view, so that's good too. ;)

Some languages, like C# have the ability to group code in "regions" that have no effect on compilation but might make it easier to keep related functions together, then hide/display them with the IDE. As MainMa pointed out, there are some who consider this a bad practice. I have seen good and bad examples of regions being used this way, so if you're going to go this way, be careful.

Body:
tl;dr

Only if the language you're working in requires a specific ordering. Other than that, the ordering is up to you. Pick a system which is consistent and makes sense, and try to stick with it as much as possible.

1 . Does order matter?

Only if the language you are working needs to have a function defined earlier in the file than where it is called, such as in this example:

void funcA()
{
   funcB();
}

void funcB()
{
   //do something interesting...
}

you will get an error because you call funcB() before you use it. I think this is an issue in PL/SQL and possibly in C as well, but you can have forward declarations such as:

void funcB();

void funcA()
{
   funcB();
}

void funcB()
{
   //do something interesting...
}

This the only situation I can think of where if the ordering is "wrong", you won't even be able to compile.

Otherwise, you can always re-order them however you want. You could probably even write a tool to do that for you (if you can't find one out there).

2 . Is there a "best" order?

If the language/environment doesn't have ordering requirements, then the "best" order is the one that works best for you. For me, I like to have all getters/setters together, usually at the beginning of the class (but after constructors/static initializers), and then the private methods, then protected, then public. In each scope-based group there is usually no ordering, though overloaded methods I try to keep together, in order of number of parameters. I also try to keep methods with related functionality together, though sometimes I have to break my scope-based ordering to do so; and sometimes trying to maintain scope-based ordering breaks group-by-functionality. And my IDE can give me an alphabetic outline view, so that's good too. ;)

Some languages, like C# have the ability to group code in "regions" that have no effect on compilation but might make it easier to keep related functions together, then hide/display them with the IDE. As MainMa pointed out, there are some who consider this a bad practice. I have seen good and bad examples of regions being used this way, so if you're going to go this way, be careful.


答:
In some programming languages, order does matter because you can't utilize things until after they've been declared. But barring that, for most languages it doesn't matter to the compiler. So then, you're left with it mattering to humans.

My favorite Martin Fowler quote is: Any fool can write code that a computer can understand. Good programmers write code that humans can understand. So I'd say that the ordering of your class should depend on what makes it easy for humans to understand.

I personally prefer the step-down treatment that Bob Martin gives in his Clean Code book. Member variables at the top of the class, then constructors, then all other methods. And you order the methods to be close together with how they are used within the class (rather than arbitrarily putting all public then private then protected). He calls it minimizing the "vertical distance" or something like that (don't have the book on me at the moment).

Edit:

The basic idea of "vertical distance" is that you want to avoid making people jump all around your source code just to understand it. If things are related, they should be closer together. Unrelated things can be farther apart.

Chapter 5 of Clean Code  (great book, btw) goes into a ton of detail on how Mr. Martin suggests ordering code. He suggests that reading code should work kind of like reading a newspaper article: the high-level details come first (at the top) and you get more detail as you read down. He says, "If one function calls another, they should be vertically close, and the caller should be above the callee, if at all possible." Additionally, related concepts should be close together.

So here's a contrived example which is bad in many ways (poor OO design; never use double for money) but illustrates the idea:

```<code>public class Employee {
  ...
  public String getEmployeeId() { return employeeId; }
  public String getFirstName() { return firstName; }
  public String getLastName() { return lastName; }

  public double calculatePaycheck() {
    double pay = getSalary() / PAY_PERIODS_PER_YEAR;
    if (isEligibleForBonus()) {
      pay += calculateBonus();
    }
    return pay;
  }

  private double getSalary() { ... }

  private boolean isEligibleForBonus() {
    return (isFullTimeEmployee() && didCompleteBonusObjectives());
  }

  public boolean isFullTimeEmployee() { ... }
  private boolean didCompleteBonusObjectives() { ... }
  private double calculateBonus() { ... }
}
</code>```

The methods are ordered so they are close to the ones that call them, working our way down from the top. If we had put all the private methods below the public ones, then you'd have to do more jumping around to follow the flow of the program.

getFirstName and getLastName are conceptually related (and getEmployeeId probably is too), so they are close together. We could move them all down to the bottom, but we wouldn't want to see getFirstName at the top and getLastName at the bottom.

Hopefully this gives you the basic idea. If you're interested in this kind of thing, I strongly recommend reading Clean Code.

Title: Most human-friendly way to order class method definitions?

Body:
In any given class definition, I've seen the method definitions ordered in various ways: alphabetical, chronological based on most common usage, alphabetical grouped by visibility, alphabetical with getters and setters grouped together, etc. When I start writing a new class, I tend to just type everything in, then reorder when I'm done writing the entire class. On that note, I've got three questions:

Does order matter?

Is there a "best" order?

I'm guessing there's not, so what are the pros and cons of the different ordering strategies?

Body:
In some programming languages, order does matter because you can't utilize things until after they've been declared. But barring that, for most languages it doesn't matter to the compiler. So then, you're left with it mattering to humans.

My favorite Martin Fowler quote is: Any fool can write code that a computer can understand. Good programmers write code that humans can understand. So I'd say that the ordering of your class should depend on what makes it easy for humans to understand.

I personally prefer the step-down treatment that Bob Martin gives in his Clean Code book. Member variables at the top of the class, then constructors, then all other methods. And you order the methods to be close together with how they are used within the class (rather than arbitrarily putting all public then private then protected). He calls it minimizing the "vertical distance" or something like that (don't have the book on me at the moment).

Edit:

The basic idea of "vertical distance" is that you want to avoid making people jump all around your source code just to understand it. If things are related, they should be closer together. Unrelated things can be farther apart.

Chapter 5 of Clean Code  (great book, btw) goes into a ton of detail on how Mr. Martin suggests ordering code. He suggests that reading code should work kind of like reading a newspaper article: the high-level details come first (at the top) and you get more detail as you read down. He says, "If one function calls another, they should be vertically close, and the caller should be above the callee, if at all possible." Additionally, related concepts should be close together.

So here's a contrived example which is bad in many ways (poor OO design; never use double for money) but illustrates the idea:

public class Employee {
  ...
  public String getEmployeeId() { return employeeId; }
  public String getFirstName() { return firstName; }
  public String getLastName() { return lastName; }

  public double calculatePaycheck() {
    double pay = getSalary() / PAY_PERIODS_PER_YEAR;
    if (isEligibleForBonus()) {
      pay += calculateBonus();
    }
    return pay;
  }

  private double getSalary() { ... }

  private boolean isEligibleForBonus() {
    return (isFullTimeEmployee() && didCompleteBonusObjectives());
  }

  public boolean isFullTimeEmployee() { ... }
  private boolean didCompleteBonusObjectives() { ... }
  private double calculateBonus() { ... }
}

The methods are ordered so they are close to the ones that call them, working our way down from the top. If we had put all the private methods below the public ones, then you'd have to do more jumping around to follow the flow of the program.

getFirstName and getLastName are conceptually related (and getEmployeeId probably is too), so they are close together. We could move them all down to the bottom, but we wouldn't want to see getFirstName at the top and getLastName at the bottom.

Hopefully this gives you the basic idea. If you're interested in this kind of thing, I strongly recommend reading Clean Code.


答:
I generally order my methods by relation and order of usage.

Take a networking class, I'm going to group all the TCP methods together, then all the UDP methods together. The inside TCP I would have the setup method as the first, maybe send a given message second and close tcp socket as third.

Obviously not all classes will fit in that pattern, but that is my general workflow.

I do it that way for debugging more than anything else, when I have an issue and I want to jump to the method, I don't think how is it spelled, I think what is it responsible for and go to that section.

This way in particular makes sense to a third party viewing / using your code as its grouped together and will be following the order its being used, so the code they will write with your class will follow the same structure as the class.

As regards does it matter ?

for readability, definitely.

other than that not really, only in cases where certain languages you can't call the method unless its defined above where its called etc.


答:
Create one called NANOSECONDS_IN_ONE_SECOND instead as that what it represents.

Or a shorter, better name if you can think of one.

Title: In languages that don't allow underscores in integer constants, is it a good practice to create a constant for 1 billion?

Body:
In languages that don't allow underscores in integer literals, is it a good idea to create a constant for 1 billion?  e.g. in C++:

```<code>size_t ONE_BILLION = 1000000000;
</code>```

Certainly, we shouldn't create constants for small numbers like 100.  But with 9 zeros, it's arguably easy to leave off a zero or add an extra one in code like this:

```<code>tv_sec = timeInNanosec / 1000000000;
tv_nsec = timeInNanosec % 1000000000;
</code>```


问:
Opinions on distribution of software via virtual appliance
I've created a distribution of my open source application framework in a working virtual appliance.  It includes everything to get started with the tutorial.  The distribution is Fedora 14 running Tomcat 5.5 and Oracle 10g Express Edition, plus my framework.  It is completely preconfigured and boots into a working running copy.

Would this be something you might try?

What assurances might you need to get you to try it?

Edit: The VM is just over a 2Gb download.  Alternatively it is also available via 23Mb download for the source and a PDF detailing how to configure the Tomcat and Oracle dependencies.

答: If I wanted to stand up one of these appliances, I would be willing to go get the supporting software myself (Oracle, Tomcat, Linux, etc.), especially if you had some script or installer that would help me cobble all of the software sources together.</p>


答: Constants are meant to give numbers meaning. There is not any additional meaning in ONE_BILLION to 1000000000. Actually, it makes it more confusing, because in different natural languages, a billion means something different (either a thousand million or a million million)! If you want to write it shorter, there's a good chance your programming language allows the use scientific notation, i.e. 1e9. Otherwise, I agree with @JohnB, that this number really means the number of nanoseconds in a second, so name it that.


问:
Two libraries connecting to the database, leading to code smell?
In the current company that I work for there is a very large Utilities library. It was written a few years back (long before I joined) and has grown ergonomically over time to now do everything:

Sending Emails

Exporting Files in different formats, i.e. CSV, tab delimited

Receiving data from 3rd party providers, i.e. Bloomberg, Facset

Sending files to SFTP sites

Generic database connection

The list goes on and it is pretty ugly really.

The original developer here used it in every application that he wrote for convenience sake and added to it as necessary. The utilities library itself has references to 3rd party API’s to do some data receiving from Bloomberg/Factset. Using these 3rd party API’s means that any project that wants to reference the large Utilities library also then needs to have the Bloomberg API’s and Facset API’s with it. The list is starting to grow too and it is becoming very unmaintainable and unnecessary to have all these 3rd party DLL’s accompanied with this large Utilities project but are required to compile it.

I want to rewrite this entire library it to more manageable libraries. i.e:

CompanyName.Email

CompanyName.FileExporter

CompanyName.Bloomberg

Each project will then only reference the necessary projects it needs to get its job done. i.e. reference the CompanyName.Email to send emails.
I have no issues doing that, but the complication facing me is that some of the new libraries will require their own database connection and queries.
The example below is:

```<code>[HolidayChecker]
[HolidayChecker.DAL]
</code>```

We store a list of holiday days in the database. What I would want the HolidayChecker project to do is expose a method (amongst others) to check if a particular date is a holiday.

```<code>public interface IHolidayChecker
{
    bool IsHoliday(DateTime dateToCheck);
}
public class HolidayChecker : IHolidayChecker
{
    public bool IsHoliday(DateTime dateToCheck)
    {
        //Query database for date logic...
    }
}
</code>```

Many applications will then reference this HolidayChecker project and use the IsHoliday method. These applications will also have their own connection and queries to the database to perform their own tasks.

```<code>[GenericApplication (References HolidayChecker)]
[GenericApplication.BusinessLogic]
[GenericApplication.DAL]
</code>```

If the application and the HolidayChecker project both access the database and query the data, this comes across heavily as code smell. Is anyone aware of a tidier way of achieving this? Or is there? Is this something I will just have to live with?

EDIT:

Thinking about this overnight, I don't think it is a bad as first thought. Projects like ELMAH are stand alone that also connect to the database and do their own queries. As @Allan pointed out, it is just a matter of designing my HolidayChecker project correctly.

答:
I would suggest that organization may be more important than separation. Separating things into separate DLLs could be useful when a client library only needs part (but not all) of the total functionality.

My suggestion would be to follow the DRY principle -- don't duplicate code. Shared code can be put into a base library that is shared among the more specialized ones. Just be careful that you don't get yourself into a dependency/DLL hell where you have to mess with an entire dependency tree...

To get around the DLL hell, I would recommend creating a single solution (.sln) file for the whole thing, then break down the separate DLLs as projects within it. That way you can rebuild everything at once, but still have some flexibility.

Another thought: as you work through your code base, you may find that organizing by business use case might not be as effective as by type of functionality or something else.


答:
Design For Testing, But Don't Code For Testing

You use private methods to reduce code. Less code is always more stable. Extracting a private method to another class so it can be tested makes more code, and makes something that was in the domain of the class now an external thing.

If a class is used only by one other class. That the two classes are partial representations of a whole class, then you have a problem. While your unit tests are going to pass, they aren't going to pass for long. They are going to break. It's like working on fixing a table thinking it stands on 3 legs when infact there are 4. The 4'th leg is just not within view when you're working on it.

Design for testing means you've created a collection of classes, interfaces and other things that will remain stable as your modify it. There shouldn't be a huge ripple effect when you break something (there can be a ripple cause by dependency, but failure should be horizontal. Not vertical).

A user of a class wants reliabilityfirst. Your unit tests should show that the class is stable under all possible states. You could make every method public and get 100% code coverage. Does this really make it more reliable? No it doesn't.

Think first, what unit tests I need to have to verify this stuff actually works as intended.

Having a private method double_price() doesn't mean it needs to be tested. It's likely called a few dozen times from different parts of the class. It doubles the price, and that happens in lots of places so it's reused code.

Does this method risk stability? If it does then ask yourself "Does the risk justify a different set of unit tests?" If so, then encapsulate and write unit tests for that.

Think Of It Like This.

To build a system you want to use small pieces that you know work. If you take pieces A and B that you know pass unit tests, then creating C using A and B makes C more stable.

Don't Think Like This

I have a system called A. Is it stable? I don't know. Let's open A and rip out B and C. Now I can test A, B and C.

Why is this bad? Because this can happen. A and C pass unit tests but B fails. How can A and C be stable? Because you didn't rip A apart correctly. A is actually unstable because part of it is pretending to be B.

oh man, I think I just gave myself a headache.