问:
Algorithm to 'segment' a number into blocks of n?
I'm not sure how to word the title properly, but the problem goes something like this:

I have 5 nodes, and node 0 is the "master".

User inputs a number, e.g. 100 to the master.

master "splits" the number into 5 parts, 0 - 20, 21 - 40, 41 - 60, 61 - 80, 81 - 100.

the nodes will then take the number, and do some calculation, and return the result back to the master.

The problem is the segmentation part. What if the number is something weird e.g. 101?

答:
Your problem addresses the pidgeonhole principle (http://en.wikipedia.org/wiki/Pigeonhole_principle).

It simply sais that if you got N items and you want to put them into M containers, where N is greater than M, then at least one container has to hold at least ceil(N/M) (Where ceil(x) is the smallest integer greater than or equal to x) items.

You can solve your problem for example with the following algorithm:

```<code>algorithm1(N,M)
    A = Array of size M
    i = remainder(N/M)
    for x from 0 to i-1
        A[x] = ceil(N/M)
    endfor
    for y from i to M-1
        A[y] = floor(N/M)
    endfor
    return A
</code>```

This will distribute your items equally between the containers.

Body:
Your problem addresses the pidgeonhole principle (http://en.wikipedia.org/wiki/Pigeonhole_principle).

It simply sais that if you got N items and you want to put them into M containers, where N is greater than M, then at least one container has to hold at least ceil(N/M) (Where ceil(x) is the smallest integer greater than or equal to x) items.

You can solve your problem for example with the following algorithm:

algorithm1(N,M)
    A = Array of size M
    i = remainder(N/M)
    for x from 0 to i-1
        A[x] = ceil(N/M)
    endfor
    for y from i to M-1
        A[y] = floor(N/M)
    endfor
    return A

This will distribute your items equally between the containers.


问:
Is a 'least significant bit' used anywhere practically today?
I'm working on a library that supports file reading, and right now I've always assumed that all the bytes are written in most significant bit first format. Is the least significant bit first format ever practically used anywhere today on any platform? The library I'm writing isn't targeted at older operating systems (ideally anything onwards from the year 2000).

I'm curious if writing such a feature in might be a waste of time that could be spent on other things.

答:
Well, you might have heard of a little thing called Ethernet, which transmits most-significant byte first, but least-significant bit first.

The thing is, no one cares unless they happen to be designing an Ethernet card, because the card's hardware packs the data into bytes, which is how it's accessed everywhere else in the system.

So if your library happens to be designed to run directly on a disk drive controller chip, and you have to read data written by other controllers following their own standards, by all means include the option.  Anywhere else, it doesn't matter.

ContentLicense: CC BY-SA 3.0


问:
Should code comments explain the control flow?
Should comments explain how the application control flow works? For example, the relationships between classes, how this function is used by other functions, and what we are  trying to do with these objects and processes? I suppose what I'm asking is should a person be able to understand how an application works simply from reading your comments and walking through the code? Or is this something we mainly do with other external documentations outside of the code? </p>

答:
In my opinion, comments should explain anything that cannot be made self-evident by the actual code, and any detailed external documentation you need should be generated from those comments (presumably as part of your automated build/deployment system).

Clarifying what a class or function should be used for, what problems it was created to solve, and where it fits into the program as a whole probably are things worth commenting on. Just make sure the comment is right on top of whatever it's talking about, and it's no longer than it needs to be, since we want to make it easy for future devs to keep code and comments in sync. An outdated comment is usually worse than none at all.

"Control flow" normally means things like using if statements and for loops, which should almost never need comments, but it sounds like what you're trying to ask about is more like a big comment on top of main() that summarizes what top-level functions get called in what order and why; that would be fine if you can ensure it stays up to date (which is easier said than done).

For the very, very high-level conceptual view of how your program works, you probably should rely on a short hand-written file outside the source code (such as the README.md file on a Github repo). But once people know that basic information, yes they should be able to dive into any part of the source tree and figure out what's going on from just the code and comments they see in front of them.


答:
No.

If people cannot read the code and understand what the code is doing, that is a sign that your code is poorly designed, overly complex, or poorly named (or some combination thereof). Comments don't fix those problems - they only exacerbate them.

Use comments to describe why code is doing weird things.

More conventional documentation is better for describing the wider architecture/application.

Title: Should code comments explain the control flow?

Body: Should comments explain how the application control flow works? For example, the relationships between classes, how this function is used by other functions, and what we are  trying to do with these objects and processes? I suppose what I'm asking is should a person be able to understand how an application works simply from reading your comments and walking through the code? Or is this something we mainly do with other external documentations outside of the code? </p>


答:
Comments should not explain how the code works.  The code is there to explain how it works. If the implementation is changed, the comment becomes incorrect.

Mostly the comments should explain What the purpose of the code is.  This allows you to change the implementation over time without invalidating the comment.   Changing the purpose of the code is rarely a good idea.

For public interfaces you may want to provide machine extractable documentation which explains:

What its purpose is and what is returned.

Describe purpose and valid values are for each parameter.

Possibly explain how the functionality is expected to / might be used.

There are various tools that extract documentation from contents.  Java has javadoc, which extracts certain comments and build a documentation tree for a package of classes.

Good names can be sufficient documentation.  Avoid names which explain how functionality is implemented.

If the code has been optimized, it may be appropriate to include a comment explaining why the code was changed and what the results where.  This should reduce the chance that the code is refactored to remove the optimization.  Likewise, if a particular algorithm is required, a comment explaining the requirement would be appropriate.  These two comments may be at odds as a more accurate algorithm may be a slower algorithm.

Comments on bug fixes should be in the version control.  These should explain why the change was required/done rather than how it was implemented.


问:
Differences between Instruction set (architecture) and machine language?
Tanenbaum's Structured Computer Organization says:

Every computer has an ISA (Instruction Set Architecture), which is
  a set of registers, instructions, and other features visible to its
  low-level programmers.

This ISA is commonly referred to as machine language, although the
  term is not entirely accurate.

A program at this level of abstraction is a long list of binary
  numbers, one per instruction, telling which instructions to execute
  and what their operands are.

My questions are:

ISA includes instructions and registers. As far as I know, an instruction consists of an opcode (i.e. operation) and operand(s). Is an opcode  too small to be an member in the ISA?

As far as I know, a programming language is a set of some programs. So is a machine language also a set of some programs?

What is the difference between ISA and machine language? Is it that a machine language is a set of programs, while a ISA is not a set of programs but a set of more basic units (e.g. registers, instructions) which together form programs?

答:
It looks like you borrowed some vocabulary from theoretical computer science (regarding the words "set" and "language"), and tried to use that to interpret the textbook description of the lower level computer systems (CPU and hardware).

The word "set" as in "instruction set architecture" refers to the set of predefined opcodes that are valid for the given CPU architecture.

For example, this page (x86 instruction listings, on Wikipedia) lists the opcodes one can expect on various generations of the IA32 architecture. Each opcode is a member in this "instruction set".

When the author says "... is not entirely accurate", my guess is that he is referring to the fact that there is no grammar one could expect from a sequence of machine instructions.

To clarify further, the CPU reads the instruction bytes, and if it is a valid machine instruction, it will be executed. Otherwise, typically an "invalid instruction" hardware exception will be generated, which will stop the current execution and transfer control to a different program (possibly belonging to the operating system).

However, there is no grammar that defines what is a valid sequence of machine instructions. In some sense, there is no structure or hierarchy that one can expect all valid sequences of machine instructions to conform to.

The machine instructions found in most compiled software programs are formed with some structure; however, not all of them do. The CPU will happily execute a "spaghetti sequence of machine instructions", performing unconditional or conditional jumps as it encounters each; and until recently, it is possible for a sequence of machine instructions to modify parts of itself.

Some CPU instructions are designed to facilitate structured programming:

the stack register and push / pop instructions

the return address register, and the call / return instructions for executing subroutines (also known as procedures or functions)

loop instructions (increment or decrement a register, checks against a limit, and then jumps to a specified address if the limit has not been reached)

string copy instructions (a loop instruction that repeatedly copies bytes from one address range to another address range)

Even though some of these instructions appear to form pairs (push vs pop, call vs return), in reality a valid sequence of machine instructions does not need to match these pairs. That is, one could write the next program counter value into the memory address pointed to by the stack register (simulating a push), and then perform a jump into the start of a subroutine (which, together with the previous push, becomes a simulation of a subroutine call). The subroutine could use the regular return instruction.


答:
Note that Tanenbaum talks about what is exposed to low level programmers, not what happens at the level of CPU execution cycles. Down at that level are various micro operations that are involved in branch prediction, prefetch, pipelining, etc.

Machine code instructions get broken down into smaller chunks after the point where programmers have direct access.

Title: Differences between Instruction set (architecture) and machine language?

Body:
Tanenbaum's Structured Computer Organization says:

Every computer has an ISA (Instruction Set Architecture), which is
  a set of registers, instructions, and other features visible to its
  low-level programmers.

This ISA is commonly referred to as machine language, although the
  term is not entirely accurate.

A program at this level of abstraction is a long list of binary
  numbers, one per instruction, telling which instructions to execute
  and what their operands are.

My questions are:

ISA includes instructions and registers. As far as I know, an instruction consists of an opcode (i.e. operation) and operand(s). Is an opcode  too small to be an member in the ISA?

As far as I know, a programming language is a set of some programs. So is a machine language also a set of some programs?

What is the difference between ISA and machine language? Is it that a machine language is a set of programs, while a ISA is not a set of programs but a set of more basic units (e.g. registers, instructions) which together form programs?


问:
Releasing open source software too soon
What is the moral responsibility of releasing open source software too soon?  For instance, a close-to-complete product that hasn't been fully tested.

What is the expectation of the programmer? Wait until it is fully tested, or release to open source and then continue further development, testing, and advancements?

The fear is that software is open sourced and could potentially lead to issues for consumers.

Is this an unfounded fear?

答:
There is no moral responsibility whatsoever. No one is being forced to use your half-baked software.

The only thing to be concerned about would be your credibility.

Title: Releasing open source software too soon


问:
Design, how to utilize The Hardware (multiple threads and/or GPU) while indexing (via a database) a very large set of binary files
Problem

How can design my file parser to maximize the hardware when processing (creating meta data for) a large file

(i.e. how to avoid being blocked by IO and running out of memory)

preferably I would like to give the user a "high priority" (locks the system apart from some progress UI) and a "run in background" option (Allows the user to start using data that has already been indexed/loaded)

Assumptions

Presumably I will have no problems having multiple threads reading the same set of files?

The way I see it the biggest bottleneck / will be writing to the database. Presumably I will have to lock/unlock that and have each thread queue up data to write in batches?

As each thread will need its own data queues I am unsure how to make sure the machine does not run out of memory

When processing the data blocks I basically want to get stuff like averages, minimums and maximums, I have assumed I can't use the GPU to process the data blocks like this? it feels like there is too much shared data to utilize the GPU here.

Detail:

I am working with very large data sets, split across multiple files (each "full" data file is 1.5gb and there are often several of these files (I am looking at one now that has 10)

The data effectively contains a series of buffers that I want to access 1 or more at a time.

|headerInfo-datablock|HeaderInfo-datablock|HeaderInfo-datablock| (thousands)

I want to go through the data file, filling a database with index information (so i can access specific blocks quickly based of either information in the header or the datablock itself). If I can I would also want to blit information to a graph image as I do it.

Hardware

The machine it will be ran on is a proper workstation PC so there is plenty of ram and processing power to utilize :)

On the top spec machine there is 64GB of ram and a i7 that is 12 cores (hyperthreaded) so in theory i could get away with loading the whole file into memory and then processing. But some of the lower spec machines have a lot less ram and the files that people are producing are getting bigger every day, so Its not very forward thinking to rely on that plan.

Technology

I am using C# so any tips on the best ways to judge the hardware capabilities in C# (at run time) and maximize them when accessing a set of large files, would be a great bonus

答:
You should throw as many I/O jobs as possible and let the OS does its job, use async I/O to do that or mmap(). Don't assume you know how to it better than the OS, instead you can give hint. That's why there's call like madvise(), to let the OS know if you only need the data to be read once or sequentially, etc. Yes, even with magnetic disks you want to use every spindle and try to saturate the i/o bandwidth.

The only thing you shouldn't do is use more memory than what you have. Trashing happens when OS has to read something, discard and read it again. It's not the same as keeping the system busy, which is the goal of having good OS (high utilisation).


答:
I believe on the contrary that you should release an open source software as soon as possible. There is no "too soon" for that (but it should compile).

Or at least publish the source code very early and continuously (e.g. by frequent pushes on github), without making formal releases.

However, it is very important to flag it as alpha or beta stage, and if possible to say (e.g. in a README or TODO file, and on some blog, etc...) what is missing, not tested, or in bad shape. You should also use the version number to convey such information.

With free software, the best that should happen is that someone glances into the source code and propose you a small patch improving it. This is why you make your software free!

Hence, you need to make visible your daily work on your free software! External contributors would be pissed off if their patch won't work with, or is a duplicate of, your recent software source code.

What you should be afraid of is nobody getting interested by your software (and contributing to it). Attracting outside interest to a free software (in particular, attracting external contributors) is a long journey.

Title: Releasing open source software too soon

Body:
What is the moral responsibility of releasing open source software too soon?  For instance, a close-to-complete product that hasn't been fully tested.

What is the expectation of the programmer? Wait until it is fully tested, or release to open source and then continue further development, testing, and advancements?

The fear is that software is open sourced and could potentially lead to issues for consumers.

Is this an unfounded fear?


答:
The point is that the same Instruction Set can be used differently.

And in practice, for efficiency purposes, that may matter a lot. An optimizing compiler can (and will, e.g. GCC with -O2 -mtune=native) produce different machine code for the same ISA, depending on the target processor. So the code optimized for an Intel processor is not the same as the code optimized for a AMD processor, even if it uses the same ISA. Machine code optimized for one will  not be the fastest code on the other one.


问:
In MVP, should presenters instantiate and control other presenters?
I've implemented an application using MVP with GWT, which is working out very nicely for views that have a single purpose.  Now, it has evolved into views that are achieving multiple purposes in a single window.  So now I have a view of views with each view having its own presenter.  I used this example as my model for building out the application, take a look.

The "view of views" also has its own presenter, which instantiates (or receives) the presenters for each of the other views it needs to fulfill its purpose.  I reveal event interfaces through those presenters for the "view of views" presenter to hook into and listen and react to what's going on inside those other presenters & views.

My questions are:

Am I still following MVP principles or have I violated the separation of concerns somewhere by having presenters create/receive and control other presenters?  aka Should I be doing this?

What are some other design patterns for creating interfaces that are also composed of other complex interfaces?

Update

In response to Robert Harvey's question, there is difficulty with passing objects from a presenter of a view to the presenter of the "view of views" when an event is triggered.  For instance, a button will flag a ClickEvent and the handler attached to this will need to pick up the data object related to the ClickEvent through another method revealed by the view's presenter.  So this works, but do feel it will cause more problems later on as this kind of object handling grows in complexity.

答:
Sorry for replying to this so late but someone else may see this....

This is a common issue on Android and the usual solution is to have the views implement interfaces owned by the calling views.

This makes a real mess however, and really makes it hard to know whats going on.

We solved this is issue by using the Observer pattern embodied in a Bus (EventBus) from square.

The presenters registered for events and told their views when necessary because sometimes they also needed to do other things (make network requests, store data in db, etc).


问:
Loggers - Functional, non-functional or layered?
We use different loggers to break up and apply specific rules to different kinds of log data. We typically specify which logger to be used with something like this:

```<code>var logger = Logger.GetLogger("MyLogger");
</code>```

What is a recommended strategy on loggers?

Functional: For example, "Sales", "Administration", "Orders", etc.

Non-functional: For example, "Performance", "Caching", "Authentication", etc.

Layered: For example, "DAL", "Models", "Infrastructure", "BLL", etc.

Classes: For example, "OrderRepository", "OrdersController", etc.

I have often see the use of class names, but surely this is too granular?

答:
It depends on what that string you're passing in actually does. For this answer, I'm going to assume that string is a "scope prefix", i.e. a string that simply gets printed out at the beginning of every log message output via this logger to make it clear where it comes from, because that's how every logger I've ever worked with did things (if it does do anything fancier, magic string values probably aren't the best way to implement that fancier thing).

Logs are important because one day, that one bug will happen on production to that one client and none of you devs will know how to reproduce it. Pretty much anything to do with logging should be designed around maximizing the chances you can quickly get a useful hint out of whatever your program logged, because that might be all you have.

So your logger's "scope prefix" should be as fine-grained and explicit as possible, preferably specifying the file or class it's been created in, not just the layer or department that file belongs to. Where I work, each file's logger is required to use the full filepath as its prefix (relative to the top of the package), and this has been very helpful for quickly pinning down where log output comes from in the heat of debugging.

Of course, that's assuming you have no silly technical constraints on logging like "only 80 characters per line; the rest get dropped" or "the server explodes if we log more than 100 characters per second". If you do, then would I begrudgingly consider using a prefix as coarse and terse as "DAL" or "BLL".


问:
Executing scripts in parallel based on dependency tree
We have an app that is using a fairly simple stack (Linux, PHP, Oracle, Shell Scripts, etc).

We have a series of scripts that need to be executed:

/scr/app1/start.sh

/scr/app2/start.php

/scr/app3/kickoff.py

/scr/app4/test.sh

The dependency rules are as follows:

app1 must be run first

app2 then must be run next

app3 and app4 can be run in parallel

That being said, I am looking to capture the following from ALL scripts:

exit codes (used to determine success of failure / breakage of chain)

standard out and/or standard error

The solution does not necessarily have to be written in PHP, it just has to work. Node.js / io.js is part of our build stack so we are comfortable building there.

Basically the parallelism is the real challenge that I see. What is the best approach to this problem while satisfying all of the requirements?

答:
You can write a shell script to do this.

Run app1 and redirect the stdout and stderr to a file. Check the exit code, if fail, exit.

Same as above.

for running app3 and app4 parallely, you can run it in background. To capture the output and return codes, you should take a look into bash coproc (http://wiki.bash-hackers.org/syntax/keywords/coproc). Redirect the outputs to separate files, so they don't get messed up, later you can concat it if you wish.


答:
It is the same as with closed source software. Communication is important.

Inform users what the state of the software is and why it is available for download.

Software will always lead to customer issues, no matter if it is fully tested or not. Most customers do accept that fact, and some customers never do. But if the software will lead to more issues than could be reasonably expected, there is a moral obligation to inform the customer of the risk they are taking. Information should be both in short form ("Alpha/Beta/EarlyAccess" labels)*, and in detail: A list of known issues, workarounds, and special considerations, e.g. if it's likely that data can be corrupted.

*Be aware that users have been trained by some big software companies to think of "Beta" as a state where the software is rather solid, so telling the user that the software is "Beta" is often not sufficient information.

Title: Releasing open source software too soon


问:
What is the ettiquite for releasing a Perl module based on someone else's module?
I have written a Perl module by starting with an existing Perl module of related functionality and modifying heavily. In fact, acccording to git blame I have changed (or created) every line of non-biolerplate code in the module. Of course, I have also changed the name of the module, so if I uploaded it to CPAN, it would not directly conflict with the original module.

Anyway, despite my heavy modifications, the module is still conceptually based on its predecessor, and I would like to give credit to its authors. However, I can see how they might not appreciate having their names and emails slapped on what appears to be a new module without their knowing. So should I just put myself as the sole author and put the original module's authors in an "Acknowledgements" section? What is the best way to credit the original authors in my module?

答: How about you email the author and ask them how they want to be acknowledge? The seems like the logical thing to do. Don't Perl modules include the email address of the author?</p>

ContentLicense: CC BY-SA 2.5


问:
Addition or deletion of elements of a dynamic array
Is there any consensus among programmers (or a common convention) on the "right way" to deal with the addition or deletion of one or more elements of a dynamic (mutable) array at runtime while gracefully handling changes to the references to the other elements?

For example within a loop in JavaScript, to remove some elements

does one use delete() to replace the items with 'undefined' while keeping the length of the array unchanged, so that references to the other elements have not changed?

Or do you slice() or splice(x,1) the array and then somehow update all current references?

Or do you make a copy of the array at the beginning of a function call, for example, then use delete() while still in that function, then at the end use filter() to remove the undefined slots and then write that back out to the original object?

What if more than one user or thread is trying to access this array simultaneously? Is the only choice a locking mechanism for writes? Or perhaps the answer is simply, "it just depends on what you want/need it to do".

Thanks in advance for your opinions.

答:
Only convention I know for situations where you have a lot of inserting and deleting in a list is to not use an array.

Use a linked list or a binary tree instead. These data-structures are made for inserting and deleting.


问:
How does branch prediction work, if you still have to check for the conditions?
I was reading the popular answer about Branch Prediction from https://stackoverflow.com/q/11227809/555690, and there is something confusing me:

If you guessed right, it continues on.

If you guessed wrong, the captain will stop, back up, and yell at you to flip the switch. Then it can restart down the other path.

If you guess right every time, the train will never have to stop.

If you guess wrong too often, the train will spend a lot of time stopping, backing up, and restarting.

But this is what I don't get: to know whether your guess was right or wrong, you have to make a condition check anyway. So how does branch prediction even work, if either way you are still doing the same conditional check?

What I am trying to say is, isn't branch prediction exactly the same as having no branch prediction at all because you are doing the same conditional checks anyway? (obviously I'm wrong, but I don't get it)

答:
Short form:

Some CPUs can start working on a new instruction before finishing the old one. These are the CPUs that use branch prediction.

A pseudocode example:

```<code>int globalVariable;
int Read(int* readThis, int* readThat)
{
    if ((globalVariable*globalVariable % 17) < 5)
       return *readThis;
    else
       return *readThat;
}
</code>```

The above code checks a condition and based on the outcome it needs to return either the value stored at memory location addThis or the value stored at readThat. If branch prediction predicts the condition to be true, the CPU will already read the value stored at memory location addThis while doing the calculation necessary to evaluate the if statement. This is a simplified example.

Body:
Short form:

Some CPUs can start working on a new instruction before finishing the old one. These are the CPUs that use branch prediction.

A pseudocode example:

int globalVariable;
int Read(int* readThis, int* readThat)
{
    if ((globalVariable*globalVariable % 17) < 5)
       return *readThis;
    else
       return *readThat;
}

The above code checks a condition and based on the outcome it needs to return either the value stored at memory location addThis or the value stored at readThat. If branch prediction predicts the condition to be true, the CPU will already read the value stored at memory location addThis while doing the calculation necessary to evaluate the if statement. This is a simplified example.


答:
TL;DR:

Release Early. Release Often.

Personal anecdote:

I was really excited about the project I was working on. Like, really excited. I couldn't sleep at night excited. So, I pushed my co-dev into releasing v1.0 faster than he wanted to.

It was terrible. Nothing worked the way it was supposed to. There were bugs at every turn, but we logged them and fixed them. We even had a few early adopters submit bugs we might not have found. A week or two later we released a new release that addressed a lot of the issues and then went back to building new features.

Releasing early was the best thing we could have done. It put our product in front of real users. Doing this exposed bugs we may or may not have found and made our project better. It also let those early adopters know that we're serious about this project. There are going to be more releases and active development.

It could have easily gone the other way too though. We could have ignored those bug reports. Or we could have not reacted quickly. It might have been a different story if it took us 3 months to release v1.1 instead of a few weeks.

Title: Releasing open source software too soon


答:
The consensus I am aware of (I only know a couple languages, not all of them) is as follows:

If the use of the array is somewhat complex, such as in the case of multithreaded access to the array, the array is put in a wrapper class. The wrapper class then exposes the minimum necessary amount of operations that can be performed on the array.

If the use is simple and the array is used synchronously, then it doesn't matter as long as the code has a good balance in terms of performance and being readable. Where that balance lies depends on the requirements, but it's usually "As readable as possible while being fast enough".

Title: Addition or deletion of elements of a dynamic array

Body:
Is there any consensus among programmers (or a common convention) on the "right way" to deal with the addition or deletion of one or more elements of a dynamic (mutable) array at runtime while gracefully handling changes to the references to the other elements?

For example within a loop in JavaScript, to remove some elements

does one use delete() to replace the items with 'undefined' while keeping the length of the array unchanged, so that references to the other elements have not changed?

Or do you slice() or splice(x,1) the array and then somehow update all current references?

Or do you make a copy of the array at the beginning of a function call, for example, then use delete() while still in that function, then at the end use filter() to remove the undefined slots and then write that back out to the original object?

What if more than one user or thread is trying to access this array simultaneously? Is the only choice a locking mechanism for writes? Or perhaps the answer is simply, "it just depends on what you want/need it to do".

Thanks in advance for your opinions.


答:
Yes, the condition is checked either way. But the advantage of branch prediction is that you can do work instead of waiting for the result of the condition check.

Lets say you have to write an essay and it can be about topic A or topic B. You know from previous essays that your teacher likes topic A better than B and chooses it more often. Instead of waiting for his decision you can start writing the essay about the first topic. Now there are two possible outcomes:

You began your essay on the wrong topic and have to drop what you have written so far. You have to start writing about the other topic and it is the same time effort as if you had waited.

You guessed right and you have already work done.

Modern CPUs are idling most of the time because they are waiting for IO responses or the outcome of other calculations. This time can be used to do some future work.

Even if you have to dismiss what you are doing in this idle time - it's most likely to be more effective if you have the ability to guess which path the program will chose. And modern CPUs have this ability.

Title: How does branch prediction work, if you still have to check for the conditions?

Body:
I was reading the popular answer about Branch Prediction from https://stackoverflow.com/q/11227809/555690, and there is something confusing me:

If you guessed right, it continues on.

If you guessed wrong, the captain will stop, back up, and yell at you to flip the switch. Then it can restart down the other path.

If you guess right every time, the train will never have to stop.

If you guess wrong too often, the train will spend a lot of time stopping, backing up, and restarting.

But this is what I don't get: to know whether your guess was right or wrong, you have to make a condition check anyway. So how does branch prediction even work, if either way you are still doing the same conditional check?

What I am trying to say is, isn't branch prediction exactly the same as having no branch prediction at all because you are doing the same conditional checks anyway? (obviously I'm wrong, but I don't get it)


问:
Is Pair programming works good when it come to backend developer and frontend developer working together?
If there's a work that need frontend and backend developers to work together, should they:

Pair programming all the times? When it's backend work, frontend developer is navigator, backend developer is driver and vice-versa. This would most time-consume and I don't really sure it's has benefit enough for all time wasted.

Pair programming with only some part like only API part that need to communicate the data with each other. Frontend may need to know some database structure to be able to pair with backend too.

Just do the API Documentation together and after that, just do their own work base on the API Documentation. (Fastest way but I don't know if there will be any drawback).

P.S. They work at the same place and can ask the others anytime when they do not understand something.

答:
In my opinion there are the following advantages of pair programming:

Two peope check the logical consistency along the way

The code gets more readable and understandable

Annoying bugs and typos are more likely to be found while writing the code

One person can write tests/documentation alongside

The main connection between front- and backend are interfaces. Good interfaces can be the result of pair programming, but I think that the interfaces should be defined before you start writing the code.

I personally would roll with the third point but I also think that there is nothing wrong with the second point if the development team is small. I dislike the first point, because I think that pair programming between two programmers with the same field of activity will be more productive.


问:
In C, what is an unconditional jump?
I have to fill out some documentation regarding a C project i worked on. One topic is whether I used "unconditional jumps".

As far as I know, a "break" statement counts as a jump. And I have a few of those that fire when a condition in a loop is met. Does that make it a "conditional jump"?

Another example is when there are standard "break" statements in a switch case, are those conditional or unconditional?

Basically, what constitutes an "unconditional jump" in C?

答:
Conditional means it may not be followed depending on some condition. Unconditional means that is program flow reaches that point it always will continue at the target.

A if and a switch are a conditional jumps.

At the end of the then clause of an if is an unconditional jump to after the else clause. breaks in a switch are also unconditional.

Title: In C, what is an unconditional jump?


答:
It is a matter of terminology.

IMHO, any break, continue, goto, return which is not in the body of an if or else or case is an inconditional jump.

So obviously

```<code>if (foobar) goto somelabel;
</code>```

is a conditional jump.

In

```<code>if (foobar) {
   x = something();
   y = other(x);
   return;
}
</code>```

I would believe that the return is conditional. Some people might object that because of the previous statements it is not (and only the entire block is conditional)

BTW, I heard of "unconditional jump" more when speaking of machine code than everything else.

Read also about basic blocks

I believe that your bureaucracy is just asking you if you used goto; you could ask your management or client about what is really meant. I feel sorry for you that you have to lose your time on such (IMHO stupid or useless) questions.

Title: In C, what is an unconditional jump?

Body:
I have to fill out some documentation regarding a C project i worked on. One topic is whether I used "unconditional jumps".

As far as I know, a "break" statement counts as a jump. And I have a few of those that fire when a condition in a loop is met. Does that make it a "conditional jump"?

Another example is when there are standard "break" statements in a switch case, are those conditional or unconditional?

Basically, what constitutes an "unconditional jump" in C?

Body:
It is a matter of terminology.

IMHO, any break, continue, goto, return which is not in the body of an if or else or case is an inconditional jump.

So obviously

if (foobar) goto somelabel;

is a conditional jump.

In

if (foobar) {
   x = something();
   y = other(x);
   return;
}

I would believe that the return is conditional. Some people might object that because of the previous statements it is not (and only the entire block is conditional)

BTW, I heard of "unconditional jump" more when speaking of machine code than everything else.

Read also about basic blocks

I believe that your bureaucracy is just asking you if you used goto; you could ask your management or client about what is really meant. I feel sorry for you that you have to lose your time on such (IMHO stupid or useless) questions.


问:
Team member questioning moving from VBA to C#
Background

Last year, I was asked to create a tool to be used for business planning for around 10 users. This was done on behalf of another IT team who "sub-contracted" the work to me, and due to the project deadlines being a little unplanned on their side, I had to implement it in a bit of a rush.

At the time, we decided that the quickest way would be to create an Excel workbook with VBA and then have the users download this VBA-enhanced workbook from an Intranet to use on their PCs. Excel was a constraint in this case because the planning system (i.e. database) we use can only interact via an Excel add-in which must be loaded at the same time the planning workbook is open. However, VBA was not a constraint at that time.

The workbook I created around 4,000 lines of VBA code and whilst I tried to separate data and presentation layers, I couldn't in all cases due to the project deadlines. To be honest, whilst I am proud of creating this workbook, I am at the same time a little disappointed in that it could've been done better, in both terms of coding and also deployment to the users.

Today

Back to today and the IT team has again come to me to request a similar workbook (so I could reuse parts of the other workbook above), but this time it is a lot more complicated and will be used by a greater number of users (around 200).

However, this time, it is a little better planned and I can see that we have a bit more time to plan things. Based on this, I thought about the solution and infrastructure as programming for 100 users has more of an impact than for 10 users. Therefore, I suggested to the team that perhaps we should consider migrating the existing code to a C# solution so that we could manage the code in a more refined way. I'm still considering it as an add-in written using VSTO / Excel-DNA which can then be deployed to the users.

I discussed this with the IT team two weeks ago and everything seemed to be fine, until yesterday I received a mail from one of the team (who does not know VBA or C#) questioning why we should start this new project in C# versus using the same approach as before. Some of their concerns were:

It is a fairly important project so it has to work - a C# solution would not be as stable or work as well as the existing a VBA-based solution.

We would have to throw away what we [I] had done in the VBA solution and recreate it from scratch in C#.

Someone will have to support two separate solutions, one in VBA and one in C#. [actually, they currently do not have anyone for support, I usually step in].

Now, I can understand some of their concerns to some degree, but I need to come to a decision on next steps and what to go back to them with. Personally, I would like to implement in C# because I feel it would lend itself better to building an "Enterprise" solution like this. Furthermore, I would like to take this opportunity brush up on my C# skills as I am currently not as competent in C# as I am VBA and I'd like a project like this to take me to the "next level".

I prepared a list of points that I could use to try and convince them that a C# solution would be better for this project, this is what I have so far:

Unit testing.

Source control.

Code documentation - for knowledge transfer to other support persons.

Better coding conventions - can use things like ReSharper to enforce better naming and structure.

Better IDE - fewer mistakes due to error highlighting.

More modularity through assemblies - can promote re-use in future tools.

Managed deployment - can control who this tool is used by.

Question: What other points could I add to convince them? Or am I trying to bite off more than I can chew with this project? Should I just keep quiet and do it in VBA anyway?

I am aware that just moving to a new language because its "newer" or seen to be "cooler" should not be a basis for a decision and as such I have resisted to include it as a decision point - this is about facts.

Also, I am not asking for a literal comparison between C# and VBA as languages, as there are plenty of comparisons on SO.

答:
You can point out that even Microsoft states in this article:

Updating the code to improve features or to fix bugs would require
that the Office artifact be re-emailed, re-structured, and re-worked
by every single user and in every single file that has been using the
customization.

The article is about different approaches of developing stuff based on Office, maybe you can take also some other pros and cons from it in your discussion.

ContentLicense: CC BY-SA 4.0


答:
The three points you listed seem fair:

It is a fairly important project so it has to work - a C# solution would not be as stable or work as well as the existing a VBA-based solution.

Indeed, later, you tell: "I would like to take this opportunity brush up on my C# skills as I am currently not as competent in C# as I am VBA" (emphasis mine).

In other words, you have a solution which works and went through intensive user testing. You want to throw all this and rewrite everything in a language you don't know well. See the problem?

We would have to throw away what we [I] had done in the VBA solution and recreate it from scratch in C#.

Things You Should Never Do comes to mind. You are throwing the code, as well as the user testing. Not a good thing.

Someone will have to support two separate solutions, one in VBA and one in C#. [actually, they currently do not have anyone for support, I usually step in].

If the VBA version would still be used, the rewrite is indeed even more problematic. Why would you have two disparate systems which require your attention, when you may have only one which already works and which you can refactor and add features to?

Some of your points, on the other hand, can be criticized:

Unit testing.

You can unit test your current project as well. If there is no convenient framework for that, create one.

Source control.

Source control deals with text. Your current code is text, therefore you can use source control for it.

The language, the operating system, the framework or the ecosystem are completely irrelevant. You can (and should) use source control for any code you write: code in Visual Studio, or a piece of code you draft in a few minutes in LINQPad, or PowerShell scripts which automate a task, or database schema, or Excel macros.

Code documentation - for knowledge transfer to other support persons.

Agreed.

Better coding conventions - can use things like ReSharper to enforce better naming and structure.

Define "better". Are there coding conventions for Excel's macros? If yes, use them: they are not better or worse than any other. If not, create ones and publish them so that other people can use them too. The answers to a question posted in 2010 seem rather disappointing, but there may be new tools available since then.

Note that the important part of coding conventions is that they should be enforced on commit.

Better IDE - fewer mistakes due to error highlighting.

Agreed. The fact that we can't write macros in Visual Studio is very unfortunate.

More modularity through assemblies - can promote re-use in future tools.

I'm pretty sure your current product can use some degree of modularity as well.

Managed deployment - can control who this tool is used by.

Agreed.

Instead of a complete rewrite, you might search for a way to progressively move code from the macro to an ordinary assembly written in VB.NET. Why in VB.NET? Three reasons:

There is less difference between VBA and VB.NET as there is between VBA and C#.

You know VBA better, and this alone is a good reason to use VB.NET instead of C#. If you want to "brush up on your C# skills", do it with your personal projects, not business critical stuff.

Any rewrite from a language to another leads to potential bugs. You don't need that for this project.

Moving to a .NET assembly can give you the convenient environment of Visual Studio, with the convenient unit testing, TFS and error highlighting you currently use in other projects.

At the same time, if you move your code step by step, you don't take the risk of a complete rewrite (i.e. spending four months creating something nobody wants to use because the high number of new bugs). For instance, you need to work on a specific feature? Think how you can move this particular feature to .NET first.

This is quite similar to refactoring. Instead of rewriting the whole thing because you learnt some new design patterns and language features, you simply do small changes on the code on which you work right now.

Title: Team member questioning moving from VBA to C#

Body:
Background

Last year, I was asked to create a tool to be used for business planning for around 10 users. This was done on behalf of another IT team who "sub-contracted" the work to me, and due to the project deadlines being a little unplanned on their side, I had to implement it in a bit of a rush.

At the time, we decided that the quickest way would be to create an Excel workbook with VBA and then have the users download this VBA-enhanced workbook from an Intranet to use on their PCs. Excel was a constraint in this case because the planning system (i.e. database) we use can only interact via an Excel add-in which must be loaded at the same time the planning workbook is open. However, VBA was not a constraint at that time.

The workbook I created around 4,000 lines of VBA code and whilst I tried to separate data and presentation layers, I couldn't in all cases due to the project deadlines. To be honest, whilst I am proud of creating this workbook, I am at the same time a little disappointed in that it could've been done better, in both terms of coding and also deployment to the users.

Today

Back to today and the IT team has again come to me to request a similar workbook (so I could reuse parts of the other workbook above), but this time it is a lot more complicated and will be used by a greater number of users (around 200).

However, this time, it is a little better planned and I can see that we have a bit more time to plan things. Based on this, I thought about the solution and infrastructure as programming for 100 users has more of an impact than for 10 users. Therefore, I suggested to the team that perhaps we should consider migrating the existing code to a C# solution so that we could manage the code in a more refined way. I'm still considering it as an add-in written using VSTO / Excel-DNA which can then be deployed to the users.

I discussed this with the IT team two weeks ago and everything seemed to be fine, until yesterday I received a mail from one of the team (who does not know VBA or C#) questioning why we should start this new project in C# versus using the same approach as before. Some of their concerns were:

It is a fairly important project so it has to work - a C# solution would not be as stable or work as well as the existing a VBA-based solution.

We would have to throw away what we [I] had done in the VBA solution and recreate it from scratch in C#.

Someone will have to support two separate solutions, one in VBA and one in C#. [actually, they currently do not have anyone for support, I usually step in].

Now, I can understand some of their concerns to some degree, but I need to come to a decision on next steps and what to go back to them with. Personally, I would like to implement in C# because I feel it would lend itself better to building an "Enterprise" solution like this. Furthermore, I would like to take this opportunity brush up on my C# skills as I am currently not as competent in C# as I am VBA and I'd like a project like this to take me to the "next level".

I prepared a list of points that I could use to try and convince them that a C# solution would be better for this project, this is what I have so far:

Unit testing.

Source control.

Code documentation - for knowledge transfer to other support persons.

Better coding conventions - can use things like ReSharper to enforce better naming and structure.

Better IDE - fewer mistakes due to error highlighting.

More modularity through assemblies - can promote re-use in future tools.

Managed deployment - can control who this tool is used by.

Question: What other points could I add to convince them? Or am I trying to bite off more than I can chew with this project? Should I just keep quiet and do it in VBA anyway?

I am aware that just moving to a new language because its "newer" or seen to be "cooler" should not be a basis for a decision and as such I have resisted to include it as a decision point - this is about facts.

Also, I am not asking for a literal comparison between C# and VBA as languages, as there are plenty of comparisons on SO.


问:
Scheme/Design Pattern for allowing a certain outside class to set properties
I came up with a solution (in PHP) to a problem and am wondering if it is a named Design Pattern, and if it is good practice.

I have a collection class and an item class. The collection class is the only one allowed to set the item class's protected data, besides the class itself.

I did that by giving the item class a method that takes the collection object as an argument. The item object then sets its data with the collection objects.

That way, we can say:

```<code>$item_coll = new collection();
$item_coll->load($criterion1, $criterion2);
</code>```

Because the collection implements IteratorAggregate, we can also do this:

```<code>foreach($item_coll as $item) {
  echo 'Item name is ' . $item->getName();
}
</code>```

Even after a collection is loaded, you can get a sub collection using the getBy($property,$value) method:

```<code>$sub_collection = $item_coll->getBy('color','green'); // new collection object with green items
</code>```

And now I have a collection of item objects with all their data set.
Here are the classes (with impertinent methods/properties not shown).

```<code>class item {
  protected $id; // id from database table
  protected $prop1; // properties also from database
  protected $prop2;

  public function setData(collection $coll, $id) {
    $data = $coll->getData($id);
    foreach($data as $key=>$value) {
      $this->$key = $value
    }
    return $this;
  }
  public function getId() {
    return $this->id;
  }
}

class collection implements IteratorAggregate { // interface for foreach access to $collection
    protected $data = array();
    protected $collection = array(); // contains `item` objects
    public function getData($id) {
      if(array_key_exists($id,$this->data) ) {
        return $this->data[$id];
      } else return array();
    }
    public function load(someClass $obj1, someClass2 $obj2) { // arguments not relevant here, they determine the contents of the collection
      // based on arguments, data is loaded from database into $this->data;
      foreach($rows as $row) { // database data
        $this->data[$id] = $row;
        $obj = $this->collection[$id] = new item();
        $obj->setData($this,$id); // collection object passes itself into item object
      }
    }
    public function html() {//
      foreach($this as $obj) {
        // loop through collection to create an html table for display
      }
    }
    public function addItem(item $item) { // add already-existing items to collection
      if(!array_key_exists($id,$this->collection) ) {
        $this->collection[$item->getId()] = $item;
      }
    }
    public function getIterator() { // for IteratorAggregate interface
      return new ArrayIterator($this->collection);
    }
    public function getBy($property,$value) {
      $collection = new static(); // new collection created
      // loop through $this object and fill $collection with matching item objects
      return $collection;
    }
    public function getById($id) { // get a single item object by its id
      if(array_key_exists($id,$this->collection) ) {
        return $this->collection[$id];
      }
    }
}
</code>```

答:
I think you are trying to use dependency injection but the code is not easily readable. You could have used three classes instead of two:

Collection: to hold the items; in fact you could just use a simple array

Item

ItemDataManager: to load and cache the data from the DB in an efficient manner.

With this approach your code would be:

```<code>$idm = new ItemDataManager();
$idm->load(criterion1, criterion2);
</code>```

And then you could pass $idm as a parameter to $item->setData.
This way you get a clean separation of duties between the collection management and the data management..

Body:
I think you are trying to use dependency injection but the code is not easily readable. You could have used three classes instead of two:

Collection: to hold the items; in fact you could just use a simple array

Item

ItemDataManager: to load and cache the data from the DB in an efficient manner.

With this approach your code would be:

$idm = new ItemDataManager();
$idm->load(criterion1, criterion2);

And then you could pass $idm as a parameter to $item->setData.
This way you get a clean separation of duties between the collection management and the data management..


问:
Is using interfaces for datatypes an anti-pattern?
Suppose I have a various entities in my model (using EF), say User, Product, Invoice and Order.

I am writing a user control that can can print the summaries of entity objects in my application where the entities belong to pre-decided set, in this case I say that summaries of User and Product can be summarized.

The summaries will all only have a ID and a description, so I create a simple interface for this:

```<code> public interface ISummarizableEntity {
       public string ID { get; }
       public string Description { get; }
 }
</code>```

Then for the entities in question, I create a partial class that implements this interface:

```<code>public partial class User : ISummarizableEntity
{
    public string ID
    {
        get{ return UserID.ToString(); }
    }

    public string Description
    {
        get{ return String.Format("{0} {1} is from {2} and is {3} years old", FirstName, LastName, Country, Age); }
    }
}

public partial class Product: ISummarizableEntity
{
    public string ID
    {
        get{ return ProductID.ToString(); }
    }

    public string Description
    {
        get{ return String.Format("{0} weighs {1}{2} and belongs in the {3} department", ProductName, WeightValue, WeightUnit, Department); }
    }
}
</code>```

This way my user control / partial view can just bind to any collection of ISummarizableEntity and doesn't need to be interested in the source at all. I have been told that interfaces shouldn't be used as datatypes but I didn't get more information than that. As far as I can see, although interfaces normally describe behavior, just using properties isn't an anti-pattern in itself as properties are just syntactic sugar for getters/setters anyway.

I could create a concrete datatype and map from the entities to that but I can't see the benefit. I could make the entity objects inherit from an abstract class and then define the properties but then I am locking the entities to no further use as we can't have multiple inheritance. I am also open to having any object being ISummarizableEntity if I wanted (obviously I would rename the interface)

The solution I am using in my mind is maintainable, extensible, testable and fairly robust. Can you see the anti-pattern here?

答:
Interfaces don't describe behaviour. Quite the opposite, sometimes.

Interfaces describe contracts, such as "if I am to offer this object to any method that accepts an ISummarizableEntity, this object must be an entity that is able to summarize itself" -- in your case, that is defined as being able to return a string ID and a string Description.

That's a perfect use of interfaces. No anti-pattern here.


问:
How to earn team members respect as team lead
If you were hired into a new company as a team lead (say a team of 10) one of the important things to do is to earn the respect of the members of the team. In the early days the new team lead may know nothing of the team culture, code base and business domain: in other words, is a complete neophyte. </p>

<p>How does one go about this? What are the do's and don'ts? </p>

答:
This is a process that's going to take some time but it's close to optimal:

Read AntiPatterns and AntiPatterns in Program Management (both are shown at that site).

Commit personally to never doing any of those things.

Demonstrate your commitment to your team by actually never doing them.

Work with your team to do the work that needs doing.

Repeat steps 3 and 4.

Note the complete lack of "best practices" above.  There are no right answers but there are most certainly some wrong ones.

Frankly, I think that the core of good team leadership is just learning from the mistakes of others.  If you focus on not doing things that are known to be stupid then, at a minimum, the team won't hate you with the heat of a thousand suns.


答: You have chosen the better path for this design because you are defining a specific type of behavior that will be required of multiple, different, types of objects. Inheritance in this case would imply a common relationship between the classes that does not actually exist. In this case, composability is favored over inheritance.</p>

Title: Is using interfaces for datatypes an anti-pattern?

Body:
Suppose I have a various entities in my model (using EF), say User, Product, Invoice and Order.

I am writing a user control that can can print the summaries of entity objects in my application where the entities belong to pre-decided set, in this case I say that summaries of User and Product can be summarized.

The summaries will all only have a ID and a description, so I create a simple interface for this:

```<code> public interface ISummarizableEntity {
       public string ID { get; }
       public string Description { get; }
 }
</code>```

Then for the entities in question, I create a partial class that implements this interface:

```<code>public partial class User : ISummarizableEntity
{
    public string ID
    {
        get{ return UserID.ToString(); }
    }

    public string Description
    {
        get{ return String.Format("{0} {1} is from {2} and is {3} years old", FirstName, LastName, Country, Age); }
    }
}

public partial class Product: ISummarizableEntity
{
    public string ID
    {
        get{ return ProductID.ToString(); }
    }

    public string Description
    {
        get{ return String.Format("{0} weighs {1}{2} and belongs in the {3} department", ProductName, WeightValue, WeightUnit, Department); }
    }
}
</code>```

This way my user control / partial view can just bind to any collection of ISummarizableEntity and doesn't need to be interested in the source at all. I have been told that interfaces shouldn't be used as datatypes but I didn't get more information than that. As far as I can see, although interfaces normally describe behavior, just using properties isn't an anti-pattern in itself as properties are just syntactic sugar for getters/setters anyway.

I could create a concrete datatype and map from the entities to that but I can't see the benefit. I could make the entity objects inherit from an abstract class and then define the properties but then I am locking the entities to no further use as we can't have multiple inheritance. I am also open to having any object being ISummarizableEntity if I wanted (obviously I would rename the interface)

The solution I am using in my mind is maintainable, extensible, testable and fairly robust. Can you see the anti-pattern here?


问:
Is it always a best practice to write a function for anything that needs to repeat twice?
Myself, I can't wait to write a function when I need to do something more than twice. But when it comes to things that only appear twice, it's a bit more tricky.

For code that needs more than two lines, I'll write a function. But when facing things like:

```<code>print "Hi, Tom"
print "Hi, Mary"
</code>```

I'm hesitant to write:

```<code>def greeting(name):
    print "Hi, " + name

greeting('Tom')
greeting('Mary')
</code>```

The second one seems too much, doesn't it?

But what if we have:

```<code>for name in vip_list:
    print name
for name in guest_list:
    print name
</code>```

And here is the alternative:

```<code>def print_name(name_list):
    for name in name_list:
        print name

print_name(vip_list)
print_name(guest_list)
</code>```

Things become tricky, no? It's hard to decide now.

What's your opinion about this?

答:
Generally, it's a good idea to split something into a function of it improves the readability of your code, Or, if the part being oft repeated is somehow core to the system.
In the above example, If you needed to greet your users depending on the locale, then it would make sense to have a separate greeter function.</p>


问:
How to handle a memory consuming member variable
Suppose multiple objects of the same class should do something which takes a memory consuming resource. Which of the following approaches is recommended to define and use the resource by the objects?

Each object create the resource in its own

Declare one resource instance and pass it to each object

Using a static object for the resource

Let me give an example

```<code>class Section
{
     public Bitmap Page {/* set and get the page...*/}
     Bitmap page = new Bitmap(600,800);
     Draw(SomeThing s)
     {
        // Draw something on the page
     }
}

// in somewhere else
foreach (Section sect in Sections)
{
     sect.Draw(something);
     Video.AddFrame(sect.Page);
}
</code>```

Versus.

```<code>class Section
{
     public Bitmap Page {/* set and get the page ...*/}
     Bitmap page; // it isn't instantiated in the class
     Draw(SomeThing s)
     {
        // Clear the page
        // Draw something on it
     }
}

// in somewhere else
Bitmap screen = new Bitmap(600,800); // the common resource
foreach (Section sect in Sections)
{
     sect.Page = screen;
     sect.Draw(something); // it clears it before drawing something on it
     Video.AddFrame(screen);
}
</code>```

Versus.

```<code>class Section
{
     public Bitmap Page {/* set and get the page ...*/}
     static Bitmap page = new Bitmap(600,800);
     Draw(SomeThing s)
     {
        // First Clear the page
        // Draw something on the page
     }
}

// and in somewhere else
foreach (Section sect in Sections)
{
     sect.Draw(something);
     Video.AddFrame(sect.Page);
}
</code>```

First I used the first approach but it consumed a lot of memory as each object in my Sections array had a bitmap. Then I was forced to try the second approach. Is this new approach better than the former on all aspects? What is the guideline for such situations?

答:
You may want to use a BitmapLoader which lazily loads the Bitmaps as and when required.
This way you don't have to maintain any internal members.
If required you can implement some sort of LRU caching in the BitmapLoader to optimise the loading of the most frequently accesses Bitmaps.</p>


答:
In layman's words:

In pair programming both partnerts get to drive and to navigate on the same codebase, so 1st point is not what one would call pair programming.

If things are done right, frontend dos not need to know the structure or the database.

Writing documentation before writing the code is at most atypical

My suggestion:
- have a couple of programmers pair-program the frontend and a couple of programmers pair-program the backend.
- If you only have two programmers then make them pair-program the backend, then the front end.
- If both frontend and backend need to advance simultaneously (and you have only two programmers) then let each programmer do his/her work by his/her own.

Title: Is Pair programming works good when it come to backend developer and frontend developer working together?

Body:
If there's a work that need frontend and backend developers to work together, should they:

Pair programming all the times? When it's backend work, frontend developer is navigator, backend developer is driver and vice-versa. This would most time-consume and I don't really sure it's has benefit enough for all time wasted.

Pair programming with only some part like only API part that need to communicate the data with each other. Frontend may need to know some database structure to be able to pair with backend too.

Just do the API Documentation together and after that, just do their own work base on the API Documentation. (Fastest way but I don't know if there will be any drawback).

P.S. They work at the same place and can ask the others anytime when they do not understand something.


答:
I am in same position, of having a very large (20k+ lines of VBA code) application built into an EXCEL workbook. Upon testing with Office 2013 it simply fails to work, believed due to changes in the sequence of start-up event in the new office model, and possibly more strict enforcement of EMET. I am thus in the position of doing a crash-conversion to C# and VB.NET before the roll-out of Office 2013 this year. Other, simpler (VBA enhanced) workbooks used around the organization have not been immune, some working and others not.

The errors occur in the Workbook_Open event, where the sheets of the workbook are no longer available, and in internal EXCEL code prior to any VBA code being referenced.

Being comfortable in all of VBA, C# and VB.NET I am writing the conversion in both of the latter two. Framework code is being written in C# because the language idioms allow me to write certain functional constructs in that language 3-4 times faster than in VB.NET. The bulk of the code is in VB.NET because then my rewrite is less extensive, and there are certain idioms there that are not present in C#.

Prior to making any decision, I strongly recommend that you test the existing application with OFFICE 2013 and the fullest extent of EMET enforcement that the organization foresees rolling out over the next 2-3 years. You might, like me, discover that the existing application will simply not run in that environment without a rewrite anyways - in which case the rewrite might as well be in DOT NET and VSTO.

Addendum:

Writing a little automated extract utility, that loops through the entire contents of the workbook VBA and exports all modules, classes and forms to files, is 1-2 days work, depending on how fancy you want it to be. Likewise with the reverse to import the files from a directory to a blank workbook. With these two it is quite possible to have all your VBA code in proper source control, and to have a Build process from source code for your workbook.

OR - use a free utility such as Excel VBA Code Cleaner


问:
What are good interview questions for a Software Tester with focus on automation?
Today's testing is not much like yesterday's testing. More services, more distributed systems, more automation. I want the kind of testers that are self-starters and will constantly work themselves out of the job by writing test code. What are good interview questions for the modern software tester?</p>

答:
If we're talking web testing, then I would ask them to talk about their experience with testing tools.  Specifically these or equivalents:

HP's Quick Test Pro

Selenium cross-browser compatibility testing framework.

JUnit/NUnit (not just for unit testing, but also tied in with Selenium and other tools to write automated tests that give you nice reports.

Great automated testers are great developers first, so make sure they understand code first and foremost.  In my experience there are testers who are great developers too (the ones you want) and those who think programming is too hard, so they decide to be testers (those you don't want for automated testing testers).


答:
It really depends on how you intend to move to C# (ie what technology you are going to use).

If you are going to use OpenXML, then you are talking a total re-write which, if you have a solution that works, isn't recommended.

If you are talking about using Interop, you may find that the process is surprisingly smooth. I've moved a lot of code from VBA to C# (with Interop) in the past and once you are plugged into the workbook, like so:

```<code>var excelApplication = new Application();
var workbook = excelApplication.Workbooks.Open(@"C:\location.xlsx");
</code>```

In a lot of cases you can copy/pasta your VBA code, prefixing function calls with workbook., replacing Dim with var etc where appropriate and adding semicolons on the end.

It's essentially the same Framework underneath (Excel), you are just changing Syntax from VBA to C#.

When you're done, be sure to save and close the application:

```<code>workbook.Save();
excelApplication.Quit();
</code>```

Then release the application with the Marshal:

```<code>Marshal.ReleaseComObject(excelApplication);
</code>```

I would probably write a wrapper class implementing IDisposable around the Excel Application object, then be sure to use using when this object is used.

A good way to make your case would be to spend an hour or so doing this, which in a short space of time would demonstrate how quickly you could port code across, and convince your colleagues that this is a good idea.

The code would remain largely unchanged in a way, but you have all of the benefits you mentioned of having a C# project within Visual Studio.

Body:
It really depends on how you intend to move to C# (ie what technology you are going to use).

If you are going to use OpenXML, then you are talking a total re-write which, if you have a solution that works, isn't recommended.

If you are talking about using Interop, you may find that the process is surprisingly smooth. I've moved a lot of code from VBA to C# (with Interop) in the past and once you are plugged into the workbook, like so:

var excelApplication = new Application();
var workbook = excelApplication.Workbooks.Open(@"C:\location.xlsx");

In a lot of cases you can copy/pasta your VBA code, prefixing function calls with workbook., replacing Dim with var etc where appropriate and adding semicolons on the end.

It's essentially the same Framework underneath (Excel), you are just changing Syntax from VBA to C#.

When you're done, be sure to save and close the application:

workbook.Save();
excelApplication.Quit();

Then release the application with the Marshal:

Marshal.ReleaseComObject(excelApplication);

I would probably write a wrapper class implementing IDisposable around the Excel Application object, then be sure to use using when this object is used.

A good way to make your case would be to spend an hour or so doing this, which in a short space of time would demonstrate how quickly you could port code across, and convince your colleagues that this is a good idea.

The code would remain largely unchanged in a way, but you have all of the benefits you mentioned of having a C# project within Visual Studio.


问:
Web software license for redistribution by our customer
I work in a web agency; we developed a web application for a customer.
Once the app was done, the customer asked us the property rights for
our whole app so he can sell it to others.

In this case, how can we handle the lincense?
Can we use a license which allows us to control and make a profit on every
solt copy of our app?

答:
If you have full ownership of all the code in the project, you can use whatever license terms you like.

If you have used 3rd-party components in your project, then their licenses may restrict what license terms you can use.

In any case, if you want to use a different license than a well-known open-source license, you must consult with a lawyer. Licenses are legal documents and should be written by a legal professional if you want to be sure that the terms are enforceable.


答:
Yes, why not.

What you get from pair programming is the benefits of someone else looking at an overview of what's happening with the code, while the main coder gets caught up in the details. You also gain from the spread of knowledge that will transfer between the two.

So in this case, your back end guy will code up the interface the front end guy will later consume, and will know the interface he'll be presented with later - he can also suggest additions because he'll know what data he wants there and then, saving the costly rework later. And vice versa.

Both guys will gain knowledge of the product from an unfamiliar area, will see it being used and tested and will know the configuration and setup of it. Even if they don't become cross-area developers, the benefits will still be seen in overall product knowledge.


问:
Do you still need created_by and updated_by attributes with dedicated auditing?
For as long as I have been writing database-backed websites, I have included created_by, created_at, updated_by, and updated_at in every single table.  As you can guess, whenever a record gets created or updated the appropriate fields are set.  Currently I'm working on an auditing module for my website so that every insert/update gets added to an Audit table along with the field values from the record being changed.  Habit has me still adding those create/update columns to each record but I'm wondering if they are even needed anymore.

Are created_by/created_at/updated_by/updated_at fields still necessary or helpful if those same actions are being tracked in a dedicated table?

答:
No, they're not. The purpose of auditing is to determine who did what in the past. The current data is irrelevant for this purpose, but you will need to record which data changed - there's no point in saying "user Dave change the person table" without saying what he changed. This information doesn't have to be recorded so formally though.

You might like to store the table that was modified, and a text field containing the data changes to assist in filtering the audit records during an investigation, or just the data changes if you can filter on other factors or substring searches of the text.


答:
I hate to say it, but your arguments just don't hold water.

Unit testing.

This has been a solved problem for a very long time. There are many Unit Testing frameworks out there. Pick one. You should have been doing this already. I recommend ours, because it integrates into the IDE and provides other great features.

Source control

This one is a bit tougher, there are few ready built solutions, but it's really just a matter of getting your code into and out of a repository. Here's a low brow way to do it, but there are other better options as well.

Code documentation

Also a solved problem. MZ-Toolshas an XML documentation feature that works very similarly to .Net's XML comment docs.

Better coding conventions

Just like Visual Studio has the ReSharper plugin, both MZ-Tools and Rubberduck have such features.

Better IDE

Again, there are plug-ins available for the VBA IDE.

More modularity through assemblies - can promote re-use in future tools.

Also a solved problem. No, you can't create assemblies, but you can reference other VBA Projects.

Managed deployment - can control who this tool is used by.

A bit sticker, you'll need to write code to control who is able to access the program and who can't, but you (again) probably already should have written security code.

As for deployment, it is also a solved problem. Yes, it requires code, but there are examples out there that you could use/modify.

On top of all of this, is the fact that you would be starting from scratch. I too will recommend Joel Spolsky's article.

They did it by making the single worst strategic mistake that any software company can make:

They decided to rewrite the code from scratch.

Your IT guys are right. You shouldn't be re-writing this from scratch. You should be solving the problems with your current solution.

Now, with all of that said, I can absolutely understand why you would want to do this in either C# or VB.Net. They really are a better solution, if you're starting a new project, but from the sounds of it, it's not a new project. It's much better to improve what you have then to break it by starting over.


问:
Why VB local variables can be 'static', not 'shared'?
In Visual Basic .NET, I can see different keyword for the same(?) concept:

```
• methods                 Shared
• properties              Shared
• class-level variables   Shared
BUT
• local variables         Static
```

Why there is Static and not Shared in case of local variables? Does different keyword indicate a different concept? Or is it only due to historical reasons?

To be clear - I understand that both static and shared variables are allocated on heap instead of stack and retain their value independently of instances. I would expect the same keyword then.

答:
Isn't it correct to say that if something is Shared then you know there will be only one instance of it throughout the whole application. However if something is Static then there could well be many live instances of class but each instance will retain it's own value after termination of the procedure it lives in? Conceptually they are different.

Behavior

When you declare a static variable in a Shared procedure,
only one copy of the static variable is available for the whole
application. You call a Shared procedure by using the class name, not
a variable that points to an instance of the class.

When you declare a
static variable in a procedure that isn't Shared, only one copy of the
variable is available for each instance of the class. You call a
non-shared procedure by using a variable that points to a specific
instance of the class.

https://msdn.microsoft.com/en-us/library/z2cty7t8.aspx


答:
Sure you can use such a license. You can use any license terms the other party agrees to (within the limits of your local law). But license agreements are tricky. When they aren't worded by a legal professional, you risk writing one which doesn't actually say what you think it says.

Just to give one example. Let's say you write a clause like "[developer] gets 20% of all profits generated by [customer] from transfering the rights to [application] to a 3rd party". Sounds good, right? But what if the people they transfer it to also transfer it to a 4th party? You only asked for 20% of the profits generated by [customer], not any of [customer's customer], so you would gain nothing on that 2nd transaction. That means [customer] could sell the software for $1 to a subsidiary company (of which you would get 20 cent) and make that subsidiary sell it to others for millions without having to pay you anything. And that's just one example of one mistake you could make.

For that reason you and your customer should hire lawyers which negotiate a licensing contract which says exactly what you want it to say and is free of any obvious loopholes.

By the way: When you do a work-for-hire, you should usually make such a contract before you start working. Who owns the copyright of the resulting work is one of the most important clauses of a work contract.

Title: Web software license for redistribution by our customer

Body:
I work in a web agency; we developed a web application for a customer.
Once the app was done, the customer asked us the property rights for
our whole app so he can sell it to others.

In this case, how can we handle the lincense?
Can we use a license which allows us to control and make a profit on every
solt copy of our app?


问:
Delegating work and programming to component interfaces
I have a MessageHandler class which receives and validates messages before determining which components in the architecture they should be delegated to so they can be processed. This involves calling functions with different names and possibly different signatures on classes in different components.

What is the best way to implement the delegation?

The diagram below shows two possible approaches.

Option 1 - each component that must process messages exposes an interface, which is realised by a Facade. For each message, the MessageHandler calls the appropriate operation on the interface and the facade delegates it to the appropriate class internally.

Option 2 - for each message, the MessageHandler calls the appropriate operation directly in the relevant component.

Weighing up the advantages/disadvantages of each:

Option 2 means polluting the message handler with a handle of each class in every component that will process a message. It also makes it harder to test the message handler in isolation. Doesn't seem right.

Option 1 - seems like a better approach. The message handler depends on an interface rather than concrete classes, which also makes it easier to test.

I'm wondering if option 1 a good approach? Or is there a better way to achieve what I want?

答:
I'm guessing the image represents both approaches at the same time.

I think approach 1 is the obvios winner and the beneficts of programming against interfaces are well documented.

I would ask, nonetheless:

Are you sure there's no commonality between the classes behind the facadem so all of them could implement the same interface?

If MessageHandler is able to do all its calls using an interface to the facade, how is that not every class behind the facade can't implement the same interface. It seems to me that they are not getting any more info from MessageHandler than that interface allows.


答: An interface implemented by only one class gains you nothing in this situation. Will the interfaces ever be implemented by more than one class? If not, you have substituted a dependency for a concrete class, for a dependency on an interface implemented by one concrete class, which adds complexity and no advantage, unless the testing framework must use interfaces.</p>

Title: Delegating work and programming to component interfaces

Body:
I have a MessageHandler class which receives and validates messages before determining which components in the architecture they should be delegated to so they can be processed. This involves calling functions with different names and possibly different signatures on classes in different components.

What is the best way to implement the delegation?

The diagram below shows two possible approaches.

Option 1 - each component that must process messages exposes an interface, which is realised by a Facade. For each message, the MessageHandler calls the appropriate operation on the interface and the facade delegates it to the appropriate class internally.

Option 2 - for each message, the MessageHandler calls the appropriate operation directly in the relevant component.

Weighing up the advantages/disadvantages of each:

Option 2 means polluting the message handler with a handle of each class in every component that will process a message. It also makes it harder to test the message handler in isolation. Doesn't seem right.

Option 1 - seems like a better approach. The message handler depends on an interface rather than concrete classes, which also makes it easier to test.

I'm wondering if option 1 a good approach? Or is there a better way to achieve what I want?


问:
Is there are any common pattern/practice to handle exception list (Java)?
Suppose I've got a sophisticated parser for something.
And a I don't want Throw Early/Fail-Fast strategy.
If I've got multiple problems, i want to have list of exceptions in my log file
because I want exactly know where cause in source code is.</p>

答:
Continuing under parse errors can be a bit nontrivial, and simply crying “parser combinator” will not fix that.

The central point is that your parser won't throw exceptions when it encounters syntax errors. Instead, these exceptions are queued in a list until a problem is sufficiently fatal, you have too many problems, or the end of input has been reached.

After you encounter a syntax problem, you have to try to re-sync your parser with the input. For common mistakes, create special productions that match these mistakes. This can be used to create truly helpful error messages, and provides excellent recovery. Errors such as “missing closing paren” or “missing semicolon” can be handled well by this. Just make sure that the error rules have lower precedence than the normal syntax. After an error rule is completed, you can continue with the normal grammar.

However, error rules only handle the minority of issues. In most cases, you will want to skip a part of the input until it is safe to continue. Don't worry about creating an invalid parse tree, since after an error the parse will be discarded. One possibility to recover is to skip until an expected token of a production higher in the parse tree has been found. Consider foo(1, 2 3) + 4; bar();. Between 2 and 3 there should have been a comma or a binary operator, we don't know. We do know that we are inside the “function arguments” production, and that the next expected symbol would be a comma or a closing paren. Or we could see that we are in the “statement” production and skip to the next semicolon. In either case, we need to look through the stack of current productions and search for predicted symbols. This may require nontrivial manual adjustments in the case of a top-down parser, but provides really decent error recovery. On the other hand, you might end up skipping a lot of input.

In the worst case, you simply skip the current token and attempt to restart the parse. This may require you to skip multiple tokens until a legal parse appears, and while this method is simple, it should be only used as a last resort.


问:
Content delivery design
I'm designing a system where users can access files stored in an external content storage service such as AWS's S3. Here's a simple diagram:

```<code> ------       ------------       -----------------
| User | <=> | Web Server | <=> | Content Storage |
 ------       ------------       -----------------
</code>```

The files are stored with a (long) unique ID. I'm concerned mainly about two things: performance and information security.

There are two options that come to mind but I'm sure it can be done in a better way (performance and security-wise):

Give the user a url with which the file can be downloaded directly from the content storage service. Cons: the URL could be brute forced. This could be solved putting a password to the file, but I'd like to use that as a last resort.

The web server downloads the file from content storage service and then serves it to the user. Cons: too much traffic.

Is there a way to make an HTTP redirect without exposing the file's resolved URL? Something like proxying packets?

I don't want to make this technology-specific (that's what SO is for), but just in case it adds any value, I'm using Rails a rails server behind nginx. I have full control over the web server, but I'm limited on the content storage service since I'm using S3.

答: Perhaps you already suggested this with "password to the file": combine option 1 (url to download directly) with encryption of the file, so that it can be securely decrypted by the client application only by clients with possession of a secret key. That is probably a minimum level of security anyway, if you are concerned about security at all. It won't help with denial of service attacks.</p>

Title: Content delivery design


答:
I would support going to C#.  Others have covered your points very well, so I won't rehash what they've said. There are definitely a lot of good reasons to stick with VBA.

However, one of my employers did an impeccable job at creating meaningful documentation.  So much so that design decisions were actually written down with justification - if only all software projects had that!  My point? One of the design decisions was "We're choosing to write this program in Java, because Mr. So-and-so want's to put x years of Java experience on his resume".  If that's a strong reason for you to move to C#, then it can't be ignored as a triviality.  It just can't be one of the reasons you use to justify it to the IT team, because they don't really care what you want on your resume, they care about the working product.

There's also the perception of VBA to think about.  I know it's not true, but I know quite a few people who see 'VBA' on a resume and think "What, this guy was stuck doing intern work?  Why doesn't he have experience with a real language?" They see 'VBA' and think 'excel macro developer'.  Like copying/pasting one cell to another, doing simple calculations, etc.  Usually the kind of people who can appreciate real development in VBA are those who have done it, and that seems like an increasingly small pool, at least in my experience.  You might have a better sense of the perception of VBA in your area, but I've seen a lot of unjustified negativity towards it.

The other thing I want to zero in on: MainMa mentioned the similarities between VBA and C#.  This is absolutely true, and JMK's answer offers a couple of technologies to read up on.  Try copying/pasting your VBA code to a C# project and see how easy the syntax errors look to correct.

You said you had 4,000 lines of code, which is a good chunk of code and probably encompasses a lot of functionality...but it's only 4,000 lines of code. Try the copy and paste thing. I really wouldn't be surprised if you could clean up those syntax errors and have a working project.  Without knowing the details of your code or the amount of free time available to you, I would think you could knock this out in a weekend.

It might not follow C# best practices, it may be inefficient, but you would end up with a functionally equivalent project in C#.  You could also be relatively certain that your new C# code is no more defect-prone than your old VBA code.

Converting your VBA code to C# on your own time would do a couple of things for you:

As you research syntax errors you'll become more familiar with C# practices - a sort of primer for actually working in C#

It'll shine a light on any obvious issues with loading the plug-in into excel(since excel is presumably still a requirement).  Perhaps there's an issue you haven't considered yet that may be a roadblock.

It'll show a proof-of-concept to your customer(the IT team).  If they can see you have a working C# plug-in with current functionality, then you'll be reducing their level of perceived risk with C#.

And going back to IT's three points:

• It is a fairly important project so it has to work - a C# solution would not be as stable or work as well as the existing a VBA-based solution.

As mentioned, your C# code will cover the same functionality and be just as stable as your VBA.  Strictly speaking, there is a chance you introduce bugs/defects or inefficiencies, but that seems unlikely.  We're not talking about a port from iOS/Objective C to Android/Java, we're talking about a port between two languages that share a lot of similarities in syntax and can utilize the exact same technology - excel workbooks.

• We would have to throw away what we [I] had done in the VBA solution and recreate it from scratch in C#.

With this, you're not throwing away any effort or code.

• Someone will have to support two separate solutions, one in VBA and one in C#. [actually, they currently do not have anyone for support, I usually step in].

You'll only have 1 solution, all in C#.

All in all, your customer sees a lot of risk.  If you can take the steps to mitigate that risk, they might embrace the change to C#.


问:
In ifs inside for loops, prefer checking for true, or for false and continue?
I'm discussing this with a work colleague.
Say we want to sum the numbers from 0 to 9 skipping 5.
He prefers this:

```<code>int sum = 0;
for(int i = 0; i < 10; ++i)
{
    if(i == 5)
    {
        continue;
    }

    sum += i;
}
</code>```

I prefer this:

```<code>int sum = 0;
for(int i = 0; i < 10; ++i)
{
    if(i != 5)
    {
        sum += i;
    }
}
</code>```

Any reason to prefer one over the other?
Cyclomatic complexity is the same in both cases, right?

答: Technically he will have one more line of execution for the continue statement. Otherwise, the code is identical. It is O(n) in both cases.


答:
I personally would go with the first example, given your task. The first example more closely matches your original problem statement. The 2nd requires a little bit more mental parsing to determine if it fulfills your problem statement.

Look at how you worded what is going on: "Sum the numbers from 0 to 9 skipping 5". That is exactly what the first statement does. The 2nd doesn't read quite the same way.

Ultimately, what is right is going to depend on the context of the greater problem you are going to solve. The less thinking you have to do to verify it's doing what it is supposed to, the better.

Title: In ifs inside for loops, prefer checking for true, or for false and continue?

Body:
I'm discussing this with a work colleague.
Say we want to sum the numbers from 0 to 9 skipping 5.
He prefers this:

```<code>int sum = 0;
for(int i = 0; i < 10; ++i)
{
    if(i == 5)
    {
        continue;
    }

    sum += i;
}
</code>```

I prefer this:

```<code>int sum = 0;
for(int i = 0; i < 10; ++i)
{
    if(i != 5)
    {
        sum += i;
    }
}
</code>```

Any reason to prefer one over the other?
Cyclomatic complexity is the same in both cases, right?


答:
Any reason to prefer one over the other?

At some places and in some languages, the use of continue and break are frowned upon as glorified gotos. They make it harder to read the code since you need to stop and then find the end of the loop you're in rather than noting the condition and reading along.

The second version will work in pretty much any language too. continue isn't always available.