问:
Parameterization vs subclassing
Example taken from : Agile software development : principles, patterns and practices

A new employee is added by the receipt of an AddEmp transaction. This transaction contains the employee's
name, address, and assigned employee number. The transaction has three forms:

```<code>AddEmp <EmpID> "<name>" "<address>" H <hourly-rate>
AddEmp <EmpID> "<name>" "<address>" S <monthly-salary>
AddEmp <EmpID> "<name>" "<address>" C <monthly-salary> <commission-rate>
</code>```

proposed employee class

Add employee transaction

My question would it be "better" if instead of subclassing AddEmployeeTransaction we have a factory for salary classification and pay schedule?

If better is too vague a term, what are disadvantages of my design over the one proposed by Uncle Bob?

Say inside EmployeeTransaction we have SalaryClassificationFactory and we call SalaryClassificationFactory.get(SalaryDetails d)

where,

```<code>enum SalaryId{H,S,C};

struct hourly
{
    int hourlyRate;
};

struct monthly
{
    int monthlySalary;
};

struct commissioned
{
    int salary;
    int commisssionRate;
};
struct SalaryDetails
{
    SalaryId kind;
    union SalaryUnion
    {
        hourly h;
        monthly s;
       commissioned c;
    }
};
</code>```

答:
Typical factory patterns defer creation of some object(s) to some factory, allowing the factory to choose the final type or object, but they do this from a common, shared (usually simple, often abstract) interface that requests an object.  For example, (from http://www.oodesign.com/factory-pattern.html)

```<code>Product ProductFactory.createProduct(ProductId id)
</code>```

Here the factory can create the appropriate subclass of Product by consulting the ProductId, and presumably a product catalog.  All the different types that the factory can create are requested using the same method.

It seems to me that the parameters needed to accomplish each of the three salary classification transactions are substantially different from each other.  Thus, a traditional factory method pattern probably would not apply across all three.

You could hide the existing subclass-based implementation behind a some other class, but you would still need three methods, each with different parameters, and as a result, that hiding class would not, in my opinion look like a factory.

Unless you could unite the various salary classification descriptions under a common type, say as in:

```<code>AddEmployeeTransaction
    AddEmployeeFactory.createAddEmployee ( EmployeeCompensationClassification ecc,
                                           EmployeeInfo who )
</code>```

Now this method looks like a factory pattern, but we haven't accomplished anything because all we have done is defer the same kind of problem to creating the EmployeeCompensationClassification.

If you could reduce all salary compensation classifications to that of a simple code (e.g. a classification name, or, a classification id number), I think a factory pattern would have merit.

Title: Parameterization vs subclassing

Body:
Typical factory patterns defer creation of some object(s) to some factory, allowing the factory to choose the final type or object, but they do this from a common, shared (usually simple, often abstract) interface that requests an object.  For example, (from http://www.oodesign.com/factory-pattern.html)

Product ProductFactory.createProduct(ProductId id)

Here the factory can create the appropriate subclass of Product by consulting the ProductId, and presumably a product catalog.  All the different types that the factory can create are requested using the same method.

It seems to me that the parameters needed to accomplish each of the three salary classification transactions are substantially different from each other.  Thus, a traditional factory method pattern probably would not apply across all three.

You could hide the existing subclass-based implementation behind a some other class, but you would still need three methods, each with different parameters, and as a result, that hiding class would not, in my opinion look like a factory.

Unless you could unite the various salary classification descriptions under a common type, say as in:

AddEmployeeTransaction
    AddEmployeeFactory.createAddEmployee ( EmployeeCompensationClassification ecc,
                                           EmployeeInfo who )

Now this method looks like a factory pattern, but we haven't accomplished anything because all we have done is defer the same kind of problem to creating the EmployeeCompensationClassification.

If you could reduce all salary compensation classifications to that of a simple code (e.g. a classification name, or, a classification id number), I think a factory pattern would have merit.


问:
Name-Based Sorting Algorithms For Maximized Common Letters
I am attempting to write a program for a competition (we're allowed to consult Stack Exchange, as long as I'm not given physical code) that takes in a list of 5000 people's names (distributed fairly evenly from A-Z, but are real names - not random character strings, and each name is unique) and sorts this list of people into "rooms" of exactly 4 people each, with each person being placed in exactly one room only (cannot reuse names, cannot omit names).

Each "solution" consists of 1250 of such rooms (I store it in a 2d array and am using java), and the solution's "score" is defined to be the sum of each room's score, where the room score is the number of common letters held in each of the 4 peoples' names. A given letter is only counted more than once if it appears exactly that many times in each person's name.

I began with algorithms that simply placed the names into random rooms just to test the waters and see what the low-end of scores might look like (around 650). I then tried doing a simple alphabetical sort of the list containing the names (using Collections.sort()), which considerably improved the score (around 3800), but still had quite a bit of room for improvement.

My latest algorithm has been a slightly modified version of simulated annealing, where I begin with the alphabetically sorted list and continuously switch two people from two rooms (by picking two random room numbers and two random indices in the rooms). Inside each outer level iteration, I update the annealing temperature and conduct an inner loop search of 1000 iterations (at the temperature of the outer loop) where I get 1000 random swaps, pick the best one (no temperature-probability selection in the inner loop), and use that in the outer loop, accepting it as the new solution if its score is higher and accepting it with some probability if it is lower.

This SA approach has gotten me a score in the low 6000's, and runs quite quickly, but it seems to have asymptoted. Are there any other algorithms or optimizations I should consider? Should I move away from a stochastic approach and look for construction approaches that make use of the alphabetical nature of the words themselves? Thanks!

答:
A heuristic worth considering:

Pick a random name and add it to a group.

Scan the remaining names for the highest point match and add it to the group.

Scan the remaining names for the highest total point match against the two grouped names and add it to the group.

Scan the remaining names for the highest total point match against the three grouped names and add it to the group.

Repeat to complete the remaining groups.

The result would likely miss some excellent matches because its members would be matched with others prematurely. Still, it might be a good starting state for stochastic methods.

A further enrichment might be to pre-calculate "distances" between all names. That's 12,500,000 measurements -- a lot, but do-able. Sort the measurements and start the process above with the best match.

A final thought is k-means clustering. We could think of the names as points in 26 dimension Euclidean space. That's one dimension per character. Each character is one "unit" along that dimension. "Aaron" is two units along the A axis, zero units along B, zero along C, etc.. 1 along R... Therefore, he shares a point with "Roana", is pretty close to "Rona", but is no where near "Ziggy". (This isn't a perfect way of measuring. For instance, "Ziggy" is really no further or closer to "Aaron" than "Tim", but our Euclidean layout suggests it is. I'll have to think a bit more on it...)

True k-means is infeasible with a complexity of O(ndk+1logn) [d == dimensions (26), k == cluster count (1250)] Ouch. Still, conceptualizing as points in space seems useful. There are all sorts of tricks you can try with nearest neighbor search.

ContentLicense: CC BY-SA 3.0


问:
How can you plan long range resources and budgets when using Agile methodology?
Agile does not encourage a lot of up-front design.  This is good from a requirements management and software development standpoint, and allows the project to adapt to changing business needs.

However, how does one do any long range planning of resources if you don't really know what you're going to build when you start?  Oh sure, you have a conceptual model of what you're going to build, but you don't have any measurable detail from which to gague how many resources you will need to complete the project, or how much it will cost.

Does anyone have any suggestions on how to go about long range planning in an agile environment?

答:
Try the Get Things Done methodology by David Allen; I remembered a passage of his book (the first/main one about GTD) where he says something like "being long term doesn't mean you have a lot of time to start doing it".

GTD helps you think in actionable terms, so you can program actual tasks that you can do or program to do in a system of your own. This is GTD in a nutshell: http://lifedev.net/gtd-cheatsheet/

GTD works for both life and work, and for shortest term to longest term as long as you keep thinking in actions, and not just things that worry you and/or your team. If you don't have a lot of time to read the book, get the audiobook, it is really worth it.

You can also try Scrum (and even combine with GTD)... you make a list of features, box 'em in a month of development and end up with a working version of the product.

Finally, I'd recommend you to read Rework by Jason Fried, where they talk a lot about prioritization and some informal project planning notions that are quite useful.

ContentLicense: CC BY-SA 2.5


问:
Methods of debugging code (Nightmare situation)
I am frequently tasked with debugging an application at my job. It is a BI Application that we deploy to businesses, which includes a test environment, and a production environment. I am wondering if there are any apps/tools/methods that people can suggest, based on these constraints:

Debugger cannot be used on client site or locally, because the software depends on custom third party applications that we don't have test environments for. (EDIT: to be fair, it is possible to debug locally in some cases. If we use nothing but the core code. Much of the problematic code resides in a dll that encapsulates third party specific communication: sockets, process pipes, soap calls, custom logic that changes the behavior of core code. Typically during an implementation or enhancement for a client, we would be writing new code to this area.)

There is virtually no logging done in our apps. There are no unit tests.

Version control only has 1 version of the full solution (using source safe 2005). So it's not possible to get a previous version of the entire solution, only individual files. (Unless someone knows ways around this).

Cannot reproduce locally, often times cannot reproduce on test environment (High chance that test and production are not the same version).

There is a high chance that the version the client is using is different from the one on source safe. This is because individual files are updated, which have embedded custom logic for that specific client. Often what happens is an update is made to a binary, which requires changes to several other binaries, but when a commit is done, no one has any record or knowledge of this. A somewhat common error I see is the 'Function/Method not found' or 'Method call has too many/too few parameters specified' on a clients environment.

This is a .net VB solution

Cannot install any software on client sites, but can locally

Our application is extremely customizable, but unfortunately the customization logic is spread out across all the classes and files, from the front end all the way to the data layer, including custom changes made to the database on a per client basis.

There are virtually no comments in the code. There is no documentation about the architecture. No documentation about the api. The only thing we have are hundreds upon hundreds of email chains that somewhat explain what's going on. The only people that know the code are the ones that originally wrote it, but they're no longer developers per say so they don't get involved that much.

And before you say it... yes I know; I want to shoot myself as well. It doesn't help that there's spaghetti code, hundreds of compiler warnings, and broken polymorphism that REALLY should be fixed, but I don't have a say in it.

Most common sort of errors I run into are null reference errors, invalid casts, and missing functions/function signature mismatches. Sometimes I am lucky and event viewer will log the class, method, and exception message. It's not the most helpful, but it's still something. The worst are the errors that have no trace, no repro steps besides a screenshot, and are generic error messages like the ones mentioned above. Sometimes it's not possible to find out why they occurred, only to pray that the environment is not properly configured, and that it will go away later.

I know this comes off as a bit of a rant, and to some extent it is. But I'm desperate for options. Are there other methods / tools I can use?

答:
First, all the above... ditto.

Some heuristics:

Use source control on your development computer. It's the best thing I've done. It is not a substitute for the project's version control, which we have. It's a tool that gives amazing freedom to fearlessly experiment, hack, work problems simultaneously yet independently, etc. I am better at using version control because I have the freedom to be bold, screw up, and learn.

What's the difference between Git and Mecurial?

Git is Mcgyver, Mecurial is James Bond

To the extent you add comments, prioritize the public interface elements, to take advantage of intellisense. Do this as you decipher during your debug adventures.

Be persistent with minor refactorings. Sooner or later, for a given hunk of code, you will get to a critical mass that enables big refactorings like DRYing up redundant code across classes.

Do not mix code reformatting and actual changes in the same version control commits.

SOLID principles

Never ignore single responsibility. Well done, this is the path to the promise of object oriented; IMHO.

Always ignore Open/Closed.

We're not talking new code here.

Making interfaces without purposeful design hinders maintenance.

Refactoring

There is a methodology to it. Buy the book.

Refactoring: Improving the Design of Existing Code

Some code files need complete reformatting, variable renaming, etc. before even attempting debugging. Don't be shy about using visual studio's refactor menu without unit tests.

The only documentation that can't be misplaced is in the code files.

When you do get version control give forethought to VC plan. And document it! And come up with a naming convention for branches, tags that will highlight major software versions and milestones.

Use good equipment

Get a monitor that pivots. Vertical is the way to read code quickly.

External drive for backups, keyboard with the right kind of keys, multi-function mouse. At least 1 really good USB drive. I even have my own Herman Miller chair.

Get very good comparison software. I'm happy with Beyond Compare.

Practice Rubber Ducky Debugging

Sometimes the worst thing that can happen is that they don't fire you.

Edit

Brownfield Application Development in .NET

Try this book. An initial cover to cover read through is probably best. This book will help your thinking about the big picture, possibilities, and developing both strategic and tactical plans of attack.

Sticking it out

Stay, say, 1.5 years if you can; long enough to know if you are making experiential progress. You will know if you are getting 2 years of experience or 6 months of experience 4 times.

Being "junior with 1/2 years experience" I'm concerned that a potential employer will view it as bailing out early because you couldn't hack it. It's one thing to say you learned z, y, x, took some names and kicked some ass - but was not allowed to contribute to your capabilities; and another simply risking dissing the job, the code, management, etc. by way of explanation.

I may be off base on this but my "best of times and worst of times" was my 1st job, which happened to be literally unmaintainable code. I had a great supervisor (all the rest were from the management in-breeding program) who gave me the space to re-write some key programs. That experience was revelation.

end Edit


答:
One of the design decisions Uncle Bob made when creating his design is that Payment Classification should be Open for Extension. Which means that adding new payment classifications shouldn't require changing nor recompiling existing code. Your design breaks that design decision, because to add new payment classification, you have to add new value to SalaryId enum, new structure and add it to SalaryUnion, forcing recompile of all code that depends on SalaryId and SalaryDetails.

But that is Uncle Bob's decision. If you yourself decide that you don't want to accept complexity created by making the design Open for Extension, you can go with your design.

Title: Parameterization vs subclassing

Body:
Example taken from : Agile software development : principles, patterns and practices

A new employee is added by the receipt of an AddEmp transaction. This transaction contains the employee's
name, address, and assigned employee number. The transaction has three forms:

```<code>AddEmp <EmpID> "<name>" "<address>" H <hourly-rate>
AddEmp <EmpID> "<name>" "<address>" S <monthly-salary>
AddEmp <EmpID> "<name>" "<address>" C <monthly-salary> <commission-rate>
</code>```

proposed employee class

Add employee transaction

My question would it be "better" if instead of subclassing AddEmployeeTransaction we have a factory for salary classification and pay schedule?

If better is too vague a term, what are disadvantages of my design over the one proposed by Uncle Bob?

Say inside EmployeeTransaction we have SalaryClassificationFactory and we call SalaryClassificationFactory.get(SalaryDetails d)

where,

```<code>enum SalaryId{H,S,C};

struct hourly
{
    int hourlyRate;
};

struct monthly
{
    int monthlySalary;
};

struct commissioned
{
    int salary;
    int commisssionRate;
};
struct SalaryDetails
{
    SalaryId kind;
    union SalaryUnion
    {
        hourly h;
        monthly s;
       commissioned c;
    }
};
</code>```


问:
What are good habits for designing command line arguments?
While developing the application I started to wonder - How should I design command line arguments?

A lot of programs are using formula like this -argument value or /argument value. Solution which came to my mind was argument:value. I thought it is good because with no white spaces there is no way that values and arguments can be messed up. Also it is easy to split a string into two on the first from the left : character.

My questions are:

Is popular -argument value formula better than argument:value (more readable, easier to write, bugfree, easier to understand by expert developers)?

Are there some commonly known rules which I should follow while designing command line arguments (other than if it works it is OK)?

Asked for some more details I will provide it. However I think they should not affect the answers. The question is about a good habits in general. I think they are all the same for all kinds of applications.

We are working on an application which will be used in public places (touch totems, tables). Applications are written using Qt Quick 5 (C++, QML, JS). Devices will have Windows 8.1/10 installed. We will provide front-end interface to manage the devices. However some advanced administrators may want to configure the application on their own. It is not very important from the side of the business but as I agree with what Kilian Foth said I do not want my application to be a pain for a user. Not finding in the Internet what I want I asked here.

To more advanced Stack Exchange users: I wanted this question to be general. Maybe it qualifies to the community wiki (I do not know if existing question can be converted with answers). As I want this question to be operating system and programming language independent the answers appearing here can be a valuable lesson for other developers.

答:
The fact that a data format convention is popular is its advantage.

You can easily see that using = or : or even ' ' as a separator are trivial differences that could be converted into each other by computer with little effort. What would be a big effort is for a human to remember "Now see, did this infrequently-used program delimit things with : or with = ? Hmmm..."

In other words, for the love of god, don't deviate from extremely entrenched conventions without a compelling reason. People will remember your program as "the one with the weird and annoying cmdline syntax" instead of "the one that saved my college essay".


答:
Agile has a concept of "Release Planning". The entire team gets together to plan out an upcoming release. I've done for up to 2-3 months in advance. This is usually done after the product owner has determined the "minimum viable product" and they know exactly what has to be done in order to release the product.

The team can take the known stories or epic story. An epic is large story or feature that has not yet been fully defined. Maybe something like "Allow international payments". Because this story or epic is so general, the estimates will be large and account for that. The team can do something called "t-shirt" sizes and give each epic a "small", "medium" or "large". This give the product owner some sense of the size of the stories in questions and allows the scrum master to make some estimates on what the actual release date will be.

The key is to start some where and continue to refine the story points or estimates as more information is know.

Here's a couple of links on release planning:

https://www.mountaingoatsoftware.com/blog/tag/release-planning

https://digital.ai/resources/agile-101/agile-development-release-planning

Title: How can you plan long range resources and budgets when using Agile methodology?

Body:
Agile does not encourage a lot of up-front design.  This is good from a requirements management and software development standpoint, and allows the project to adapt to changing business needs.

However, how does one do any long range planning of resources if you don't really know what you're going to build when you start?  Oh sure, you have a conceptual model of what you're going to build, but you don't have any measurable detail from which to gague how many resources you will need to complete the project, or how much it will cost.

Does anyone have any suggestions on how to go about long range planning in an agile environment?

ContentLicense: CC BY-SA 4.0


答:
On POSIX systems (e.g. Linux, MacOSX), at least for programs possibly started in a shell terminal (e.g. most of them), I would recommend using the GNU coding conventions (which also lists common argument names) and look into the POSIX utilities guidelines, even for proprietary software:

always handle --version and --help (even /bin/true accepts them!!). I curse the authors of software not understanding --help, I hate them (because prog --help  is the first command I am trying on a new program)! Often --help can be abbreviated as -h

Have the --help message list all the options (unless you have too many of them... in that case list the most common ones and explicitly refer to some man page or some URL) and default values of options, and perhaps important (and program-specific) environment variables. Show these option lists on option argument error.

accept -a short argument (single letter) and have some equivalent --long-argument, so -a2 --long-argument=2, --long-argument 2; of course you could have (for rarely used options) some --only-long-argument name; for modal arguments without extra options -cf is generally handled as -c -f, etc. so your -argument:value proposal is weird, and I don't recommend doing that.

use GLIBC getopt_long or better (e.g. argp_parse, in OCaml it's Arg module, ...)

often use - for standard input or output (if you can't do that, handle /dev/stdin & /dev/stdout even on the few operating systems not having them)

mimic the behavior of similar programs by reusing most of their options conventions; in particular -n for dry run (à la make), -h for help, -v for verbosity, etc...

use -- as separator between options & file or other arguments

if your program uses isatty to test than stdin is a terminal (and behave "interactively" in that case), provide an option to force non-interactive mode, likewise if your program has a GUI interface (and tests getenv("DISPLAY") on X11 desktop) but could also be used in batch or command line.

Some programs (e.g. gcc) accept indirect argument lists, so @somefile.txt is meaning read program arguments from somefile.txt; this could be useful when your program might accept a very big lot of arguments (more than your kernel's ARG_MAX)

BTW, you might even add some auto-complete facilities for your program and usual shells (like bash or zsh)

Some old Unix commands (e.g. dd, or even sed) have weird command arguments for historical compatibility. I would recommend not following their bad habits (unless you are making some better variant of them).

If your software is a series of related command-line programs, take inspiration from git (which you surely use as a development tool), which accepts git help and git --help and have many gitsubcommand and gitsubcommand--help

In rare cases you might also use argv[0] (by using symlinks on your program), e.g. bash invoked as rbash has a different behavior (restricted shell). But I usually don't recommend doing that; it might make sense if your program could be used as a script interpreter using shebang i.e. #! on first line interpreted by execve(2). If you do such tricks, be sure to document them, including in --help messages.

Remember that on POSIX the shell is globbing arguments (before running your program!), so avoid requiring characters (like * or $ or ~) in options which would need to be shell-escaped.

In some cases, you could embed an interpreter like GNU guile or Lua in your software (avoid inventing your own Turing-complete scripting language if you are not expert in programming languages). This has deep consequences on the design of your software (so should be thought of early!). You should then easily be able to pass some script or some expression to that interpreter. If you take that interesting approach, design your software and its interpreted primitives with care; you could have some weird user coding big scripts for your thing.

In other cases, you might want to let your advanced users load their plugin into your software (using dynamic loading techniques à la dlopen & dlsym). Again, this is a very important design decision (so define and document the plugin interface with care), and you'll need to define a convention to pass program options to these plugins.

If your software is a complex thing, make it accept some configuration files (in addition or replacement of program arguments) and probably have some way to test (or just parse) these configuration files without running all the code. For example, a mail transfer agent (like Exim or Postfix) is quite complex, and it is useful to be able to "half-dry" run it (e.g. observing how it is handling some given email address without actually sending an email).

Notice that the /option is a Windows or VMS thing. It would be insane on POSIX systems (because the file hierarchy uses / as a directory seperator, and because the shell does the globbing). All my answer is mostly for Linux (and POSIX).

P.S. If possible, make your program a free software, you would get improvements from some users & developers (and adding a new program option is often one of the easiest things to add to an existing free software).
Also, your question depends a lot on the intended audience: a game for teenagers or a browser for grandma probably does not need the same kind and amount of options than a compiler, or a network inspector for datacenter sysadmins, or a CAD software for microprocessor architects or for bridge designers. An engineer familiar with programming & scripting probably likes much more having lots of tunable options than your grandma, and probably might want to be able to run your application without X11 (perhaps in a crontab job).

Title: What are good habits for designing command line arguments?

Body:
While developing the application I started to wonder - How should I design command line arguments?

A lot of programs are using formula like this -argument value or /argument value. Solution which came to my mind was argument:value. I thought it is good because with no white spaces there is no way that values and arguments can be messed up. Also it is easy to split a string into two on the first from the left : character.

My questions are:

Is popular -argument value formula better than argument:value (more readable, easier to write, bugfree, easier to understand by expert developers)?

Are there some commonly known rules which I should follow while designing command line arguments (other than if it works it is OK)?

Asked for some more details I will provide it. However I think they should not affect the answers. The question is about a good habits in general. I think they are all the same for all kinds of applications.

We are working on an application which will be used in public places (touch totems, tables). Applications are written using Qt Quick 5 (C++, QML, JS). Devices will have Windows 8.1/10 installed. We will provide front-end interface to manage the devices. However some advanced administrators may want to configure the application on their own. It is not very important from the side of the business but as I agree with what Kilian Foth said I do not want my application to be a pain for a user. Not finding in the Internet what I want I asked here.

To more advanced Stack Exchange users: I wanted this question to be general. Maybe it qualifies to the community wiki (I do not know if existing question can be converted with answers). As I want this question to be operating system and programming language independent the answers appearing here can be a valuable lesson for other developers.


问:
Indentation in a multi-language file
In files that contain multiple languages (ie. template files), are there any best practises regarding indentation?

I mostly use this:

```<code><div>
    IF FOO
        <div>
            <p>contents>
        </div>
    END FOO
</div>
</code>```

Indent for every new block, regardless of language. This has a few disadvantages, though. In more complex files it can break the indentation of either language:

```<code><div>
    IF FOO
        <div someattribute>
    ELSE
        <div otherattribute>
    END FOO
        <p>content</p>
    </div>
</div>
</code>```

I've also seen this used:

```<code><div>
    IF FOO
    <div>
       <p>contents>
    </div>
    END FOO
</div>
</code>```

Ie. indent only one language. This has the advantage of always being consistent, but in more complex files can almost completely hide some implementation details, like a block being conditional.

The goal here is obviously maximizing readability.

答:
In my opinion, the main principle for good coding is minimize the intermixture of code.

Two-language files are inherently a mess to work with.  Your priority should be to minimize the extent to which the two languages are intertwined.

For example, in a template file, the logic implemented by the templating language should be kept at a bare minimum.  Whenever possible, move logic elsewhere and just present a value in the templating file.

Even something like your example:

```<code><div>
    IF FOO
        <div someattribute>
    ELSE
        <div otherattribute>
    END FOO
        <p>content</p>
    </div>
</div>
</code>```

Could be better implemented as

```<code><div>
    <div [FOO_ATTRIBUTE]>
        <p>content</p>
    </div>
</div>
</code>```

with the attribute to use calculated elsewhere.  In this case, then, I would let readability of the file's main language be the driver of the indentation strategy.  I wouldn't indent the templating language, and any templating code complex enough to need indentation is probably badly designed.

Title: Indentation in a multi-language file

Body:
In my opinion, the main principle for good coding is minimize the intermixture of code.

Two-language files are inherently a mess to work with.  Your priority should be to minimize the extent to which the two languages are intertwined.

For example, in a template file, the logic implemented by the templating language should be kept at a bare minimum.  Whenever possible, move logic elsewhere and just present a value in the templating file.

Even something like your example:

<div>
    IF FOO
        <div someattribute>
    ELSE
        <div otherattribute>
    END FOO
        <p>content</p>
    </div>
</div>

Could be better implemented as

<div>
    <div [FOO_ATTRIBUTE]>
        <p>content</p>
    </div>
</div>

with the attribute to use calculated elsewhere.  In this case, then, I would let readability of the file's main language be the driver of the indentation strategy.  I wouldn't indent the templating language, and any templating code complex enough to need indentation is probably badly designed.


问:
Problem on recursion
```<code>void function(int x){
    if(x<=0)
        return;
    function(x--);
}
</code>```

This is a recursion function which is called with the value of x = 20.

The Recursive call will take place in this way

```<code>function(20)...function(19).......function(0)
</code>```

Each function call will use some memory and if the data is big it will throw StackOverflowException.

So what I want to know is:

Is there any way by which we can call a function and remove it from the call stack so that its memory can be utilized (eg. after function(20) calls function(19) the memory for function(20) should be de-allocated), and the the end of the recursive call (here function(0) ) it should get returned from the first place from where it was called (i.e. function(20)).

Can this be done in Java and C?

答:
What you have here is a Tail Call, and even more, it is Tail Recursion (Direct Tail Recursion) to be precise.

Many languages have Proper Tail Calls (e.g. Scheme, ECMAScript), and even more languages have Proper Tail Recursion (e.g. Scala, at least for Direct Tail Recursion). Unfortunately, neither C nor Java support Proper Tail Calls or even the much weaker Proper Tail Recursion, so, for large enough values of x, you will blow the stack, there is no way around it.

Obviously, you have a bug in your code that leads to infinite recursion, which means even if you have Proper Tail Recursion, your program will run for an infinite amount of time.

Proper Tail Calls have the semantics of a subroutine call but the time and space performance of a GOTO (because they are in fact operationally equivalent to a GOTO and often implemented that way). Proper Tail Recursion, then, is obviously operationally equivalent to a GOTO back to the beginning of the subroutine. Or, in other words, a loop.

So, if your language has loops, but no Direct Tail Recursion, you can always replace Direct Tail Recursion with a loop with the same space and time performance, but losing the safety and readability properties of a subroutine call.

Title: Problem on recursion


问:
Which data store is best for my scenario?
I'm working on an application that involves very high execution of update / select queries in the database.

I have a base table (A) which will have about 500 records for an entity for a day. And for every user in the system, a variation of this entity is created based on some of the preferences of the user and they are stored in another table (B). This is done by a cron job that runs at midnight everyday.

So if there are 10,000 users and 500 records in table A, there will be 5M records in table B for that day. I always keep data for one day in these tables and at midnight I archive historical data to HBase. This setup is working fine and I'm having no performance issues so far.

There has been some change in the business requirements lately and now some attributes in base table A ( for 15 - 20 records) will change every 20 seconds and based on that I have to recalculate some values for all of those variation records in table B for all users. Even though only 20 master records change, I need to do recalculation and update 200,000 user records which takes more than 20 seconds and by then the next update occurs eventually resulting in all Select queries getting queued up. I'm getting about 3 get request / 5 seconds from online users which results in 6-9 Select queries. To respond to an api request, I always use the fields in table B.

I can buy more processing power and solve this situation but I'm interested in having a properly scaled system which can handle even a million users.

Can anybody here suggest a better alternative? Does nosql + relational database help me here? Are there any platforms / datastores which will let me update data frequently without locking and at the same time give me the flexibility of running select queries on various fields in an entity?

答:
The question really is what system calculates the record to insert into B and the size of the B data.

Any database (eg MSSQL) should be able to handle the volume of inserts you are talking about no problem assuming the object isn't huge.

Updates may by a more difficult problem, but with the right indexing and locking, again shouldn't be a big problem.

99% of the time when I see a problem like this its due to the B record being calculated by a stored proc. This puts all the load on the db server

If this is the case the solution is to move this code to a offline service which can be called via a queuing system.

So your update A message would trigger a worker process which would loop through the users and create an update B message for each user

A second worker process B would pickup the update User X with data A event create the B record and update the DB

This can be scaled by adding more boxes with queue workers on them, so you have more and more processing power behind the calculation, leaving your db free to concentrate on updates and selects.

you can further optimize by separating the selects from the update/inserts. have a new DB which gets all the select requests as a replication slave the the old DB which gets all the updates.


问:
What software do you use to help plan your team work, and why?
Planning is very difficult. We are not naturally good at estimating our own future, and many cognitive biases exacerbate the problem. Group planning is even harder. Incomplete information, inconsistent views of a situation, and communication problems compound the difficulty.

Agile methods provide one framework for organizing group planning--making planning visible to everyone (user stories), breaking it into smaller chunks (sprints), and providing retrospective analysis so you get better at planning. But finding good tools to support these practices is proving tricky.

What software tools do you use to achieve these goals? Why are you using that tool? What successes have you had with a particular tool?

答:
I've used both Rally and JIRA with Greenhopper.

I'll start with JIRA. JIRA is an excellent bug tracking tool. Greenhopper is an add-on that enables teams to begin working with agile. Because it was not designed as an agile tool from the ground up, some of the processes feel awkward. The tool is also time consuming and hard to use. However, it is extremely customizable. In general, it feels like a tool you have to cram you agile processes into.

Rally was designed from the ground up to be an agile tool and it shows. It follows a lot of the agile processes extremely well and it complements the process. I've used this tool in an extremely agile organization and it allowed us to keep track of cross-team dependencies and complicated projects that involve several agile teams. Cross-team coordination is something other tools struggle with, but Rally has done this well. Also, Rally has an excellent web services based API. It allowed my team to write some custom software using Rally as our backend as well as generate some custom reports.


答:
In layman's terms

When in Rome, do as the Romans do.

If your CLI app is intended for Linux/Unix use the -p value or --parameter value convention. Linux has tools for parsing such parameters and flags in an easy way.

I usually do something like this:

while [[ $# > 0 ]]
do
key="$1"
case $key in
    --dummy)
    #this is a flag do something here
    ;;
    --audit_sessiones)
    #this is a flag do something here
    ;;
    --destination_path)
    # this is a key-value parameter
    # the value is always in $2 ,
    # you must shift to skip over for the next iteration
    path=$2
    shift
    ;;
    *)
    # unknown option
    ;;
esac
shift
done
```

If your CLI app is intended for Windows, then use /flag and /flag:value conventions.

Some apps like Oracle use neither though. Oracle utilities use PARAMETER=VALUE.

One thing I like to do is, besides accepting parameters in the command line, providing the option of using a parfile, which is a key-value pair file to avoid lengthy parameter chains. For that you should provide an additional --parfile mifile.par parameter. Obviously if --parfile is used, all other parameters are discarded in favor of what's inside the parfile.

An additional suggestion is allowing the use of some custom environment variables, for example, setting environment variable MYAPP_WRKSPACE=/tmp would make it unnecessary to always set --wrkspace /tmp.

In Linux don't forget to add parameter auto-completion, meaning users can type half a switch, hit TAB and then shell would complete it for them.

Body:
In layman's terms

When in Rome, do as the Romans do.

If your CLI app is intended for Linux/Unix use the -p value or --parameter value convention. Linux has tools for parsing such parameters and flags in an easy way.

I usually do something like this:

while [[ $# > 0 ]]
do
key="$1"
case $key in
    --dummy)
    #this is a flag do something here
    ;;
    --audit_sessiones)
    #this is a flag do something here
    ;;
    --destination_path)
    # this is a key-value parameter
    # the value is always in $2 ,
    # you must shift to skip over for the next iteration
    path=$2
    shift
    ;;
    *)
    # unknown option
    ;;
esac
shift
done

If your CLI app is intended for Windows, then use /flag and /flag:value conventions.

Some apps like Oracle use neither though. Oracle utilities use PARAMETER=VALUE.

One thing I like to do is, besides accepting parameters in the command line, providing the option of using a parfile, which is a key-value pair file to avoid lengthy parameter chains. For that you should provide an additional --parfile mifile.par parameter. Obviously if --parfile is used, all other parameters are discarded in favor of what's inside the parfile.

An additional suggestion is allowing the use of some custom environment variables, for example, setting environment variable MYAPP_WRKSPACE=/tmp would make it unnecessary to always set --wrkspace /tmp.

In Linux don't forget to add parameter auto-completion, meaning users can type half a switch, hit TAB and then shell would complete it for them.


问:
How to handle user created expressions in application
In our application users can enter custom expressions to calculate certain things. For instance they can specify an invoice and define a number of lines for cost calculation.

Example for a course with $400 price $10 transaction fee and a number of free people (say because of some credit)

(?numberOfParticipants? - ?creditedtTickets?) * 400 + 10

We currently have custom code that parses and executes this. But we recently found a bug in it and need to spend some time on this.

We could improve the current hacky code, we could build a proper parser but I feel this is a very generic problem that lots of people have and there should be an off the shelf solution but I can't seem to find one.

Does anybody recognize this problem and how did you handle it?

答:
Your expression uses what we call an infix notation, which is the notation commonly used in arithmetical statements.

One way of simplyfing parsing such expressions is converting them to Reverse Polish Notation (RPN) which turns them into a stack-based operation, for example your expression would turn into:

```<code>PUSH numberOfParticipants
PUSH creditedtTickets
SUBSTRACT
PUSH 400
MULTIPLY
PUSH 10
ADD
</code>```

That list is not code, it's just a series of steps you should perform when you want to run the formula.

As you can imagine, every operation (substract, add, etc) pops the last two elements of the stack and applies the operation on them, pushing the result back into the stack.

That can be saved for executing later. You run it by iterating through the steps and doing the operations in your language of choice.

There is a known and proven algorithm called the Shunting-yard algorithm to parse back and forth between infix notation and RPN. That algorithm deals with parenthesis and operator precedence by using a railroad junction metaphor. You can parse the RPN steps back into infix notation to show them in the screen for users to see.

Body:
Your expression uses what we call an infix notation, which is the notation commonly used in arithmetical statements.

One way of simplyfing parsing such expressions is converting them to Reverse Polish Notation (RPN) which turns them into a stack-based operation, for example your expression would turn into:

PUSH numberOfParticipants
PUSH creditedtTickets
SUBSTRACT
PUSH 400
MULTIPLY
PUSH 10
ADD

That list is not code, it's just a series of steps you should perform when you want to run the formula.

As you can imagine, every operation (substract, add, etc) pops the last two elements of the stack and applies the operation on them, pushing the result back into the stack.

That can be saved for executing later. You run it by iterating through the steps and doing the operations in your language of choice.

There is a known and proven algorithm called the Shunting-yard algorithm to parse back and forth between infix notation and RPN. That algorithm deals with parenthesis and operator precedence by using a railroad junction metaphor. You can parse the RPN steps back into infix notation to show them in the screen for users to see.


问:
Retrieving an incorrectly stored tree data structure
Way back in the hazy origins of our platform it was decided that we were going to need some hierarchical data structures stored in the RDBMS. The relationships between nodes were stored via a 'parent_id' column that referenced another row in the same table. Although at face value this may seem slightly sensible, the reality has turned out very differently.

I have now been tasked with implementing some functionality that requires traversing the hierarchy - Specifically, I need to build a list of all of the descendents of a node for a given node. This would be trivial if the relationships were stored as 'parent -> children' but as the relationships are stored as 'child -> (unique) parent' I can't figure out a performant way of doing this (the naive approach is O(n^2) I believe).

Having wrestled with this for a few hours, the current thinking is that we should refactor the database but if anyone has experienced this before it'd be good to hear about your solution. If not, let this be a warning to anyone trying to save a tree in this fashion if you ever plan on having to traverse it!

答:
With an index on parent_id, I actually think this is a good way to organize the relationship, and we have been using it that way in many places. Also, I see no obvious better way, as the relationship is 1:N, so if you try to store parent->child, you need an extra table, and you end up with the same logic again.

The core point is having the index on parent_id; with that, access is fast and easy, and you could build a real tree in memory if you need it continuously.


问:
Why exactly can't PHP have full unicode support?
Everybody knows, that PHP has problems with Unicode. Version 6 is effectively abandoned, because of Unicode implementation difficulties. But I wonder if anyone knows what are the exact reasons? Architecture/design problems, performance concerns, community problems (I bet not), something other?

答:
TLDR: many PHP libraries are just a thin layer over native C libraries that don't support unicode, or support it in ways that are incompatible with each other. Rectifying this situation is likely to introduce backward incompatible changes.

DISCLAIMER: as I've switched from PHP to Python (to never look back) a few years ago, my opinion is clearly biased.

I think PHP is a nice and clever hack. As a hack, it started unpretentious and grew somewhat chaotically from a bunch of sparse libraries - lacking a well thought and unified design (from the computer language theory perspective).

As said by Machiavelli, "he who has not first laid his foundations may be able with great ability to lay them afterwards, but they will be laid with trouble to the architect and danger to the building".

For a programming language, the more popular, the harder to change. That is why languages like C changes once every 10 years. For example, Python 3 made many backward incompatible changes, and it was not pretty. The unicode support in previous Python incarnations was already considered superior to the current state of affairs in PHP, but guess what: the most polemic changes in Python 3 are related to unicode handling. This rant from Armin Ronacher summarizes the frustration from a huge share of the Python community.

PHP being "the" ubiquitous web platform makes it victim of its own success. Bring unified support for unicode in PHP is inevitable, but will require a lot of blood, sweat and tears.


答:
This is one of the primary reasons for avoiding systems that mix two languages together like this. It can get really difficult to check how the control flow of the outer language affects the block structure of the inner language, and when you can't see that, bugs happen.

I prefer to keep them separated and when generating output in another structured language always use a template system that respects the structuring of the language and doesn't require control flow blocks for common tasks.

Title: Indentation in a multi-language file

Body:
In files that contain multiple languages (ie. template files), are there any best practises regarding indentation?

I mostly use this:

```<code><div>
    IF FOO
        <div>
            <p>contents>
        </div>
    END FOO
</div>
</code>```

Indent for every new block, regardless of language. This has a few disadvantages, though. In more complex files it can break the indentation of either language:

```<code><div>
    IF FOO
        <div someattribute>
    ELSE
        <div otherattribute>
    END FOO
        <p>content</p>
    </div>
</div>
</code>```

I've also seen this used:

```<code><div>
    IF FOO
    <div>
       <p>contents>
    </div>
    END FOO
</div>
</code>```

Ie. indent only one language. This has the advantage of always being consistent, but in more complex files can almost completely hide some implementation details, like a block being conditional.

The goal here is obviously maximizing readability.


答:
It's not necessarily as bad as you think and may even be the most optimal representation if you have an index on parent_id.

Let's say you're interested in the descendants of B above. In that case, you would first query for nodes which have parent_id matching the ID of B. That gives you D,E. Now query for nodes which have the parent ID of either of these. That gives you H,I,J. Do it once more for H,I,J, we get nothing, and so we're done.

Assuming the queries are in constant time (hash index, e.g.), that's actually optimal from an algorithmic complexity standpoint (worst-case having linear complexity). Each query to find the child nodes of a parent node in that case would be O(1). Even if the queries are logarithmic, it's actually optimal in terms of the number of queries (logN) unless you actually memoized the entire list of descendants in each node (which would be explosive in terms of memory use) and definitely not as bad as quadratic complexity as you think.

For an RDBMS, it actually seems very optimal to me to store things in this bottom-up fashion, especially if the tree is n-ary and not merely binary. Don't worry, be happy. I think the only thing storing child IDs in the nodes would save you is the need for an index, but it would amount to the same number of queries and pretty much the same amount of work to get a list of all descendants.

If you need more speed, and the tree fits, you can transfer the tree to memory, linearly building the tree out of nodes in the memory of the client and then just do the search in memory, updating it when the database is modified. But you might not even need that.

Title: Retrieving an incorrectly stored tree data structure

Body:
Way back in the hazy origins of our platform it was decided that we were going to need some hierarchical data structures stored in the RDBMS. The relationships between nodes were stored via a 'parent_id' column that referenced another row in the same table. Although at face value this may seem slightly sensible, the reality has turned out very differently.

I have now been tasked with implementing some functionality that requires traversing the hierarchy - Specifically, I need to build a list of all of the descendents of a node for a given node. This would be trivial if the relationships were stored as 'parent -> children' but as the relationships are stored as 'child -> (unique) parent' I can't figure out a performant way of doing this (the naive approach is O(n^2) I believe).

Having wrestled with this for a few hours, the current thinking is that we should refactor the database but if anyone has experienced this before it'd be good to hear about your solution. If not, let this be a warning to anyone trying to save a tree in this fashion if you ever plan on having to traverse it!


问:
Charging a fee for GPL software
If I extend software under the GPL licence, I understand that my source code must be freely available. If my source code is freely available can I legally charge a fee for using the version that I publish?

My situation: I'm using data from a program in my program and have an In-App purchase for access to all the data. The source code is publicly available and is mentioned in the program. Is this allowed?

Obviously my software isn't extremely popular and I'm banking on the fact that lots of people have no interest in downloading and compiling it themselves.

I have read Can I use GPL software in a commercial application which discusses in detail, whether or not my software would have to be under the GPL, but it does not discuss money!

答:
The GPL license does not forbid you to ask money for obtaining your program.

However, when using the GPL, there is usually not much sense in asking money, because users of your program must have the right to re-distribute the program either in its original form or after making changes to it.

Due to this, once you have sold your first copy, you have a potential competitor who can charge a fraction of the price you sell for (down to not asking any money). For that reason, GPL programs are usually available free of charge.

Title: Charging a fee for GPL software


答:
I am not a lawyer, this is my understanding of the situation but it is not legal advice. If you want that pay a lawyer. I'm also basing this on GPLv2, the principles are mostly the same in GPLv3 but there may be differences in the details.

I understand that my source code must be freely available.

Not exactly, basically you must either provide the source along with the binaries[1] or provide a written offer valid for at least 3 years to provide the source to anyone on "a medium customarily used for software interchange" for "a charge no more than your cost of physically performing source distribution". If you distribute the source along with the binaries there is no requirement for you to directly make it available to the general public (but there is also nothing stopping anyone you provide it to from making it available to the general public)

If my source code is freely available can I legally charge a fee for using the version that I publish?

The GPL does not in general forbid charging money for stuff. As far as I can tell there would be nothing stopping you implementing in a GPL application a lockout that required for example date and machine ID based license codes. There would also be nothing stopping someone getting the source code and ripping your lockout code out.

My situation: I'm using data from a program in my program and have an In-App purchase for access to all the data.

Data that can be loaded by an program (but is not actually built-in to the programs binaries) is not considered part of the program. So it's perfectly fine to use non-free data with a GPL application. I would not think that making the data available via an in-app purchase would change anything in this regard.

Whether you can control distribution of the data depends on the type of data, local laws and whether you actually own the data in the first place. In some countries some types of data are not eligable for copyright and similar protection.

The source code is publicly available and is mentioned in the program.

That may not strictly speaking be enough (though in practice if people can reasonablly get the source code they are unlikely to be too picky on the details).

[1] "If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. "

Title: Charging a fee for GPL software

Body:
If I extend software under the GPL licence, I understand that my source code must be freely available. If my source code is freely available can I legally charge a fee for using the version that I publish?

My situation: I'm using data from a program in my program and have an In-App purchase for access to all the data. The source code is publicly available and is mentioned in the program. Is this allowed?

Obviously my software isn't extremely popular and I'm banking on the fact that lots of people have no interest in downloading and compiling it themselves.

I have read Can I use GPL software in a commercial application which discusses in detail, whether or not my software would have to be under the GPL, but it does not discuss money!


问:
In SPA what happens in terms of memory and performance when user hops across all the pages?
Imagine a humongous web aplication built using Single Page Application framework such as AngularJS. With its each route it downloads a couple of HTML template files. Each of these template files contain JS files unique to it. So, now when each of these template files download it will also pull in and download the JS files as well.

This is just a hypothetical situation to understand how browsers would work under such a situation.

What will happen in terms of memory and performance when user quickly hops across all the pages (which can be 100s or 1000s of such pages)? Will all the JS variables consume the memory and unnecessarily clog it or will the JS Garbage Collector come to the rescue?

答:
It depends upon your JavaScript code and your DOM (and in principle, of the JavaScript implementation in the browser; invite your users to use recent versions of browsers). You need to read more about garbage collection techniques (e.g. the GC handbook), see Mozilla SpiderMonkey's GC page.

A value which is still indirectly reachable from global or local variables won't be garbage collected. The GC will follow references in aggregate values (including closures, arrays, objects, ...).

You might want to carefully and cleverly use weak references, e.g. JavaScript WeakMaps.

Conceptually, the GC is computing the transitive closure of the reference graph, starting from global and local variables (on the call stack). These values are alive and the dead values are eventually destroyed by the GC since they are garbage. A value which is only reachable thru weak references won't be kept.

Even with a GC, a program can have a memory leak, in particular if it keeps in some variable a value which would never be useful in the future. And detecting this thru static code analysis techniques is an undecidable problem, provably equivalent to the halting problem.


问:
Optimization problem where to start, what algorithms to use?
I have an optimization problem and I was wondering where to start from to be able resolve it. I think it can be solved with an NP-complete algorithm but I am not sure where to start from. The problem is the following:

There are N types of different colored same-size rectangles that have to be printed.

For each type there is a minimum count that has to be printed.

Arranging them on a printing plaque costs X amount of money, each piece of paper printed costs Y amount of money.

They are all the same size so the maximum amount of rectangles on piece of paper is given as an input, of course you can arrange less than the maximum amount.

There could be more pieces printed than the minimum amount required.

What is the best way to combine the rectangles having the given input of types and count and prices for arranging and printing so the amount of X + Y to be the lowest?

Where should I start with this one, it really sounds like an NP problem where I try all the combinations of pieces of paper and record the best outcome.

答:
What you are trying to do is variation on a Bin packing problem. Effectively you are placing items into bins (plaques) and trying to minimize the wasted space, since in your example wasted space directly corresponds to lost money. The wikipedia article shows how this can be done/solved.

You may end up with an optimization problem on top of this, because you also have a variable number of items to be placed. In this case you would have a bin packing problem embedded in an optimization loop, running multiple bin packing problems attempting to find the optimal profit that satisfies your constraints.


答:
You can charge a fee for software covered by the GNU GPL. It's totally fine. The GNU project encourages you to charge what you can. GNU's "Free Software" philosophy is "about freedom, not price".

If you provide binaries to a customer, you also must provide source (or access to source). You don't have to provide the source to non-customers. You do have to make it just as easy to access the source as the binary -- for example, you can't charge an extra fee for the source.

You suspect that most of your customers won't be interested in exercising the rights that the GNU GPL gives them, and that's a fair assumption -- many people on this site use GPL'd software every day but a much smaller number modify or distribute it. The GNU GPL does say that if a customer wants to exercise their rights, you can't get in the way.

So it's quite likely that a tiny few will make use of the source code, and fewer still will distribute that code to others. But the GPL allows them to distribute it, and they can charge fees for distributing it or they can distribute it publicly without charge. As long as they follow the GPL distribution rules, you can't stop them. As you say, it's not super-likely to happen, and you are of course welcome to ask them not to do that.

From the GPL FAQ:

Does the GPL allow me to sell copies of the program for money?

Yes, the GPL allows everyone to do this. The right to sell copies is part of the definition of free software. Except in one special situation, there is no limit on what price you can charge. (The one exception is the required written offer to provide source code that must accompany binary-only release.)

Also from the GPL FAQ:

If I distribute GPL'd software for a fee, am I required to also make it available to the public without a charge?

No. However, if someone pays your fee and gets a copy, the GPL gives them the freedom to release it to the public, with or without a fee. For example, someone could pay your fee, and then put her copy on a web site for the general public.

Title: Charging a fee for GPL software


问:
What can be the cause of new bugs appearing somewhere else when a known bug is solved?
During a discussion, one of my colleagues told that he has some difficulties with his current project while trying to solve bugs. "When I solve one bug, something else stops working elsewhere", he said.

I started to think about how this could happen, but can't figure it out.

I have sometimes similar problems when I am too tired/sleepy to do the work correctly and to have an overall view of the part of the code I was working on. Here, the problem seems to be for a few days or weeks, and is not related to the focus of my colleague.

I can also imagine this problem arising on a very large project, very badly managed, where teammates don't have any idea of who does what, and what effect on other's work can have a change they are doing. This is not the case here neither: it's a rather small project with only one developer.

It can also be an issue with old, badly maintained and never documented codebase, where the only developers who can really imagine the consequences of a change had left the company years ago. Here, the project just started, and the developer doesn't use anyone's codebase.

So what can be the cause of such issue on a fresh, small-size codebase written by a single developer who stays focused on his work?

What may help?

Unit tests (there are none)?

Proper architecture (I'm pretty sure that the codebase has no architecture at all and was written with no preliminary thinking), requiring the whole refactoring?

Pair programming?

Something else?

答: Tight coupling, lack of testing, these are probably the most common culprits. Basically the common issue is just shoddy standards and procedure. Another is just incorrect code managing to get lucky for a while with correct behavior. Consider memcpy bug from Linus Torvalds where changing its implementation exposed (not caused) bugs in clients which used memcpy in places where they should have used memmove with overlapping source and destination.


答:
One thing that didn't come up yet:

Try to design your software from the command line arguments upwards.
Meaning:

Before designing the functionality, design the user interface.

This will allow you to drill down on edge cases and common cases early on.
Of course you'll still abstract the outside and the inside, but it's going to give much better result than just writing all the code and then slamming a CLI to it.

Furthermore, check out docopt (http://docopt.org/).

docopt is a great help with that in many languages, especially for python where you have severely limited, user-adverse argument parsers like argparse still being considered as "OK".
Instead of having parsers and subparsers and conditional dicts, you just define the syntax help (according to the matching POSIX standard) and it does the rest.


答:
In agile, this is called inspect and adapt. Use history as your guide.

You need to know your speed before you can start making any assumption about how quick you can get to the goal. In other words, run through a couple of iterations to see how fast you are running and then use that information to make plans.

The answer to your question is that you must first gather data before trying to do any long range planning.


问:
Modeling specific objects interaction
I want to model an interaction between classes, e.g. there is a general class Hero and he can have some items. (I came up with this analogy so it is easier to understand) Some of them are e.g. potions and can modify hero's hp, regen, strength etc., and others can be equipped ( run method hero.setArmor(item) )

I want to know how to maintain loose coupling so hero is only running methods like hero.use(item) and in items I can implement various actions that affect hero's private sections and use hero's methods. Items must have known who called them (because they hold information on what to do on hero).

I already tried another approach, using items inside hero, e.g hero have a list of items he can use on himself. That would look like item.use(this) where this is an instance of hero. OK now items must implement their use action on various classes, have modification rights of heroes. I can declare friend class in hero for this, but items have derived classes which are not friends to hero and have no access to private section. Inheriting friendship would solve the case, but I know it is not allowed in C++. Looking for general solution.

Is making heroes setters public a good approach in that situation?

答:
I'm really tempted to suggest entity-component systems, but that would be a total change in mindset and design strategy and possibly overkill. So sticking to the spirit of the question, I'll try to suggest some immediate steps.

The main goal I suggest to focus on is:

Make Each Entity Have as Little Knowledge as Possible

That is, don't make a hero know about more things than he needs to. Don't make a potion know about more things than it needs to in order to cause effects to some creature. This will ultimately reduce coupling quite effectively.

Given that goal, my first suggestion is to prefer this:

```<code>potion.apply(hero);
</code>```

... over this:

```<code>hero.use(potion);
</code>```

This is not a matter of syntactical preference (I actually prefer the second one). It's about coupling, cohesion, encapsulation.

I'm assuming the external system needs to know what a hero is carrying in his backpack, to list the items he possesses to the user. That's most likely a fundamental requirement.

Now, given that requirement, there is no need for a hero to know that he's using a disposable/consumable/usable item, like a potion. All that's needed is for the potion to know just enough about the hero to cause the desired effects for the type of potion involved (a temporary boost to strength, e.g.). Thus, I recommend potion.apply(hero), because otherwise you might simply end up with this:

```<code>void Hero::use(Disposable& item)
{
    item.apply(*this);
}
</code>```

... which is just a pointless kind of forwarding function, and it's increasing the number of responsibilities the hero class has when he probably already has plenty.

Abstractions

Again, with the idea of minimizing the amount of objects that things have to have about other things, a potion can just be a concrete implementation of a Disposable item, like so:

```<code>class Disposable
{
public:
     virtual ~Disposable() {}
     virtual void apply(Hero& hero) = 0;
};

class MinorHealingPotion: public Disposable
{
public:
     virtual void apply(Hero& hero)
     {
         hero.set_health(hero.health() + 10);
     }
};
</code>```

... but we can do better. Why does a potion need to know everything about a hero? Perhaps a hero himself models some abstract concept, like a Creature.

```<code>class Creature
{
public:
     virtual ~Creature()
     virtual int health() const = 0;
     virtual void set_health(int new_health) = 0;
     ...
};

class Hero: public Creature
{
public:
    ...
};
</code>```

Now we can do like so:

```<code>class Disposable
{
public:
     virtual ~Disposable() {}
     virtual void apply(Creature& creature) = 0;
};
</code>```

... and now we've increased the flexibility and loosened the coupling of our designs. We can even make health potions apply to a random NPC, e.g.

Interface Queries

But we can go even further. What if we had a base object which provides an interface query to see what interfaces they support? Maybe we can do this:

```<code>class Object
{
public:
     virtual ~Object() {}

     template <class Interface>
     Interface* query_interface()
     {
         return dynamic_cast<Interface*>(this);
     }
};
</code>```

Now we can start doing things like this:

```<code>class Health
{
public:
     virtual ~Health() {}
     virtual int health() const = 0;
     virtual void set_health(int new_health) = 0;
     virtual void apply_poison(int poison_amount) = 0;
     virtual void apply_disease() = 0;
     virtual void resurrect() = 0;
     ...
};

class Hero: public Object, public Health
{
public:
     ...
};
</code>```

Potions might implement interfaces like Item and Disposable.

```<code>class Item
{
public:
    virtual ~Item() {}
    int weight() const = 0;
};

class Disposable
{
public:
    virtual ~Disposable() {}
    virtual void apply(Object& obj) = 0;
};

class MinorHealingPotion: public Object, public Item, public Disposable
{
public:
     virtual int weight() const
     {
         return 20;
     }

     virtual void apply(Object& obj)
     {
         Health* health = obj.query_interface<Health>();
         assert(health && "The specified object has no notion of health!");
         health->set_health(health->health() + 10);
     }
};
</code>```

With a COM-style approach you can design really narrow interfaces that focus on one thing, like Health, Disposable, HandEquipment, etc. A shield might implement Item and HandEquipment. You then pass objects around and query if they satisfy the necessary interface requirements.

This can be really helpful because game rules can go all over the place with what would otherwise be very painful design-breaking obscure requirements unless you apply a much more flexible design strategy upfront than usual which can respond to the wildest set of design requirements. You might find a new need for a disposable item, for example, like a magic scroll which randomly causes an item in the reader of the scroll's inventory to catch on fire. Now you need disposable items to know about inventories possessed by the creatures to which they are applied, and before you know it, a disposable item might need a super-abstraction like just an all-encompassing, monolithic Creature interface to cover the full range of use cases unless you apply this COM-style interface query approach*. The "query interface" approach is precisely what protects you from being tempted to design huge blobs of functionality all in one interface.

* What I've shown above is not exactly COM as it's not focused on ABI, but just conforms to the basic query_interface part -- is there a formal name for this?. Maybe just a component-based design?

Setters and Getters

And finally, on to the last question, it's probably perfectly okay in this case to use setters and getters for things like health and strength attributes.

Again, a game design can potentially do so many wild things with objects and really tax object-oriented designs to the brim that it's hard to get a richer design than that. You might try to come up with more meaningful functions like heal and hurt instead of set_health, but it'll likely just make your classes more complicated.

So I recommend just using getters and setters when there isn't an easy way out of it with a property-oriented mindset, but paying attention to this information above of minimizing unnecessary knowledge that one entity possesses about another. With the COM-style approach, you only have to couple things like heros to the basic notion of an Item without really knowing whether it's body equipment or hand equipment or leg equipment or a disposable/consumable or whatever. Things like disposable items only need to know about Health if they do nothing more than affect the health of the object to which they are applied.

Title: Modeling specific objects interaction

Body:
I'm really tempted to suggest entity-component systems, but that would be a total change in mindset and design strategy and possibly overkill. So sticking to the spirit of the question, I'll try to suggest some immediate steps.

The main goal I suggest to focus on is:

Make Each Entity Have as Little Knowledge as Possible

That is, don't make a hero know about more things than he needs to. Don't make a potion know about more things than it needs to in order to cause effects to some creature. This will ultimately reduce coupling quite effectively.

Given that goal, my first suggestion is to prefer this:

potion.apply(hero);

... over this:

hero.use(potion);

This is not a matter of syntactical preference (I actually prefer the second one). It's about coupling, cohesion, encapsulation.

I'm assuming the external system needs to know what a hero is carrying in his backpack, to list the items he possesses to the user. That's most likely a fundamental requirement.

Now, given that requirement, there is no need for a hero to know that he's using a disposable/consumable/usable item, like a potion. All that's needed is for the potion to know just enough about the hero to cause the desired effects for the type of potion involved (a temporary boost to strength, e.g.). Thus, I recommend potion.apply(hero), because otherwise you might simply end up with this:

void Hero::use(Disposable& item)
{
    item.apply(*this);
}

... which is just a pointless kind of forwarding function, and it's increasing the number of responsibilities the hero class has when he probably already has plenty.

Abstractions

Again, with the idea of minimizing the amount of objects that things have to have about other things, a potion can just be a concrete implementation of a Disposable item, like so:

class Disposable
{
public:
     virtual ~Disposable() {}
     virtual void apply(Hero& hero) = 0;
};

class MinorHealingPotion: public Disposable
{
public:
     virtual void apply(Hero& hero)
     {
         hero.set_health(hero.health() + 10);
     }
};

... but we can do better. Why does a potion need to know everything about a hero? Perhaps a hero himself models some abstract concept, like a Creature.

class Creature
{
public:
     virtual ~Creature()
     virtual int health() const = 0;
     virtual void set_health(int new_health) = 0;
     ...
};

class Hero: public Creature
{
public:
    ...
};

Now we can do like so:

class Disposable
{
public:
     virtual ~Disposable() {}
     virtual void apply(Creature& creature) = 0;
};

... and now we've increased the flexibility and loosened the coupling of our designs. We can even make health potions apply to a random NPC, e.g.

Interface Queries

But we can go even further. What if we had a base object which provides an interface query to see what interfaces they support? Maybe we can do this:

class Object
{
public:
     virtual ~Object() {}

     template <class Interface>
     Interface* query_interface()
     {
         return dynamic_cast<Interface*>(this);
     }
};

Now we can start doing things like this:

class Health
{
public:
     virtual ~Health() {}
     virtual int health() const = 0;
     virtual void set_health(int new_health) = 0;
     virtual void apply_poison(int poison_amount) = 0;
     virtual void apply_disease() = 0;
     virtual void resurrect() = 0;
     ...
};

class Hero: public Object, public Health
{
public:
     ...
};

Potions might implement interfaces like Item and Disposable.

class Item
{
public:
    virtual ~Item() {}
    int weight() const = 0;
};

class Disposable
{
public:
    virtual ~Disposable() {}
    virtual void apply(Object& obj) = 0;
};

class MinorHealingPotion: public Object, public Item, public Disposable
{
public:
     virtual int weight() const
     {
         return 20;
     }

     virtual void apply(Object& obj)
     {
         Health* health = obj.query_interface<Health>();
         assert(health && "The specified object has no notion of health!");
         health->set_health(health->health() + 10);
     }
};

With a COM-style approach you can design really narrow interfaces that focus on one thing, like Health, Disposable, HandEquipment, etc. A shield might implement Item and HandEquipment. You then pass objects around and query if they satisfy the necessary interface requirements.

This can be really helpful because game rules can go all over the place with what would otherwise be very painful design-breaking obscure requirements unless you apply a much more flexible design strategy upfront than usual which can respond to the wildest set of design requirements. You might find a new need for a disposable item, for example, like a magic scroll which randomly causes an item in the reader of the scroll's inventory to catch on fire. Now you need disposable items to know about inventories possessed by the creatures to which they are applied, and before you know it, a disposable item might need a super-abstraction like just an all-encompassing, monolithic Creature interface to cover the full range of use cases unless you apply this COM-style interface query approach*. The "query interface" approach is precisely what protects you from being tempted to design huge blobs of functionality all in one interface.

* What I've shown above is not exactly COM as it's not focused on ABI, but just conforms to the basic query_interface part -- is there a formal name for this?. Maybe just a component-based design?

Setters and Getters

And finally, on to the last question, it's probably perfectly okay in this case to use setters and getters for things like health and strength attributes.

Again, a game design can potentially do so many wild things with objects and really tax object-oriented designs to the brim that it's hard to get a richer design than that. You might try to come up with more meaningful functions like heal and hurt instead of set_health, but it'll likely just make your classes more complicated.

So I recommend just using getters and setters when there isn't an easy way out of it with a property-oriented mindset, but paying attention to this information above of minimizing unnecessary knowledge that one entity possesses about another. With the COM-style approach, you only have to couple things like heros to the basic notion of an Item without really knowing whether it's body equipment or hand equipment or leg equipment or a disposable/consumable or whatever. Things like disposable items only need to know about Health if they do nothing more than affect the health of the object to which they are applied.


问:
Best practice for getting last record inserted in DB
Me and a couple of colleagues are having a discussion regarding the following case:

In an OrderStatus table we're keeping track of all the statuses an order goes through in time, including "Pending", "Available", "Returned", etc. There's a timestamp field in the table to keep track of when each status was added. However, there are two statuses that may be added exactly at the same time, one after the other, in which case both may have exactly the same timestamp (including milliseconds). In another part of the code, we need to check which is the last status an order was set to, and since we're ordering by the timestamp we can easily get the wrong record from the database.

The table has an IDENTITY(1,1) primary key, and my colleagues think we should order using that column, since that will always necessarily give you the latest record added to the table.

I feel like an IDENTITY column should be voided of any meaning and thus should not be used for any sorting, and would rather do a Thread.Sleep(1) to make sure the timestamps are different and we can keep sorting using that field.

What do you think is the best practice in this case?

答:
It sounds like an event sourcing approach would be helpful here

http://martinfowler.com/eaaDev/EventSourcing.html

essentially, each time you update the object, you load it, add the event to the history and save everything.

When you save the object, you check to see that nothing else has updated the history in the meantime. If they have, you rebuild the object from the new history and reattempt adding your event

Alternatively you can lock the object to cause other events to wait for you to finish.

This is superior to things like auto-inc columns because it ensures that the events are processed in order, not just saved in an order.

In your particular case however, it seems to me that your status is a function of the events which have happened. Instead of having the status read from the last event make it a calculation based on all the events which have occured.

In this case, you don't really mind which event happened first, or if two happened at the same time.

ie

say you have 'order picked' and 'customer credit check passed'

conceptually both of these can happen at the same time, but the status might be

'not picked' - no picked event

'pending credit check' - picked event but no credit check event

'ready for delivery' - both picked AND credit checked


答:
A better approach would be two keep two tables, current and history.  The current table would always be the latest update.  The other table would be a history table, which would always be just inserts and reads.  If you want to get the latest record, query the current table.  If your not allowing any dirty reads it will always be the latest record.  If you need the history, query the history table and sort by the PK.

For the current table you want to keep a timestamp so if someone updates the record after your read it you can handle the conflict appropriately before making the update.  For the history table you are always inserting so no check is necessary.  You could handle the history inserts with a trigger off the current table if desired.

In your example:

ORDER (CURRENT)

ORDER_HISTORY (HISTORY)

That would make the logic straight forward.

Title: Best practice for getting last record inserted in DB

Body:
Me and a couple of colleagues are having a discussion regarding the following case:

In an OrderStatus table we're keeping track of all the statuses an order goes through in time, including "Pending", "Available", "Returned", etc. There's a timestamp field in the table to keep track of when each status was added. However, there are two statuses that may be added exactly at the same time, one after the other, in which case both may have exactly the same timestamp (including milliseconds). In another part of the code, we need to check which is the last status an order was set to, and since we're ordering by the timestamp we can easily get the wrong record from the database.

The table has an IDENTITY(1,1) primary key, and my colleagues think we should order using that column, since that will always necessarily give you the latest record added to the table.

I feel like an IDENTITY column should be voided of any meaning and thus should not be used for any sorting, and would rather do a Thread.Sleep(1) to make sure the timestamps are different and we can keep sorting using that field.

What do you think is the best practice in this case?


问:
In REST is HATEOAS really about self-discovery or about navigation?
I'm trying to learn about REST and having problems with the concept of HATEOAS (Hypermedia As The Engine Of Application State).  What is it for?

It seems to me the majority of commenters on the web think that HATEOAS should be used by a client to discover how to use a RESTful web service.  And most seem to conclude that HATEOAS is not worth including in RESTful web services for one of two reasons:

1) HATEOAS only gives URLs but these are useless by themselves without knowing what methods can be used with each URL (eg HTTP GET, POST, PUT).  Since the additional information must be passed to the client out of band (eg via documentation) then there is no point in using HATEOAS;

2) Similar to (1) but takes it a step further:  The client can figure out what methods are applicable to a given URL by calling the HTTP OPTIONS method.  However, the client still needs out of band information, to describe the format of the data it must pass for, say, POST or PUT methods.  So we end up in the same place as (1) - HATEOAS isn't sufficient for a client to discover everything it needs to know, so why bother with it.

These arguments seem valid if HATEOAS is supposed to be used by a client to discover how to use a RESTful web service.  However, is that what HATEOAS is for?  From the few examples I've seen, it seems to me to be perfect for navigating through a web service - I've performed a certain action, now what are the valid actions I can perform next?  That seems to me to gel with the "Application State" part of HATEOAS but very few articles I've read talk of it in terms of navigation, almost all are about discovery.

So, is HATEOAS about discovering how to use a RESTful web service or is it really about navigation?

答:
Disclaimer: answer offered without first rereading the Fielding thesis.

HATEOAS supports the discovery of previously unknown application states.

Think state machine.  The hypermedia representation sent to the application describes a current application state, and it describes which triggers are valid transitions out of the state.

It doesn't necessarily describe how to implement the trigger.

As usual, consider the web as the Ur example.  You start your Wikipedia application by directing your browser to the landing page, and three hours later you find yourself reading about Citrus Taxonomy.

How does that happen?  Wikipedia sends a hypermedia description (text/html) of the application state (the landing page); included in the hypermedia are links (anchor tags).  The application (browser) knows what to do with those because the implementation was written with awareness of the html specification.

When we write html that conforms to a new version of the specification, the hypermedia doesn't tell old browsers how to implement it -- Netscape 2.0 doesn't magically "discover" how to implement html5 embedded video.

In general, the hypermedia document provides the triggers that are supported, but the client is expected to ignore any triggers that it doesn't recognize.  Definitions of the triggers themselves are out of band.

So, is HATEOAS about discovering how to use a RESTful web service or is it really about navigation?

Consider a "Choose Your Own Adventure" book.

To visit the Cave of Wonders, turn to page 17.

Is the book telling you how to navigate the pages, or is it telling you how to discover the story?


答:
I did a stint at a huge printing company. I believe we ran into the same problem. Let me rephrase it. The constraints:

An industrial printing plate costs X dollars to layout and fabricate. It's not an insignificant amount.

Each printed sheet costs Y dollars. It's a smaller number but can add up.

There are N unique "rectangles" to print. For the sake of explanation, we can say they're different colors, but really they're just different pages of a magazine, different letters, different posters, or whatever.

You can layout these rectangles on any number of plates in any configuration you wish. Just keep in mind that plates cost money and it's complicated to keep track of the numbers of rectangles printed when they're on more than one plate.

You need a certain number of each rectangle. Given the complications of laying out plates, you'll likely print a few too many. But you can never print too few.

It's not obvious, but these givens provide a system of linear equations:

```<code>(# of plates * plate cost) + (# of sheets * sheet cost) = total cost
# of red rectangles >= min red
# of blue rectangles >= min blue
# of yellow rectangles >= min yellow

# of red rectangles = sum(
    # of red rectangles on plate p * # sheets printed from plate p)
# of blue rectangles = sum(
    # of blue rectangles on plate p * # sheets printed from plate p)

etc...
</code>```

So... all you need to do is solve the system of linear equations to minimize total cost. Easy, right? Not really. Solving linear systems is a big topic and no less NP-hard than any other optimization. To give you an idea of how big:

Intro. from the University of Iowa (pdf)

Intro. from UCLA (pdf)

Topic overview from the University of Baltimore

Research: solving via gradient systems (pdf)

To be honest, the topic is too big for a Q&A. My hope is that seeing it as a linear system might give you an entry point, but the truth is that it's pretty complicated stuff. Without some in-house expertise, you may need to settle for "good enough". If your project has a little money available, consider bringing in a consultant for a short time.

Title: Optimization problem where to start, what algorithms to use?

Body:
I have an optimization problem and I was wondering where to start from to be able resolve it. I think it can be solved with an NP-complete algorithm but I am not sure where to start from. The problem is the following:

There are N types of different colored same-size rectangles that have to be printed.

For each type there is a minimum count that has to be printed.

Arranging them on a printing plaque costs X amount of money, each piece of paper printed costs Y amount of money.

They are all the same size so the maximum amount of rectangles on piece of paper is given as an input, of course you can arrange less than the maximum amount.

There could be more pieces printed than the minimum amount required.

What is the best way to combine the rectangles having the given input of types and count and prices for arranging and printing so the amount of X + Y to be the lowest?

Where should I start with this one, it really sounds like an NP problem where I try all the combinations of pieces of paper and record the best outcome.

Body:
I did a stint at a huge printing company. I believe we ran into the same problem. Let me rephrase it. The constraints:

An industrial printing plate costs X dollars to layout and fabricate. It's not an insignificant amount.

Each printed sheet costs Y dollars. It's a smaller number but can add up.

There are N unique "rectangles" to print. For the sake of explanation, we can say they're different colors, but really they're just different pages of a magazine, different letters, different posters, or whatever.

You can layout these rectangles on any number of plates in any configuration you wish. Just keep in mind that plates cost money and it's complicated to keep track of the numbers of rectangles printed when they're on more than one plate.

You need a certain number of each rectangle. Given the complications of laying out plates, you'll likely print a few too many. But you can never print too few.

It's not obvious, but these givens provide a system of linear equations:

(# of plates * plate cost) + (# of sheets * sheet cost) = total cost
# of red rectangles >= min red
# of blue rectangles >= min blue
# of yellow rectangles >= min yellow

# of red rectangles = sum(
    # of red rectangles on plate p * # sheets printed from plate p)
# of blue rectangles = sum(
    # of blue rectangles on plate p * # sheets printed from plate p)

etc...

So... all you need to do is solve the system of linear equations to minimize total cost. Easy, right? Not really. Solving linear systems is a big topic and no less NP-hard than any other optimization. To give you an idea of how big:

Intro. from the University of Iowa (pdf)

Intro. from UCLA (pdf)

Topic overview from the University of Baltimore

Research: solving via gradient systems (pdf)

To be honest, the topic is too big for a Q&A. My hope is that seeing it as a linear system might give you an entry point, but the truth is that it's pretty complicated stuff. Without some in-house expertise, you may need to settle for "good enough". If your project has a little money available, consider bringing in a consultant for a short time.


问:
How useful are function points?
How useful is it to measure function points?

We use function points at my new job.  I've heard of function points but haven't had any training or experience... but I don't have much confidence in things that cannot be explained succinctly.

答:
I work in an organization where we introduced function points for calculating fixed price projects, i.e. customer and we count based on specs, agree the count and then multiply the #FP with a FP price in order to determine the project price. All this in an environment with two-digit Million Euro yearly project turnover. Intention is to remove ambiguity and negotiation from price determination which was a constant cause of friction.

We have done an initial calibration, evaluating about 2 years of project history worth two-digit Million Euro.

We clearly see that #FP and project costs correllate very indirectly. Deviations of +/- 50% are reasonably possible. However, we see (well we expect, or better: we hope) that in the long run function point counts and project costs converge.

We are now in the process of rolling this out into the organization and experience (from a suppier point of view):

Discussions about applications of FP counting rules. There are standards on this, however, these are subject to neglectance if one cannot argue about prices directly.

Client impressions that prices went up, despite the efforts we spent and are spending in calibration and calibration verification. Suspected reason is that this procedure makes costs brutally clear, no way to hide, shift or cover costs in some "don't ask" or strategic projects.

Need to handle projects that do not cover their costs (50% undershoot...)

Title: How useful are function points?