问:
C API in C++ with RAII, two alternatives to implement error handling (Exceptions)
I have an API written in C, which produces a result by returning a pointer to allocated memory.

For using it with C++ (C++11) I've wrapped the function calls in objects, which keep the result in a std::shared_ptr. So far so good.

However, the C library features two functions for every operation. One produces possibly an error, the other never. Let's call them

some_pod * do_it_with_error(Parameter ..., Error **)

and

some_pod * do_it_without_error(Parameter ...)

I can pass in the address of an Error * pointer to the first function and if there's an error it won't be NULL afterwards.

For solving this I thought of two different implementations.

First, I could SFINAE for choosing between the with_error and without_error functions, like so:

```<code>template<typename NoThrow = void>
struct do_it {
  public:
    void operator()(...)
    {
      Error * error = NULL;
      m_result = std::shared_ptr<some_pod>(do_it_with_error(..., &error));
      if (error) {
        throw(MyExceptionWithError(error));
      }
    }
  private:
    std::shared_ptr<some_pod> m_result;
};

template<>
class do_it<std::nothrow_t> {
  public:
    void operator()(...) noexcept
    {
      if (! m_result) {
        m_result = std::shared_ptr<some_pod>(do_it_without_error(...));
      }
    }
  private:
    std::shared_ptr<some_pod> m_result;
};
</code>```

Usage:

```<code>do_it<> di_error;
try {
  di_error(...); // might throw
} catch (...) {}

do_it<std::nothrow_t> di_no_error;
di_no_error(...); // won't throw for sure
</code>```

However, since the result is wrapped in a std::shared_ptr there will also be
a get() method:

```<code>const std::shared_ptr<some_pod> & get(void) { return m_result; }
</code>```

For error checking I could just implement a another method check.

The default implementation would now look like this:

```<code>struct do_it {
  public:
    // will never throw
    const std::shared_ptr<some_pod> &
    get(void) noexcept
    {
      if (! m_result) {
        m_result = std::shared_ptr<some_pod>(do_it_without_error(...));
      }
      return m_result;
    }

    // might throw
    do_it &
    check(void)
    {
      if (! m_result) {
        Error * error = NULL;
        m_result = std::shared_ptr<some_pod>(do_it_with_error(..., &error));
        if (error) {
          throw ...;
        }
      }
      return *this;
    }

  private:
    std::shared_ptr<some_pod> m_result;
};
</code>```

Usage:

```<code>do_it di_error;
try {
  auto result = di_error.check().get();
} catch (...) {}
do_it di_no_error;
di_no_error.get();
</code>```

So, both implementations seem to be equally good (or bad) to me.

How could I decide which one to use.

What are the Pros and Cons?

答:
Too complicated - wrap them both as if either could throw an error, that the 2nd fn will never throw only means the compiler will never have to call the error handling routines (and might even optimise it out entirely) - either way your code will perform just as well thanks to C++s design.

Your code will also be much easier to understand, even with this redundant error handling (that one day might be used for other, unexpected errors)


答: In C the error objects are somewhat pain to handle, so there is the other overload that stores the errors somewhere. But in C++ exceptions make it all much easier to handle. So I would only wrap the variant that reports errors and converted the errors to exceptions and ignore that the other API even exists.</p>

ContentLicense: CC BY-SA 3.0

Title: C API in C++ with RAII, two alternatives to implement error handling (Exceptions)

Body:
I have an API written in C, which produces a result by returning a pointer to allocated memory.

For using it with C++ (C++11) I've wrapped the function calls in objects, which keep the result in a std::shared_ptr. So far so good.

However, the C library features two functions for every operation. One produces possibly an error, the other never. Let's call them

some_pod * do_it_with_error(Parameter ..., Error **)

and

some_pod * do_it_without_error(Parameter ...)

I can pass in the address of an Error * pointer to the first function and if there's an error it won't be NULL afterwards.

For solving this I thought of two different implementations.

First, I could SFINAE for choosing between the with_error and without_error functions, like so:

```<code>template<typename NoThrow = void>
struct do_it {
  public:
    void operator()(...)
    {
      Error * error = NULL;
      m_result = std::shared_ptr<some_pod>(do_it_with_error(..., &error));
      if (error) {
        throw(MyExceptionWithError(error));
      }
    }
  private:
    std::shared_ptr<some_pod> m_result;
};

template<>
class do_it<std::nothrow_t> {
  public:
    void operator()(...) noexcept
    {
      if (! m_result) {
        m_result = std::shared_ptr<some_pod>(do_it_without_error(...));
      }
    }
  private:
    std::shared_ptr<some_pod> m_result;
};
</code>```

Usage:

```<code>do_it<> di_error;
try {
  di_error(...); // might throw
} catch (...) {}

do_it<std::nothrow_t> di_no_error;
di_no_error(...); // won't throw for sure
</code>```

However, since the result is wrapped in a std::shared_ptr there will also be
a get() method:

```<code>const std::shared_ptr<some_pod> & get(void) { return m_result; }
</code>```

For error checking I could just implement a another method check.

The default implementation would now look like this:

```<code>struct do_it {
  public:
    // will never throw
    const std::shared_ptr<some_pod> &
    get(void) noexcept
    {
      if (! m_result) {
        m_result = std::shared_ptr<some_pod>(do_it_without_error(...));
      }
      return m_result;
    }

    // might throw
    do_it &
    check(void)
    {
      if (! m_result) {
        Error * error = NULL;
        m_result = std::shared_ptr<some_pod>(do_it_with_error(..., &error));
        if (error) {
          throw ...;
        }
      }
      return *this;
    }

  private:
    std::shared_ptr<some_pod> m_result;
};
</code>```

Usage:

```<code>do_it di_error;
try {
  auto result = di_error.check().get();
} catch (...) {}
do_it di_no_error;
di_no_error.get();
</code>```

So, both implementations seem to be equally good (or bad) to me.

How could I decide which one to use.

What are the Pros and Cons?


问:
Object-Oriented design and proper Java architecture for my program
This is the very first time that I think I want to create a program which really uses OOP principles and I want to do it in the most effective and efficient way.

First of all we are given this (great) riddle :

100 prisoners are imprisoned in solitary cells. Each cell is windowless and soundproof. There's a central living room with one light bulb; the bulb is initially off. No prisoner can see the light bulb from his or her own cell. Each day, the warden picks a prisoner equally at random, and that prisoner visits the central living room; at the end of the day the prisoner is returned to his cell. While in the living room, the prisoner can toggle the bulb if he or she wishes. Also, the prisoner has the option of asserting the claim that all 100 prisoners have been to the living room. If this assertion is false (that is, some prisoners still haven't been to the living room), all 100 prisoners will be shot for their stupidity. However, if it is indeed true, all prisoners are set free and inducted into MENSA, since the world can always use more smart people. Thus, the assertion should only be made if the prisoner is 100% certain of its validity.

Before this whole procedure begins, the prisoners are allowed to get together in the courtyard to discuss a plan. What is the optimal plan they can agree on, so that eventually, someone will make a correct assertion?

So I've got a solution and I want to create a program to run it. I want my program to be as modular as possible, meaning that if I find a better solution, I don't to have to rewrite all of my code. I think OOP is really suited for this.

Here's what I've done so far:

A Main class : where I just run several games to test solutions

A Game class : which just runs one 'attempt'. It has a 'jail' (which is just an array of prisoners), a day counter and other useful stuffs.

And a Prisoner class : which just represent one single prisoner.

After thinking this through, the only things that one prisoner can do are changing the light where they're picked and stating (or not) that everyone has come in the room.

In the solution I've come up with, I have two types on Prisoner. What I've done is that I just implemented my Prisoner class with the most classic type of Prisoner and created a subclass which simply overrides methods from the Prisoner class.

Right now, I see two possible improvements if I want to reuse my code :

make the Prisoner class a Java interface, so that when I want to create a new type, I'd just have to implement a Prisoner. But the main issue is that I mostly have 'typical prisoners', a lot of people having the same pattern. Do I just create a implementation 'Classic_Prisoner' ?

creating a Behaviour class which handles what behaviour one Prisoner have given a single situation. But isn't just the same problem ? I mean I would also have to create one Behaviour subclass for each type of Prisoner I'm considering.

What to do to have the cleanest code there and be able to reuse it when the time comes?

答:
Different "Behaviours" sounds to me like the "strategy" pattern (which inhibits an example for correct use of inheritance or interface usage). This will allow you to change the behaviour of each prisoner easily at run time, which is not easily possible with different Prisoner subclasses.

Besides that, to my understanding of your problem, all Prisoners are equal (at least from the viewpoint of data management and available behaviours), so I don't think inheritance is a good idea for modeling Prisoner objects.


问:
What is the general tech news website every programmer should read?
A link and a quick explanation why would be very helpful.

General tech news, I mean not like InfoQ which is too technical. Probably much more like P.SE than SO.

EDIT: site should help developers gain general knowledge about the industry, technologies, inventions, etc. Much like when we listen to the news every morning in our car to know what is happening in our world. But target audience must be either programmmers, geeks or any other persons interested in technology.

答:
http://www.h-online.com/ - heise open

It's a very broad and general tech related news site, not very programming specific, but security topics come up quite frequently. It's the international variant of http://heise.de/ which is the de-fecto no 1 programmer/IT news source in .de

However, there's no need to subscribe to it directly. It's low traffic and the most interesting stories are usually linked from reddit, slashdot, dzone.

ContentLicense: CC BY-SA 2.5


问:
Design in "mixed" languages: object oriented design or functional programming?
In the past few years, the languages I like to use are becoming more and more "functional". I now use languages that are a sort of "hybrid": C#, F#, Scala. I like to design my application using classes that correspond to the domain objects, and use functional features where this makes coding easier, more coincise and safer (especially when operating on collections or when passing functions).

However the two worlds "clash" when coming to design patterns. The specific example I faced recently is the Observer pattern. I want a producer to notify some other code (the "consumers/observers", say a DB storage, a logger, and so on) when an item is created or changed.

I initially did it "functionally" like this:

```<code>producer.foo(item => { updateItemInDb(item); insertLog(item) })
// calls the function passed as argument as an item is processed
</code>```

But I'm now wondering if I should use a more "OO" approach:

```<code>interface IItemObserver {
  onNotify(Item)
}
class DBObserver : IItemObserver ...
class LogObserver: IItemObserver ...

producer.addObserver(new DBObserver)
producer.addObserver(new LogObserver)
producer.foo() //calls observer in a loop
</code>```

Which are the pro and con of the two approach? I once heard a FP guru say that design patterns are there only because of the limitations of the language, and that's why there are so few in functional languages. Maybe this could be an example of it?

EDIT:
In my particular scenario I don't need it, but.. how would you implement removal and addition of "observers" in the functional way? (I.e. how would you implement all the functionalities in the pattern?) Just passing a new function, for example?

答:
Your "FP guru" is partially right; many OO patterns are hacks to do functional things. (His claim that this is the reason there's few FP languages seems dubious at best.) The Observer and Strategy patterns are trying to emulate first-class functions. The Visitor Pattern is a hack to simulate pattern matching. Your IItemObserver is just a function in disguise. Pretending it's different from any other function that takes an item doesn't buy you anything.

Objects are just one kind of data abstraction. This paper will help shed some light on that topic. Objects can be useful, but it's important to recognize they're not appropriate for everything. There is no dichotomy; simply a matter of choosing the right tool for the right job, and functional programming in no way requires that you give up objects. That aside, functional programming is more than just using functions. It's also about minimizing side effects and mutation.


问:
Even distribution through a chain of resources
I'm working on an algorithm which routes tasks through a chain of distributed resources based on a hash (or random number).

For example, say you have 10 gateways into a service which distribute tasks to 1000 handlers through 100 queues. 10,000 connected clients are expected to be connected to gateways at any given time (numbers are very general to keep it simple).

Thats

10,000 clients

10 gateways (producers)

100 queues

1000 workers/handlers (consumers)

The flow of each task is client->gateway->queue->worker

Each client will have it's own hash/number which is used to route each task from the client to the same worker each time, with each task going through the same gateway and queue each time. Yet the algorithm handles distribution evenly, meaning each gateway, queue, and worker will have an even workload.

My question is what exactly would this be called? Does such a thing already exist? This started off as a DHT, but I realized that DHTs can't do exactly what I need, so I started from scratch.

答:
Each client will have it's own hash/number which is used to route each task from the client to the same worker each time, with each task going through the same gateway and queue each time. Yet the algorithm handles distribution evenly, meaning each gateway, queue, and worker will have an even workload.

These two characteristics are not compatible.

Consider the case where your system is new and process each client one time.  Now sort all your clients according to the worker that processed them and send the clients in this order to your system:  you will attain the highest possible congestion while respecting the first condition.

If you do not want to drop completely the second requirement, you will probably need to specialise the problem and make an assumption on the distribution of client arrivals.


问:
Why do we need years in a software license?
I start every .java file in my project with a license (BSD, in my case). And its first line says:

```<code>/**
 * Copyright (c) 2011-2014, Firstname Lastname
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 etc.
</code>```

The question is, why do I need to show years there? I see many other projects are doing the same. What will I lose by just saying Copyright (c) Firstname Lastname, without that time interval.

答:
Dates aren't so much a licensing thing as a copyright thing.

Although the particulars vary from jurisdiction to jurisdiction, copyrights generally apply for a finite amount of time. By including a date range, you can state unambiguously when the term of your copyright started, and thus remove the question of whether or not that copyright is still in force. Computing is a young enough field that this is not presently very much of a concern: most of the code that has ever been copyrighted still hasn't been around long enough for the copyright to expire. But as the years go by, it will eventually start to be an issue.

In some jurisdictions, you can release the copyright on your code by dedicating it to the public domain. However, even in these cases, the date stamp remains important. Stamping public-domain code shows unambiguously when it was released.


问:
Data sharing across processes
I have a C# .NET app that downloads a users Tweets using LinqToTwitter. This is for TV broadcast - the client wants to show Tweets on air. We have two other apps that need to access these tweets. One is a C++ app and one will use MS Script Host. These two apps don't run at the same time - it's one or the other.

My question is, of the many ways to share this data, which would you choose?

DataBase - Like MySql. This was my first choice. But then it seemed like overkill for the 10-20 tweets they would get per day.

Streaming - Like TCP or named pipes. This would involve some type of protocol. Like "Give me the last 10 tweets..."

Xml - Store the data in a file all programs can access. Simplest, but just doesn't feel right for some reason.

Memory Mapped IO - I think this would require a COM library for the scripts to be able to use it

There are others. Just curious what you would use. I am the only programmer in a small company and don't have others to bounce ideas off of.

Thanks.

答:
I vote for a database. Any concerns around locking, concurrent access, persistence etc would be dealt with by the database, and more clients can be added without impacting the others. The architecture would then be;

```<code>                              +--> Reader A
                              |
Data Extractor --> Database --+--> Reader B
                              |
                              +--> Reader C
</code>```

It would also be straightforward to run reports on the tweets later e.g. stats per day.

Title: Data sharing across processes

Body:
I vote for a database. Any concerns around locking, concurrent access, persistence etc would be dealt with by the database, and more clients can be added without impacting the others. The architecture would then be;

                              +--> Reader A
                              |
Data Extractor --> Database --+--> Reader B
                              |
                              +--> Reader C

It would also be straightforward to run reports on the tweets later e.g. stats per day.


问:
C# open source projects
What C# project(s) would you consider contributing to if you were a beginner trying to sharpen your skills in C# and .NET framework ? The project should be (besides all) active and not something less active and/or stagnant. </p>

答: BlogEngine.NET is a high-quality project, and what might make it even better to contribute to is that is has an extension framework so you could get started writing an extension to implement some interesting bit of functionality, rather than having to dive head-first into a complex codebase.</p>

OwnerDisplayName: Vicky

Title: C# open source projects


问:
Is it bad practice to encapsulate a single operation in a class?
I recently had a back and forth over at StackOverflow about my answer to this question.

The question was simple. The author wanted to transform a number into an abbreviated version that appended a K, M, or B depending on the size of the number.

One user suggested a very straightforward and naive answer:

```<code>function round_thousands($number){
    if($number < 1000){
        return $number;
    } else {
        return number_format($number/1000, 1).'K';
    }
}
</code>```

Ignoring the fact that the name of the function doesn't match what it does, and that it only converts into K, I can see why this answer might be attractive at first.

However, I elected to take a more robust approach, and create an interface:

```<code>interface Quantifier {
    public function quantify($value);
}
</code>```

I then created a default quantifier called NumberQuantifier:

```<code>class NumberQuantifier implements Quantifier {
    protected $quantifierList;

    public function __construct($quantifierList) {
        $this->quantifierList = $quantifierList;
        arsort($this->quantifierList); //Make sure they are largest too smallest.
    }

    public function quantify($number) {
        foreach ($this->quantifierList as $symbol => $threshold) {
            if ($threshold > $number) continue;

            return number_format($number / $threshold, 1) . $symbol;
        }
    }
}
</code>```

Simple stuff, I thought.

This allows you to create quantifiers for all sorts of things: file size, mass, length, volume, etc. Without having to copy/paste a new function every time:

```<code>$numberQuantifier = new NumberQuantifier(array(
    'B' => 1000000000,
    'M' => 1000000,
    'K' => 1000
));
</code>```

Furthermore, in the event that you had a more advanced case, you could implement Quantifier and create some custom functionality for quantifying.

However, I was soon met with a critic who insisted that I shouldn't be using a class for this at all. In fact, he was adamant, despite my numerous attempts to satisfy why a class would be ideal.

Argument

His argument was that a class

Must have some mutable state

Must encapsulate more than a single operation

Otherwise, he contends, it should be a global function.

His alternative (I think) would be to do something like:

```<code>function number_quantify($value, $quanitfierList) {
    foreach ($quantifierList as $symbol => $threshold) {
        if ($threshold > $number) continue;

        return number_format($number / $threshold, 1) . $symbol;
    }
}

function quantify_mass($value) {
    $quantifieryList = array(); //quantifiers here.

    return number_quantify($value, $quantifierList);
}

function quantify_length($value) { //.. }

//etc.
</code>```

Basically, for any type of quantifier, you have to create a new function that would always live in global space. Alternatively, you could manually pass the $quantifierList to each function call of number_quantify which seems like a maintenance nightmare.

I believe that my use of an interface and polymorphism not only makes the code cleaner and more maintainable, but also would facilitate better unit testing.

Question

Am I wrong? Is having a class that encapsulates a single operation and no mutable state some type of code smell?

答:
No, you aren't wrong--provided that you're working with a language where a class is required for downstream replacement.

In (older versions of) C#, you could finagle a static function somehow, but its more work to override that than just subclassing a simple class, especially if you use a factory pattern.

In JavaScript, however, its easier to replace a function than define a new prototype, so the overhead of a declared interface and class is just wasted memory without benefit.

And even in JavaScript, there are reasons to make a prototype class with only a single method.  Not the least of which is if that "simple" method may be replaced with a very complicated set of functions instead of a few lines.


问:
How to convince my company (operating in the financial sector) to switch from PHP to Java
My company is in the financial sector and it is using PHP as programming language. I am a PHP developer myself.

I am leading a big project started from almost scratch. I can see how PHP is not the best candidate for building robust platforms.

I want to convince my company to gradually switch to Java (which I have experience with).

I was trying to find as many supporting arguments as possible. Can you help with this?

So far I have found these:

Most of the competitors are using Java (anyway not PHP)

Most financial companies use Java rather than PHP

On average, Java developers are better prepared (on average!)

The compilation process catches a lot of problems before the software runs in production

Strong typing makes everything more robust as contracts between interfaces is well defined

Any other points I am missing?

Thanks!

答:
The only reasons that could justify a language switch are those that overcome all of the advantages of staying put.

The company has an entire software division whose primary employment is writing PHP.  Switching to a new language, especially one as different as PHP to Java, WILL require training and several months of lost productivity.

The company has several systems built on PHP.  Switching to Java implies re-writing those, which is a huge undertaking that should be avoided if practical.

Several of the company's software systems already work together the way PHP expects to work together, which is amazingly different from the way Java works between programs.

Depending on your development stacks, you may have a not-insignificant investment in PHP specific IDE's and reference materials.

Of course, none of the above are without reasonable counters.  If there are available frameworks and tooling that may be used exclusive to Java, or a likelihood of the company merging or collaborating a competitor, or your software team is full of people with a lot of Java proficiency, there's less risk and more gain in making the switch.

Honesty, though, you may have more luck in ADDING Java to your company's stable of languages than trying to switch.  I would hope that, if nothing else, your company already uses SQL, JavaScript, and either XML or JSON in addition to PHP.  Adding a more strongly-typed OOP language like Java or C# could be a great complement to your host of PHP apps.


问:
How to comment on a PEP?
Proposals for new Python features are collected in documents called PEPs (Python Enhancement Proposals). There's a master list at http://www.python.org/dev/peps/ which links to (for example):

Labeled break and continue
http://www.python.org/dev/peps/pep-3136/

Asynchronous IO support
http://www.python.org/dev/peps/pep-3153/

Remove Backslash Continuation
http://www.python.org/dev/peps/pep-3125/

It's great that proposals are published publicly for the community to read. However, how is the community supposed to participate? The pages don't allow comments.

It strikes me as weird the Python developers would make proposals public then deliberately exclude the community from discussion. Have I missed something?

In particular, I'd like to read other people's comments on http://www.python.org/dev/peps/pep-0453/ and add my own.

For comparison, Ruby feature proposals are made as posts to its bug tracker. You can read everyone's comments below, and add your own (after making an account)

Refinements and nested methods https://bugs.ruby-lang.org/issues/4085

Frozen string syntax https://bugs.ruby-lang.org/issues/8579

Exception#cause to carry originating exception along with new one  https://bugs.ruby-lang.org/issues/8257

Nodejs feature requests are plain GitHub issues, which is probably the most inclusive. It's very easy to join GitHub and post a comment.

https://github.com/joyent/node/issues?labels=feature-request

答:
Python PEPs are discussed on the Python-Dev mailinglist, which anyone is free to join.

There is a Gmane gateway for web reading too.

I do advice you to study the Python developer's guide before wading into any discussions, though. The contained FAQ has some entries on communication that cover new feature discussions as well.

The Python community formed in the early 1990, and the community established itself around mailinglists (built on the now-venerable Mailman list manager) and newsgroups (comp.lang.python is gatewayed to the python@mail.python.org list), and the model has worked well enough for this community.

Title: How to comment on a PEP?


问:
Is it normal to get your software development products critiqued?
I am currently a software developer on coop that was in an interesting situation today. I cannot say too much, as the things I do are under NDA, but I make Grasshopper 3D (which is a Rhino plugin) components.

Our firm has under three software developers including me. We all specialize in different languages. This project I was working on, I was in charge of creating a piece of software that has a very broad general use. It's an extension from typical Grasshopper behavior.

With this said, the other developer I worked with has been in this industry for a good... decade or two. He is very knowledgeable towards the use of Grasshopper. His prior education involved great use of it, and his daily work involves the use of Grasshopper (though not explicitly what I am doing, which is creating C# components for it).

With that said, my final component went through a number of iterations. It seemed each iteration was better than the previous. An interesting point is, the other developer I worked with (I was essentially under his wing) manages to break my component every single time. I don't mean this in a malicious way.

By breaking, I meant, he was able to overflow particular lists. He was able to, after almost every iteration, find ways that my component could be improved on. Honestly, I really feel grateful for his suggestions and critique, because these were honestly things that either I overlooked, or did not know could happen.

My question is are three-fold:

Is it normal in software development practices/companies to have someone critique and improve your code? There was no code review. It was simply ways improving the tool through either UX improves or back-end improvements. And honestly, even though there was no code review, I learned so much from his suggestions which I always found success in implementing.

Are there any suggestions for a more "formal" testing procedure? I am relatively new to the software development world, and thus am interested in software dev testing procedures.

How can I improve on my way to "predict" issues?

At one side, I feel like there are issues that I cannot normally find out myself because everyone uses a piece of software differently. On another side, I feel it may be my oversight or incompetence that's causing this.

I'm reading up on this thread, and it seems in a way, we have a loose testing procedure, though it's all dependent on me to ask for critique.

答:
To improve your ability to predict problems:

Look for edge cases.  If your function operates on numbers, how does it handle 0?  Negative numbers?  Very large numbers?  If it operates on strings, can it handle an empty string?  A string with 10,000 characters?  What didn't you expect to happen when you wrote it?

Look for problems similar to others that have been found before.  You said he was able to overflow particular lists.  Be on the lookout for list overflow issues.

Look for patterns in the bugs.  Is there something in particular that you "always" miss?  Then be on the lookout for it.

Learn this Grasshopper software you're working on better.  Part of the senior developer's ability to see problems may be due to his familiarity with it.

Ask the senior developer.  As someone with a lot of experience, he probably has good advice about finding bugs and writing code in general, and about Grasshopper specifically.


问:
What programming language generates fewest hard-to-find bugs?
What language, in your opinion, allows the average programmer to output features with the least amount of hard-to-find bugs? This is of course, a very broad question, and I'm interested in very broad and general answers and wisdoms.

Personally I find that I spend very little time looking for strange bugs in Java and C# programs, while C++ code has its distinct set of recurring bugs, and Python/similar has its own set of common and silly bugs that would be detected by the compiler in other languages.

Also I find it hard to consider functional languages in this regard, because I've never seen a big and complex program written in entirely functional code. Your input please.

Edit: Completely arbitrary clarification of hard-to-find bug: Takes more than 15 minutes to reproduce, or more than 1 hour to find cause of and fix.

Forgive me if this is a duplicate, but I didn't find anything on this specific topic.

答:
Traditionally the hardest to find bugs are race-conditions in multi-threaded applications as they are

almost impossible to reproduce

can be very subtle

Hence you need languages that manage the parallism for you as much and unintrusively as possible.  These are not yet mainstream.  Java does some, but leave you with the hard part.

To my understanding, you need a functional language since the "no sideeffects" is the thing that in the first place makes the two bullet points go away.  I've seen that work is ongoing in transparently making Haskell an efficient multi-thread language, and I believe Fortress is designed from the ground up to be an efficient parallel language.

Edit:  In Java Executors handle even more of the hard parts.  You need to make the individual tasks conform to the Callable interface.


答:
A database would work well. If you are concerned about deploying the database, or licensing, you might want to look at something built into the operating system, such as MSMQ (called Message Queuing in the latest documentation), or the built in database, ESENT:

Managed ESENT stand alone library

As built into Windows 8.1: Blog entry with link to MSDN documentation

Title: Data sharing across processes

Body:
I have a C# .NET app that downloads a users Tweets using LinqToTwitter. This is for TV broadcast - the client wants to show Tweets on air. We have two other apps that need to access these tweets. One is a C++ app and one will use MS Script Host. These two apps don't run at the same time - it's one or the other.

My question is, of the many ways to share this data, which would you choose?

DataBase - Like MySql. This was my first choice. But then it seemed like overkill for the 10-20 tweets they would get per day.

Streaming - Like TCP or named pipes. This would involve some type of protocol. Like "Give me the last 10 tweets..."

Xml - Store the data in a file all programs can access. Simplest, but just doesn't feel right for some reason.

Memory Mapped IO - I think this would require a COM library for the scripts to be able to use it

There are others. Just curious what you would use. I am the only programmer in a small company and don't have others to bounce ideas off of.

Thanks.

ContentLicense: CC BY-SA 4.0


问:
What is the shortcoming of custom factory comparing to generic factory
I have a factory method as given below

```<code>public class AutomobileFactory
{
    Dictionary<string, ICar> internalFactory = new Dictionary<string, ICar>();
    public AutomobileFactory()
    {
        internalFactory.Add("fiat",new Fiat());
        internalFactory.Add("ford", new Ford());
    }

    public ICar Create(string carType)
    {
        return internalFactory[carType];
    }
}
</code>```

It is a very humble code. Now, I referred Factory pattern with generics. But I am not able to understand what extra this generic approach can offer.

QUESTION

What is the shortcoming of the above given factory when compared to the generic factory?

答:
Generic versions of algorithms generally provide type safety.  Your version accepts a string to specify the type.  That string could be anything, and the compiler cannot check it for you to see if it is correct.

If you specify a type in your version that you haven't registered, you won't know that until the program actually executes, where it will either cause an error, or do nothing.  In the generic version you linked, you don't even have to register the types; it will just use whatever type you provide it.

For what it's worth, the article you linked seems to describe a lot of ceremony for not much benefit.  "I know; I'll write the mother of all factories so that I never have to write another factory again."  Or, you could, y'now, just instantiate the type you need, and get on with it.

See Also

Abstract Astronaut Factories


问:
Best way to hide API key in source code
I need some ideas on how to protect a private API key in an application, specifically in a c# .NET application.

Firstly, I understand that it is theoretically impossible to hide anything in the source code, so I came up with another idea, but I'm not sure how plausible it is. Anyway, would it be possible to somehow communicate with a web server to verify the private key and then talk back to the application to confirm that it is a legitimate handshake?

I'm have two keys to work with: a public key (as the name suggests, it doesn't have to be treated with the same care as the private), and a private key, which needs to be kept secure from others.

Any ideas on how I could do this would be greatly appreciated.

答:
To summarize:

You have an API key issued to you by a vendor so you can use their API, and you have an obligation to prevent this key from being known by anyone else

You are making calls to that vendor's API (which require the API key) in your application code

You are deploying the application to systems where customers have access to the binaries and thus could potentially decompile/deobfuscate the code or intercept traffic

The best way to prevent compromise of this key is to keep control of it. This means it should never be deployed on a server where anyone besides you could read the binary, and never go over a communication link you don't control.

Ultimately, if the binaries are out of your control, everything in them is out of your control. Likewise, if someone can intercept traffic, they can capture the API key (potentially even if you're using SSL).

I can see two primary ways to accomplish this, both of which don't include your private API key in your deployed application:

Get a unique API key for each deployment

This would require some additional relationship with the vendor, where you can obtain keys or have your customers obtain keys.

This is actually quite common with, for example, products that use Google Maps API. The creator of the software has their own key they use while developing/running their copy, but they do not include it in the software, and instead, require you, as the user installing said software, to go to Google and obtain your own API key. The software merely has a configuration option to set the Google Maps API key to use.

In fact, many vendors that issue API keys contractually require you do things this way, so you may even be off on the wrong path anyway, and this may be the only solution you're allowed to use according to the vendor's Terms of Service and/or any legal contracts you may have with them.

Use a Proxy

Set up a proxy API, where your application calls your API (on your servers), and in turn, your API calls the vendor's API using the key.

You may need additional protection on your API, eg, something to ensure only your application is using it. This could be done by:

making the functionality so specific nothing but your app can use it

IP whitelists

Some existing licensing/authorization mechanism you already have for your servers

Your own API key system where you can issue keys to your customers

The thing to keep in mind here is that you may not be allowed to do this. Your vendor may have Terms of Service or legal contracts that prevent you from building an "aggregation service" or proxy, so you need to check with that.

Handling Misbehaviour

Even if your key doesn't get compromised, if one of your customers is doing something that causes the vendor to block your key, suddenly ALL your customers are disabled, and your only fix is to update everybody else.

Similarly, if you want to block one of your customers (eg, they stopped paying, have pirated the software, etc) then you can't do it without issuing an update to everybody else, and then disabling the key.

The logistics of this for anything beyond a handful of clients will quickly becoming untenable.

Whether you act as a proxy or have a unique key for each installation, you can handle any of these situations relatively easily (and with little to no impact to anyone else).

Trying to protect the key while it's embedded in your software is ultimately a futile effort. No matter what you do, any attacker that has access to the binaries, source, and/or communications channel and is determined enough to get at they key will be able to do so.

So don't embed it. "The only winning move is not to play."

Title: Best way to hide API key in source code


问:
Better use on the name of variables
I have a method that looks like this:

```<code>Public Function NormalizeStreetAddress(country As Namespace.Country,
                                       streetAddress As Namespace.StreetAddress) _
                                   As Namespace.StreetAddress

        Dim _streetAddress As New Namespace.StreetAddress = streetAddress

        If My.Settings.Streeteable = True Then
            Dim _AddressCustom As New Namespace.AddressCustom
            _streetAddress = _AddressCustom.NormalizeStreetAddress(country, streetAddress)
        End If
        Return _streetAddress
End Function
</code>```

I receive a streetAddress object, but inside the method I need to use another streetAddress object which I called _streetAddress — is that following the standard? A friend of mine told me that object names such as _yourNameObject are for global variables, but I can't find info about this and I want to make this method more readable.

答:
This is largely opinion, the only thing I care about when it comes to variable names is consistency. You want to have a flow from your project that is continued in all its facets.

I don't see why it would matter what it's named as long as it's not actively confusing it's function.

Furthermore, I'd really like to see people take on the modified-Hungarian notation.

Seriously, people too often name their variables like this

EXAMPLE OF BAD VARIABLE NAMES:

```<code>int statistic;
float statistics;
string stats;
</code>```

What's wrong with that? Well, it is telling me that it's a statistic, but do I really need to dig through the code to find all these definitions? It would be good practice to do so, but it's also nice for a programmer to think ahead about others reading his code.

Example of good variable names:

```<code>int nStatistic; //n prefix for ints
float fStatistics; //f prefix for floats
string sStats; //s for strings
</code>```

Of course, whatever you do the most important thing is CONSISTENCY. I don't want to get reading through your code, and half-way down you decided to start naming the variables after a different pattern.

Title: Better use on the name of variables

Body:
This is largely opinion, the only thing I care about when it comes to variable names is consistency. You want to have a flow from your project that is continued in all its facets.

I don't see why it would matter what it's named as long as it's not actively confusing it's function.

Furthermore, I'd really like to see people take on the modified-Hungarian notation.

Seriously, people too often name their variables like this

EXAMPLE OF BAD VARIABLE NAMES:

int statistic;
float statistics;
string stats;

What's wrong with that? Well, it is telling me that it's a statistic, but do I really need to dig through the code to find all these definitions? It would be good practice to do so, but it's also nice for a programmer to think ahead about others reading his code.

Example of good variable names:

int nStatistic; //n prefix for ints
float fStatistics; //f prefix for floats
string sStats; //s for strings

Of course, whatever you do the most important thing is CONSISTENCY. I don't want to get reading through your code, and half-way down you decided to start naming the variables after a different pattern.


答:
First you need to convince yourself. You have to exclude personal preferences from your reasoning. You may also try to change word Java to C++ (C#) in your list of arguments - most of them will stay valid but you should explain why C++ (C#) is not a good choice. If after all manipulations you find that the real reason is personal preference - you can set up your own start up or join competitors.

UPDATE:
This is marketing problem - you found number of benefits and disadvantages of switching to Java. You should choose those that are important for stakeholders. Better be honest because later you would be blamed if something goes wrong. That is why you should remove all subjective arguments. Personal preferences are important but they are not convincing. Think in terms of investment and return from it. It's not just features of programming languages - you should provide busines plan with details of how you would do PHP to Java transition.

Title: How to convince my company (operating in the financial sector) to switch from PHP to Java

Body:
My company is in the financial sector and it is using PHP as programming language. I am a PHP developer myself.

I am leading a big project started from almost scratch. I can see how PHP is not the best candidate for building robust platforms.

I want to convince my company to gradually switch to Java (which I have experience with).

I was trying to find as many supporting arguments as possible. Can you help with this?

So far I have found these:

Most of the competitors are using Java (anyway not PHP)

Most financial companies use Java rather than PHP

On average, Java developers are better prepared (on average!)

The compilation process catches a lot of problems before the software runs in production

Strong typing makes everything more robust as contracts between interfaces is well defined

Any other points I am missing?

Thanks!


问:
Is there anyone who has used Python/Ruby and PHP for a long time and still prefer PHP?
I am usually fascinated by articles defending PHP and the arguments being used. Quite often authors of these types of articles don't mention what experience they have with other languages. Personally I find it hard to imagine that somebody would know either Python or Ruby, and PHP at a high level and still prefer PHP.

So if anyone fits this description, I would be interested in hearing why you prefer PHP to either of these languages.

答:
From a language semantics point of view, I absolutely prefer Python. (Disclaimer: not yet using it for really long.)

However PHP is way more useful for building web apps. And I would blatantly describe it as suitable for that. The language itself suffers from serious misdesigns (and I just accidentially mention the new namespace syntax in brackets here), and many PHP programmers are prone to cargo cult programming. Yet, the vast amount of libraries tailored for webdevelopment makes it the better choice for what I'm doing.

As example (my favourite example), none of the Python HTTP libraries supports content encoding correctly out of the box. Whereas writing Gtk/GUI apps would is a joke in PHP in comparison to Python. So it really comes down to what sort of applications people are building. The language preference is probably just that.


问:
single table w/ extra columns vs multiple tables which duplicate schema
I am working on a project where at some point, I needed to make a decision on whether or not, in the database, I should have a single table with multiple columns that not every record uses, or multiple tables with duplicated schema.

I am creating a Sports information application which can handle multiple sports. We can handle NBA,NHL,MLB,NFL for example. Each sport has very similar concepts - Teams, Schedules, Injuries, Player info..

Our data source of course does not give us each piece of data in the same schema. Each sport has a different Schema to which we receive data from our vendor.

Because there wasn't enough time (client demands) to do upfront analysis of the data feeds to determine commonalities, I hedged my bet and took the  'safe bet' and made individual separate tables for each sport instead of one set of tables that all sports used.

The result is duplicated schema in several of the tables, and so duplicated interfaces to the database (e.g. stored procs) as well. I have something like NBA_Game, NFL_Game, NBA_Team,NFL_Team, etc..  each table might have a few properties that the other one doesn't, and several that are shared. it goes on for say 5-10 tables across 4 or 5 sports. I'm still not sure if this is entirely a bad thing - the alternative, having a single set of tables which had properties on it that not all sports would use, might have on its own been unwieldy as well.

Has anyone that has done this run into pitfalls of this kind of design and could share their experience here? Things that might help me to know now instead of learning the hard way down the road? Have you done it the other way, having one big table/set of tables, with columns that not every record would use? What pitfalls did you run into doing that?

Is there some alternative such as table inheritance that you have used in the past that worked better?

Thanks

答:
Ultimately, it comes down to use and architecture.

Architecture

Does the system handle "any sport"? Is the idea that you put on your architecture astronaut hat, and build a generic system that can handle any future type of sport that may not even exist today?

If so, obviously having dynamically-named tables is a huge pain, so it would make sense to have a schema that supports n sports, if required.

That said, I have a very strong bias against this approach: this is almost always more work and leads to poorer results. Making a separate UI, schema, etc, for each sport will ultimately lead to better user experience and easier to maintain code, even if it does mean some superficial amount of duplication (how to avoid/minimize this is a separate question).

How do you handle players that play multiple sports? Do they get two entries (eg, you treat as different people) or are you trying to do something specific with them?

Use

So let's assume you don't do sports dynamically (eg, if someone wants to add a new sport, it requires development effort to add it).

Is there ever a time where you're displaying players (or any other object you mentioned) from more than one sport at a time?

I could see this for a search function, where you could search by player or team name (regardless of sport), but beyond that I can't imagine many use cases.

If you never need to do this, then your approach is perfectly fine. You can stop reading here.

Alternative Schemas

Views

I'm a fan of KISS. In 15+ years of software development, I continue to fall back to the philosophy "build the simplest thing that works".

So my initial reaction, assuming a cross-sport search function is really the only use case, is to create views:

```<code>SELECT PlayerName, 'NFL' as [Sport], TeamName FROM NFL_Players JOIN NFL_Teams ...
UNION
SELECT PlayerName, 'NHL' as [Sport], TeamName FROM NHL_Players JOIN NHL_Teams ...
UNION ....
</code>```

Of course, if you add a new sport, you have to add to the view. It may also be useful to include other common information but really that's dependent on what needs to get shown.

I'd try to keep all the sport-specific stuff in the View definition, so the search code doesn't need to have much or any specific code (besides maybe knowing how to link to /nhl/players/player-name vs /nfl/... or however your app does that).

Table Inheritence

Table inheritance can work, but is pretty complex. I don't have a ton of experience with it, and in fact, I think every time I've been involved in evaluating it we ended up doing something simpler (like I'm suggesting here).

So personally, I have yet to find why this would be useful, but maybe there is a convincing use case (that I don't know of) that justifies the complexity (eg, Table inheritance solves the use case better than any other solution).

Separate tables for sport-specific attributes

You could do a single players table which has attributes common to all players of all sports, and then another set of tables like nhl_players_details that contains a playerId and columns with additional info on the player. If there are a ton of common attributes, or you have many uses of "all players from all sports" then this may make sense.

Key value pairs for sport-specific attributes

Completely alternative approach: have a players table (again, with common attributes like name) and then a player_data table that has PlayerId, Sport, Attribute, Value. The attribute names entered would be sport-specific.  This allows you to essentially add new attributes without modifying the schema (your code would still have to know to load/display them of course). The drawback is you lose some integrity: value would typically be a string field, so your app code would have to be resilient and handle potential failures converting the string value to a specific data type (like integer).

This concept can of course apply to Teams, Games, etc.

Body:
Ultimately, it comes down to use and architecture.

Architecture

Does the system handle "any sport"? Is the idea that you put on your architecture astronaut hat, and build a generic system that can handle any future type of sport that may not even exist today?

If so, obviously having dynamically-named tables is a huge pain, so it would make sense to have a schema that supports n sports, if required.

That said, I have a very strong bias against this approach: this is almost always more work and leads to poorer results. Making a separate UI, schema, etc, for each sport will ultimately lead to better user experience and easier to maintain code, even if it does mean some superficial amount of duplication (how to avoid/minimize this is a separate question).

How do you handle players that play multiple sports? Do they get two entries (eg, you treat as different people) or are you trying to do something specific with them?

Use

So let's assume you don't do sports dynamically (eg, if someone wants to add a new sport, it requires development effort to add it).

Is there ever a time where you're displaying players (or any other object you mentioned) from more than one sport at a time?

I could see this for a search function, where you could search by player or team name (regardless of sport), but beyond that I can't imagine many use cases.

If you never need to do this, then your approach is perfectly fine. You can stop reading here.

Alternative Schemas

Views

I'm a fan of KISS. In 15+ years of software development, I continue to fall back to the philosophy "build the simplest thing that works".

So my initial reaction, assuming a cross-sport search function is really the only use case, is to create views:

SELECT PlayerName, 'NFL' as [Sport], TeamName FROM NFL_Players JOIN NFL_Teams ...
UNION
SELECT PlayerName, 'NHL' as [Sport], TeamName FROM NHL_Players JOIN NHL_Teams ...
UNION ....

Of course, if you add a new sport, you have to add to the view. It may also be useful to include other common information but really that's dependent on what needs to get shown.

I'd try to keep all the sport-specific stuff in the View definition, so the search code doesn't need to have much or any specific code (besides maybe knowing how to link to /nhl/players/player-name vs /nfl/... or however your app does that).

Table Inheritence

Table inheritance can work, but is pretty complex. I don't have a ton of experience with it, and in fact, I think every time I've been involved in evaluating it we ended up doing something simpler (like I'm suggesting here).

So personally, I have yet to find why this would be useful, but maybe there is a convincing use case (that I don't know of) that justifies the complexity (eg, Table inheritance solves the use case better than any other solution).

Separate tables for sport-specific attributes

You could do a single players table which has attributes common to all players of all sports, and then another set of tables like nhl_players_details that contains a playerId and columns with additional info on the player. If there are a ton of common attributes, or you have many uses of "all players from all sports" then this may make sense.

Key value pairs for sport-specific attributes

Completely alternative approach: have a players table (again, with common attributes like name) and then a player_data table that has PlayerId, Sport, Attribute, Value. The attribute names entered would be sport-specific.  This allows you to essentially add new attributes without modifying the schema (your code would still have to know to load/display them of course). The drawback is you lose some integrity: value would typically be a string field, so your app code would have to be resilient and handle potential failures converting the string value to a specific data type (like integer).

This concept can of course apply to Teams, Games, etc.


答:
You're talking about Database normalization.  You may be relieved to learn that there is no such thing as a perfect data model, and that more normalization is not always better.  Normalization can impose costs in terms of clarity of the data model and database performance.  Therefore, the best model to select will depend on your usage requirements.

On the surface, your examples seem similar enough in concept (X_Game vs Y_Game and X_Team vs Y_Team) that the extra overhead of a few columns doesn't seem unreasonable.  That said, if each sport is going to add several dozen extra columns to the table, it would indeed be unwieldy.

In that case, you may wish to consider a hybrid model, where the common data is kept in a central table, but sport-specific data is kept in a linked data structure.  Something like:

```<code>table Game {
    gameId int,
    teamId1 int fk,
    teamId2 int fk
}

table HockeyGame {
    gameId int fk,
    penaltyMinutes int
}

table BasketballGame {
    gameId int fk,
    freeThrows int
}
</code>```

Title: single table w/ extra columns vs multiple tables which duplicate schema

Body:
I am working on a project where at some point, I needed to make a decision on whether or not, in the database, I should have a single table with multiple columns that not every record uses, or multiple tables with duplicated schema.

I am creating a Sports information application which can handle multiple sports. We can handle NBA,NHL,MLB,NFL for example. Each sport has very similar concepts - Teams, Schedules, Injuries, Player info..

Our data source of course does not give us each piece of data in the same schema. Each sport has a different Schema to which we receive data from our vendor.

Because there wasn't enough time (client demands) to do upfront analysis of the data feeds to determine commonalities, I hedged my bet and took the  'safe bet' and made individual separate tables for each sport instead of one set of tables that all sports used.

The result is duplicated schema in several of the tables, and so duplicated interfaces to the database (e.g. stored procs) as well. I have something like NBA_Game, NFL_Game, NBA_Team,NFL_Team, etc..  each table might have a few properties that the other one doesn't, and several that are shared. it goes on for say 5-10 tables across 4 or 5 sports. I'm still not sure if this is entirely a bad thing - the alternative, having a single set of tables which had properties on it that not all sports would use, might have on its own been unwieldy as well.

Has anyone that has done this run into pitfalls of this kind of design and could share their experience here? Things that might help me to know now instead of learning the hard way down the road? Have you done it the other way, having one big table/set of tables, with columns that not every record would use? What pitfalls did you run into doing that?

Is there some alternative such as table inheritance that you have used in the past that worked better?

Thanks

Body:
You're talking about Database normalization.  You may be relieved to learn that there is no such thing as a perfect data model, and that more normalization is not always better.  Normalization can impose costs in terms of clarity of the data model and database performance.  Therefore, the best model to select will depend on your usage requirements.

On the surface, your examples seem similar enough in concept (X_Game vs Y_Game and X_Team vs Y_Team) that the extra overhead of a few columns doesn't seem unreasonable.  That said, if each sport is going to add several dozen extra columns to the table, it would indeed be unwieldy.

In that case, you may wish to consider a hybrid model, where the common data is kept in a central table, but sport-specific data is kept in a linked data structure.  Something like:

table Game {
    gameId int,
    teamId1 int fk,
    teamId2 int fk
}

table HockeyGame {
    gameId int fk,
    penaltyMinutes int
}

table BasketballGame {
    gameId int fk,
    freeThrows int
}


问:
How to keep a big and complex software product maintainable over the years?
I have been working as a software developer for many years now. It has been my experience that projects get more complex and unmaintainable as more developers get involved in the development of the product.

It seems that software at a certain stage of development has the tendency to get "hackier" and "hackier" especially when none of the team members that defined the architecture work at the company any more.

I find it frustrating that a developer who has to change something has a hard time getting the big picture of the architecture. Therefore, there is a tendency to fix problems or make changes in a way that works against the original architecture. The result is code that gets more and more complex and even harder to understand.

Is there any helpful advice on how to keep source code really maintainable over the years?

答:
I just want to place a non-technical issue and a (maybe) pragmatic approach.

If your manager doesn't care about technical quality (manageable code, simple architecture, reliable infrastructure, and so on), it becomes hard to improve the project. In this case it is necessary to educate said manager and convince to "invest" efforts into maintainability and addressing technical debt.

If you dream with code quality found in those books you also need a boss that is concerned about this.

Or if you just want to tame a "Frankenstein project" these are my tips:

Organize and simplify

Shorten functions

Prioritize readability over efficiency (when acceptable of course, and some efficiency gains are too miserable to be kept)

In my experience, programming is entropic rather than emergent (at least in the popular imperative-structured paradigm). When people write code to "just work" the tendency is to lose its organization. Now organizing code requires time, sometimes much more than making it just work.

Beyond feature implementation and bug fixes, take your time for code clean-up.


问:
How to measure that a team is doing Test Driven Development
My team is considering a department goal of doing Test Driven Development next (fiscal) year.

TDD sounds good and my manager is on board.  The only problem is measurement.

Our company rules require that department goals be measurable.

Is there any (sane) way to measure if a team is doing TDD?

Note: We had a goal for writing unit tests already, so a code coverage goal will not work. We write the unit tests but we do it after the fact, not before.

Is there a way to measure that TDD is being done?

(NOTE: We use Visual Studio 2013 and TFS in case it matters)

答:
Since you are going to measure unit test separately (code coverage, decision coverage, etc.), let me add a couple more tweaks to the process.

All check-ins must go through code review.

Code reviews should be trackable, i.e, should not be an over-the-shoulder review or like pair programming. You should be able to retrieve the code review comments, iterations and such details at a later time. TFS lets you do this.

When signing-off on a code review, the sign-off comments can a predetermined piece of text that tells TDD was followed. e.g.: "TDD FOLLOWED".
This way you know which check-ins followed TDD, and at the end of the year, you can invent/calculate more metrics like percentage of LOC with TDD.

HOWEVER,
I would not judge the value/effectiveness of TDD purely based on these metrics. I think the industry has evolved enough that the majority understands the value of TDD.


答:
Since you want to switch from a test-second development to test driven design, you can best measure that by looking for proof that the tests were written before program was changed.

Teach your team to commit their failing tests first, so they can be measured, and then write the code to pass the test.  You may need to either manually inspect the repository history, or write a custom tool to do such for you.

(You'll wind up treating it like a check-off for each project, so if check-in-first is needed you could always just have it be part of the reported information, and trust the programmers / project manager.  i.e., "were the tests written before the code?")

Title: How to measure that a team is doing Test Driven Development

Body:
My team is considering a department goal of doing Test Driven Development next (fiscal) year.

TDD sounds good and my manager is on board.  The only problem is measurement.

Our company rules require that department goals be measurable.

Is there any (sane) way to measure if a team is doing TDD?

Note: We had a goal for writing unit tests already, so a code coverage goal will not work. We write the unit tests but we do it after the fact, not before.

Is there a way to measure that TDD is being done?

(NOTE: We use Visual Studio 2013 and TFS in case it matters)


答:
In my opinion Haskell helps you avoid some common sources of errors:

it's purely functional: functions cannot have (unintentional) side-effects and this makes multicore programming easier and less error-prone

it is strongly typed: you can not e.g. accidentally mix bool, char, int and float values

it's statically typed: many programming errors are caught at compile time

null is not part of value type definitions: by this you avoid the billion dollar mistake

there are a lot of ready-made higher-order functions which you can reuse instead of writing your own, possibly faulty, implementations

it has a garbage collector: memory errors are almost eliminated (except for "space leaks" due to its lazy evaluation strategy)

Title: What programming language generates fewest hard-to-find bugs?

Body:
What language, in your opinion, allows the average programmer to output features with the least amount of hard-to-find bugs? This is of course, a very broad question, and I'm interested in very broad and general answers and wisdoms.

Personally I find that I spend very little time looking for strange bugs in Java and C# programs, while C++ code has its distinct set of recurring bugs, and Python/similar has its own set of common and silly bugs that would be detected by the compiler in other languages.

Also I find it hard to consider functional languages in this regard, because I've never seen a big and complex program written in entirely functional code. Your input please.

Edit: Completely arbitrary clarification of hard-to-find bug: Takes more than 15 minutes to reproduce, or more than 1 hour to find cause of and fix.

Forgive me if this is a duplicate, but I didn't find anything on this specific topic.


答:
It's a stupid request proving the idiocy of many managers/accountants/cto etc who don't understand that software development is a kinda unique process in itself (so no, it doesn't matter that Toyota uses a specific process, you're not building cars)

Anyway, the only things that matters to be measured are RESULTS. Do you deliver higher quality software? Do you deliver it faster? Does the current method of developing (TDD or not) yields at least equal or better results with lower cost (time and money)?

It simply boils down to cost and results. You want better results with the same or lower costs or at least the same result with less costs. It's the ratio between the final result and the bottom line that matters.

Your team has to show that the TDD approach improves productivity (maintainability -> easier changes -> faster results -> less time required) and/or product quality (less bugs -> less time spent debugging -> reliable product | less people pissed off -> happier stakeholders).

I know that it takes more time to think and write tests but software devel doesn't stop when the first release is out. And even beancounters need to (forcefuly) understand that software development has its quirks, it's not an exact science and if they can do a better job, let them do it. You don't build houses how you build cars or airplanes, a cupcake business or cargo services. Why should you build software this way?

Edit: It might be news for some people but a lot of things simply CAN'T be measured reliably. You can pretend you're measuring it and come up with bullshit metrics but that's all. Marketing is one of the domains greatly affected by this plague.


答:
If a team truly wants to do TDD, they you just need to do some minimum tracking to satisfy the rule. Check in your tests first and then check in the code and after comparing the initial dates, you have some semblance of proof.

To have another layer of approval, make this a part of the code review where someone can verify these are meaningful tests. It's not that hard to write a test that fails without even referencing the code it is suppose to test. It's just not in the spirit of what you're trying to do.

During some semblance of pair-programming, everyone can "sign-off" that TDD was going on.

You may not feel the need to take things this far, but you have to be prepared to serve the powers that be.

Personally, I think TDD should be used and evaluated to solve some larger problem. If releasing fewer bugs on your next upgrade is a concern because it lowers customer satisfaction, you can do a survey and ask customers: On a scale of 1-10 (10 being most painful) how much more painful was our latest upgrade (built on TDD) compared to the previous one? It's good enough for pain medication drug trials, is should be good enough for software.


答:
TDD is not something a team commits to doing. It's only a means to an end. Objectives can be writing more maintainable code, decreasing the number of defects, delivering faster, or improving test coverage, but not "doing TDD".

TDD is not a silver bullet. Measuring "if the team is doing TDD" does not guarantee success like making sure they drink their magic potion every day. Besides, demanding that the team produce indicators showing that they are practising a technique that the team itself asked for in the first place is a bit... absurd. Or command-and-control fundamentalistic.

Managers and decision makers shouldn't demand control over how code is produced at a micro level (a typical red/green/refactor cycle is the order of a few minutes). Since when do bean counters care about how the beans were harvested ?


问:
Why is PHP's method of comparing different types bad?
I'm working on designing a new programming language and trying to decide how I will do variable comparisons.  Along with many different types of languages, I've used PHP for years and personally had zero bugs related to its comparison operations other than situations where 0 = false. Despite this, I've heard a lot of negativity towards its method of comparing types.

For example, in PHP:

```<code> 2  <  100      # True
"2" < "100"     # True
"2" <  100      # True
</code>```

In Python, string comparison goes like this:

```<code> 2  <  100      # True
"2" < "100"     # False
"2" <  100      # False
</code>```

I don't see any value in Python's implementation (how often do you really need to see which of two strings is lexicographically greater?), and I see almost no risk in PHP's method and a lot of value.  I know people claim it can create errors, but I don't see how.  Is there ever really going to be a situation where you are testing if (100 = "100") and you don't want the string to be treated as a number?  And if you really did, you could use === (which I've also heard people complain about but without any substantial reason).

So, my question is, not counting some of PHP's weird conversion and comparison rules dealing with 0's and nulls and strings mixed with characters and numbers, are there any substantial reasons that comparing ints and strings like this is bad, and are there any real reasons having a === operator is bad?

答:
One of the more complicated projects that I have undertaken was embedding the PHP library into Google's v8 in order to allow javascript to create and otherwise access PHP objects directly, without a form of bridge, and without any form of interpretation (outside of javascirpt that is). This required access to the zend tables of a PHP object, and all properties and methods of a PHP object were accessible directly in this way from javascript.

From this experience I also got a taste of the challenge of handling PHP data types within C (the lower level structures that is) in a way that is useful in a more dynamic, abstract level above. This was within javascript at this point, not PHP, but was still the value of the true, internal representation of a PHP object.

There are many challenges in these situations, including when it comes to comparisons. In the end though, at least in my opinion, it was more important to respect and adhere to the dynamic nature of PHP. This was a matter of function, not a matter of logical interpretation or intuitive perception etc.

The discussion of whether "0" == true needs to be based on what "0" really is. As a numerical type, 0 is the binary value for false. However, as a string, "0" is valid, non null, and non empty. So in the end, it's a matter of whether you think "0" should be seen as a string, a numerical type, or as third option, whether you should try to handle it as both in different situations. Each view has valid, empirical reasons for why one way is more or less useful than the other, yet in the end there is no real or "factual" answer to this, and will always come down to how you, I, and the other guy values "0".

Edit: Also keep in mind that comparisons are one of the most basic operation of a language. While it is possible to make comparisons more "intelligent", this requires more logic within the actual comparison operation itself. With the frequency that comparisons are used, this can cause a negative effect on performance, especially with string type. So even this side of the discussion would likely become a matter of preference and/or priority.

Edit 2: To answer the root of your question more fully, dynamic types need either a form of dynamic comparison or a larger variety of comparison operators.

'==' alone will only suffice if the operation '==' performs is smart enough to know how to handle each type under all use scenarios, specifically if the left operand and the right operand are different types. The downside to the more dynamic operation is a likely performance hit. The smarter the operation is, the more noticeable the cost is likely to be.

more forms of operators (such as the addition of '===') may seem foreign to people new to your language and will likely receive criticism.

third option would be forcing appropriate comparisons for each type at all times, but this will sacrifice dynamism and will go against the goals of a dynamic language (at least in my opinion).

PHP tries to handle comparisons dynamically, but includes '===' to allow strict comparisons as well. The only other option would be to make the default comparisons 'smarter' which will cost performance.

While it's true that the additional operators add complication and dynamic comparisons leave room for error, a junior high student should be able to grasp the concept (and many do). '==' means that left and right operands can be different types, but can lead to different results in specific, defined situations. '===' means that left and right must be the same types. As for practice, it's better to use '===' when checking the return value of a function, as well as is_string, is_int, is_bool, etc. This is the downside of a dynamic language, and not doing so will likely lead to unexpected comparison results at times.

But in the end, a 'good' comparison will always follow a defined, documented behavior. A language can use Klingon for comparisons as long as the results are well defined.


问:
C API in C++ with RAII, two alternatives to implement error handling (Exceptions)
I have an API written in C, which produces a result by returning a pointer to allocated memory.

For using it with C++ (C++11) I've wrapped the function calls in objects, which keep the result in a std::shared_ptr. So far so good.

However, the C library features two functions for every operation. One produces possibly an error, the other never. Let's call them

some_pod * do_it_with_error(Parameter ..., Error **)

and

some_pod * do_it_without_error(Parameter ...)

I can pass in the address of an Error * pointer to the first function and if there's an error it won't be NULL afterwards.

For solving this I thought of two different implementations.

First, I could SFINAE for choosing between the with_error and without_error functions, like so:

```<code>template<typename NoThrow = void>
struct do_it {
  public:
    void operator()(...)
    {
      Error * error = NULL;
      m_result = std::shared_ptr<some_pod>(do_it_with_error(..., &error));
      if (error) {
        throw(MyExceptionWithError(error));
      }
    }
  private:
    std::shared_ptr<some_pod> m_result;
};

template<>
class do_it<std::nothrow_t> {
  public:
    void operator()(...) noexcept
    {
      if (! m_result) {
        m_result = std::shared_ptr<some_pod>(do_it_without_error(...));
      }
    }
  private:
    std::shared_ptr<some_pod> m_result;
};
</code>```

Usage:

```<code>do_it<> di_error;
try {
  di_error(...); // might throw
} catch (...) {}

do_it<std::nothrow_t> di_no_error;
di_no_error(...); // won't throw for sure
</code>```

However, since the result is wrapped in a std::shared_ptr there will also be
a get() method:

```<code>const std::shared_ptr<some_pod> & get(void) { return m_result; }
</code>```

For error checking I could just implement a another method check.

The default implementation would now look like this:

```<code>struct do_it {
  public:
    // will never throw
    const std::shared_ptr<some_pod> &
    get(void) noexcept
    {
      if (! m_result) {
        m_result = std::shared_ptr<some_pod>(do_it_without_error(...));
      }
      return m_result;
    }

    // might throw
    do_it &
    check(void)
    {
      if (! m_result) {
        Error * error = NULL;
        m_result = std::shared_ptr<some_pod>(do_it_with_error(..., &error));
        if (error) {
          throw ...;
        }
      }
      return *this;
    }

  private:
    std::shared_ptr<some_pod> m_result;
};
</code>```

Usage:

```<code>do_it di_error;
try {
  auto result = di_error.check().get();
} catch (...) {}
do_it di_no_error;
di_no_error.get();
</code>```

So, both implementations seem to be equally good (or bad) to me.

How could I decide which one to use.

What are the Pros and Cons?

答:
For each operation, you have three distinct subjects to take care about, say, workload, result and error handling. Let's see them all in isolation:

Workload: shouldn't be duplicated. Always call the C function possibly producing error information, as it's the most complete of each pair.

Result: PODs can be kept as they are in the C API and hold/retrieved through shared_ptr objects, but this is only one of many possible options -if, certainly, a quite straightforward one. Maybe some of this PODs are worth to be wrapped into, or converted to, copy-constructible/move-constructible classes and directly returned from the operator() call.

Error handling: the way your C++ function objects do (or do not) communicate error-related information is seconday and orthogonal to the main workload. Ideally, you want to be able to change that error handling mechanism depending on the context, without affecting the workload itself. So view it as a dependency that you inject on the function object at your will, either at construction time or at calling time. This way, you can add additional error handling mechanisms in the future, other than current do-nothing and exception-throwing ones (what if you do end wanting to notify errors thorugh console messages, for example?).

I'll end providing a simple implementation that could serve as example:

```<code>class DoSomeStuff
{
public:
    class Result
    {
    public:
        Result() : _result() {}
        Result(const Result &rhs) : _result(rhs) {}
       ~Result() {}

        Result &operator=(const Result &rhs)
        {
            if(&rhs != this)
                _result = rhs._result;

            return *this;
        }

        int GetSomeData() const { return _result->_some_int_value; }

    private:
        shared_ptr<some_pod> _result;
    };

    struct IErrorHandler
    {
        virtual void NotifyError(Error &) = 0;
    };

    Result operator()(/*params*/, IErrorHandler &errorHandler)
    {
        Error *error = { nullptr };

        shared_ptr<some_pod_type> result = { do_some_stuff_with_error(/*params*/, &error) };

        if(error != nullptr)
            errorHandler.NotifyError(*error);

        return Result(result);
    }
};
</code>```

Note that Result and IErrorHandler don't have to be included inside the function class; I've done this way because they're both dependencies, but can be extracted in order to avoid duplication among several function classes.

Body:
For each operation, you have three distinct subjects to take care about, say, workload, result and error handling. Let's see them all in isolation:

Workload: shouldn't be duplicated. Always call the C function possibly producing error information, as it's the most complete of each pair.

Result: PODs can be kept as they are in the C API and hold/retrieved through shared_ptr objects, but this is only one of many possible options -if, certainly, a quite straightforward one. Maybe some of this PODs are worth to be wrapped into, or converted to, copy-constructible/move-constructible classes and directly returned from the operator() call.

Error handling: the way your C++ function objects do (or do not) communicate error-related information is seconday and orthogonal to the main workload. Ideally, you want to be able to change that error handling mechanism depending on the context, without affecting the workload itself. So view it as a dependency that you inject on the function object at your will, either at construction time or at calling time. This way, you can add additional error handling mechanisms in the future, other than current do-nothing and exception-throwing ones (what if you do end wanting to notify errors thorugh console messages, for example?).

I'll end providing a simple implementation that could serve as example:

class DoSomeStuff
{
public:
    class Result
    {
    public:
        Result() : _result() {}
        Result(const Result &rhs) : _result(rhs) {}
       ~Result() {}

        Result &operator=(const Result &rhs)
        {
            if(&rhs != this)
                _result = rhs._result;

            return *this;
        }

        int GetSomeData() const { return _result->_some_int_value; }

    private:
        shared_ptr<some_pod> _result;
    };

    struct IErrorHandler
    {
        virtual void NotifyError(Error &) = 0;
    };

    Result operator()(/*params*/, IErrorHandler &errorHandler)
    {
        Error *error = { nullptr };

        shared_ptr<some_pod_type> result = { do_some_stuff_with_error(/*params*/, &error) };

        if(error != nullptr)
            errorHandler.NotifyError(*error);

        return Result(result);
    }
};

Note that Result and IErrorHandler don't have to be included inside the function class; I've done this way because they're both dependencies, but can be extracted in order to avoid duplication among several function classes.


问:
Sharing programming fees with a fellow software developer
My question relates to how I should share the fees paid by clients to me and a fellow programmer, both of whom are freelancers.

I've thought of a few options, but I'm in a dilemma as to which one would be the most motivating for both of us.

1) The first option I've thought is a fifty-fifty share. However, more brainwork is going to be done by my colleague, while initially at least, I will be handling the communication with customers.

2) The second option is a 60-40 share, where the colleague exerting more efforts gets a bigger share. This is the option I feel most inclined to adopt, but I'm not sure how it's going to feel in the long run.

3) The third option is calculating each one's contribution in terms of the number of hours spent, and sharing the revenue accordingly.

It will be wonderful to hear everybody's thoughts on this!

答:
Sharing ?  Seems like the wrong choice of word to me, you are not sharing. You are working together for a fixed fee.

To be honest I can't understand how you have got this far down the line without agreeing the split.

Why have you agreed to do some work without knowing how much money you will be receiving.

I find this question really weird.


问:
I know what I want to do, but I have a hard time coding it?
After doing some interviews, I've realized that I usually know what I want to do to solve a problem, but I often get my logic complicated (and introduce a lot of bugs) when I'm actually coding.

For example, when I tried to code up insertion into a sorted singly linked list, this is what I knew I had to do:

I had to check for the case where the list is currently null

I had to check if the element I want to insert is less than the current head

To insert between nodes, we had to link one node to the new node, and the new node's next to the one that is supposed to be after.

I had trouble inserting between nodes because I was actually supposed to check the NEXT node's data and not the node which I had my pointer pointing to (so I could set current's next to the new node). I also struggled on this problem (note that this was coded on white board) because I was pressured under time and I think I made it more complicated in my mind that I should have. When I went back to this problem after the interview, it turns out the solution isn't complicated at all (as it shouldn't be). However, I just tend to complicate things and confuse myself.

Would anyone have any suggestions on how I could improve this vulnerability of mine?

答:
Talk to the interviewers.  Explain what you're trying to do.  Ask questions.  Say "does this look right?"

Interview questions about coding are only a rough estimate of ability.  Most people doing interviews have been there before, and understand that coding on a whiteboard is more difficult than coding at a computer.  If you share your thought process, and solicit frequent feedback from the interviewers, you redirect focus to your collaborative ability, rather than the mistakes that we all make when we're nervous.

Given the choice between somebody who stands up and does the problem without looking at me, or somebody who is a little unsure of themselves but engages me during problem solving, I'll almost always favor the latter.


答:
Write more code, and continue to refine and improve it, with the help of outside sources of information like books and blogs.  That's the only way I know of how to do it.

Put your emphasis on writing more code, not reading more blogs.

If you're good a reading code, read the code of others, to see how they solve problems.  There are plenty of open-source projects that you can look at. Compare their process to the process you use to write code, and get better at doing it.

But I can't stress enough that the best way to write better code is to simply write more of it, and work on ways to make it better code.

For what it's worth, I'm not sure that interviewers are the best source of feedback on whether or not you're writing good code.  You can get critiques from other peers, or post your working code at http://codereview.stackexchange.com (I've seen very good advice there).

Title: I know what I want to do, but I have a hard time coding it?

Body:
After doing some interviews, I've realized that I usually know what I want to do to solve a problem, but I often get my logic complicated (and introduce a lot of bugs) when I'm actually coding.

For example, when I tried to code up insertion into a sorted singly linked list, this is what I knew I had to do:

I had to check for the case where the list is currently null

I had to check if the element I want to insert is less than the current head

To insert between nodes, we had to link one node to the new node, and the new node's next to the one that is supposed to be after.

I had trouble inserting between nodes because I was actually supposed to check the NEXT node's data and not the node which I had my pointer pointing to (so I could set current's next to the new node). I also struggled on this problem (note that this was coded on white board) because I was pressured under time and I think I made it more complicated in my mind that I should have. When I went back to this problem after the interview, it turns out the solution isn't complicated at all (as it shouldn't be). However, I just tend to complicate things and confuse myself.

Would anyone have any suggestions on how I could improve this vulnerability of mine?


问:
Choosing the right Design Pattern
I've always recognized the importance of utilizing design patterns. I'm curious as to how other developers go about choosing the most appropriate one. Do you use a series of characteristics (like a flowchart) to help you decide?

For example:

If objects are related, but we do not want to specify concrete class, consider Abstract

When instantiation is left to derived classes, consider Factory

Need to access elements of an aggregate object sequentially, try Iterator

or something similar?

答:
I ask myself:

What problem am I trying to solve?

Which software design pattern (if any) most closely solves the same problem, or provides a logical path towards solving my problem?

Do I need the additional abstraction (and complexity) that the pattern provides, or is it over-engineering for my particular problem?  Can the problem be solved in a simpler, more efficient way without the pattern?

The process of choosing a software pattern is not unlike the process of choosing a data structure, except that in choosing a data structure, you would evaluate the performance and memory characteristics of your problem, and choose the data structure that most closely fits those characteristics.

Title: Choosing the right Design Pattern


答:
You need to study algorithms.  Lots of people know how to stamp out some code. The interviewers are looking for a person who has an understanding about what is being written, and to do that, you need to have a deep appreciation for what the code is doing.

I recommend that you take a course in algorithms. Best of all, there's one free that has just started on Coursera, and it's taught by Robert Sedgewick, the co-author of one of the best books on algorithms ever written. The course just started this week. You can still sign up, I believe.


答: Perhaps surveying the number of tools available for static and dynamic code analysis for every programming language could give an idea.  The more tools for a language, it is more likely the language is either very popular among users or very popular in generating hard to find bugs.  But I am unable to get Google point me to any study made on this subject.  It should also be noted that some languages such as C can be used to work around the underlying hardware bugs as well as work around the wear and tear of the hardware as it ages.</p>


答:
A key misconception in today's coding world is that patterns are building blocks.  You take an AbstractFactory here and a Flyweight there and maybe a Singleton over there and connect them together with XML and presto, you've got a working application.

They're not.

Hmm, that wasn't big enough.

Patterns are not building blocks

That's better.

A pattern is something that you use when you find that you've got a problem - you need some flexibility that the pattern provides, or that you've stumbled across when you are making a little language in the config file and you say "wait a moment, stop, this is its own interpreter that I'm writing — this is a known and solved problem, use an Interpreter pattern."

But note there, that it's something that you discover in your code, not something you start out with. The creators of Java didn't say "Oh, we'll put a Flyweight in the Integer" at the start, but rather realized a performance issue that could be solved by a flyweight.

And thus, there's no "flow chart" that you use to find the right pattern. The pattern is a solution to a specific type of problem that has been encountered again and again and the key parts of it distilled into a Pattern.

Starting out with the Pattern is like having a solution and looking for a problem. This is a bad thing: it leads to over engineering and ultimately inflexibility in design.

As you are writing code, when you realize that you're writing a Factory, you can say "ah ha! that's a factory I'm about to write" and use your knowledge of knowing the Factory pattern to rapidly write the next bit of code without trying to rediscover the Factory pattern. But you don't start out with "I've got a class here, I'll write a factory for it so that it can be flexible" — because it won't.

Here's an excerpt from an interview with Erich Gamma (of Gamma, Helm, Johnson, and Vissides): How to Use Design Patterns:

Trying to use all the patterns is a bad thing, because you will end up with synthetic designs—speculative designs that have flexibility that no one needs. These days software is too complex. We can't afford to speculate what else it should do. We need to really focus on what it needs. That's why I like refactoring to patterns. People should learn that when they have a particular kind of problem or code smell, as people call it these days, they can go to their patterns toolbox to find a solution.

The best help for the "what to use, when" is likely the Wikipedia page for software design pattern - the "Classification and list" section describes the category each pattern is in and what it does. There's no flowchart; the description there is probably the best you'll find as a short snippet for "what to use, when."

Note that you'll find different patterns in different areas of programming. Web design has its own set of patterns while JEE (not web design) has another set of patterns. The patterns for financial programming are completely different to those for stand alone application UI design.

So any attempt to list them all is inherently incomplete. You find one, figure out how to use it and then it eventually becomes second nature and you don't need to think about how or when to use it ever again (until someone asks you to explain it).

Title: Choosing the right Design Pattern

Body:
I've always recognized the importance of utilizing design patterns. I'm curious as to how other developers go about choosing the most appropriate one. Do you use a series of characteristics (like a flowchart) to help you decide?

For example:

If objects are related, but we do not want to specify concrete class, consider Abstract

When instantiation is left to derived classes, consider Factory

Need to access elements of an aggregate object sequentially, try Iterator

or something similar?


问:
How to split up ASP MVC Project using Code-First Entity Framework
For an academic exercise, we have been tasked with creating a small website. We have already gathered the requirements and fleshed out the business domain to see the classes we are supposed to support. It is to be on Microsoft stack, so I decided to use ASP MVC with code first Entity Framework. I am now looking for the best way to split up a 6 man team in order to best tackle the project.

TLDR: What are some effective ways of splitting up an ASP MVC project so that multiple developers can work on it concurrently?

I have researched where projects have been split across the tiers, i.e. database, business, views, and such, but I don't exactly know how to instruct them to go about designing a view for which there is no controller.

Is splitting it up between the different business models used a decent strategy? I have read that this has led to an application that didn't mesh well, due to the different aesthetics.

答:
The way our small team approached the problem was to cooperatively develop the domain layer and database logic, and then proceeded to split the work up by Area, so I worked on settings while another person worked on our core CRUD pages. Once that was done we picked another area and off we go again. There are several problems with this approach:

Our initial development work produced views that didn't look at all similar. We had to go back and redo the views. This could be avoided by having specifications and design work done thoroughly beforehand (we are doing this now, and it makes things much better).

We both developed library methods to do the same thing independently, and refactoring was needed to remove the duplicate (this was sometimes easy, but often difficult as we wrote them quite differently).

If I had my time again I would do the following:

Write your business logic together and decide on URL endpoints (controllers and actions and their arguments). If you are using separate business entities and MVC models, design the MVC models too.

Now one person can write views based on the MVC models and for the URLs decided upon, whilst another person would write the controllers/actions necessary.

That's not perfect (can't really test the views until the controllers are written) but it does minimize interaction so more work can be done faster.

Another option (although not true MVC) is to write the application as a single-page application, and have one group write everything behind the REST API, and have another group write the JavaScript on the front-end.