问:
Agile tools, can't find any that suits my case or I'm wrong somewhere?
We have huge modules in our project, each module has a bunch of user-stories, each story contains developer tasks. Actually, we take tasks from multiple modules, since we have some core module features and optional.

Each developer task I should review and merge into master.

So, basically it is just project-task-subtask, right? But it doesn't fit our case.

Each project has it's own board - we need one board, actually

Sub-tasks cannot have status beside completed/not. So, sub-task is completed, but not reviewed, but PM sees it like this part is done and ready to be tested and touched. Waiting for whole user story to be completed isn't acceptable every time.

I know it is not a resource to find apps, but I dunno where I can ask this questions.

答:
It sounds like you're thinking about what a project is differently to how most of this kind of software does. As a result, you're also breaking down other pieces differently.

In a tool like Jira:

A project is an entire piece of software - a product. So in your case, you have one project.

Modules within a piece of software are called components. In your case, each of the modules would line up 1-to-1 with a component.

Stories (developer tasks) belong to a project, and can be associated with 1 or more components. Each story has it's own state (open, in progress, done, closed; these are configurable in Jira), and follows a predefined workflow. In your case, a task and a story are equatable.

A story can be broken down in to sub-tasks. Each sub-task (like a story) has it's own state, following a predefined workflow.

A backlog is a collection of stories which need working on. In Jira, this is defined by a filter over all stories in the system.

A scrum board is a team's view on a product backlog, showing which stories from that backlog are being worked on in the current sprint. The scrum board has a swimlane (row) for each story, and a column for each state, with stories and subtasks appearing in the appropriate columns.

A large internal project within the product is an epic. An epic can have any number of stories in it.

If you were to use a tool like Jira, you would have a single project, with a scrum board and backlog per team. Stories would be associated with the modules, and work on them would follow the normal workflow.

You could easily divide your teams and backlogs along module boundaries by using an appropriate filter when creating a backlog; eg "only those stories associated with this module"


问:
Programming in Linux (C++)
So I don't know If this is the right place to ask this. I am new to programming, I am not very in to it (I know classes,arrays,functions..etc(Basic Things)).

I was programming with Visual Studio 2013 , so I decided to change my OS to Linux.

First things I notice is that the code is not exactly the same also the including headers. For example: I can't use conio.h and with it I can't end my main function with _getch(); function.

My question is: What's the difference between windows and linux programming? Can someone recommend me where can I look/read for this changes(whats the different and what can I use with linux).

Any help will be appreciated! Thank you in advance !! :)

答:
The reason you find differences is that the C you are using is not GNU C or ANSI C. It's better if you learn the language well instead of trying to find the differences.

I'd suggest referring

C: The C Programming Language, 2nd Edition by Brian W. Kernighan  and Dennis M. Ritchie

C++: The C++ Programming Language (3rd Edition) by Bjarne Stroustrup

ContentLicense: CC BY-SA 3.0

Title: Programming in Linux (C++)


问:
The dream of declarative programming
Why hasn't the dream of declarative programming been realized? What are some concrete obstacles getting in the way? For a simple example why can't I say

```<code>sort(A) is defined by sort(A) in perm(A) && asc(sort(A))
</code>```

and automatically get a sorting algorithm out of it. perm means permutations and asc means ascending.

答:
Not everything can be represented in a declarative way.

Often, you explicitely want to control the flow of execution

For example following pseudo-code:

if whatever
   read a file
   call an URL
else
   call an URL
   write a file

How would you represent it declaratively?

Sure, there are probably some exotic ways to do it. Like monads. But these usually are more cumbersome, complicated and far less intuitive than their procedural part.

It all boils down to the fact that "interacting" with your environment/system is not declarative. Everything related to I/O is procedural by essence. You have to tell exactly when and what should happen, and in what order.

Declarative is great for everything that is purely related to computation. Like a giant function, you put X in and you get Y. That's great. An example for this is HTML, the input is text, the output is what you see in your browser.

Title: The dream of declarative programming


问:
Database design to store localized country names and language names
I'm working on swift / iOS with a parse.com backend but this question could be applied to any language and is a general conceptual question. I'll use a specific example for illustration purpose.

I have a content type, let's say "user" that is saved in a database. Each user is categorized by countries. The app is localized.
Any user, must be able to filter users list by country. And here is the problem:

On database user table "countries" field, each user has entered his own country from a drop down list of countries, but these country names are localized.
So for example, an american user, has chosen "United States of Americas" as his country, and that is the string in the "Countries" user table, but a french user looking to filter all users from USA, will launch a search to corresponding localized "Etats-Unis d'Ameriques" which will not match "United States of Americas" users.

To avoid this localization categorization problem, I was thinking of abstracting the name countries by associating each with a numeric ID, in a tuple or array, then store in the database that ID. So when referring to it I would look-up the array ID and refer to localized string other member in the array.

Is this a proper way to handle this scenario ? I guess there is a "right" way to handle this.

答:
An enterprise application I work on does this which makes for messy queries but allows as many languages as you want.  The following is an overview not intended to be run on an ANSI compliant database

```<code>Table Locale
ID number primary key
VALUE  string: examples, English, French, German....

Table Countries
ID number primary key
Date_created
Date_last_modified
...

Table Countries_Locale
ID number part 1 of primary key, foreign key to Countries
LOCALE_ID part 2 of primary key, foreign key to Locale
VALUE string: examples United States, Les Etats Unis.....
</code>```

So a dropdown list would be this query:

```<code>Select Countries_locale.VALUE, Countries_locale.ID
From Countries_locale
where Countries_locale.LOCALE_ID = 2  --all English names for countries
</code>```

Body:
An enterprise application I work on does this which makes for messy queries but allows as many languages as you want.  The following is an overview not intended to be run on an ANSI compliant database

Table Locale
ID number primary key
VALUE  string: examples, English, French, German....

Table Countries
ID number primary key
Date_created
Date_last_modified
...

Table Countries_Locale
ID number part 1 of primary key, foreign key to Countries
LOCALE_ID part 2 of primary key, foreign key to Locale
VALUE string: examples United States, Les Etats Unis.....

So a dropdown list would be this query:

Select Countries_locale.VALUE, Countries_locale.ID
From Countries_locale
where Countries_locale.LOCALE_ID = 2  --all English names for countries


问:
Why is there only code review?
In my team I have applied a culture of code review and feature review.

The code might look great, written spectacularly, however the feature might not work.

It seems to me as 2 different scopes for review. While code reviews require a very technical and in depth knowledge, feature review requires only familiarity with the spec.

When I google code review I get a bunch of results.
However can't find anything on any other kind of review.

A brief reference can be found at https://softwareengineering.stackexchange.com/a/92417/95463 where BillThor says "You were asked to review the code do so, it is not the same as testing it"..

Do you use other kind of reviews and what are their goals and process?

We use a feature review where someone is actually running the tests and the feature manually and verifies it is intuitive and applies to spec.

答:
You sort of answered your own question... "Feature" reviews are what integration and system tests do. In a requirements based test environment, the tests are developed independently from the code and are used to verify that whatever the code implementation turns out to be, it still does what the requirement said it should do.

If there are no requirements, or you don't develop tests based on requirements, then your development process will be missing the 'feature' reviews you're looking for. Note that informal testing by playing with the application and running it through its intended use is a form of feature testing. You're just not using written requirements, which becomes a bigger deal as the software's scope increases.

EDIT: Ultimately, your users are the final feature testers. It's always easier to find your own shortcomings than to let your users find them for you.

Title: Why is there only code review?


问:
How to monitor code review efficiently?
I suspect major code review cover up in my team.
Too many code reviews are merged without any comment.

Seems to me like there's no such thing as a code review without a single comment.

How can I as a team lead properly monitor that my team is doing a proper code review process and how can I help them to maximize the process' benefits?

Update

Thought people might want to know about any update. I tried a lot of suggestions that were given here. most were already in use.
some helped a bit.
However, the problem remained - some people continuously got bad code in when I was not looking.

I found that code review monitoring is not as helpful as giving my team tools to make their code better to begin with.

So I added a library named "jscpd" to detect copy pastes.
The build failed on copy pastes.
That eliminated one problem immediately.

next we are going to try codeclimate.

I am also doing a manual review on old code reviews once a sprint for half a day.
I am converting todos into issues/tickets - as I found out people are writing them, but they are never handled at a later point.
I am also doing meetings with the entire teams to review code when it is appropriate.

in general it feels like we are moving in the right direction.

答:
You could document what the team wants in code reviews that you've discussed and agreed with developers. Some things you could consider as part of code reviews are:

Check that the code does what it's supposed to do i.e. it meets the requirements

Code style to ensure that developers are coding to a consistent style

Optimisation e.g. number of function calls

Architecture and reusability

Exception handling and logging

Technical debt: is the code in a better state than when the developer started working on it

Check out and build the code (I find this useful but other devs in my team prefer to leave this to testers)

Using an automated tool (I've used SonarQube). I find it useful to integrate this into your build process to enforce improvements to the code e.g. increasing the test coverage

Some of the steps above can be covered by an automated tool but while you're trying to improve the way code reviews or done it's probably worth using both the tool and eyeball review. However, the most important steps for preventing technical debt (architecture and reusability) cannot be wholly automated.

If your team is inconsistent in applying this you could try only allowing the developers who are carrying out code reviews properly to have merge rights. For example, you might just want to start with the lead dev on the team. The trade-off with this approach is that those developers could become a bottleneck in the development process, so you and the team need to decide if you want this. Personally I would accept this trade-off and through the code reviews increase the discipline across the rest of the team and then when ready you can increase the number of developers with merge rights.

Finally, it's worth reviewing the reviews. So once a week get together with the developers and constructively discuss the reviews and ways of improving them.

Title: How to monitor code review efficiently?


答:
I'm going to offer a different take from my fellow answerers. They are right - be involved if you want to see how things go. If you want more tracability, there are tools for that.

But in my experience, I suspect that there's something else going on.

Have you considered that your team may feel that the process is broken/stupid/ineffective for most commits? Remember, process is documenting what works well, not rules to obey. And as the team lead, you're there to help them be their best, not enforce rules.

So in your retrospectives (if agile) or one on ones (if you're a manager) or in random impromptu hallway meetings (if you're a non-agile team lead and there's another manager doing one on ones), bring it up. Ask what people think of the code review process. How is it working? How is it not? Say you think it's maybe not benefiting the team as much as it could. Make sure you listen.

You can do some advocacy for code reviews in these meetings, but it's better to listen to the feedback. Most likely, you'll find that either you team thinks that the "proper" process needs adjusting, or that there is some root cause (time pressure, lack of reviewers, Bob just commits his code so why can't we) to address.

Forcing a tool on top of a broken process won't make the process any better.

Title: How to monitor code review efficiently?

Body:
I suspect major code review cover up in my team.
Too many code reviews are merged without any comment.

Seems to me like there's no such thing as a code review without a single comment.

How can I as a team lead properly monitor that my team is doing a proper code review process and how can I help them to maximize the process' benefits?

Update

Thought people might want to know about any update. I tried a lot of suggestions that were given here. most were already in use.
some helped a bit.
However, the problem remained - some people continuously got bad code in when I was not looking.

I found that code review monitoring is not as helpful as giving my team tools to make their code better to begin with.

So I added a library named "jscpd" to detect copy pastes.
The build failed on copy pastes.
That eliminated one problem immediately.

next we are going to try codeclimate.

I am also doing a manual review on old code reviews once a sprint for half a day.
I am converting todos into issues/tickets - as I found out people are writing them, but they are never handled at a later point.
I am also doing meetings with the entire teams to review code when it is appropriate.

in general it feels like we are moving in the right direction.


问:
Project structure for overlapping product generations?
Our company is developing 2 generations of a product in parallel. Our product cycle is about 2-3 years. Today we're working on:

generation N "production": next product to be released, getting things into the market, new features, fixing bug

generation N+1 "research": concept work, studies, prototypes, research, requirements analysis

We're follow the Scrum methodology (roles, backlog, sprints, ...) in our team where possible, but the transition is still in progress. Especially: the rest of the company is (still) following a waterfall approach. The focus of our management is mostly on generation N.

Our company so far tried the following project structures, but all have severe drawbacks:

symbols:

(+) = good

(‒) = bad

Two separate teams for production (generation N) and research (generation N+1):

(+) good progress in the research for generation N+1

(+) Production team can focus on generation N.

(‒) The research team has the more interesting job, the production job is not so popular.

(‒) Knowledge loss when transferring a project from research to production.

(‒) The research team never experiences the problems of the production team and vice
versa. Especially the research team does not investigate all of the relevant aspects.

One team for both generations:

(+) Good knowledge sharing between generations.

(+) No handover required.

(‒) N+1 does not get the attention it deserves as the management focus in on N.

(‒) So there are not many innovations in generation N+1 as we did not have time for it.

Have only one team but dedicate 2 (or 3) "researchers" to focus on generation N+1:

(+) Good knowledge sharing between generations.

(+) No handover required.

(‒) In the beginning: Inefficient meetings (daily, sprint planning) as the two sub teams work on different topics.

(‒) In the end: The research progress is slow, as the researchers get pulled into production problems.

How should we set up our projects in this environment?

答:
You could go with the two team approach and reduce the negative impacts by:

allowing developers to work in both teams when it makes sense to swap the team resources around

documenting and presenting research work to developers in the production team to allow them to raise any concerns or highlight things that the research team are not aware of, maybe put regular presentations in place e.g. every Friday afternoon or inviting production team members to research sprint demos at the end of every sprint

Another approach would be to have one team and ask the management to appoint a product owner to create one prioritised backlog across both streams of work. The team shouldn't be doing work that is not valuable to the business. The product owner should prioritise on the basis of business value so, how valuable is each feature to the business (whether that's research or production).

Yes this might mean that the production work is more valuable so is prioritised higher; but if the prioritisation is done on business value, and research for N+1 ensures the company stays competitive in the market, then research work may get prioritised above some of the production features.


问:
Limiting complexity in JPA programs Java/Hibernate
I've been working on a new application for some months now. It's my first big JPA program, and is still in the early stages. However, the complexity of my JPA object tree is becoming a growing problem.

For instance I have an object tree of Users, who have Companies, Divisions, Related Divisions, Currencies, Local Currencies, Currency Exchange Rates. At lower levels, things are not so bad. For instance if I pull out Currencies, matters are easier to cope with. But for high level, tree topping elements like a list of Users, my object tree has become horrific.

Now, a small bug has slipped into the JPA object tree meaning an important join table is being overwritten by one of my entities. I hope I can find the bug, but what I'd like advice on, is how to avoid this rapidly burgeoning complexity.

Thanks!

答:
You could try using lazy loading of the related objects (Companies, Division, etc.). In your business layer, retrieve the related objects only if you require them. By default they will be null and save you heap space. If lazy loading becomes too complex (it usually does because of even more annotations and configurations), you can use indirect references.

So the User object would look like:

```<code>public class User{
    Integer id;
    Integer companyId;
    Integer divisionId;

    //usual getters and setters

    //this is not a getter - notice the different in method name
    public Company fetchUserCompany(){
        //DAO call to retrieve Company by companyId defined in the User object
    }
}
</code>```

In practice this approach makes managing complex hierarchies very simple and you can safely retrieve a large list of User objects without worrying about heap space. It's not purely 'object oriented' though. Bugs are easier to find since your UserDAO will only retrieve small User objects. In case you need the related objects the logic will be delegated to CompanyDAO.

In my experience I have seen that if the hierarchy is not very deep lazy loading is ok and easy to maintain, however in your case, you might be better off with the second approach.

Body:
You could try using lazy loading of the related objects (Companies, Division, etc.). In your business layer, retrieve the related objects only if you require them. By default they will be null and save you heap space. If lazy loading becomes too complex (it usually does because of even more annotations and configurations), you can use indirect references.

So the User object would look like:

public class User{
    Integer id;
    Integer companyId;
    Integer divisionId;

    //usual getters and setters

    //this is not a getter - notice the different in method name
    public Company fetchUserCompany(){
        //DAO call to retrieve Company by companyId defined in the User object
    }
}

In practice this approach makes managing complex hierarchies very simple and you can safely retrieve a large list of User objects without worrying about heap space. It's not purely 'object oriented' though. Bugs are easier to find since your UserDAO will only retrieve small User objects. In case you need the related objects the logic will be delegated to CompanyDAO.

In my experience I have seen that if the hierarchy is not very deep lazy loading is ok and easy to maintain, however in your case, you might be better off with the second approach.


答:
You could also be interested in the system programming aspect of your task. Then read Advanced Linux Programming, read the intro(2) & syscalls(2) man pages.  Be aware of the POSIX standard.

For thread programming, read a good Posix thread tutorial or a C++11 thread tutorial.

Regarding C++ programming, the Qt and POCO projects should interest you (and also perhaps Boost): they provide you with a cross-platform framework.

Regarding tools and programming habits, see these hints.

I recommend using at least C++11, not some earlier C++ standard (see documentation on cppreference & on cplusplus, etc...). So use recent versions of compilers (e.g. GCC 4.9 or Clang/LLVM 3.5 at least, in spring 2015). Don't forget to enable all warnings and debug info.

Study the source code of some existing free software (see e.g. sourceforge or github, etc...), you'll learn a big lot. Try even to contribute to it.

BTW, learning other programming languages (e.g. Scheme with SICP, Haskell, Ocaml, Prolog, Python, ...) will also teach you a big lot (even improve your way of thinking in C++).

Title: Programming in Linux (C++)

Body:
So I don't know If this is the right place to ask this. I am new to programming, I am not very in to it (I know classes,arrays,functions..etc(Basic Things)).

I was programming with Visual Studio 2013 , so I decided to change my OS to Linux.

First things I notice is that the code is not exactly the same also the including headers. For example: I can't use conio.h and with it I can't end my main function with _getch(); function.

My question is: What's the difference between windows and linux programming? Can someone recommend me where can I look/read for this changes(whats the different and what can I use with linux).

Any help will be appreciated! Thank you in advance !! :)


问:
How do you debug a complex application?
I have an application that is returning the wrong output, when it is run with a particular input choice.  I haven't been able to get anywhere near a diagnosis of the fault, despite spending about a day and a half on it. If it is run with Input A then it gets the correct output, if it has Input B then the output should be the same but is incorrect.  Input B goes through some slightly different processes to Input A, in an attempt to optimise it, although most of the steps are in common.

I am trying to compare side-by-side an invocation of the program with the two inputs.  Its a difficult way to debug as you have two application windows, two visual studio windows, and its easy to get mixed up.

The software is about 1 million lines of code, and some of the code is fiendishly complicated.  It has many nested loops and loops that run for a lot of iterations, with very complex variables.  It caches a lot of data, so when you find that values in one mode are different from the other you have to work out if the differences are significant, and then its hard to trap where the programs diverge since the values have already been calculated and you have to keep restarting the programs and going back.

I understand there is no silver bullet here but I just wondered if anyone had any tips?

答:
Its a difficult way to debug as you have two application windows, two visual studio windows, and its easy to get mixed up.

Really? You have two monitors. Put one variant on one screen and the other on the other. If you don't have two monitors, then welcome to the 21st century. They're like $100.

I understand there is no silver bullet here but I just wondered if anyone had any tips?

So it sounds as though you have a overly complex (read: poorly designed/implemented) codebase. And it sounds as though you have no unit tests.

Ideally, I would look to simplify the codebase. Pass in dependencies to loosen coupling. Break big functions into smaller ones. Cut out side effects. There are piles of good practices to do that, but since that is "how to write good code" - I'm not going to go into it in depth. And really, you shouldn't simplify the codebase until you get the bug fixed.

Unit tests though will help. They can isolate the bug, and help you debug just that isolated part rather than the whole complex app. They provide clear input/expected-output pairs. They prevent later users from breaking things. And they will put pressure on you to write good re-usable code. Granted, it might be infeasible to make good unit tests if your code is overly complex.

Title: How do you debug a complex application?


答:
Maintain the same team but different branches in your SCM. Your generation N product will generally be more stable so you should get (cherrypick) the stable code or any relevant improvements from branch N to N+1.

Have the same developers who worked on feature X in product N work on the same feature in product N+1. That way they will be familiar with both the codebases and any code migration or code merge will be easier. Plus it will keep them happy as they get to work on both production grade as well as cutting edge technology. Just have the management focus on N+1 in addition to N.

Depending on the situation, you can switch developers from one product to another - say product N requires a critical patch then your team working on N+1 can take a week to work on N. Similarly suppose you have implemented a stable reporting framework in N and want a cutting edge reporting framework in N+1, have the same team port the changes from N to N+1 and also improve N+1 with newer tech. This way all the developers will work as a single team which is important because after all N and N+1 are the same product, and your products will be more coherent, and help you in the long term in customer migration, devops, etc.

footnote: Apple did mac and lisa at the same time during the 80s, driving a wedge between developers of the teams. You want synergy within the company, esp if its different iterations of the same product.

Title: Project structure for overlapping product generations?

Body:
Our company is developing 2 generations of a product in parallel. Our product cycle is about 2-3 years. Today we're working on:

generation N "production": next product to be released, getting things into the market, new features, fixing bug

generation N+1 "research": concept work, studies, prototypes, research, requirements analysis

We're follow the Scrum methodology (roles, backlog, sprints, ...) in our team where possible, but the transition is still in progress. Especially: the rest of the company is (still) following a waterfall approach. The focus of our management is mostly on generation N.

Our company so far tried the following project structures, but all have severe drawbacks:

symbols:

(+) = good

(‒) = bad

Two separate teams for production (generation N) and research (generation N+1):

(+) good progress in the research for generation N+1

(+) Production team can focus on generation N.

(‒) The research team has the more interesting job, the production job is not so popular.

(‒) Knowledge loss when transferring a project from research to production.

(‒) The research team never experiences the problems of the production team and vice
versa. Especially the research team does not investigate all of the relevant aspects.

One team for both generations:

(+) Good knowledge sharing between generations.

(+) No handover required.

(‒) N+1 does not get the attention it deserves as the management focus in on N.

(‒) So there are not many innovations in generation N+1 as we did not have time for it.

Have only one team but dedicate 2 (or 3) "researchers" to focus on generation N+1:

(+) Good knowledge sharing between generations.

(+) No handover required.

(‒) In the beginning: Inefficient meetings (daily, sprint planning) as the two sub teams work on different topics.

(‒) In the end: The research progress is slow, as the researchers get pulled into production problems.

How should we set up our projects in this environment?


问:
Best strategy for converting change in longitude and latitude to north, south, east, west in degrees
This is not a class assignment but a conceptual question I'm struggling with for a personal project.

I need to convert a large paired group of long and lat coordinate values that show a two-dimensional directional change to degrees change (0-360).

What are the fastest ways to make this kind of transformation? I am hoping to avoid nesting a lot of conditional statements.

答:
For accuracy better than the general tools use to gather the data is a Python module pyproj  Feed your data into something like the odometer function extracted from waypoint.py

```<code>from pyproj import Geod  # sudo pip3 install pyproj
geoid = Geod(ellps='WGS84')  # See pyproj documentation for other fun options

def odometer(start, end):
    """Calculate bearings and distance between start and end.

    Arguments:
      start (tuple of float): latitude and longitude of starting position
      end (tuple of float): latitude and longitude of ending position

    Returns:
      float: True North bearing start -> end
      float: True North bearing end -> start
      float: distance start <-> end in meters
    """
    try:
        bearing_to, bearing_fro, distance = geoid.inv(*start + end)
    except Exception as error:  # more specific?
        print("odometer({}, {}) created error:{}".format(start, end, error))
        return None

        bearing_to %= 360
        bearing_fro %= 360
    return bearing_to, bearing_fro, distance
</code>```

Body:
For accuracy better than the general tools use to gather the data is a Python module pyproj  Feed your data into something like the odometer function extracted from waypoint.py

from pyproj import Geod  # sudo pip3 install pyproj
geoid = Geod(ellps='WGS84')  # See pyproj documentation for other fun options

def odometer(start, end):
    """Calculate bearings and distance between start and end.

    Arguments:
      start (tuple of float): latitude and longitude of starting position
      end (tuple of float): latitude and longitude of ending position

    Returns:
      float: True North bearing start -> end
      float: True North bearing end -> start
      float: distance start <-> end in meters
    """
    try:
        bearing_to, bearing_fro, distance = geoid.inv(*start + end)
    except Exception as error:  # more specific?
        print("odometer({}, {}) created error:{}".format(start, end, error))
        return None

        bearing_to %= 360
        bearing_fro %= 360
    return bearing_to, bearing_fro, distance


答: There are the features that the language provides, and there are other features that the OS provides. iostream for example is built in to the language. conio.h is specific to Windows. There are other headers too that are specific to Linux.

Title: Programming in Linux (C++)


问:
Cyclomatic complexity for 2 IFs - why not just FF or TT?
I know that cyclomatic complexity defines the number of independent paths in the code. Using the simple way, it can be calculated as number of IF +1. In that case, for a simple code with two IFs, CC would be 3.

That would make sense in terms of TRUE/FALSE outcomes  - TT, TF, FT. Each test case would traverse a new edge.

But what if I chose TT and FF? I would traversed all edges, how could there be another independent path?

EDIT: I might have understood...I assume linearly independent means that I change only one decisions outcome at time...

答:
Cyclomatic complexity when applied to testing places two bounds on the test cases needed.

From Wikipedia Cyclomatic complexity: Implications for software testing

M is an upper bound for the number of test cases that are necessary to achieve a complete branch coverage.

M is a lower bound for the number of paths through the control flow graph (CFG). Assuming each test case takes one path, the number of cases needed to achieve path coverage is equal to the number of paths that can actually be taken. But some paths may be impossible, so although the number of paths through the CFG is clearly an upper bound on the number of test cases needed for path coverage, this latter number (of possible paths) is sometimes less than M.

All three of the above numbers may be equal: branch coverage <= cyclomatic complexity <= number of paths.

For the code:

```<code>if( c1() )
   f1();
else
   f2();

if( c2() )
   f3();
else
   f4();
</code>```

This has a complexity of 3.  Yes, testing TT or FF is two test cases and will cover the branch coverage of the code.  The Npath coverage would require four tests.

A module should have at least as many tests as its complexity.

Consider a bug that requires that f1() be called before f3().  The tests TT and FF will not uncover the bug, while the tests TF and FT will show the bug.  You should have at least 3 tests for this method according to cyclomatic complexity.

Though the key point in all of this is that the complexity establishes the bounds on the number of tests needed to adiquetly test the code.  It does not say what tests you need (nor if you have the right tests).

Body:
Cyclomatic complexity when applied to testing places two bounds on the test cases needed.

From Wikipedia Cyclomatic complexity: Implications for software testing

M is an upper bound for the number of test cases that are necessary to achieve a complete branch coverage.

M is a lower bound for the number of paths through the control flow graph (CFG). Assuming each test case takes one path, the number of cases needed to achieve path coverage is equal to the number of paths that can actually be taken. But some paths may be impossible, so although the number of paths through the CFG is clearly an upper bound on the number of test cases needed for path coverage, this latter number (of possible paths) is sometimes less than M.

All three of the above numbers may be equal: branch coverage <= cyclomatic complexity <= number of paths.

For the code:

if( c1() )
   f1();
else
   f2();

if( c2() )
   f3();
else
   f4();

This has a complexity of 3.  Yes, testing TT or FF is two test cases and will cover the branch coverage of the code.  The Npath coverage would require four tests.

A module should have at least as many tests as its complexity.

Consider a bug that requires that f1() be called before f3().  The tests TT and FF will not uncover the bug, while the tests TF and FT will show the bug.  You should have at least 3 tests for this method according to cyclomatic complexity.

Though the key point in all of this is that the complexity establishes the bounds on the number of tests needed to adiquetly test the code.  It does not say what tests you need (nor if you have the right tests).


答:
It would look something like this..
{(whatever => read a file & call a url) | call a url & read a file}
However, these are actions to execute, and the state of the system changes as a result, but that is not obvious from the source.

Declaratives can describe a finite state machine and its transitions.
The FSM is like the opposite of declaratives without actions, even if the only
action is to change state to the next state.

The advantage of using this method is that transitions and actions can be
specified by predicates that apply to multiple transitions, rather than just one.

I know this sounds a little strange, but in 2008 I wrote a program generator
that uses this method, and the generated C++ is from 2 to 15 times as much as
the source.  I now have over 75,000 lines of C++ from 20,000 lines of input.
Two things go with this: consistency and completeness.

Consistentcy: No two predicates that can be true at the same time can imply
inconsistent actions, as both x = 8 and x = 9, nor different next states.

Completeness: The logic for every state transition is specified.
These may be difficult to check for systems with N substates, with > 2**N states, but there are interesting combinatorial methods that can verify everything.
In 1962 I wrote phase 1 of a system sort for the 7070 machines, using this kind
of conditional code generation and combinatorial debug.  Of the 8,000 lines in the sort, the number of bugs from the day of the first release forever was zero!

Phase two of the sort, 12,000 lines, had over 60 errors in the first two months.
There is much more to say about this, but it works.
If car manufacturers used this method to check the firmware, we would not see
the failures that we see now.

Title: The dream of declarative programming

Body:
Why hasn't the dream of declarative programming been realized? What are some concrete obstacles getting in the way? For a simple example why can't I say

```<code>sort(A) is defined by sort(A) in perm(A) && asc(sort(A))
</code>```

and automatically get a sorting algorithm out of it. perm means permutations and asc means ascending.


问:
Why use an enum to determine node type in a parse tree?
The Sun Compiler Tree API uses an interface called Tree as the parent of all the different kinds of parse tree nodes (assignments, if-statements, class declarations, etc.). A part of this interface is an enumeration called Kind that holds the type of the node.

I have yet to encounter a case where the enum is not faithful to the node's type as a Java object. What is the advantage gained here? Just to open the door to switch statements? What does this achieve that polymorphism cannot?

答:
What would be he alternative to enums?

A non-formalized integral type? That's a step backwards. Making all distinctions by dynamic dispatch on subclass methods of the node type? That only works for some problems; in languages without multiple dispatch, there are a lot of situations that you can't handle that way. If the language doesn't give a better option, switching on an enum is exactly the right thing to do.


答:
For parse trees especially, it is very uncommon to use polymorphism. It would require the base node type to know about all of the different capabilities/properties/attributes of every different node type in the parse tree. That can get out of hand quickly.

By using an enum, it makes it easier to build visitors to walk the tree and do things to it depending on what node they're visiting. Since that sort of visitation is the common usage pattern for static analysis, optimization and back end compilation, it makes sense to make that easy.

Title: Why use an enum to determine node type in a parse tree?

Body:
The Sun Compiler Tree API uses an interface called Tree as the parent of all the different kinds of parse tree nodes (assignments, if-statements, class declarations, etc.). A part of this interface is an enumeration called Kind that holds the type of the node.

I have yet to encounter a case where the enum is not faithful to the node's type as a Java object. What is the advantage gained here? Just to open the door to switch statements? What does this achieve that polymorphism cannot?


问:
how to introduce a culture of quality into the work environment?
Currently we're not doing any code reviews and we have effectively zero unit tests (we have some but they are never run by anyone else other than myself) and there's no coding standards for style and we're dealing with C#, Python, JavaScript and HTML/CSS.

We're starting to use branches and pull requests in github with very quick code reviews and no unit tests associated with the code.

The manager explicitly said that cutting corners on quality is okay, however half of the bugs we're fixing are regressions and the other half is basically re-work of low quality contractor work.

Is there a nice way to introduce a culture of quality into an environment like this?

答:
Just like with anything else you are trying to sell - you have to dig up for that value proposition which is unique to the management and developers respectively.

Most developers on a logical level would understand that unit testing, code reviews are very important but internalizing that information is very different.

As with management they mostly see unit testing, dev testing as extra work that slows down the process.

Obviously both of these statements are pretty generalized.

One way you could go about doing this is introducing this slowly, bit by bit. Do it iteratively.

Start with management and work your way down to developers.

When you're with managers think about all the ways that unit testing, dev testing can make them more money in the long-term despite the fact that the process will be slowed down inevitably in the short-term.

When you're with developers show them how it can increase the quality of their daily lives by not having to deal with crappy tickets that are the results of what they are not doing that you want them to do.


答:
An enum models a finite set of different choices where you need to know which one you're dealing with before you can proceed. Dynamic dispatch solves a completely different problem - allowing for an unlimited number of options and handling them uniformly.

An enum is most likely more efficient and generally safer than inspecting the class of the node:

```<code>if (node instanceof Type1Node) {
    ...
} else if (node instanceof Type2Node) {
    ...
} else {
    throw new AssertionError("Someone added a new node type.");
}
</code>```

VS

```<code>switch (node.type) {
case Tree.Kind.AND:
    ...
case Tree.Kind.AND_ASSIGNMENT:
    ...
}
throw new AssertionError("Someone modified this enum");
</code>```

The enum version has only one jump and you'll get warnings if you miss any cases, either through negligence or because the enum has been updated. You can't get those warnings with a ton of instanceof tests because new subclasses can be added.

A reasonable alternative is to use some form of Visitor. But even with lambdas enabling more compact syntax for visitors, there's still advantages to a switch - you can easily merge multiple cases whenever they're handled the same way.

Body:
An enum models a finite set of different choices where you need to know which one you're dealing with before you can proceed. Dynamic dispatch solves a completely different problem - allowing for an unlimited number of options and handling them uniformly.

An enum is most likely more efficient and generally safer than inspecting the class of the node:

if (node instanceof Type1Node) {
    ...
} else if (node instanceof Type2Node) {
    ...
} else {
    throw new AssertionError("Someone added a new node type.");
}

VS

switch (node.type) {
case Tree.Kind.AND:
    ...
case Tree.Kind.AND_ASSIGNMENT:
    ...
}
throw new AssertionError("Someone modified this enum");

The enum version has only one jump and you'll get warnings if you miss any cases, either through negligence or because the enum has been updated. You can't get those warnings with a ton of instanceof tests because new subclasses can be added.

A reasonable alternative is to use some form of Visitor. But even with lambdas enabling more compact syntax for visitors, there's still advantages to a switch - you can easily merge multiple cases whenever they're handled the same way.


问:
Always set form input max length?

Background

I'm looking to put together a single page web application with many form inputs. I've run into issues with other web pages where there is an ugly SQL error sent to the user if the maxlength constraint of the field in the table was violated. I'd like to know how to manage this type of validation.

Questions

Should I put the effort into making sure that the HTML form input is limited in size for every input field (as opposed to targeting significant fields)?

Should the maxlength of the input field be tied programmatically to the constraints of database fields (through a query of the database system tables) or would this be unrealistic?

I'm looking for both what is best practice and what is maintainable (I don't want to have to do a lot of extra work if the database design changes). Is it easier just to decode the SQL error post-submit and inform the user?

Related Questions

max length validation check - More specific to what length to set fields at. I'm more interested in the broader question of applying the length.

When and how much should we validate input when working with (C)AP storage? - Probably the most similar. It is about validation in general.

Data input validation - Where? How much? [closed] - Broadly touches on some principles including stating:

use of additional validation like "between 6 and 20 characters" less frequent, as this increases maintenance work on changes

答:
Yes, you probably should put maxlength constraints on every field where such constraints exist. The reason for doing that is mainly so that the user can get immediate feedback, instead of having to send the request and having the application tell them that they cannot do that (though that may still happen in some cases);

Attempting to derive maxlength from the database schema is necessarily going to tie the technical database implementation / definition with the front-end HTML - that is, you are going to have, in one form or another, the view generation code be aware of the underlying data structures, and of how the underlying database tables map to the UI. Such a coupling, in my experience, actually increases the burden of introducing a change. It may also yield the wrong value anyway, as HTML5 maxlength is defined in terms of Unicode code points, whereas max length in databases is often defined for UTF-16 or byte length;

In my experience, once the maxlength of some data is set, it should only change rarely, and because of that, the maintenance burden is acceptable.

Also, even if you put maxlength and minlength in the HTML form, you will still need to validate on the server side, because anyone may still send a form with data that would not validate in the HTML form.

Title: Always set form input max length?


答:
First, I believe you know this, but it may not be clear to other readers.  The interface in question provides both an enum and polymorphic dispatch via the visitor pattern.  Given that, I think in general you should prefer to use polymorphism, if you can do so cleanly without duplication.

I think the enums are there not necessarily to allow for switch statements, but for other simplifying structures.  You can use them to index a map, for example.    You could create a KindsWithConditionals array.  You can store a kind enum in a database column.  You can easily log it with toString.  There are lots of things you can do with an enum that are cumbersome without one.


问:
When are nonblocking read or receive operations useful?
Regardless of library, language, or spec, asynchronous send/write operations make sense to me, because code later in the execution path may not have any dependency upon the success or failure of the write operation.

However, asynchronous receive/read operations are not motivated for me.

Can anyone suggest specific situations or general patterns where async message receipt is useful?

Context

My question is prompted by the MPI specification, but the more general the answer the better.  Specifically, there are blocking calls to communicate between processes or machines:

MPI_Send(...)
MPI_Recv(...)

and there are analogous nonblocking calls that take an additional parameter MPI_Request * parameter to handle the send/receive operations asynchronously:

MPI_Isend(..., &request)
MPI_Irecv(..., &request)

答:
Non-blocking reads can be especially useful in contexts where data may or may not arrive, but if data does arrive it should affect the behavior of an action being performed.  For example, if an interactive program that communicates via TCP expects to perform some computations in response to a request, but it's possible that the client might discover--before the computations are complete--that it will no longer be interested in the results, the application might benefit from using a non-blocking read that looks for an "abort" signal.  Requiring the client to sent continuous "yes I'm still interested" messages could be annoying, especially if the client has no idea how long the computation will take.

In cases where one wishes to perform several I/O operations independently but they're expected to run to completion, it's often easier and cleaner to use multiple threads than to use asynchronous I/O.  In cases where the whole purpose of I/O would be to affect a process which is running on another thread, however, creating an extra thread just to sit on the socket would be wasteful and inelegant.


问:
Factory for abstract class
I have an abstract class MyAbstractClass.

I also have lots of implementations of that class, and I want to create a factory for these implementations.

Need to end up with usage like that: MyAbstractClass.Factory.CreateSomething();

Now I don't know which style I should use:

1) Factory should be nested static class with static methods

2) Factory should be static property which returns instance of FactoryClass

   ... a) (will not work) //FactoryClass have static methods, and public or internal constructor

   ... b) FactoryClass have instance methods, and public or internal constructor

What do you think?

答:
Need to end up with usage like that: MyAbstractClass.Factory.CreateSomething();

Why? Syntax is largely irrelevant compared to the semantics of the design. This for example makes it more difficult to use different instance of the factory in different places. In other words, it's a coupling issue. Maybe it's a good place to introduce coupling (since it is not meaningful to instantiate these classes other ways) but probably not.

If you do really want this, then don't get fancy. Just have a static readonly instance of Factory on the abstract class. This allows you to make the factory class just another class. It makes it easy to use elsewhere. It makes it easy to test.

Simple is good.

Title: Factory for abstract class


问:
Creating one-line method for the single purpose of self-documenting code
Given the following two snippets:

Snippet 1:

```<code>public void foo(Data data, AbstractNode node)
{
    int originalId = data.getCurrentId;
    node.execute(data);

    //If node changed currentId reset it to the original.
    data.setCurrentId(originalId);
}
</code>```

Snippet 2:

```<code>public void foo(Data data, AbstractNode node)
{
    int originalId = data.getCurrentId;
    node.execute(data);

    resetCurrentIdIfChangedByNode(data, originalId);
}

private void resetCurrentIdIfChangedByNode(Data data, int originalId)
{
    data.setCurrentId(originalId);
}
</code>```

In both cases it is not be known whether node.execute() changes the currentId or not.

Does the one-line method in Snippet 2 make the code more readable? Or is it preferable to use comments as in Snippet 1?

EDIT: I understand that node has side effects. This is why I'm resorting to creating a method that explains (or tries to explain) that the data.currentId might be changed by node. Depending on which subclass of AbstractNode is being used, it might be changed or not.

EDIT 2: The reason there is no if statement around the reset in Snippet 2 is that it would be pointless, since the result would be the same whether we check or not.

```<code>private void resetCurrentIdIfChangedByNode(Data data, int originalId)
{
    data.setCurrentId(originalId);
}
</code>```

same result as

```<code>private void resetCurrentIdIfChangedByNode(Data data, int originalId)
{
    if(data.getCurrentId() != originalId)
    {
        data.setCurrentId(originalId);
    }
}
</code>```

答:
I like the general idea. Instead of depending on a comment, which can be deleted or not updated when things change, making what's happening an explicitly named function explains what's happening and prevents the explanation from being lost.

Though as others have mentioned, I'd name it differently, perhaps resetDataToOriginalID(), and being a C++ programmer, I'd probably use a RAII based solution to provide exception safety if needed. Something like this.

```<code>class DataIdGuard
{
    int    m_originalID;
    Data & m_data;

    public:
    DataIdGuard( Data & data ) : m_originalID( data.getCurrentId() ), m_data( data )
    { }

    ~DataIdGuard()
    {
        m_data.setCurrentId( m_originalID );
    }

};

void foo( Data & data, AbstractNode & node )
{
    DataIdGuard guard_data_id( data );
    node.execute( data );
}
</code>```

Body:
I like the general idea. Instead of depending on a comment, which can be deleted or not updated when things change, making what's happening an explicitly named function explains what's happening and prevents the explanation from being lost.

Though as others have mentioned, I'd name it differently, perhaps resetDataToOriginalID(), and being a C++ programmer, I'd probably use a RAII based solution to provide exception safety if needed. Something like this.

class DataIdGuard
{
    int    m_originalID;
    Data & m_data;

    public:
    DataIdGuard( Data & data ) : m_originalID( data.getCurrentId() ), m_data( data )
    { }

    ~DataIdGuard()
    {
        m_data.setCurrentId( m_originalID );
    }

};

void foo( Data & data, AbstractNode & node )
{
    DataIdGuard guard_data_id( data );
    node.execute( data );
}


答:
I'll tell you how my team quickly integrated code review into its workflow.

First, let me ask you a question. Are you using a version control system (e.g. Mercurial, Git)?

If your answer is yes, then proceed.

prohibit everybody from pushing anything (even small fixes) directly to the master branch (trunk)*

develop new features (or fixes) in separate branches

when developers believe the branch is ready to be integrated in master, they will create a "pull request"

prohibit everybody from merging their own pull request*

have another developer evaluate the pull request and review new code

if the code passes the review, good, the pull request can be merged, otherwise fixes can be applied

repeat step 6 until code matures enough (can be done without starting over)**

done, all your new code gets reviewed (at least summarily), by someone with a name

Now you have a precise point in your workflow where code review gets done.

Act there.

* can be enforced automatically, with server-side hooks

** this procedure is fully supported by GitHub (among others), and is fairly easy to use, check it out

Title: How to monitor code review efficiently?


答:
I would give the variable a ridiculously long name to make everything clear

```<code>public void foo(Data data, AbstractNode node)
{
    int savedOriginalIdBecauseNodeDotExecuteMightChangeIt = data.getCurrentId;
    node.execute(data);

    data.setCurrentId(savedOriginalIdBecauseNodeDotExecuteMightChangeIt);
}
</code>```

On further thought

Something about this code really bothers me.  You take care to reset the currentId of the data, in case node.execute() changes it.  What else might get changed?  How do I know that other properties like data.name or data.foobar didn't get changed?  This is a big can of worms which indicates a code smell and possible need for refactoring.

Title: Creating one-line method for the single purpose of self-documenting code

Body:
Given the following two snippets:

Snippet 1:

```<code>public void foo(Data data, AbstractNode node)
{
    int originalId = data.getCurrentId;
    node.execute(data);

    //If node changed currentId reset it to the original.
    data.setCurrentId(originalId);
}
</code>```

Snippet 2:

```<code>public void foo(Data data, AbstractNode node)
{
    int originalId = data.getCurrentId;
    node.execute(data);

    resetCurrentIdIfChangedByNode(data, originalId);
}

private void resetCurrentIdIfChangedByNode(Data data, int originalId)
{
    data.setCurrentId(originalId);
}
</code>```

In both cases it is not be known whether node.execute() changes the currentId or not.

Does the one-line method in Snippet 2 make the code more readable? Or is it preferable to use comments as in Snippet 1?

EDIT: I understand that node has side effects. This is why I'm resorting to creating a method that explains (or tries to explain) that the data.currentId might be changed by node. Depending on which subclass of AbstractNode is being used, it might be changed or not.

EDIT 2: The reason there is no if statement around the reset in Snippet 2 is that it would be pointless, since the result would be the same whether we check or not.

```<code>private void resetCurrentIdIfChangedByNode(Data data, int originalId)
{
    data.setCurrentId(originalId);
}
</code>```

same result as

```<code>private void resetCurrentIdIfChangedByNode(Data data, int originalId)
{
    if(data.getCurrentId() != originalId)
    {
        data.setCurrentId(originalId);
    }
}
</code>```

Body:
I would give the variable a ridiculously long name to make everything clear

public void foo(Data data, AbstractNode node)
{
    int savedOriginalIdBecauseNodeDotExecuteMightChangeIt = data.getCurrentId;
    node.execute(data);

    data.setCurrentId(savedOriginalIdBecauseNodeDotExecuteMightChangeIt);
}

On further thought

Something about this code really bothers me.  You take care to reset the currentId of the data, in case node.execute() changes it.  What else might get changed?  How do I know that other properties like data.name or data.foobar didn't get changed?  This is a big can of worms which indicates a code smell and possible need for refactoring.


问:
adding the digits of a number
I am trying to write a program that asks the user for a decimal number and then calculates the sum of its digits. for example if the number is 123.25 then the sum will be 1+2+3+2+5=13.

I decided to first turn the number to 0.12325 (any number will be formatted this way but I am using the example) and then move the decimal point to the right one place and isolate the digits one by one.

here is what I got (I tried it in python and c++ i get the same problem in both):

```<code>number = float(raw_input ("please enter a Decimal number: "))
total = 0

while number >= 1:
    number = number / 10 ## turning 123.25 to 0.12325

while number > 0:
    number = number * 10 ## making 0.12325 to 1.2325
    total = total + int(number)  ## storing the digit on the left of the decimal point
    number = number  - int (number) ## getting rid of the digit left to the decimal point

print total
</code>```

The problem is that everything works fine until the last digit. When it comes to the point where it's 5.0 than the statement number = number - int(number) gives me 1 instead of zero. It is supposed to be 5.0 - 5 = 0 but it isn't.

This is what I get when i print the number at every stage:

```
please enter a Decimal number: 123.25
0.12325
0.2325
0.325
0.25
0.5    ##### Here is where the problem starts #####
0.999999999999
0.999999999993
0.999999999929
..... here it goes on for  a while. I spared you the rest .....
```

More accurately, I printed the number at every step in the loop:

```
please enter a Decimal number: 123.25

number at start of loop:  0.12325
number after 'number * 10' :  1.2325
number at the end of the loop:  0.2325

number at start of loop:  0.2325
number after 'number * 10' :  2.325
number at the end of the loop:  0.325

number at start of loop:  0.325
number after 'number * 10' :  3.25
number at the end of the loop:  0.25

number at start of loop:  0.25
number after 'number * 10' :  2.5
number at the end of the loop:  0.5

number at start of loop:  0.5
number after 'number * 10' :  5.0
number at the end of the loop:  0.999999999999
```

All of a sudden it stops being accurate.

答:
This can be done with the following python one-liner:

```<code>>>> f = 123.25
>>> sum(int(ch) for ch in str(f) if ch.isdigit())
13
>>>
</code>```

To break down how this works:

Convert to string as @whatsisname recommends to avoid floating point rounding issues

```<code>str(f)
</code>```

Create a list containing each character

```<code>ch for ch in str(f)
</code>```

Throw out everything that isn't a digit

```<code>ch for ch in str(f) if isdigit(ch)
</code>```

Convert everything in the result to an int

```<code>int(ch) for ch in str(f) if isdigit(ch)
</code>```

Sum everything

```<code>sum(int(ch) for ch in str(f) if isdigit(ch))
</code>```

There are three key points here:

Do not be afraid to convert numbers to strings.  The performance hit of doing so is usually inconsequential on modern machines, and this makes manipulating digits much more natural

Python list comprehensions combined with standard functions are extremely useful for anything that involves "do something with this list of something".

When using floating point math, you should never expect exact results except in trivial cases (like 0.0) because of precision issues.

Title: adding the digits of a number

Body:
This can be done with the following python one-liner:

>>> f = 123.25
>>> sum(int(ch) for ch in str(f) if ch.isdigit())
13
>>>

To break down how this works:

Convert to string as @whatsisname recommends to avoid floating point rounding issues

str(f)

Create a list containing each character

ch for ch in str(f)

Throw out everything that isn't a digit

ch for ch in str(f) if isdigit(ch)

Convert everything in the result to an int

int(ch) for ch in str(f) if isdigit(ch)

Sum everything

sum(int(ch) for ch in str(f) if isdigit(ch))

There are three key points here:

Do not be afraid to convert numbers to strings.  The performance hit of doing so is usually inconsequential on modern machines, and this makes manipulating digits much more natural

Python list comprehensions combined with standard functions are extremely useful for anything that involves "do something with this list of something".

When using floating point math, you should never expect exact results except in trivial cases (like 0.0) because of precision issues.


问:
Creating a separate table for images or adding "image fields" to many tables?
I need to create a database in which several tables have images.

For example, users have profile pictures and uploaded ones and products have many pictures, as well.

Is it better to have one SQL table "images" or add "images" to every table that contains them?

Also, how would you add many images into one column?

I've read about the advantages of storing the file paths vs the actual files in the database but what about a long string with many file paths vs many rows?

For example

INSERT INTO images (userid, image1, image2, image3)
VALUES (autoincrementedPK 'pathtofile1', 'pathtofile2', 'pathtofile3')
```
<p>or</p>
<pre class="lang-sql prettyprint-override"><code>INSERT INTO images (userid, images)
VALUES (autoincrementedPK, 'pathtofile1, pathtofile2, pathtofileN')
</code>```

Which option is better and why? Is option two viable? and if so, how would you implement it?

答:
I agree wholeheartedly with Tulains Córdova on the question of file paths, but can't disagree strongly enough about BLOBS.

Although the question doesn't specifically mention if it's a web application or a more traditional client-server application, it sounds like we're talking about a web app from the context provided about USERS & PRODUCTS.

If that's the case, then there is no excuse not to be using a CDN, especially with amazing free transparent CDN's like cloudflare.  There are others, but I love CloudFlare and can't recommend it enough.  I suppose it matters more that you use a CDN at all than which particular one you prefer...

Storing images in the DB as BLOBS has never really been faster than the file system unless you have specialized hardware which you can tune at a very low level to optimize file IO (and there are few experts I've run across who really do this better than the thousands of engineers working on this problem at the OS / driver level).

Even worse, by using DB BLOBS, you not only preclude the incredibly faster CDN option of geographically distributing and hosting static image (and CSS, and JS, and fonts...) assets as close to your web visitors as possible, but you also wind up giving up the option of using faster web servers like nginx or front-end caching systems like Varnish to serve up your images (and CSS, JS, etc...) which is a shame because they are WAY faster than apache and IIS if properly configured.

Obviously, you'd also give up the option of combining nginx, varnish, and a CDN since you can't use the individual components unless the assets are stored on the file system.

I've developed some apps that were being deployed onto clustered cloud environments which created a challenge of distributing file assets that were needed by every server in a cluster.  Initially you might be tempted to consider storing image assets in the DB as BLOBS so every node could access them and then you don't need to worry about deploying those assets...

Avoid this temptation.  I've found it's better to let file systems, web servers, caches, and CDN's do what they do BEST and leave the DB to do what it does best.  And that's definitely not storing images and serving them quickly to web applications.

ContentLicense: CC BY-SA 4.0


问:
What is the (craziest, stupidest, silliest) thing a client/boss asked you to do?
See title, but I am asking from a technical perspective, not

Take my 40 year old virgin niece on a date or you're fired.

答:
Small team of programmers, boss wants us to do a ticket reservation system for a small airline (in a very short timeframe, of course). Team says:

-- as you can imagine, we will need some testers for this project

Boss says:

-- don't worry, learn from the car industry. They recall cars from time to time: users will do the testing.

ContentLicense: CC BY-SA 2.5


问:
Should I focus on being deep or broad
I have been a professional developer for just over half a year and have been amazed at how big the world really is out of college. I have continued to learn in my free time but I am wondering where should I focus?

FOCUS 1) The development stack used by my company. Quickest payoff in my day to day development. #Deepest

FOCUS 2) A different language with the same paradigm. See if I can generalize my knowledge and way of thinking.

FOCUS 3) Different language, different paradigm. Expand my borders and learn new ways to do things. #Broadest

If anyone has a different focus feel free to put that out there.

答:
When people ask me for career advice your question is one of the first questions I ask them.  I don't think anyone can answer this question for you; I think you have to decide for yourself whether focussing on depth or breadth is more likely to meet your career goals.

When I last changed teams I had two opportunities: to work on the XBOX developer tools team, or to work on the C# compiler team. I realized that it came down to breadth vs depth. On the XBOX team I could work on security systems one day, audio systems the next, video, networking, hardware interfacing, you name it. Sure, some people are experts, but everyone has to know a bit about everything. On the C# compiler team I could dive into one language and one compiler and really understand the whole thing in depth.

I gave it a lot of thought and decided that I was more tempermentally suited to being an expert on one thing rather than a dilettante at many. That was a good choice for me, but it might not be for you. Some people are highly successful knowing a little bit of everything.

My advice therefore is to turn the question around. Figure out what kind of person you are, and then see if your company has opportunities for someone like you. If not, find one that does.

Title: Should I focus on being deep or broad


问:
Does streaming video pass through the website's server when embedded with javascript from another site?
Not sure how else to phrase this question, so my apologies if it's been asked before.

We use Brightcove for streaming video. They offer an option to embed one of their players on your webpage using Javascript embed code.

From a high-level standpoint, when the a user types in the URL of our webpage, that call hits our server, which sends the page back to the user's browser to render. If the page has the Brightcove embed Javascript on it, which happens?...

Javascript request goes to our web server, our web server goes to Brightcove's servers for the video stream, Brightcove's servers send the video stream to us, and we send it down to the user's browser.  OR...

Javascript request goes to Brightcove's servers for the stream, and Brightcove's servers send the video stream back to the user's browser (no video bandwidth needed from our web server).

We're assuming the latter is true, but we want to double check?

答: This is JavaScript. Your server's not involved that much. If the embedding is done in pure JavaScript without calls you your server, then the video should go straight to the User's browser.</p>


问:
Why do schools teach arrays over List?
Most of the assignments in my school for the initial programming classes required me to use arrays. I work full time now, and I never used an array for any project that I have worked on. Even in the exisiting projects I never saw the use of arrays anywhere. In my opinion, List is easier to use and is a standard. Why do professors tell students to use arrays in their assignments? Is it just so that students understand the basics? </p>

<p>Since most of the universities teach Java, this question is specific to Java. </p>

答:
Because arrays teach concepts like indexing and bounds, two fundamentally important concepts in computer programming.

Lists are not a "standard." There is a wide variety of problem spaces for which arrays are a perfect fit.

Title: Why do schools teach arrays over List?


问:
Decorater pattern or strategy pattern
I'm constructing a c# serverside application and I'm trying to do this in a way it can easily be maintained aswell as extended if needed.

So what we have is 4 different requests that need to be done (SOAP, HTTPREQUEST and so on). These are then to be combined with a chunk of different actions like Importing/Exporting/Updating.

What I'm thinking is that every request should be a strategy, much like the switching algorithms description for the strategy pattern. Then I want to extend the strategy with a decorator, adding new functionality to the request. Is there a need to contain this in a separate class(SoapRequest_Import/HTTPRequest_Update) or how should I think? Last one about containing everything in a class seems to take away the flexibility?

So with that said, am I wrong?
First question, is this done better with each of the patterns or is it okay to combine them. I was thinking strategies for the different clients, and decorators for the commands(or added functionalites). Or am I just overdoing this?

Lastly how would it look codewise if I did combine them. I do understand that I need at least one interface for the decorators. Do I need one for the strategies too?

答:
Stop thinking in terms of specific patterns. At least stop looking for places to apply patterns. Start thinking in terms of separation of concerns, and if that leads you back to a pattern, so be it.

You have two different groups of concerns there. The communication interfaces (Http, Soap, etc) and the data interfaces (Import, Export, Update, etc). Your goal should be to separate those concerns as completely as possible.

That is, imagine that you need to add 100 more communication protocols and 100 more data actions. Would it be better if you could do that by writing 200 more classes or would you expect to have to write 10,000 classes? If you're answering "10,000" then you're thinking about it all wrong.

So what you need is a framework that hooks everything together. Take messages from some kind of communication protocol, without knowing which protocol, and route these messages into actions that write to a data source, without ever knowing where the message is coming from or why it has been sent to this action.

Now, stretch your mind a little bit and this is starting to sound like a problem that's already been solved.

Data Source = Model

Communications protocols = View

Actions = Controller

Routing = well ... routing

Take a look at MVC frameworks. One of them may actually suit all your needs, or at least allow you to extend the framework to suit your needs. If not then look at the patterns used by an existing framework, see what you can learn and reapply in your own framework.

In places, I'm sure, you will recognise all sorts of GoF patterns. I'm certain there will be adapters, factories, maybe strategies. But the overall problem you're trying to solve is a problem that MVC at least partly resolves (for example, you can route web page requests and Json requests to the same methods in a controller).

So that would probably be a good place to start researching. But, ultimately, the problem you're trying to solve is separation of concerns, so that the extension of one concern doesn't heavily affect existing code in the other concern.

So keep that in mind throughout.

Title: Decorater pattern or strategy pattern


答:
They probably wanted to start with the data structure that most accurately represents how a computer works, so you're familiar with the fundamentals before they start introducing higher-level abstractions like Lists which make it easier to work with. Otherwise you'd have no way of understanding why a certain structure or algorithm is slow/fast for some operations and not others; if computer memory was actually made out of linked lists the world would be a very different place.

For much the same reason, my first programming class at college was in C, and the rest of the classes were all in C++, Java and other languages. It's not that C is somehow better or easier, it's that C (and Array) hides nothing from you.

Title: Why do schools teach arrays over List?

Body:
Most of the assignments in my school for the initial programming classes required me to use arrays. I work full time now, and I never used an array for any project that I have worked on. Even in the exisiting projects I never saw the use of arrays anywhere. In my opinion, List is easier to use and is a standard. Why do professors tell students to use arrays in their assignments? Is it just so that students understand the basics? </p>

<p>Since most of the universities teach Java, this question is specific to Java. </p>


问:
Calculating winning probability for 2 teams using their history?
So I'm working on this project where I have a database full of team winning history. For example let's say these are all football teams. Every match has 2 participants (2 teams) and always a winner.

Now I'm trying to make a script that actually calculates the winning probability using this info but I'm having a hard time trying to figure out a proper algoritm for this to actually predict effectively.

To make this more clear, let's make an example. We have two teams playing against each other: team 1 and team 2. Now the easiest way to calculate something would be to check if those two exact teams have ever played before and what were the results. For example if team 1 once beat team 2 and then in another game team 2 instead was the winner, then the probability for this game would be 50-50.

But I'd like to make this a little more complicated than that. For example, let's say there are three teams: team 1, team 2 and team 3. This is the match history for those teams:

team 1 beats team 2

team 2 beats team 3

And now we have a match that's team 1 vs team 3. And looking at the history, we can calculate that team 3 is very likely going to lose.

So I guess my question is, how does one code such an algorithm? I'm not looking for code snippets but instead a logical approach for these algorithms. If you have any code examples I'd be happy to look at those as well. I'm programming this in PHP myself but the snippets can be in any language. And also I'm looking for more algorithm ideas if anyone has any.

Thanks in advance!

答:
Why reinvent the wheel? Try ELO rating system - it was developed for exactly this purpose, and is best known for being used to rate chess players, although not exclusively. And it stood the test of time, to be sure.

As for calculating the probability that player (or team) A defeats B, look under http://en.wikipedia.org/wiki/Elo_rating_system#Mathematical_details for a formula.

Here's a piece of ready-made code that implements ELO: https://github.com/Chovanec/elo-rating

It's in PHP, since you mention it specifically, but I'm sure you could find something similar for every major language.

Note that I have not tested it and I'm in no way affiliated with the author.


问:
Best algorithm for "ACM ICPC Team"
I have this problem (complete description):

There is a list of persons N and M topics.

I have to find out the maximum number of topics a 2-person team can know. And also find out how many teams can know that maximum number of topics.

2<= N <= 500

1<= M <= 500

Ex.

Rows are persons, columns are topics.

If there is 1 the person know that topic, 0 otherwise.

```<code>10101
11100
11010
00101
</code>```

The result are 5,2

My algorithm is a bruteforce implementation, I think the complexity is O(n^3)

```<code>vector<bitset<501>> v;
int nMax = 0;
int nMaxCounter = 0;
for(int i=0; i<N; i++) {
    for(int j=i+1; j<N; j++){
        bitset<501> t = v[i] | v[j];
        if(t.count() > nMax) {//t.count() -> returns the number of bits set to true
            nMax = t.count();
            nMaxCounter = 1;
        } else {
            if(t.count() == nMax)
                nMaxCounter++;
        }
    }
}

cout<<nMax<<endl;
cout<<nMaxCounter<<endl;
</code>```

First question:

Is the complexity O(n^3) ?

Second question

Do you are able to find a better algorithm?

答:
1) Let's assume that t.count() is a linear-time operation with respect to the size of the bitset (it probably isn't on real hardware, but ignore that). Then it would be correct to say that the algorithm is O(M*N^2), for the obvious reason that you have an M-iteration-loop (t.count()) inside an N-iteration-loop inside an N-iteration-loop. That might be equivalent to O(n^3) if you chose a somewhat awkward definition of n, but since your problem size is already defined in terms of two different variables there's not much point trying to smush them into one.

2) In general, you can only beat the brute force solution to an algorithm if checking one or more solutions lets you "rule out" other solutions you haven't checked yet. For example, binary search beats linear search because after checking the middle element, you can rule out half of the list without checking all the elements individually. With this problem, unless your input is in some sense "pre-sorted", I don't see any way of getting around the need to check every single pair, so no I cannot find a better algorithm (in terms of time complexity class).

Title: Best algorithm for "ACM ICPC Team"


问:
What features would you like to have in PHP?
Since it's the holiday season now and everybody's making wishes, I wonder - which language features you would wish PHP would have added? I am interested in some practical suggestions/wishes for the language. By practical I mean:

Something that can be practically done (not: "I wish PHP would guess what my code means and fix bugs for me" or "I wish any code would execute under 5ms")

Something that doesn't require changing PHP into another language (not: "I wish they'd drop $ signs and use space instead of braces" or "I wish PHP were compiled, statically typed and had # in it's name")

Something that would not require breaking all the existing code (not: "Let's rename 500 functions and change parameter order for them")

Something that does change the language or some interesting aspect of it (not: "I wish there was extension to support for XYZ protocol" or "I wish bug #12345 were finally fixed")

Something that is more than a rant (not: "I wish PHP wouldn't suck so badly")

Anybody has any good wishes?

Mod edit: Stanislav Malyshev is a core PHP developer.

答:
I'd one day like to see data type,
however -- I also like the simplicty
of not having to deal with data
types, this is a double edged sword
for me.

namespaces!

Overload function calls with different method signatures

Better support for unit testing and code injection, PHPUnit is an amazing tool, as well Symfony code injection framework does wonders... however they all come with their own learning curve.


问:
Is this architecture feasible? Maintaining two tcp sockets open from the server to two clients in order to relay events between the two
Basically I need to keep track of two clients and need pass messages between the two. I am thinking of creating a tcp connection between the clients and the server and using the server to manage this connection between the two and relay messages as needed. I need to know if my architecture is realistic in the sense that it needs to be able to scale to hold thousands of these relays.</p>

答:
Yes, this is feasible. In fact there are numerous real-world examples (more complex, but the same core idea) that prove it.

For example, any instant messaging network that is not P2P (e.g. Lync) does precisely this. Modern multiplayer games are similar, often using UDP/IP instead of TCP/IP. IRC servers do this.

It is a solid high-level design, but the devils are always in the details. How do you efficiently track many users? You say you want this to scale. You will likely need to consider concurrent data structures to track user connections that perform well under high load.


问:
What level of a computer system does firmware run on?
In the following levels of a computer system, on which level does firmware (e.g. BIOS) run?

I guess:

BIOS doesn't depend on OS, so it must run on some level lower than level 3.

BIOS is written in machine language, so is it a program running no  level 2?

Thanks.

答:
I'm not quite sure if the image is accurate enough to expose such details as Firmware. For example the top 2 levels usually happen well before rest, the OS is not interpreting the program in usual sense of the word... unless we mean loader etc.

In the end the model does not have straightforward mapping to a 'real life' computer - I would even consider it more as a model of computation contracts then of computer as physical machine. There are some gaps between those two - for example virtually no OS is interpreting the program - it's done in silicon/by microcode directly while OS is handling error conditions and syscalls with ISA sitting in between microcode and both OS and program.

Depending on what you mean by of firmware, you may get different answers:

The firmware of various components may be executed on their chips. They roughly corresponds to levels 1 to 5 of 'computers' (i.e. processors) located on the harddrives etc.

The firmware can be used as a synonym of OS on mobile phones. In this sense it corresponds to Level 3.

Microcode is kind of firmware so it corresponds to Level 2.

Finally the firmware such as UEFI or BIOS can mean various functions provided for OS in the address space. They would correspond to Level 2(a) while true OS would correspond to Level 2(b)

Conceptually the firmware would belong to Level 1 if we treat it as model of computation and not of computer.


答:
The answers above are great, but I have another in mind. Java's main() method means that students encounter basic arrays very early on, often as soon as the first day of class. Why?

```<code>public static void main(String[] args)
</code>```

It's the first thing you're going to have to deal with to write Hello World and beyond. (I've seen some courses use teaching IDEs like BlueJ at first, which allow you to point-and-click to run arbitrary methods, but we'll set those aside...) While it might be worthwhile to handwave over some of these keywords for a little while, sooner or later most teachers are going to want to explain them. Indeed, a classic beginner-level test question is to ask students to give the meaning of each keyword in a basic Hello World program. And what do we find as part of our main method signature? An array (The reason for that is, in part, historical. ArrayList didn't exist in Java 1.0). Arrays are part of that basic set of knowledge. List is not.

That said, it's not that uncommon for classes to introduce ArrayList a little later into the course, especially once objects and their use have been covered. Even the AP Computer Science curriculum for Java includes ArrayList (I know it used to, and Google seems to indicate that it still does), although it ignores the fact that ArrayList implements List and the rest of the Collections Framework.

Finally, it's my experience that university CS programs use Java as a means to exploring CS and programming concepts rather than to teach students how to become good Java developers. Some programs may be more focused on churning out professional developers while others focus more on theory, but in either case, there's a lot to learn about how to use Java in real professional work that won't be taught in most college curricula. This ranges from design patterns and techniques like those in Effective Java to frameworks like Spring, Hibernate, or JUnit, or even more common things like JSP or JDBC. With that philosophy in mind, emphasizing arrays over the more commonly used ArrayList makes a little more sense.

Title: Why do schools teach arrays over List?

Body:
The answers above are great, but I have another in mind. Java's main() method means that students encounter basic arrays very early on, often as soon as the first day of class. Why?

public static void main(String[] args)

It's the first thing you're going to have to deal with to write Hello World and beyond. (I've seen some courses use teaching IDEs like BlueJ at first, which allow you to point-and-click to run arbitrary methods, but we'll set those aside...) While it might be worthwhile to handwave over some of these keywords for a little while, sooner or later most teachers are going to want to explain them. Indeed, a classic beginner-level test question is to ask students to give the meaning of each keyword in a basic Hello World program. And what do we find as part of our main method signature? An array (The reason for that is, in part, historical. ArrayList didn't exist in Java 1.0). Arrays are part of that basic set of knowledge. List is not.

That said, it's not that uncommon for classes to introduce ArrayList a little later into the course, especially once objects and their use have been covered. Even the AP Computer Science curriculum for Java includes ArrayList (I know it used to, and Google seems to indicate that it still does), although it ignores the fact that ArrayList implements List and the rest of the Collections Framework.

Finally, it's my experience that university CS programs use Java as a means to exploring CS and programming concepts rather than to teach students how to become good Java developers. Some programs may be more focused on churning out professional developers while others focus more on theory, but in either case, there's a lot to learn about how to use Java in real professional work that won't be taught in most college curricula. This ranges from design patterns and techniques like those in Effective Java to frameworks like Spring, Hibernate, or JUnit, or even more common things like JSP or JDBC. With that philosophy in mind, emphasizing arrays over the more commonly used ArrayList makes a little more sense.


答: Firmware doesn't really fit into that hierarchy. Firmware is really just a place where a library of machine code (in the sense of level 2) is stored. Often the code stored in firmware is for the management of the motherboard and IO channels, but it need not be. I've got an old Tandy laptop that has Multiplan, a text editor, a BASIC interpreter, and a calendar in firmware.</p>

Title: What level of a computer system does firmware run on?

Body:
In the following levels of a computer system, on which level does firmware (e.g. BIOS) run?

I guess:

BIOS doesn't depend on OS, so it must run on some level lower than level 3.

BIOS is written in machine language, so is it a program running no  level 2?

Thanks.


问:
Black box or white box testing - which do you do first?
On a very small team, where the black box and white box testing is done by the same person, which should the tester do first?</p>

答:
If you want to have a good test cycle, you should have different people doing Both:

A developer focused mainly on white-box testing knows what has changed in the code recently, which areas are more complex (and therefore likely to break), etc and can focus efforts appropriately in these areas most likely to introduce new defects.

On the other hand, a QA tester focused on black-box testing can more easily approach testing like an end user. Without any internal knowledge of the code, they can take a fresh approach and are not biased by the knowledge of how different parts of the solution are implemented. They will catch bugs that the developer may have overlooked, or regressions from code changes that accidentally broke other areas of the application.

To answer your question, the white-box testing should be done first. But you really need to have a different person doing the black box testing if you want to it to be effective.


答:
Firmware is software that runs on Read-Only Memory (ROM) or something similar.  Firmware is firmer than software because software can be changed somewhere along the chain from where it is stored in some Read-Write media and loaded into writable memory and executed from there.

Firmware cannot work as in-place self-modifying code.  Software can run as in-place, self-modifying code.

If you can think of a ROM and as some form of programmable hardware, then "firmware" is a form of hardware.  If you can think of an FPGA as some form of programmable hardware, then you can think of FPGA Verilog and the like as a form of "firmware".

As time marches on, the lines between software, firmware, hardware get blurred more and more.


问:
keeping of all javascript functions in one place
In php website I am using different javascript functions in different pages for example page a calls functions 1,2,3  and page b calls functions 2, 4, 6 and page c calls functions 3, 6
can I place all javascript functions in one file</p>

答:
Yes. In HTML you can include an external Javascript file like this:

```<code><script src="js/six_util_functions.js"></script>
</code>```

So as long as your PHP outputs that in the right place, you should have no trouble calling functions 1-6 from anywhere in your HTML pages.

Body:
Yes. In HTML you can include an external Javascript file like this:

<script src="js/six_util_functions.js"></script>

So as long as your PHP outputs that in the right place, you should have no trouble calling functions 1-6 from anywhere in your HTML pages.


问:
Points to Understand Architecture of an Application/System
We are working on a knowledge transition of multiple applications (around 700). To make the process easy, I am preparing a list of key points we need to consdier for understanding the architecture of each application like below.

Why the list is important is once the transition is over, we are
  trying to integrate/rewrite/refactor these applications.

Technology Stack (
a.  Programming languages
b.  Tools used
c.  Third party components)

Database (
a.  Data model
b.  Data flow
c.   Clustering)

Interfaces with other applications

Dependencies

NFR

Anyone has any exclusive check list for this or enrich the above list?

答:
If you built a house and you want to describe it to someone, would you talk about what kind of flooring material you used? About what kind of hammer and tools you used? About the plumbing?

You might, but none of this has to do with architecture.

Architecture is about what kind of rooms there are, where they are and how they are connected.

So the first thing you should talk about when describing your application is what it does. What its modules are and what those individual modules do. Then you should talk about how those modules relate to and interact with each other. That's its architecture.

The next thing is to talk about how the application and its modules work.

And the last thing is to talk about what tools you used to make that.

Your list so far only mentions tools and implementation details. I'm afraid none of those has to do with the architecture of the system.


问:
have we come full circle with microservices, back to very old school approaches?
In terms of software architecture and design, how do microservices "stack up" (pun intended) against middleware?  I'm coming from Java, and it seems like as you move away from straight REST as an API, and abstract away different layers and connection parameters, at least in Java, you've almost come full circle back to some very old school ideas.  We've come back to virtualization...wheras the JVM is already virtual.

In an agnostic way, you can, and I would argue the advantages to, abstracting a RESTful API to CORBA.  Or, in a more java-centric way, JMS or MDB.

At one time EJB was a big deal in Java, then it was recognized to a bit of a cluster eff, but, now, are we back to the beginning?

Or, do microservices offer something which CORBA, or even better, MDB, lacks?  When I read (TLDR) Martin Fowler explaining microservices, it strikes me as a good solution to a bad problem, if you will.  Or rather, a closed minded approach which introduces a level of complexity only pushing the problem around.  If the services truly are micro, and are numerous, then each has a dollar cost to run and maintain it.

Furthermore, if one microservice amongst many changes its API, then everything depending on that service breaks.  It doesn't seem loosely coupled, it seems the opposite of agile.  Or am I misusing those words?

Of course, there are an indeterminate amount of choices between these extremes.

Shark versus Gorilla...go!  (For the pedantic, that's meant to be ironic, and isn't my intention at all.  The question is meant to be taken at face value.  If the question can be improved, please do so, or comment and I'll fix.)

Envision a multitude of microservices running in docker, all on one machine, talking to each other...madness.  Difficult to maintain or admin, and next to impossible to ever change anything because any change will cascade and cause unforeseeable errors.  How is it somehow better that these services are scattered across different machines?  And, if they're distributed, then surely some very, very old school techniques have solved, at least to a degree, distributed computing.

Why is horizontal scaling so prevalent, or at least desirable?

答:
Every software development technique we've ever invented has been about managing complexity somehow. A huge portion of them have been and continue to be about abstraction, encapsulation and loose coupling. Microservices are yet another way of doing those things, which is probably why it resembles a lot of older techniques at a high theoretical level, but that doesn't make it any less useful or relevant.

Regarding loose coupling, I think you've misunderstood the goal a bit. If task A needs to call task B, there's never going to be way to make A and B 100% decoupled. Never going to happen. What you can do is ensure that, if task B calls task C, then task C should never have to worry about changes to A. If these three tasks are all linked together in one big blob, passing structs to each other, then there's a significant chance they'll all have to change if any one of them does. But if all three are microservices, then you're basically guaranteed that a change to A will only force B to update (unless it's such a huge change to A's core functionality that you probably should've made it a brand new service). This is especially true if all microservice updates are done in a backwards compatible way, which they should be.

Regarding the agile comment, I can tell you from personal experience that our microservice-y code plays far better with agile than our "linked into a big blob" code. In the latter, whenever someone fixes a bug in a low level function, he literally has to send the entire R&D department an e-mail saying "please relink your tasks or they'll all crash on Friday". We get a couple of these every week. If his code was in a microservice, we would all automagically benefit from the fix as soon as he deployed a new version.

I don't fully understand the comment about COBRA and MDB, as they don't seem to be software architectures but rather components of one; to my understanding they're potential ways of defining your microservices' messaging protocols and/or implementing said microservices, not in and of themselves alternatives to microservices.