问:
What list of database features/elements are necessary for a programmer to understand?
What database features/elements are necessary for a programmer to understand in order to create non-trivial applications?

I was once asked in a job interview (by a DBA) to rate my understanding of database concepts -- I thought it would be interesting to get opinions.

I'm looking for basic and advanced skills, also any opinions on where developers are typically the weakest (what lack of skills or knowledge creates the most problems).  Also, is it better that developers are need-to-know, and pass more advanced work onto a DBA -- where does that "line in the sand" exist?

答:
Normalisation - and all the other details of how to properly structure a database, couple of random examples:

That you almost always want to use a synthetic key (in my case most often an auto incrementing int called ID)

That you want to store dates, times and the like as native types (or as close as you can get)


问:
Why should your code not use 100% CPU?
I'm speaking specifically about a C# .NET 4 program running on Windows XP or higher, but general answers are also acceptable.

Assume an already optimized and efficient program. The problem here is entirely down to effects of high CPU usage on hardware, and whether a high-usage program should be throttled to reduce wear, not on whether my implementation is efficient.

A colleague today suggested that I should not aim for 100% CPU utilization on my data load processes because "modern CPUs are cheap and will degrade quickly at 100% CPU".

Is this true? And if so, why? I was previously under the impression that 100% CPU usage was preferable for an intensive or long operation, and I couldn't find any respectable sources on the subject either way.

答:
So the situation is this: You have some code that runs say for five hours using 100% of all CPUs, that is optimised as much you can, the owner of the machine is fine with the machine being unusable for five hours, and your colleague claims it would be better to run your code in 6 hours using 83.33% of all CPUs, because it puts less wear and tear on the computer.

It depends on the computer that you are using. I know that a computer manufacturer refused warranty repairs within the warranty time on cheap home computers that were used in a scientific setting running 24/7. They clearly wanted the customer to buy their more expensive servers or "business" computers. Whether they were successful, I don't know.

Every Mac that I've owned has at some point in its life run code at 100% CPU usage for days at a time. In one case I had to turn the display off, because I didn't have the original charger for a laptop, and with 4 cores and hyper threading it used more power than the charger supplied - so the battery went down, and when it reached 5 percent the computer slowed down the clock speed until the battery was up to 10% ! (With the display turned off it ran at full speed for several days). In no case, any ill effects.

So with a well-designed computer, you are right. With a badly designed, cheap computer, your colleague might be right. On the other hand, you might consider the cost of your waiting time vs. the cost of buying a replacement computer.

ContentLicense: CC BY-SA 3.0

Title: Why should your code not use 100% CPU?


问:
PHP framework most similar to ASP.NET MVC3?
I've done a bit of work with CodeIgniter and a lot with straight PHP...

I had the opportunity to use asp.net mvc3 recently and was absolutely blown away with my productivity. Despite not "knowing" the framework, the combination of scaffolding + intellisense + code generation through the context menus left me feeling just as productive with asp.net as with PHP.

I've evaluated YII, CakePHP, symfony (a long time ago, pre 2.0), and Kohana... and while YII seems most promising none quite matched up to my experience with mvc3.

答:
I wasn't sure if you were requesting an IDE or an MVC framework, but I wanted to share a new MVC for PHP that is very close to .NET.

https://github.com/DominicArchual/Php-One

Here's how it works:

Define your view model:

```<code>require_once('bin/System.php');

class MovieViewModel
{
    public $Id = 0;
    public $Title = "";
    public $Rating = '';
    public $ReleaseDate = '';

    public function __construct($id, $title, $rating, $releaseDate)
    {
        $this->Id = $id;
        $this->Title = $title;
        $this->Rating = $rating;
        $this->ReleaseDate = $releaseDate;
    }
}
</code>```

Define your controller:

```<code>require_once('/repositories/MovieRepository.php');
require_once('/models/MovieViewModel.php');

class HomeController
{
    public $MovieRepo;

    public function __construct()
    {
        $this->MovieRepo = new MovieRepository(); // create an instance of our repo
    }

    public function Index()
    {
        $model = []; // create a variable to store our movies (don't actually need this, but it's nice)

        $movies = $this->MovieRepo->GetMovies(); // get data from our repo

        // do some transformations and populate our view model
        foreach ($movies as $movie)
        {
            $model[] = new MovieViewModel(
                $movie->Id,
                $movie->Title,
                $movie->IsRRated ? 'R' : 'PG',
                $movie->ReleaseDate->format('F jS, Y')
            );
        }

        View::Render('views/home/index.php', null, $model); // call our view and send the model
    }
}
</code>```

Define your view:

```<code><ul class="list-group">
<?php
foreach($Model as $movie)
{
    echo <<<HTML
        <li class="list-group-item">
            <strong>{$movie->Title}</strong> ({$movie->Rating}) - {$movie->ReleaseDate}
        </li>
HTML;
}
?>
</ul>
</code>```

And, presto!

Body:
I wasn't sure if you were requesting an IDE or an MVC framework, but I wanted to share a new MVC for PHP that is very close to .NET.

https://github.com/DominicArchual/Php-One

Here's how it works:

Define your view model:

require_once('bin/System.php');

class MovieViewModel
{
    public $Id = 0;
    public $Title = "";
    public $Rating = '';
    public $ReleaseDate = '';

    public function __construct($id, $title, $rating, $releaseDate)
    {
        $this->Id = $id;
        $this->Title = $title;
        $this->Rating = $rating;
        $this->ReleaseDate = $releaseDate;
    }
}

Define your controller:

require_once('/repositories/MovieRepository.php');
require_once('/models/MovieViewModel.php');

class HomeController
{
    public $MovieRepo;

    public function __construct()
    {
        $this->MovieRepo = new MovieRepository(); // create an instance of our repo
    }

    public function Index()
    {
        $model = []; // create a variable to store our movies (don't actually need this, but it's nice)

        $movies = $this->MovieRepo->GetMovies(); // get data from our repo

        // do some transformations and populate our view model
        foreach ($movies as $movie)
        {
            $model[] = new MovieViewModel(
                $movie->Id,
                $movie->Title,
                $movie->IsRRated ? 'R' : 'PG',
                $movie->ReleaseDate->format('F jS, Y')
            );
        }

        View::Render('views/home/index.php', null, $model); // call our view and send the model
    }
}

Define your view:

<ul class="list-group">
<?php
foreach($Model as $movie)
{
    echo <<<HTML
        <li class="list-group-item">
            <strong>{$movie->Title}</strong> ({$movie->Rating}) - {$movie->ReleaseDate}
        </li>
HTML;
}
?>
</ul>

And, presto!


问:
Grouping multiple Git repositories that are part of the same overall project
Let's say I have a project that has multiple components: a server component, a web app component, an iOS component, an Android component, etc.  These components are all separate codebases, but are also loosely coupled (eg. a change to the server code could require a change to all other components too)

What is the most efficient way in Git to organize this project? If you put it all in one repository, you would always have the latest versions but things become quite messy when you start changing one component and not the others.

On the other hand, if you make each component as a separate repository, how would you be able to "link" these repositories so that you would know that version 2.0 of the app requires version 1.5 of the server component, etc?

Is there a feature in git outside of keeping up to date readmes(or some better solution I don't see) to more effectively manage multiple, related repos?

答:
In my opinion, this would depend on how much they are actually coupled. It is really nice to be able to run an automated git bisect when tracking down a regression, but this will be difficult to do if every commit depends on a different version of your other dependencies to run.

Two possible options would be one repository with submodules or multiple repositories with good versioning practices in place.

how would you be able to "link" these repositories so that you would know that version 2.0 of the app requires version 1.5 of the server component, etc?

This is usually the domain of some dependency management framework (e.g. Gradle, Maven), not Git itself.


问:
Choosing a Programming Language Systematically
I am looking for a methodology for choosing a language. I am not asking for opinions about languages.  I have been tasked with the process of comparing our shop's current language with others that are available. We are a web development shop btw.

Our CEO would like a full white paper about all web based languages that are available, What parent language they are derivatives of (e.g jsp is from java which is from c/c++). I need to create a matrix with all the key factors of a particular language as well and the short comings of that given language.  Is the language limited by platform, is it designed for functional programming, procedural or OO or can it be used with any programming paradigm?

I also need to have information less technical, like the size of the talent pool for a given language and the median salary in that pool. How will the marketplace view our choice?

We started looking for a consultant to help us understand all of these things but what we have found it that most consultants are coming from a development background and often it seems that the answer is "xxx is the best language because it is the one that I have used the most over the last n years and it has never let me down. You could Supplement it with yyy for front end and use zzz library"

I am feeling overwhelmed with this task and I feel like the best course of action, given what our CEO is looking for, is to look in the world of academia and hire a professor with no actual development experience to come in and "teach" us about all possible languages.

Has anyone else had to go through this exercise? If you have can you share the steps and/or methodology you used to go through the process?

答:
Some broad brush strokes to consider:

Language popularity

This really shouldn't matter, because popularity does not necessarily equate with productivity, expressiveness or any of the other language qualities that matter more, but this consideration often trumps all other considerations because:

It's easier to find software developers in a popular language.

It's easier to find tools and libraries in a popular language.

Decision makers don't understand language tradeoffs, so they'll make the safe decision ("many companies use this language, so it must be good").

Applicability to the problem domain

Any program can be written in any Turing-complete programming language, but some languages are better suited for certain problem domains than others.  If you're writing web applications, you probably will gravitate to languages and tools that are well-suited for that, and they most likely will be object-oriented languages.

On the other hand, if you're going to be writing software that's primarily research-based or math-based, you will probably gravitate towards languages that embrace functional paradigms.

And, of course, there's everything in between.  Many languages support multiple paradigms, and some software patterns exist solely to overcome limitations in those languages that lack certain features or paradigms.

Expressiveness and productivity

Some languages are more expressive than others.  What can be written in one language using a thousand lines of code can be written in a more expressive language using a hundred lines of code.  The tradeoff is that the hundred lines of code is probably written in a less popular language, by people with greater expertise.

A lot of the lines of code present in object-oriented languages used to write line-of-business applications are ceremony.  This ceremony, while costing time and effort to develop, also provides a visible structure that wouldn't otherwise be readily apparent in a more expressive language.  It allows people with less expertise than they would otherwise need to work on the code with a reduced amount of risk.

The era of multiple languages

I'll conclude by asserting that the desire to decide on a single language may be a false dilemma.  Applications today are often written, not in one, but in many languages.  Each language has its own strengths, and (in theory) is specifically designed for the task it is being used.  Some problem domains (such as web browser logic or database access) require specific languages.


问:
How often to open pull requests
We are planning to use Git pull requests for code review in our company. Before we start I have a basic question: How often should I open a pull request? Is it best to open one for every little commit I create? Or should I open a single pull request for a larger quantum of work, such as all the commits in, say, a user story? What is the right size?

What do you do in your team?

答:
open a single pull request for a larger quantum of work, such as [...] a user story?

That's what you should do.

Two reasons:

There is a mantra that one should "commit early and often". Once you get used to it, you will recognize that this is a good habit. The side effect of it is, that you will produce a larger number of commits, which you may or may not want to squash later into fewer ones. That's perfectly ok as long as you didn't publish the stuff in any way.

Once you're finished with your work and want it to be merged, you open a PR. Keep in mind that the people who are acting upon your PR are not interested in every single minorish step of the development. They want a completed feature as a whole, because they will have to review it.

One major point about DVCS is exactly that: There is no need to publish every tiny step, but you still have the benefits of a repository. Once the branch is merged into the main development branch and/or repository you are contributing to via PRs, typically only the end result is of interest.

Title: How often to open pull requests


问:
Would this be a proper use of threading?
After reading various MSDN articles, tutorials, and posts on here I came up with a design for a windows service that I wanted to make sure my threading strategy is proper and won't lead to memory, cpu, database issues.

Here is the basic flow.

MAIN THREAD

Collect list of service to be loaded.

Loads each service.

SERVICE THREAD (started by timer event on step 3)

Start Service

Setup Timer - Setup so there is no overlapping, only 1 processing call can be made.

Processing method

Makes database call to get information which is a list of Commands.

Gathers a collection of Handlers.

Does a Parallel.ForEach() over the list of Commands.

Immediately does a normal foreach() over the Handlers

COMMAND THREADS

Command does a normal foreach() over the Handlers passing in the Command.

Each Handler executes code that may CRUD the database or reach out to various other services.

Due to the Parallel.ForEach() I am spinning up 1 new thread per Command.

There could be 1000+

Since each Command has multiple Handlers these Handlers will run on the same thread as the Command.

This is to prevent database clashes since each Handler will be working with the same set of data.

This is to make each Command wait on its own Handler threads.

WAIT POINTS

Service waits for all Commands to finish executing before firing another round of round of commands.

Commands wait for all Handlers to to finish.

Handlers wait for one to finish before moving onto the next.

PERFORMANCE

3000x FOREACH Console.WriteLine() avg. 160ms

3000x FORALL Console.WriteLine() avg. 275ms

3000x FOREACH DatabaseCallAsync() avg. 1200ms

3000x FORALL DatabaseCallAsync() avg. 600ms

Interesting how the normal foreach was faster with just the WriteLine() but twice as slow with the database call. I still have concern about competing for resources with the other services.

QUESTIONS

Do you recognize any immediate issues with this design?

Do you have any suggestions that would make it more efficient with resources and speed?

I am noticing extremely high CPU usage on all cores when running just Console.WriteLines() in the actual execution point, should I be limiting the threads?

I noticed when I used a normal foreach() it still had pretty high cpu usage but had more resting points, I still need to put a counter in there to see how many calls are actually being made for each to see which is actually processing more but right now I am just concerned with the high usage.

答:
You do not need to use dedicated threads: a thread is an expensive object so it is generally better to use the thread pool since it will reuse threads to process your work items. Using a dedicated thread is a good idea if you need thread-local storage, thread identity, thread priorities, custom scheduling (picking work item from a stack or a priority queue rather than a queue), a higher priority than work items (if you have thousands of work items in the queue, a thread is likely to get a time slice earlier) or conversely if you want to leave the queue free for something else, etc.

Enqueuing a work item on the thread pool is still a moderately expensive operation (above hundreds of nanoseconds). Besides the algorithm used to dynamically adjust the number of threads in the pool works best when each work item is not too long (let's say less than one millisecond). If your work items are longer than this or if they suffer a poor scalability (database or IO contention), you may want to limit the max number of threads in the pool.

Some timers will enqueue their callbacks over the ThreadPool and some others on the UI. You need to check whether your timer will conflate with any other work you could have enqueued, especially long-running work items on the ThreadPool, and if it is important that your callbacks run before pending work items.

Async/await are mostly necessary when the identity of the thread matters, typically for agents. For example the UI typically can only be manipulated from the UI thread (this is a thread affinity mechanism that serves as a synchronization pattern) and you often need to dispatch a task to a background thread from the UI thread then continue it later over the UI again. While on one hand your services look like agents, on the other hand it may be a design mistake as I just explained and anyway it does not seem like you need to dispatch continuations back to the service.

However tasks are a nice abstraction to use and Parallel.Foreach, Task.Run and others will use the thread pool by default.

Edited the async/await section to take into account the comments below from Robert Harvey
Edited to mention timers's callbacks.

OwnerDisplayName: Tony


问:
When does one hard-code actual data values into the code as opposed to using a DB?
A long-standing question for me has been: when do I store data (actual values) in a database table, and when do I store them right in the code?

The untold consensus has typically been as such(*):

If it is a single variable or a simple structure, or an array of a few values, put data right in the code.

[* consensus has been debated in comments and answers, but basically I wanted some kind of a premise to jump-start the question, so feel free to challenge and improve upon it]

Example:

```<code>$number = 44;
$colors = array("blue", "yellow", ... "mauve");
</code>```

If it has hundreds+ of rows of data of the same type, use a database.

But there seems to be a gray area; what about cases that are not so clear? What considerations and factors does one need to pay attention to in order to make a decision?

Example:

Say your company uses 10-15 different types of motors frames that can be represented as "412T". You have about 30 of them and they change rarely.  You can either create a DB table for those or hard-code them in a database.  In this case, motors are static, physical things that are not likely to change often.

Keeping them in code subjects them to source control, where in a database, DB changes are typically not tracked.  But keeping them in a database frees up (separates) code from data.

Another (actual) example I can use is this question of mine: https://stackoverflow.com/questions/26169751/how-to-best-get-the-data-out-of-a-lookup-table (currently 48 rows of option data).

答:
I'd go with the third option: a config file!

For applications that I work on (in Java, so all my examples are use Java+Spring ), such values are usually stored in config files and injected (via Spring) into the code that needs them when the application starts up. In a properties file:

```<code>motorFramesString=412T, 413T, ...
</code>```

In the spring config:

```<code><bean="motorFrameManager" class="myCompany.MotorFrameManager" >
    <property name="motorFrames" value="${motorFrames}"/>
</bean>
</code>```

The advantage of this is that you can change or add more of these mostly-static values easily enough, without a recompile, and you don't have to worry about filling your (relational) database with reference data (since that seems to be a concern, and maybe not everything needs to be in the database anyway).

As for why these values should go into a config file instead of a reference table: Do you plan to use these values mostly in code, or mostly in the database? If you have many existing queries and view and procedures that depend on these values, then it might be best to put them in the database as reference data, as it's easier than loading them from config files and sending them as parameters to every possible query/view/procedure that references them. If the values are mostly used in application code, then the config file is probably a better choice.

A more complicated example like what you link could be done too, with or with out properties.

In products.properties:

```<code>productA.name=Product A 123
productA.hasMotor=true
productA.numFeet=1
productA.hasOutlet=true
productA.needsManual=true

productB.name=Product B 456
productB.hasMotor=false
productB.numFeet=1
productB.hasOutlet=true
productB.needsManual=true
</code>```

In your spring config file:

```<code><bean name="productA" class="com.mycompany.Product">
   <property name="name" value="${productA.name}"/>
   <property name="hasMotor" value="${productA.hasMotor}"/>
   <!-- rest omitted for brevity -->
</bean>
<bean name="productB" class="com.mycompany.Product">
   <property name="name" value="${productB.name}"/>
   <property name="hasMotor" value="${productB.hasMotor}"/>
   <!-- rest omitted for brevity -->
</bean>
<!-- configure as many beans as needed -->
<bean="motorFrameManager" class="myCompany.MotorFrameManager" >
    <property name="motorFrames"> <!-- assumes that MotorFrameManager has a property motorFrames which is a List<Product> -->
        <list>
            <ref bean="productA"/>
            <ref bean="productB"/>
        </list>
    </property>
</bean>
</code>```

The nice thing about this is that if your source data is a spreadsheet  (like in the question you linked to) you can use macros in Excel to automatically generate the properties and spring snippets.

Body:
I'd go with the third option: a config file!

For applications that I work on (in Java, so all my examples are use Java+Spring ), such values are usually stored in config files and injected (via Spring) into the code that needs them when the application starts up. In a properties file:

motorFramesString=412T, 413T, ...

In the spring config:

<bean="motorFrameManager" class="myCompany.MotorFrameManager" >
    <property name="motorFrames" value="${motorFrames}"/>
</bean>

The advantage of this is that you can change or add more of these mostly-static values easily enough, without a recompile, and you don't have to worry about filling your (relational) database with reference data (since that seems to be a concern, and maybe not everything needs to be in the database anyway).

As for why these values should go into a config file instead of a reference table: Do you plan to use these values mostly in code, or mostly in the database? If you have many existing queries and view and procedures that depend on these values, then it might be best to put them in the database as reference data, as it's easier than loading them from config files and sending them as parameters to every possible query/view/procedure that references them. If the values are mostly used in application code, then the config file is probably a better choice.

A more complicated example like what you link could be done too, with or with out properties.

In products.properties:

productA.name=Product A 123
productA.hasMotor=true
productA.numFeet=1
productA.hasOutlet=true
productA.needsManual=true

productB.name=Product B 456
productB.hasMotor=false
productB.numFeet=1
productB.hasOutlet=true
productB.needsManual=true

In your spring config file:

<bean name="productA" class="com.mycompany.Product">
   <property name="name" value="${productA.name}"/>
   <property name="hasMotor" value="${productA.hasMotor}"/>
   <!-- rest omitted for brevity -->
</bean>
<bean name="productB" class="com.mycompany.Product">
   <property name="name" value="${productB.name}"/>
   <property name="hasMotor" value="${productB.hasMotor}"/>
   <!-- rest omitted for brevity -->
</bean>
<!-- configure as many beans as needed -->
<bean="motorFrameManager" class="myCompany.MotorFrameManager" >
    <property name="motorFrames"> <!-- assumes that MotorFrameManager has a property motorFrames which is a List<Product> -->
        <list>
            <ref bean="productA"/>
            <ref bean="productB"/>
        </list>
    </property>
</bean>

The nice thing about this is that if your source data is a spreadsheet  (like in the question you linked to) you can use macros in Excel to automatically generate the properties and spring snippets.


答:
@FrustratedWithFormsDesigner hinted at this above, I'll be more blunt: you've been charged with a expensive but useless task.

I suspect the CEO is looking for irrefutable, objective evidence which will support his choice of language. The problem is that preference of language is loaded with far too many subjective and extrinsic factors for the white-paper to be meaningful let alone useful.

Put another way, if there were an ideal language, everyone would be using it instead of those "objectively" defective languages. It also bespeaks a degree of micromanagement that ought be the province of the engineers who will have to make it work. Erlang might be the "objectively best" but if no one knows it, add a 6 month/engineer start up cost and 6 more  month / engineer to gain competency.

Since I don't have your job, I'm not worried about losing it, although you may. I'd give the CEO a paper on the Physical Church-Turing Thesis. I'd then get together with the senior engineers and get their non-rigorous, non-objective opinion as to what should be used and tell the CEO that's what you shall use. In exchange you'll promise the engineers will keep out of board meetings, CFOs, Accountancy Methods, selection of VPs and so on. There is a reason we specialize, and he has no more place in engineering preferences than you do in his domain.

Title: Choosing a Programming Language Systematically

Body:
I am looking for a methodology for choosing a language. I am not asking for opinions about languages.  I have been tasked with the process of comparing our shop's current language with others that are available. We are a web development shop btw.

Our CEO would like a full white paper about all web based languages that are available, What parent language they are derivatives of (e.g jsp is from java which is from c/c++). I need to create a matrix with all the key factors of a particular language as well and the short comings of that given language.  Is the language limited by platform, is it designed for functional programming, procedural or OO or can it be used with any programming paradigm?

I also need to have information less technical, like the size of the talent pool for a given language and the median salary in that pool. How will the marketplace view our choice?

We started looking for a consultant to help us understand all of these things but what we have found it that most consultants are coming from a development background and often it seems that the answer is "xxx is the best language because it is the one that I have used the most over the last n years and it has never let me down. You could Supplement it with yyy for front end and use zzz library"

I am feeling overwhelmed with this task and I feel like the best course of action, given what our CEO is looking for, is to look in the world of academia and hire a professor with no actual development experience to come in and "teach" us about all possible languages.

Has anyone else had to go through this exercise? If you have can you share the steps and/or methodology you used to go through the process?


答:
Sub-projects is the place were distributed version control systems (DVCS) start to, if not unravel, certainly become a little wonky.

Git submodules and Mercurial subrepositories  both aim for sub-project support. Both have improved release-by-release (to the point that Mercurial's old "this feature exists, but you probably shouldn't use it" warning is no longer front-and-center.)

Still, multi-project repos remain more of a speciality use case rather than an everyone-uses-it feature. The documentation contain numerous caveats and "how to use this" instructions that make clear that managing "projects of projects" is a two-level concern, with the meta management slightly but genuinely different than the direct, single-level project management. As a result, there is much less experience out there. And there is no shortage of "don't use git submodules!" and "avoid mercurial subrepos!" comments and blog posts.

My own experience with subrepos was mixed. It worked...but it was also annoying. I love the idea of sub-projects, but in practice find the alternatives--either large all-in-one repos or companion sibling projects--to be more easily wrangled (though less elegant). I look forward to the day subrepos are mainstream and not a pain, but I haven't experienced that yet.

This isn't to say that managing submodules/subrepos won't work for you, but it's something that should be done with care, and definitely some prior experimentation and planning.

Given that you're focused on Git, you should also explore Git subtrees, which some find to be a better alternative to git submodules.

Title: Grouping multiple Git repositories that are part of the same overall project

Body:
Let's say I have a project that has multiple components: a server component, a web app component, an iOS component, an Android component, etc.  These components are all separate codebases, but are also loosely coupled (eg. a change to the server code could require a change to all other components too)

What is the most efficient way in Git to organize this project? If you put it all in one repository, you would always have the latest versions but things become quite messy when you start changing one component and not the others.

On the other hand, if you make each component as a separate repository, how would you be able to "link" these repositories so that you would know that version 2.0 of the app requires version 1.5 of the server component, etc?

Is there a feature in git outside of keeping up to date readmes(or some better solution I don't see) to more effectively manage multiple, related repos?


问:
What to do about "stopping point syndrome"?
I have noticed a behavior in myself that I call "stopping point syndrome"... it means I cannot stop working until I reach a "stopping point" (or I become exhausted).  In other words, if I am in the zone working on getting a feature completed, I won't stop until I get it done.   If it's a bug I'm working on, this effect is even more pronounced... I won't stop until it's fixed, or at the very least, understood.  Even though I work from a laptop and have VPN and could easily go home and pick up on the work later that evening, that fact does not help me leave work... it's like I'm afraid I will die before I find the bug.

I have a very hard time explaining this to family members who can't figure out why I never come home from work at the same time and sometimes come home at 11 pm.  Even managers have been mystified by this, and I've noticed that most of my colleagues have no trouble working the same hours every day.

Does anyone else have this problem?  Should I be worried about this and/or try to change it?  If so how?

答:
I'm surprised this hasn't been mentioned yet.

If you need to stop, then stop cold turkey, mid-line, in the middle of something easy and obvious. Your IDE will probably put some red and yellow lines everywhere saying there's an error, this is okay. Maybe make a short /* comment */ about the item you worked on prior to that line.

Save your work and exit.

When you come back the next day, you'll be like, "oh, right, I was in the middle of X because of Y" and it shouldn't be too hard to slip back into what you were working on.

The last thing I worked on (minor hobby application for personal use), I would do this when I noticed the hours fly by when I was hunting bugs. When it got too late, I would think, "screw this" and save and exit, compilation errors be damned. Then when I'd open it again, I'd be like, "errors? wtf?!1/," which would turn into, "oh yeah, I was trying to test why this method was throwing an exception."

It was surprisingly efficient and I plan on using this technique from now on.

ContentLicense: CC BY-SA 2.5


答:
I don't think these two statements really represent a consensus about when to hard code data:

If it is a single variable or a simple structure, or an array of a few values, put data right in the code

If it has hundreds+ of rows of data of the same type, use a database

Simple counter-example (I am sure there are better ones): programming language syntax tables are complex large structures that are often hard-coded. Take a look at an example from the Perl source code.

Instead I would focus first on asking:

How often does the data change?

Who might need to change it?

If the answer to "how often" is "more often than I want to deploy a new version of my app," then you should not hard code the data.

If the answer to "who changes it" is "anybody besides the programmer," then you should not hard code the data.

In a small shop, it is possible the distinction between the coder and the user has disappeared, and the idea of "deployment" has also disappeared. In this case you are the king of your own domain and you can do whatever you like.

But even in that situation, the need to collaborate can come up, and that can be difficult if a custom application does not follow a convention that programmers typically do follow.

Title: When does one hard-code actual data values into the code as opposed to using a DB?

Body:
A long-standing question for me has been: when do I store data (actual values) in a database table, and when do I store them right in the code?

The untold consensus has typically been as such(*):

If it is a single variable or a simple structure, or an array of a few values, put data right in the code.

[* consensus has been debated in comments and answers, but basically I wanted some kind of a premise to jump-start the question, so feel free to challenge and improve upon it]

Example:

```<code>$number = 44;
$colors = array("blue", "yellow", ... "mauve");
</code>```

If it has hundreds+ of rows of data of the same type, use a database.

But there seems to be a gray area; what about cases that are not so clear? What considerations and factors does one need to pay attention to in order to make a decision?

Example:

Say your company uses 10-15 different types of motors frames that can be represented as "412T". You have about 30 of them and they change rarely.  You can either create a DB table for those or hard-code them in a database.  In this case, motors are static, physical things that are not likely to change often.

Keeping them in code subjects them to source control, where in a database, DB changes are typically not tracked.  But keeping them in a database frees up (separates) code from data.

Another (actual) example I can use is this question of mine: https://stackoverflow.com/questions/26169751/how-to-best-get-the-data-out-of-a-lookup-table (currently 48 rows of option data).


问:
How to name a function type that is called by an event, but doesn't handle the event?
How would one name a function type called by a certain event? Instances of this function type would get called when a certain key is pressed. It isn't strictly an event handler type, because it doesn't have to handle the event. It might simply just want to be aware of the event. There can be multiple functions with this type listening for the same keystroke event.

I currently am using SpecificKeystrokeListener although that's not really correct as it doesn't listen, it is merely being notified.

For what it's worth, I am using Rust - though this applies to other languages as well. As an example:

type ResetFn = fn (this: *const device) -> ReturnStatus;

答:
The convention in Windows is

```<code>ObjectName_EventName
</code>```

Example:

```<code>ProductSelector_Click()
</code>```

It is done this way in Windows (.NET, specifically), because it follows a generic signature that allows you to do message passing:

```<code>public void ProductSelector_Click(object sender, EventArgs e)
</code>```

That said, if your method is merely a delegate or first-class function (and you don't need the sort of "patching" capability provided here), you can pretty much name it whatever you want.

More generally, this software pattern is called "Observer."

Body:
The convention in Windows is

ObjectName_EventName

Example:

ProductSelector_Click()

It is done this way in Windows (.NET, specifically), because it follows a generic signature that allows you to do message passing:

public void ProductSelector_Click(object sender, EventArgs e)

That said, if your method is merely a delegate or first-class function (and you don't need the sort of "patching" capability provided here), you can pretty much name it whatever you want.

More generally, this software pattern is called "Observer."


问:
I'm graduating with a Computer Science degree but I don't feel like I know how to program
I'm graduating with a Computer Science degree but I see websites like Stack Overflow and search engines like Google and don't know where I'd even begin to write something like that. During one summer I did have the opportunity to work as a iPhone developer, but I felt like I was mostly gluing together libraries that other people had written with little understanding of the mechanics happening beneath the hood.

I'm trying to improve my knowledge by studying algorithms, but it is a long and painful process. I find algorithms difficult and at the rate I am learning a decade will have passed before I will master the material in the book. Given my current situation, I've spent a month looking for work but my skills (C, Python, Objective-C) are relatively shallow and are not so desirable in the local market, where C#, Java, and web development are much higher in demand. That is not to say that C and Python opportunities do not exist but they tend to demand 3+ years of experience I do not have. My GPA is OK (3.0) but it's not high enough to apply to the large companies like IBM or return for graduate studies.

Basically I'm graduating with a Computer Science degree but I don't feel like I've learned how to program. I thought that joining a company and programming full-time would give me a chance to develop my skills and learn from those more experienced than myself, but I'm struggling to find work and am starting to get really frustrated.

I am going to cast my net wider and look beyond the city I've grown up in, but what have other people in similar situation tried to do? I've worked hard but don't have the confidence to go out on my own and write my own app. (That is, become an indie developer in the iPhone app market.) If nothing turns up I will need to consider upgrading and learning more popular skills or try something marginally related like IT, but given all the effort I've put in that feels like copping out.

答:
Don't sit on your computer all day/night every day  trying to get better. You will burn out fast. I did this, then had to stop programming for about 3 months as I just couldn't care less about it.

Read some books, and pace yourself.

Learn something mainstream (c# / java) to program in, as there are jobs and knowledge in these. Not VB though. That is evil. (Read fanboy comment below)

Do cause problems for yourself and then try to fix them in your language. This is the core of programming. Often these problems come from doing something apparently simple. So do something simple!

Learn basic unit testing! This is the fastest way to get better, as your problems become better understood as you learn to break things up into small pieces

Realise Fan boys are biased and fairly useless for opinions and that everyone is a fanboy.

ContentLicense: CC BY-SA 4.0


答:
Such degradation is theoretically possible and is called "electromigration". Electromigration is temperature-dependent, accelerating as the temperature goes up. Whether it is a practical problem for modern CPUs is up for debate. Modern VLSI design practices compensate for electromigration and chips are more likely to fail for other reasons.

Having said that, electromigration happens even at normal loads and temperatures, but it is slow enough that a well-designed chip either becomes obsolete far before failing, or it fails via another mechanism first.

The rate of electromigration depends on the chip temperature, with the lifetime doubling for every (very roughly) 10°C. This is, in fact, the basis of a test called "HTOL" (high temperature operating life), which measures how long it takes for a chip to die at, say, 125°C. A chip running at 125°C will fail roughly 100 times faster than a chip running at 55°C, so if designed to last at least 10 years at 55°C, a chip might fail within 1 month at 125°C. If running at something more reasonable like 85°C, such a chip would still fail at least 5-10x sooner than it was designed for.

Of course, CPUs are usually designed with higher temperatures in mind, so they can typically last for years at 85°C 24/7 100% load operation. So I would suggest that you don't worry about "wearing out" the CPU, and only worry about whether a 100% load is appropriate from the software engineering perspective.

Title: Why should your code not use 100% CPU?

Body:
I'm speaking specifically about a C# .NET 4 program running on Windows XP or higher, but general answers are also acceptable.

Assume an already optimized and efficient program. The problem here is entirely down to effects of high CPU usage on hardware, and whether a high-usage program should be throttled to reduce wear, not on whether my implementation is efficient.

A colleague today suggested that I should not aim for 100% CPU utilization on my data load processes because "modern CPUs are cheap and will degrade quickly at 100% CPU".

Is this true? And if so, why? I was previously under the impression that 100% CPU usage was preferable for an intensive or long operation, and I couldn't find any respectable sources on the subject either way.


问:
Is hash calculated before/after compression?
I had a question regarding compression and calculation of checksum/hash of data.

I would like to know if checksum has to be calculated before or after the compression of  data before transmission. Could someone please explain this so that I can get a better understanding of it?

答: Normally, a hash is calculated before compression. That way, the receiver can verify the hash after decompression, which verifies not only the data transmission but also the compression and decompression implementations.


问:
How to ensure multiple clients don't poll the server at the same time?
I am making an android app which will talk to a web service to get data. The web service has a rate limit of 100 calls per minute. Is there a way, recommended method to ensure that the app across various devices dont make the call to the server at the same time. Some way to stagger the requests across devices?</p>

答: Essentially you would need to proxy that web service with one of your own that does rate limiting. The devices wouldn't know anything about each other, and you can cache/re-implement the service if you need to scale further.</p>


答:
Non-SQL Developers should know the concept or RDBMS, PK/FK/CK, normalisation, indexing, transactions, table design etc. They should have an idea of how data is stored on disk and moved to memory. I would say basic to intermediate SQL along with understanding query plans, joins  is a must too.

Specialist SQL developers should know the whole gamut of Database topics, optmisation and advanced queries with in-depth knowledge of particular RDBMS product like Oracle etc in which they specialise.

Title: What list of database features/elements are necessary for a programmer to understand?

Body:
What database features/elements are necessary for a programmer to understand in order to create non-trivial applications?

I was once asked in a job interview (by a DBA) to rate my understanding of database concepts -- I thought it would be interesting to get opinions.

I'm looking for basic and advanced skills, also any opinions on where developers are typically the weakest (what lack of skills or knowledge creates the most problems).  Also, is it better that developers are need-to-know, and pass more advanced work onto a DBA -- where does that "line in the sand" exist?


问:
Algorithms: How do I sum O(n) and O(nlog(n)) together?
I have the follow algorithm which finds duplicates and removes them:

```<code>public static int numDuplicatesB(int[] arr) {
    Sort.mergesort(arr);
    int numDups = 0;
    for (int i = 1; i < arr.length; i++) {
        if (arr[i] == arr[i - 1]) {
            numDups++;
} }
    return numDups;
}
</code>```

I am trying to find the worst case time complexity of this. I know mergesort is nlog(n), and in my for loop I am iterating over the entire data set so that would count as n.
I am unsure what to do with these numbers though. Should I just sum them together? If I were to do that, how would I do it?

答:
```<code>O(n) + O(n log(n)) = O(n log(n))
</code>```

For Big O complexity, all you care about is the dominant term.  n log(n) dominates n so that's the only term that you care about.

Body:
O(n) + O(n log(n)) = O(n log(n))

For Big O complexity, all you care about is the dominant term.  n log(n) dominates n so that's the only term that you care about.


答:
If your app is going to have a very small user base (say a corporate app, with less than a few hundred users), then you can make each client rate-limit itself to check the server less than once every N/100 seconds, where N = number of clients. Add in a little extra delay as a margin of safety, and perhaps randomize that margin a bit to lower the likelihood that clients happen to bunch up on any given instant.

But beware, this is a very low-end solution. It can work adequately for very small user bases, especially if they need very infrequent updates. This is essentially how the Twitter and Facebook feed plugins for WordPress blog sites work.

But if your app is at all popular, there is no way that 100 requests/minute will suffice. None whatsoever. In that case, @Sign's proxy service is the way to go. If the app is very successful, the proxy will even need to be a multi-machine cluster with load-balancing, caching, high-availability failover, and so on.

Title: How to ensure multiple clients don't poll the server at the same time?

Body: I am making an android app which will talk to a web service to get data. The web service has a rate limit of 100 calls per minute. Is there a way, recommended method to ensure that the app across various devices dont make the call to the server at the same time. Some way to stagger the requests across devices?</p>


问:
Use case diagram, which behaviours should be included?
I teach OOD&A course to some students. When I want to draw a use case diagram or write the scenario of them for a system, I don't know should I include everything (behavior) which is done in the system by human or computer or just focus on those which is done by computer.

I think Use case diagram is a tool to analyze the behavior of any system, it could be even an automobile

But when we intend to implement a system by a computer which behaviors should be considered?
if we take into account anything could be done in the system even manually by human or automatically by the computer then how and when we can extract the behavior of the software system we intend to implement

For example suppose we want to make a software for an ATM (Automated Teller Machine):

A clerk can open the ATM and put money in it. (It's done manually, should it be considered a use case of system?)

Suppose one use case of the system is withdraw money, a scenario for it could be:

Customer insert his card into the card reader

Card reader validate the card

Customer Insert his password

System identify the customer and register him

Customer request money withdrawal

System shows a form

Customer enters the amount

System check the customer bank account and update the balance

System delivers the money through an outlet

The cases 1 and 2 are done by card reader and not our software, should we consider them?
Or the last cases are done by the dispensing mechanism and not our software

答:
A Use Case defines the interactions between an actor and a system.  The actor can be a person, another system, or a clock.

More specifically, in a use case the actor refers to a particular role.  So the behaviors that should be considered are those behaviors that are consistent with the role represented by the actor symbol in the diagram, not necessarily every action that such an actor can take.

To put it more plainly, pulling the plug out of the wall is not an action you need to be concerned with (although it might play a part in some problem mitigation strategy or physical security scenario).  Rather, the actions you need to be concerned about are those actions which a particular role is concerned with, and the manner in which the system responds to those actions.

A very simple use case example:

Which means "In the role of Registered User, this actor can perform the system action of editing an article."

The idea of collecting these use cases is (in large part) to identify all of the relevant user interactions and system responses, which will give you an overall idea of system scope, and provide a starting point for developing software requirements.


答:
There are business reasons for choosing a language, and there are engineering reasons for choosing a language, and the twain do not always meet.  Throwing in academic reasons is likely to make things worse.  I doubt a professor will be able to help you in the way you need.

The facts about a language's ancestry and features are pretty easy to find.  You could probably spend a day on wikipedia to fill most of that out.  Talent pool size and salary are more difficult, because most people don't consider themselves single-language programmers.  Companies who use less popular languages like Scala pretty much expect to hire good general programmers who don't have language-specific experience.  Judging from some presentations I've seen, that strategy seems to have worked out well.

Even knowing the facts still leaves you with a pretty subjective choice.  Your CEO is going to want it boiled down to a rough metric something like dollars per feature.  To get an accurate picture, you're going to have to do some prototypes, then talk about how easy it was to learn, how fast it was to write a prototype once you learned the basics, how easy you think it would be to maintain, and how broadly applicable you think it would be to the kind of work you typically do.

Rather than trying to cover all languages, I would seek to get representatives from the different programming paradigms and types of frameworks, and implement a prototype in each.

Here's a rough list of back end categories:

Microsoft. (May have subcategories.  I know nothing about them.)

Heavyweight OOP, like Drupal.

Lightweight OOP, like python bottle.

Play/lift/scalatra using Scala.

Play/lift using Java.

Spring-like.

Struts-like.

Rails-like.

Haskell-based.

Node.js

On the front end:

OOP-style JavaScript

Functional-style JavaScript, like with Underscore

Reactive-style JavaScript, like with Bacon

Google Web Toolkit

Elm

Spending a day or two on each category, implementing a simple prototype, would take you a couple months, after which you would have a much better idea of the strengths and weaknesses of each.  Perhaps you could rule some out more quickly based on your company's culture or experience.

Since this is a business report, I would also take some time googling things like "What language does <company> use," substituting various companies you admire.  Many of them have written whitepapers of their own on why they made specific language choices, which would make excellent references for you to include.


答:
Let's reason our way through it and remember the definition of O. The one I'm going to use is for the limit at infinity.

You are correct in stating that you perform two operations with corresponding asymptotic bounds of O(n) and O(nlog(n)) but combining them into a single bound is not as simple as adding the two functions. You know your function takes at least O(n) time and also at least O(nlog(n)) time. So really the complexity class for your function is the union of O(n) and O(nlog(n)) but O(nlog(n)) is a superset of O(n) so really it is just O(nlog(n)).

Title: Algorithms: How do I sum O(n) and O(nlog(n)) together?

Body:
I have the follow algorithm which finds duplicates and removes them:

```<code>public static int numDuplicatesB(int[] arr) {
    Sort.mergesort(arr);
    int numDups = 0;
    for (int i = 1; i < arr.length; i++) {
        if (arr[i] == arr[i - 1]) {
            numDups++;
} }
    return numDups;
}
</code>```

I am trying to find the worst case time complexity of this. I know mergesort is nlog(n), and in my for loop I am iterating over the entire data set so that would count as n.
I am unsure what to do with these numbers though. Should I just sum them together? If I were to do that, how would I do it?


答: You are essentially trying to do collision detection the same way ethernet and other network protocols perform collision detection for network packets in a distributed setting. The problem is that you don't have the benefit of the protocol being aware of such scenarios if you're talking to a server that you don't control. The only real solution in that case is to proxy all requests through an intermediary that you do control and then make it aware of collisions. Instead of a wire like in the case of ethernet you essentially have 100 wires each of which can only have one request active. Here's an article that should be helpful: Carrier sense multiple access with collision detection.</p>


答: This sounds similar to encryption and MAC order. The preferred approach in that setting is to encrypt and then add the MAC. There is no reason not to follow the same order in this case. You should compress and then add the checksum/hash. That way the integrity of the compressed payload can be checked before doing any kind of decompression. If you add the checksum/hash and then compress then you force the client to decompress to check the integrity of the payload whereas with compress-then-checksum approach you save the client the trouble of decompression if the integrity of the payload is compromised. Here's the link about encryption and MAC order: https://crypto.stackexchange.com/questions/202/should-we-mac-then-encrypt-or-encrypt-then-mac.</p>

Title: Is hash calculated before/after compression?

Body:
I had a question regarding compression and calculation of checksum/hash of data.

I would like to know if checksum has to be calculated before or after the compression of  data before transmission. Could someone please explain this so that I can get a better understanding of it?


答:
Identify and cost the shortcomings inherent to your existing development process as $A.
Identify the cost of switching to any other development process as $B.

If $A is less then $B, stop.

If your known shortcomings outweigh the cost of change (and that is a big if!) then analyse the shortcomings in detail and start looking for a language/development environment/development process changes that addresses them, one that wont introduce other more expensive problems.

To be honest, unless you are currently trying to develop web apps in Fortran, then the only impact the language you use will have is on the cost of contractors you use to fill the gaps. Main stream and mature languges/tools/development processes have already solved most of the problems you are likely to face where as the hottest, newest and sexiest tools come with the most expensive trainers and contractors, but the least mature solutions. And if you do have shortcomings that warrant such a change, it is unlikely that your choice of language will fully address them.

However, if profitability is not the primary objective here then you need to factor in the the stigma of being considered old-fashioned against the kudos of being cutting edge. Ask your boss for the dollar values to use for this part of the equation.


问:
What is the best way to create HTML in C# code?
I have a belief that markup should remain in mark-up and not in the code behind.

I've come to a situation where I think it is acceptable to build the HTML in the code behind. I'd like to have some consensus as to what the best practices are or should be.

When is it acceptable to build html in the code behind? What is the best method to create this html? (example: Strings, StringBuilder, HTMLWriter, etc)

答:
Nearly two years after the original post - here is a solution that has worked well for me. In the target document I place the following:

```<code><table>
    <%:theHtmlTableMomToldYouAbout() %>    //# Where I want my rows of table data to go
</table>
</code>```

the function being called looks like this:

```<code>    public HtmlString theHtmlTableMomToldYouAbout()
    {
        string content = "";
        HtmlString theEnvelopePlease = null;

        for (int i = 0; i < 5; i++)
        {
            content = content + "<tr><td>The Number Is: " + i + "</td></tr>";
        }
        theEnvelopePlease = new HtmlString(content);
        return theEnvelopePlease;
    }
</code>```

And the resulting output in the browser is as expected:

The Number Is: 0

The Number Is: 1

The Number Is: 2

The Number Is: 3

The Number Is: 4

When I go to view source I find the following:

```<code><table>
    <tr><td>The Number Is: 0</td></tr>
    <tr><td>The Number Is: 1</td></tr>
    <tr><td>The Number Is: 2</td></tr>
    <tr><td>The Number Is: 3</td></tr>
    <tr><td>The Number Is: 4</td></tr>
</table>
</code>```

Body:
Nearly two years after the original post - here is a solution that has worked well for me. In the target document I place the following:

<table>
    <%:theHtmlTableMomToldYouAbout() %>    //# Where I want my rows of table data to go
</table>

the function being called looks like this:

    public HtmlString theHtmlTableMomToldYouAbout()
    {
        string content = "";
        HtmlString theEnvelopePlease = null;

        for (int i = 0; i < 5; i++)
        {
            content = content + "<tr><td>The Number Is: " + i + "</td></tr>";
        }
        theEnvelopePlease = new HtmlString(content);
        return theEnvelopePlease;
    }

And the resulting output in the browser is as expected:

The Number Is: 0

The Number Is: 1

The Number Is: 2

The Number Is: 3

The Number Is: 4

When I go to view source I find the following:

<table>
    <tr><td>The Number Is: 0</td></tr>
    <tr><td>The Number Is: 1</td></tr>
    <tr><td>The Number Is: 2</td></tr>
    <tr><td>The Number Is: 3</td></tr>
    <tr><td>The Number Is: 4</td></tr>
</table>


问:
Why does java.util.ArrayList allow to add null?
I wonder why java.util.ArrayList allows to add null.  Is there any case where I would want to add null to an ArrayList?

I am asking this question because in a project we had a bug where some code was adding null to the ArrayList and it was hard to spot where the bug was. Obviously a NullPointerException was thrown but not until other code tried to access the element. The problem was how to locate the code that added the null object. It would have been easier if ArrayList threw an exception in the code where the elements was being added.

答:
The statement

```<code>File f = null;
</code>```

is valid and useful (I don't think I need to explain why). It is likewise useful to have a collection of files, some of which may be null.

```<code>List<File> files = new ArrayList<File>();
// use my collection of files
// ....
// not using this one anymore:
files.set(3, null);
</code>```

The usefulness of collections that may contain null objects proceeds directly from the usefulness of objects that may be null. It is really as simple as that.

Body:
The statement

File f = null;

is valid and useful (I don't think I need to explain why). It is likewise useful to have a collection of files, some of which may be null.

List<File> files = new ArrayList<File>();
// use my collection of files
// ....
// not using this one anymore:
files.set(3, null);

The usefulness of collections that may contain null objects proceeds directly from the usefulness of objects that may be null. It is really as simple as that.


答:
I think the premise of the question is not quite right. The dividing factor is not the quantity of records that need to change, but the frequency of changes as well as who changes them.

Frequency

When data is volatile, in the sense that it changes often and outside of a release cycle of the software, it needs to be able to be configured outside of hard-coded values or even configuration files. A database makes sense here, especially if the application itself is capable of maintaining it.

Who

When a customer needs to be able to change data, it needs to be modifiable in a user-friendly manner and outside of a release cycle.

Common Thread

The common thread here is that when data needs to change outside of a software release, it should be stored in a database. Databases might be upgraded during a release, but the data lives on without being reset or heavily modified. When a customer needs to be able to modify data (or configure functionality), it should be stored in a database with a nice front end that is idiot-proof.

Testing

Be sure to write unit tests that validate your software in a variety of configurations. Maybe your customer turns on an optional prompt, or redefines one meter to equal twelve feet. Regardless of how reasonable the change is, if your software allows it, it damn well better validate that the change works as expected no matter how inane it is.


问:
How to abide the "allocate in caller" rule when the size is computed in the callee?
Let's say we have an opaque type handle_t that is managed through a simple interface with functions such as:

```<code>handle_t *handle_init(void);
int handle_do(handle_t *);
void handle_free(handle_t *);
</code>```

The problem is that the size cannot be always determined in the initialization step and it has to be calculated in handle_do. One solution I have seen is calling handle_do two times, the first of which returns the size needed to allocate, but doesn't that affect the performance?

Is it a bad practice to allocate or reallocate memory in handle_do? Does it even matter when using handle types (since the init/free routines are made clear)?

答:
All types have their size determined in compile-time. For handle_t to change it's size in runtime, the data needs to be outside of the type system. std::vector is one way to move your data outside the type system, since it keeps separate memory area for heap-allocated array. The array does not have any type attached to it, only the items have a type. sizeof(std::vector<int>) does not contain the contents of the array.

Given these restrictions, you need to store a pointer to variable-sized memory block that needs to be reallocated when the size changes.


问:
What is the best C++ interview question?
If you could ask a C++ programmer one question to measure their C++ skills, what would it be?

The question I think is best is: Can you call "delete this;" inside a member function? (I put this as a link so you can think it through first, then go to The Best C++ Interview Question – Ever! to see the correct answer.)

I don't ask this because I expect most people to know the answer. If they did it would not be that useful a question. I ask to see if they can work their way to the correct answer and how they do so.

答: The first thing to ask is a simple question about pointers.  I was astonished to see how many people who claim to know C++ or, even worse, C, are unable to answer it.  Then I would ask a simple question about virtual functions.  This combination tells you very quickly whether or not the person actually knows C++.</p>


问:
3d Packing algorithm for item's shipping
I've received a task to build a shipping estimative that suggests the best accomodation of goods on as few boxes as possible:

There is a finite set of known retangular box sizes

There are many arbitrary retangular item to be packed inside boxes

The fewer boxes should be used the best. Because shipping two boxes 1x1x1 is way more expensive than one box 1x2x1. This should be the priority here.

It should also be optimized to use the smaller boxes as possible, as a second level priority. (eg.: if presented with a choice between one bigger box and two small, it should choose the bigger box)

Items can be rotated to fit the box, but the rotation have to be limited to increments of 45° at a minimum (in my researches it seems that some configurations allow for a 45 degrees rotation to better fit retangular boxes inside a bigger retangular box), being 90° rotations the standard to be taken.

Boxes have a weight limit and items have arbitrary weights (eg.: an item that is size is 1x1x1 can be havier than other 2x2x2 item)

I've researched a bit and found some abstracted algorithms on bin packing and the knapsack problem and came with the following somewhat bruteforce variation, similar to the best fit algorithm:

Sort the items in decrescent volume order (bigger first) on an "items to pack" list

For each item on this list:

Choose the smaller box that is on the "used boxes" list and has enough remaining volume and weight limit to fit the item (I will use fit here to mean fitting the dimensions and weight)

If there is not such box, create a new box from the know set of possible box sizes that is the smallest size that can fit the item's dimensions and weight and add it to the list of "used boxes".

If a box fits the item (using the fitting function bellow), add it to the list of "this box's items" and remove it from the "items to fit" list, marking it's relative 3d position inside the box.

Repeat from 2.1 until there is no item to be fitted on the "items to pack" list.

The fitting check function used on step 2 above:

Check if the remaining volume of the box fits the volume of the item. If not, return false.

Check if the sum of "box's items" weight plus the current item weight is less or equal to the box weight limit. If not, return false.

Check the "box's items" list to choose the first box coordinate that has the smallest Y component and that has enough space for the item's width, depth and height, considering the other items placed as unavailable space.

If the item doesn't fit at it's current orientation rotate it on one of the 6 possible rotations, not assuming 45° rotations for simplicity. (Rotations that result in sizes that where already tested can be skipped. Eg.: rotating a box 180° gives the same dimmensions as the original position because all boxes and items have the same size for opposite faces and so can be skipped.)

If the item hasn't been rotated on all the possible ways back to its original orientation, try again from step 3.

If all rotations where tried and no fit was found, consider the current coordinate as unavailable space.

If there is not avaliable space to check, return false. Else, try again from step 3.

I want to know if there can be a best solution to my problem, given the presented constraints.

This seems to work on theory but I've not tried it on code. I wish to know if I'm going in the right direction or there are better, performant ways of doing this.

References would be great.

Edit:

I've found some interesting 3rd party API that do what I want, but this will have to be disconnected, so I will not have access to these.

Some examples are:

http://v2.3dbinpacking.com/demo/main

http://www.packit4me.com/api

Edit 2:

A real world example of problem to solve would be:

I have 4 box sizes WxHxD: 10x12x18, 12x16x24, 16x20x30, 24x32x40

I have an order of 4 items, being 1 of size 6x8x10, 2x 22x14x30 and 1x 22x4x20

How do I fit this items into any amount of boxes of one or more sizes using the fewer boxes as possible, using the smallest boxes possible and leaving less free space as possible?

答:
Bin packing is very computationally difficult. Think of half of the problem: you want to pack product in shipping boxes with no wastage in the box. An optimal solution for that would require going through all possible subsets and all possible 3d arrangements of the product that needs to ship in one truck. I'll give you the optimal solution for that because I have a friend who does six impossible things before breakfast.

Now you just have to get all the boxes on the truck with no wastage. My friend does his second impossible thing and gives you the solution. Unfortunately, with the box sizes you selected above, there is empty space in the truck which could be reduced if you'd chosen different (either larger or smaller) boxes in the first task. If you change the size of one box, at best you'll have to re-pack the truck; at worst, you may have to repack all of the boxes which is just as hard as the problem we started with. And, as with the first stage, you'd have to try all possible 3d arrangements.

I found Skiena's The Algorithm Design Manual to be helpful for thinking about what class of algorithms suit which sorts of problems, but I mostly learned that good solutions for even mundane problems blow up in you face with computational difficulty. Most of what you are needing fit into the class of bin-packing problems and that article is a good jumping off point. It is worth noting that some of the best algorithms for this are commercial products because this task pops up everywhere in logistics (what's the smallest number of train cars can I get my goods into? and such). There is considerable money to be made if the right heuristics can save a manufacturer 100 train cars a month.

Unfortunately, the literature on optimizing heuristics isn't nearly as large as for algorithms. If you try to go it alone, I guarantee that you'll be dreaming about moving rectangular prisms around by your second month. I had a cutting-stock problem that if I had to do again I'd probably farm out to the experts (or their propriety software).

Thanks to @JTrana for the fine expansion of my comment.


答:
If you were going to set it out longhand it would look roughly like this:

Suppose the total time is: a n + b n log(n), where a and b are constants (ignoring lower order terms).

As n goes to infinity (a n + b n log (n)) / n log (n) -> a / log (n) + b -> b

So the total time is O(b n log(n)) = O(n log (n)).


问:
mongoDB user management (built in or own implementation)
I started to evaluate mongoDB for a product catalogue.
Regarding user management and access control: When to use the mongoDB's built in user management and when build one on the application layer?

Let us say I have a product catalogue organised as a Tree. I want to define access rights on the nodes of the tree.

Access rights could the be inherited from the parent product group to all its products and articles.

答:
MongoDB itself can only define access privileges per collection, not per document. You likely want all the nodes in the same collection so you can query them properly (MongoDB can't query more than one collection in the same command). That means enforcing the access privilege on the database won't be sufficient. You will have to implement access control on the application server.

For further reading about permissions in MongoDB I recommend the MongoDB User and Role Management Tutorial as well as the $redact aggregation stage which is primarily designed to filter documents based on application-defined permissions.


问:
Best IDE for HTML, CSS, and Javascript for mac
I'm currently looking to move to using an IDE for web development. The options I'm considering are:

Aptana Studio

Coda

Expresso

Please base your answers on the following criteria, in descending order of importance:

Supports HTML, CSS, JavaScript

Powerful (having good code completion, good debugger, great syntax highlighting etc)

Fast and light

Supports HTML5, CSS3, and major JavaScript frameworks (JQuery or YUI)

Great design (both usability and aesthetics)

Supports PHP, Ruby, and Python

Has Git integrated

I've updated the question to be more objective. I'm mainly looking for an answer that addresses how well each of the IDEs addresses my criteria.

答:
Coda

Of the three you mention I think Coda is the best buy. Espresso was (is) worthless until they integrate better. Aptana is heavy and clunky.

Note that Coda doesn't have a debugger or support for JS frameworks as far as I know. I last used Coda at 1.5 before switching to VIM / TextMate for everything.

Comparison

A: Aptana

C: Coda

E: Espresso

Supports HTML, CSS, JavaScript (ACE)

Powerful (having good code completion (ACE), good debugger (A), great syntax highlighting (ACE))

Fast and light (CE)

Supports HTML5, CSS3 (AC), and major JavaScript frameworks (JQuery or YUI) (A?)

Great design (both usability and aesthetics) (C)

Supports PHP, Ruby, and Python (ACE)

Has Git integrated (A?)

Thoughts

All support HTML, CSS, and JavaScript. By support I mean offers tag closings, some formatting options, and syntax highlighting.

Code completion is bad, as are IDE's in general

Fast and light are not indicators of good IDE's, rather they are indicators of excellent feature pruning.

What specifically do you mean by HTML5 (buzzword), CSS3 (almost a buzzword)?

All aren't horrible, Coda and Espresso are better then Aptana.

All support to some extent these languages.

None as far as I know have integrated git support, and none should. Git is best done at a command line.


问:
Where to put JPA annotations? Field, or getter?

version in field:

```<code>@Column(name = "SAMPLE_STRING")
private String sampleString;

public String getSampleString(){
  return sampleString;
}
</code>```

version in getter:

```<code>private String sampleString;

@Column(name = "SAMPLE_STRING")
public String getSampleString(){
  return sampleString;
}
</code>```

It seems both are working well, are there reasons not to use one of them, or just a good practice why I should prefer one of them? Is any one of them safer/better/desirable?

答:
Taken from https://stackoverflow.com/questions/14028198/jpa-why-the-annotations-are-applied-on-getter-or-field, if you apply the annotation to the field, the jpa provider directly sets the field. If you annotate the getter, the JPA provider uses the accessor methods.

See Chapter 2.3.1 of the specification here.

I prefer field access for a couple of reasons:

- you do not need to provide getters and setters for all properties, so this actually enhances encapsulation.

- i prefer to have the information grouped at the beginning of a class on the fields because I thinks it is more readable


问:
Codifying architecture in requirements
For the development of a next generation of a medical monitoring device consisting of several dedicated hardware systems with embedded software, I am looking at the requirements for the current generation of the device to see what can be re-used. During this process, I cam across some requirements that explicitly specify a certain architecture for one of the sub-systems and requirements that presume that particular architecture.

My question is, is it correct to have such requirements, or should such design decisions really be relegated to an architectural design? I find the requirements that presume an architecture the most troublesome, as they do have merit within that architecture but might be nonsense when a different design had been chosen and it is not always possible to rewrite them in an architecture-independent way.

Some paraphrased examples of the requirements:

The system shall be composed of hardware modules X, Y and Z.

  Rationale: This is how we have done it before and we didn't experience any trouble with it.

My problem with it: The end-user wouldn't care how we divide up the system, as long as it is not a burden to work with. I also couldn't see any other stakeholders that would have a vested interest here.

Hardware module X shall be physically detachable from hardware module Y.

  Rationale: This allows for easier storage of the system and to allow the user to exchange the more fragile module X in case of problems.

My problem: The intent of the requirement I can agree with and is something the end-user might care about, but I don't see how a requirement can refer to a hardware module whose existence is subject to a design decision that isn't a requirement.

Hardware module Y shall contain software function S.

  Rationale: Software function S needs quite a lot of processing power that is only available in module Y.

My problem: It could also have been decided to give hardware module X a more capable processor and let it handle software function S.

An additional problem is that at least some of us have a strong belief that all module/software requirements must be traceable to a system requirement, which might not be true any more if those architecture-related requirements get thrown out.

答:
No, what you wrote doesn't belong to requirements, but to the architecture.

The requirements consists of user wishes, and users shouldn't know and shouldn't care whether you used library X, or module Y.

Also, adding rationales to requirements doesn't make sense.

The system shall be composed of hardware modules X, Y and Z.

  Rationale: This is how we have done it before and we didn't experience
  any trouble with it.

It depends. If the hardware modules are internal parts of your device, then this doesn't belong in either requirement, nor in software architecture.

But, if the hardware modules are something users can plug in and out, then they do belong to requirements. For example, they want to be able to connect USB sticks. Or they want to connect a specific probe to an ultra sound system.

The fact that you did it for a prototype is irrelevant. Your rationale can go to a document related to the hardware.

Hardware module X shall be physically detachable from hardware module
  Y.

  Rationale: This allows for easier storage of the system and to
  allow the user to exchange the more fragile module X in case of
  problems.

Better text (in an agile approach) would be : As a user of device ABC, I want to be able to detach X so that it can be replaced in case of problems.

Yes, this belongs to requirements. And it influences the software.

Hardware module Y shall contain software function S.

  Rationale:
  Software function S needs quite a lot of processing power that is only
  available in module Y.

This doesn't sound like a requirement. Actually, that may be an internal requirement for the HW department, which influences the software as well. As such I would put it in the architecture (we tried to implement this in software, and it didn't go well. We do it in HW instead).

This doesn't belong to user requirements, because user doesn't care how you implemented some functionality.

Title: Codifying architecture in requirements


答:
In principle requirements should deal with the problem space and not the solution space. However when you are working with medical devices there is a regulatory justification to include this as a design constraint as you must be able to prove certain behaviour. This is especially true when it comes to proving changes, where a defined independence between modules will make it easier to explain to regulators.

The rationales that you show don't really line up well with what I said above, but you also have to consider that there are some implied hardware constraints which you have to live with (ex computing power in module Y).

So I think this has to be considered as a design constraint. Stating it as a requirement will ensure that someone doesn't decide to change this without triggering a review.

Title: Codifying architecture in requirements

Body:
For the development of a next generation of a medical monitoring device consisting of several dedicated hardware systems with embedded software, I am looking at the requirements for the current generation of the device to see what can be re-used. During this process, I cam across some requirements that explicitly specify a certain architecture for one of the sub-systems and requirements that presume that particular architecture.

My question is, is it correct to have such requirements, or should such design decisions really be relegated to an architectural design? I find the requirements that presume an architecture the most troublesome, as they do have merit within that architecture but might be nonsense when a different design had been chosen and it is not always possible to rewrite them in an architecture-independent way.

Some paraphrased examples of the requirements:

The system shall be composed of hardware modules X, Y and Z.

  Rationale: This is how we have done it before and we didn't experience any trouble with it.

My problem with it: The end-user wouldn't care how we divide up the system, as long as it is not a burden to work with. I also couldn't see any other stakeholders that would have a vested interest here.

Hardware module X shall be physically detachable from hardware module Y.

  Rationale: This allows for easier storage of the system and to allow the user to exchange the more fragile module X in case of problems.

My problem: The intent of the requirement I can agree with and is something the end-user might care about, but I don't see how a requirement can refer to a hardware module whose existence is subject to a design decision that isn't a requirement.

Hardware module Y shall contain software function S.

  Rationale: Software function S needs quite a lot of processing power that is only available in module Y.

My problem: It could also have been decided to give hardware module X a more capable processor and let it handle software function S.

An additional problem is that at least some of us have a strong belief that all module/software requirements must be traceable to a system requirement, which might not be true any more if those architecture-related requirements get thrown out.


问:
What are your favorite version control systems?
This is more a discussion question than an actual attempt to determine the "best", since that clearly varies by the needs of the organization. I'm more curious about the arguments in favor of different systems across categories (centralized vs distributed, open vs proprietary, etc).

So, what do you think is the best version control system?

答:
Team Foundation Server

Because:

It's a good, solid VCS. (I wouldn't consider it the best by any means, but it has nice extras.)

Its built in task and bug tracking that integrate into Visual Studio helps me stay focued and know what I need to work on all in one place (automatically applying a check-in to a bug or task and closing it is pretty good, though you can get plugins for other systems/eclipse/etc to do this.)

It integrates tasks/bug tracking/projects directly into Project Server so I rarely ever have to keep project plans or timesheets up to date.  Updates to the Project in Project Server automatically filters down as tasks into TFS and into Visual Studio for me to see automatically.


答:
"The system must use Windows technologies" may be a requirement because the end-user is a Windows shop and cannot run, say, Linux solutions. This is an architectural decision but will still be part of the user requirements.

Similarly modularizing along these lines might have a good reason based on the end-user's systems where these broad components must be defined in this way, you can still implement them any way you like of course.

Sometimes architectural decisions are part of the requirements, consider the most common example of whether an application will be a webapp or a desktop one. This is definitely an architectural decision, yet will often be seem in user requirements.

So whether your particular requirements are just an overzealous, micromanaging customer, or have some grounding in sensible reasons isn't something we can tell. It might depend how 'module' is defined, if they're running on a suite of hardware boxes then they sound quite realistic. If you're writing a monolithic desktop application and they're analogous to dlls, then they're probably not sensible and you should push back on them.

PS. If you require strong traceability, you cannot map everything to a user requirement as many aspects will not be defined by the end-user. In these cases, you will have to map them to a design requirement that you define yourselves.

Title: Codifying architecture in requirements


问:
What are the main differences between C++ templates and Java generics?
I'm a beginning C++ programmer coming from Java.

It feels to me that C++ templates and Java generics are actually pretty similar. You use them in pretty much the same occasions and in the same way. And they 'feel' the same. However I can think of two differences between the systems:

In Java you can only use class-types as type arguments, while in C++ any type fits. I don't think this is significant because Java autoboxing is good.

A more significant difference: C++ templates are duck typed. Meaning you can call any operation on a generic type T. If it doesn't support the operation, a compile time error is raised. Java generics however aren't duck typed. By default all type arguments are of type Object, and you can specify something more specific by the syntax T extends Something, which allows us to call on T methods defined in Something.

The second point is rather significant. However apart from that, what are the differences between the two systems? What are the pros and cons of each one? Are they similar or different overall?

答:
Implementation of the generics is night and day:

In java the compiled code removes all references to the generic type and adds casts where necessary. This is called type erasure and lets you do List<String> list; ((List)list).add(new Object()); which will only throw an error when you try to get the value as a string. All java generics actually are is syntactic sugar with extra compile-time type checking.

In C++ when you use a template the compiler will emit the template code again after replacing the generic parameter in it with the type you used. This is more powerful in several ways but can lead to bloated executables.


问:
How to name a function type that is called by an event, but doesn't handle the event?
How would one name a function type called by a certain event? Instances of this function type would get called when a certain key is pressed. It isn't strictly an event handler type, because it doesn't have to handle the event. It might simply just want to be aware of the event. There can be multiple functions with this type listening for the same keystroke event.

I currently am using SpecificKeystrokeListener although that's not really correct as it doesn't listen, it is merely being notified.

For what it's worth, I am using Rust - though this applies to other languages as well. As an example:

type ResetFn = fn (this: *const device) -> ReturnStatus;

答:
Given the way OP is phrased I think he's looking for "Subscriber", although that moniker is more often used in Publish–subscribe scenarios.  Traditionally in event handling libraries they're called "Listeners" (as the OP code snippet demonstrates), but descriptions of the Observer pattern use "Subscriber", for example, here: http://www.oodesign.com/observer-pattern.html

See https://stackoverflow.com/questions/15594905/difference-between-observer-pub-sub-and-data-binding for a discussion of the differences between these patterns.


问:
Cobol programs and copybooks versioning
in java we have ivy, maven and others for handling library dependencies. For example I tell ivy that my program uses a framework-jar version 1.0 and ivy makes sure, that my program gets this jar when being compiled. When there comes an update and the framework-jar is now available in version 1.1, then my program still gets the version 1.0. I can however tell ivy that another program of mine should take the newer version 1.1.

Are there similar mechanisms in the cobol environments so that i can make sure my cobol program A uses copybook C in version 1.0 and my cobol program B uses copybook C in version 1.1?

答: 3 old Cobol programmers sitting here and we think this CAN'T be done in the form you need. The only thing that might be helpful is that you can use the "OF" statement to include the copybook from a different library for each of your 2 programs. Alternatively, you could just add a version Suffix to the name of the copybook maybe?</p>

Title: Cobol programs and copybooks versioning


问:
How to improve code that has to handle list-objects in general and special cases?
I do have an implementation issue that I condensed to the following code snippet, because the real code is much more complicated. The core problem is that I do have a container object that has a mixed list of persons, for example Managers and Engineers:

```<code>interface Person {

}

class Manager implements Person {

}

class Engineer implements Person {

}
</code>```

In the most cases I have to access the list of persons without knowing the concrete subclass of a person. But in some methods I have to know the concrete type of the members, for example to count the members or to add the members. In both implementations I do have ugly code:

In implementation A it's the code to separate the person-types for counting.

```<code>class EnterpriseA {

    private final List<Person> members = new ArrayList<Person>();

    public void addMember(Person person) {
        this.members.add(person);
    }

    public void doSomethingWithManagers() {
        // separate by instanceof
    }

    public void doSomethingWithEngineers() {
        // separate by instanceof
    }
}
</code>```

In implementation B it's the code to add a person to the right list of Manager or Engineer.

```<code>class EnterpriseB {

    private final List<Manager> managers = new ArrayList<Manager>();

    private final List<Engineer> engineers = new ArrayList<Engineer>();

    public void addMember(Person person) {
        if (person instanceof Manager) {
            this.managers.add((Manager) person);
        } else if (person instanceof Engineer) {
            this.engineers.add((Engineer) person);
        }
    }

    public void doSomethingWithManagers() {
        // iterate over the managers.
    }

    public void doSomethingWithEngineers() {
        // iterate over the engineers.
    }
}
</code>```

How can I improve the code and avoid the ugly code in addMember() and countManagers() respectively? Smart suggestions are welcome.

Which alternative would you prefer? Please give reasons, in which cases you would prefer which solution.

答:
If these types are related - as in your example - I would say that solution A is superior.

It makes use of polymorphism - the fact that Manager and Employee are both Persons, so you could eg. create a list of all names or sum up their salaries without forcing your code to worry (or even know about) job title distinctions.

"Manual" type checks (instanceof) in solution B are typically a code smell and a pain when it comes to maintanability.

It's also more bug-prone - even your sample code contained a bug already (confusing an engineer with a manager), which I already corrected.

If another type were to be added - say, Accountant - instead of only adding countAccountants, you have to insert another if check in addMember, and possibly various other methods.

Yes, there may be performance concerns regarding solution A. Having to filter the list and recount all Managers every time could be inefficient for big lists.

But there is a solution for that: you can keep count in the class and update counters in your addMember method, as well as any other method changing the contents of your collection (like removeMember), kind of caching the data.

You could even make it more generic and create a Map<Class<? extends Person>, Integer> typeToCount, where each key (Employee.class, Manager.class) would have a corresponding value representing how many objects of this particular type are stored. This would further decrease the effort of maintaining multiple types and protect you against bugs crawling in.

Like so:

```<code>class EnterpriseAPlus {
  private final List<Person> members = new ArrayList<Person>();
  private final Map<Class<? extends Person>, Integer> countByType =
        new HashMap<Class<? extends Person>, Integer>();

  public void addMember(Person person) {
     members.add(person);
     // (thread safety concerns disregarded for the sake of simplicity)
     Class<? extends Person> personClass = person.getClass();
     int currentCount;
     if (countByType.containsKey(personClass)) {
        currentCount = countByType.get(personClass);
     } else {
        currentCount = 0;
     }
     countByType.put(personClass, currentCount + 1);
  }

  public int countEngineers() {
     return getCountOf(Engineer.class);
  }

  public int countManagers() {
     return getCountOf(Manager.class);
  }

  protected final int getCountOf(Class<? extends Person> personClass) {
     if (!countByType.containsKey(personClass)) {
        return 0;
     }
     return countByType.get(personClass);
  }
}
</code>```

Need to handle Accountants now? Just add:

```<code>public int countAccountants() {
    return getCountOf(Accountant.class);
}
</code>```

No need to mess with addMember anymore. You could even add countAccountants by subclassing EnterpriseAPlus - remember the open/closed principle...

Body:
If these types are related - as in your example - I would say that solution A is superior.

It makes use of polymorphism - the fact that Manager and Employee are both Persons, so you could eg. create a list of all names or sum up their salaries without forcing your code to worry (or even know about) job title distinctions.

"Manual" type checks (instanceof) in solution B are typically a code smell and a pain when it comes to maintanability.

It's also more bug-prone - even your sample code contained a bug already (confusing an engineer with a manager), which I already corrected.

If another type were to be added - say, Accountant - instead of only adding countAccountants, you have to insert another if check in addMember, and possibly various other methods.

Yes, there may be performance concerns regarding solution A. Having to filter the list and recount all Managers every time could be inefficient for big lists.

But there is a solution for that: you can keep count in the class and update counters in your addMember method, as well as any other method changing the contents of your collection (like removeMember), kind of caching the data.

You could even make it more generic and create a Map<Class<? extends Person>, Integer> typeToCount, where each key (Employee.class, Manager.class) would have a corresponding value representing how many objects of this particular type are stored. This would further decrease the effort of maintaining multiple types and protect you against bugs crawling in.

Like so:

class EnterpriseAPlus {
  private final List<Person> members = new ArrayList<Person>();
  private final Map<Class<? extends Person>, Integer> countByType =
        new HashMap<Class<? extends Person>, Integer>();

  public void addMember(Person person) {
     members.add(person);
     // (thread safety concerns disregarded for the sake of simplicity)
     Class<? extends Person> personClass = person.getClass();
     int currentCount;
     if (countByType.containsKey(personClass)) {
        currentCount = countByType.get(personClass);
     } else {
        currentCount = 0;
     }
     countByType.put(personClass, currentCount + 1);
  }

  public int countEngineers() {
     return getCountOf(Engineer.class);
  }

  public int countManagers() {
     return getCountOf(Manager.class);
  }

  protected final int getCountOf(Class<? extends Person> personClass) {
     if (!countByType.containsKey(personClass)) {
        return 0;
     }
     return countByType.get(personClass);
  }
}

Need to handle Accountants now? Just add:

public int countAccountants() {
    return getCountOf(Accountant.class);
}

No need to mess with addMember anymore. You could even add countAccountants by subclassing EnterpriseAPlus - remember the open/closed principle...