问:
What document/artifact should alert me when an old requirement changes the scope of new one?
I developed a software application a year ago, I delivered it with a simple documentation.

For example, it has an special and complicated login system as requirement.

Now the customer calls and ask me to change the application for support a new kind of users, then I review (quickly) the tables, views and code that I need to change to deliver the new requirement support a new kind of users and give an estimate time, but I forgot completely that I need to refactor the special and complicated login system.

This is a big mistake because the time that I will spend in the refactor of the special and complicated login system will not be paid.

What errors have I made? and how can I avoid it in the future?
A trace ability matrix gives me relations between test cases and requirements, but I need the track of old requirements in relation with new ones.

答:
Contract matters

This is a big mistake because the time that I will spend [...] will not be paid

Actually, the big mistake is that your contract makes it possible that you spend your time working for free. It doesn't matter if you are solving a bug or learning a technology required for a new project: the customer has to pay for the time you spend.

You should not work for free. That's as simple as that. It makes you feel bad, and it encourages your customer to think about you as a guy who works for free anyway, and so who don't have to be particularly respected, or paid at all, after all. As soon as your customer knows that you spend one hour working for free, your relation is screwed.

This is also why it is essential to have a contract written by an actual lawyer specialized in software development contracts.

Technical estimates

What errors I did, and how can I avoid it in the future.

Technically speaking, you error was to give an estimate too quickly. You may have spent maybe a few more hours studying the impact, and probably find the relation between the data and the authentication.

But such mistakes happen anyway, so it's not a big fault from the technical point of view.

This is not very different from cases where you give an estimate of two weeks for a task, and a week after you started the task, you find that it requires much more work. Then, you simply send to the stakeholders (would it be your manager or your customer) the readjusted estimate which takes in account the things you have discovered meanwhile.

You may have made a mistake of giving a very precise estimate. If you tell that a change will take “eighty hours”, this is not the same thing as “ten days”, and not the same thing as “two weeks”. Moreover, estimates are often represented as a range or contain a hint about the precision:

The task will take from 4 to 9 days.

or:

The task will take 16 days ± 4 days.

This makes the progressive readjustment of the estimate more intuitive.

Another important aspect is that you should be able to say no. This applies specifically to those two types of questions:

“Do you know how long this task will take?”

If you don't know how long the task will take, don't tell “Three weeks” just to get rid of the person.

“Can you make an effort to deliver it faster?”

If you answer “Yes”, it means either that your last estimate was wrong (in which case, why would you make wrong estimates in the first place?), or that you know how to be more productive, but don't do it unless specifically asked, which doesn't sound very professional either.

It's all about leverage

But, again, the most important thing is how do you interact with your customer, which boils down to two things: what contract says and what is your leverage.

For instance, compare this message:

On February 7th, I sent you an estimate of 8 days ± 3 days for the task of migrating the bottom menu to the new data source. It appears that the task also requires to make changes in the top menu, since both partially rely on the same code. Given those new elements, the updated estimate is 11 days ± 2 days.

with this one:

On February 7th, I sent you an estimate of 8 days ± 3 days for the task of migrating the bottom menu to the new data source. It appears that the task is much more difficult than I thought, so I'm not sure I'll be able to release the changes on time. Can you, please, accord me three additional days for this task?

The second one sucks. It shows that the developer has no leverage whatsoever. It doesn't give any estimate, but barely begging for extra time. It feels like the developer screwed the original estimate, and feels bad about it. The first message is purely informal: here's an estimate, I don't care what you think about it and I don't need your approval, since our contract doesn't require your approval in this case. My early estimate was correct, and the later one just takes in account additional info. Nothing more.


问:
When estimating with a fresh team on a new project, is there a reason not to use default velocity for estimating?
Generally when estimating using an Agile points system on an experienced project team, the points have meaning relative based on past experience - that take into account:

understanding of the business domain

skill and experience of the team

obvious traps in the technical environment (service integrations and environment issues)

So based on the past velocity of the team - you can forecast how long a project is likely to take.

Now imagine a completely new team thrown into a new business problem domain, new technical environment, with unknown skill levels. You can estimate with points, but you have no velocity track record.

Now you can augment this lack of historic velocity with a 'default velocity' - with the caveats that the three factors above are unknown, and so your tolerance for delivery date is much higher.

But is there an agile reason not to do this?

My question is: When estimating with a fresh team on a new project, is there a reason not to use default velocity for estimating?

答:
I don't know what a default velocity is.

But...

You got to start somewhere.

New team on a new project. Everyone estimates to the best of their knowledge, and with short iterations (say 1-week sprints) by 3rd week you should have a vastly improved understanding of your velocity. First 2 weeks will be a mess.

ContentLicense: CC BY-SA 3.0


问:
How do you approach transitive dependency conflicts that are only known at run-time?
How do you normally approach transitive dependency issues that occur at run-time in large software projects?

For the past three weeks, I have been trying to start a component of a large piece of software within another component of the software, but it intermittently dies due to transitive dependency issues that are only known at run-time.

By transitive dependency issues, I mean that certain dependencies of a given project's dependencies collide with other dependencies at run-time, causing instability, or instant failure.

There are hundreds, upon hundreds of dependencies in use, and there are approximately 50 sub-projects associated with the tool that are worked on in isolation by other teams, where all modules have deeply nested dependencies between each other. Nobody knows what all of the sub-projects are used for, given the scale, and complexity of the project.

In this situation, would you try to generate a visual representation of the DAG for each of the dependencies of the affected component, and attempt to determine where collisions may occur at run-time? I have no control over how dependencies are managed in other sub-projects, and cannot change any Java code that has been written by other developers

The solutions I've come up with only work for an hour, or two, and then they stop working due to changes in upstream components. An example of an upstream component is an artifact on which the project that I am working on is dependent on which is built at an earlier stage in the CI pipeline.

At other's requests, I am going to include information on what technology is being used, at the risk of having the question closed for providing too much information, or the body getting too long:

Maven is used for dependency management; and

Spring is used as a DI container;

Most of the dependency issues involve overlapping bean contexts as a result of the contexts of other modules being loaded at run-time

The product works properly, and there are smorgasbords of unit tests, and integration tests to elude to the functional correctness of the program

In general, I am looking for a language-agnostic approach to identifying ways of resolving dependency conflicts without enumerating through all possible combinations of a given project's dependencies.

I cannot re-architect the project, add additional quality gates, push for paradigm shifts across the company, or switch languages as a resolution.

答:
I have never worked with Maven or Spring, but to give you a generic answer to a generic question: when it comes to dependency issues, your system should be designed to detect them at the earliest possible point in time, and when those issues are detected, they should be signaled immediately, including their possible cause.

Ideally, this point in time is not at "production run time". The best point in time is "build time", but that seems to be impossible in your case. So the second best option are run time tests. You told us there are "integration tests", but as they do not detect the dependency issues, they seem to be incomplete, or they do not test dependency collisions in general. That's where you should start trying to solve the problem.

Moreover, to make the tests more effective, your components need to "fail fast" when a dependency issue arises. That means, as soon as a dependency is resolved and a component is loaded, potential dependency collisions should be checked and signaled immediately. If the system first runs for an hour before a collision will be detected, it becomes very hard to spot the cause for the problem. I do not know if Maven/Spring already provides you with an in-built "fail fast" strategy, but if this is not the case, try to think in that direction.

To mitigate problems in production, your system should be designed not to die completely when a dependency collision occurs with a less important sub-component involved. The failure should not be masked, of course, but the system should ideally reject the loading of that component, log and/or signal the problem and stay in a stable state. When the component is loaded first, the system becomes unstable and you detect the issue only afterwards, then you will probably have to shutdown and restart the system completely, which I guess is something you better want to avoid.

For example, if your system is a Web shop, and your submodule for "newsletter subscription" cannot be loaded for some hours, that's something which might be easier tolerated as if the whole shop does not work any more.

Finally, this might not be an option in your case, but if components can be made run in better isolation against each other, and if that can avoid dependency collisions, that may be an approach worth to think about.


答:
It may be possible to solve your problem using custom classloaders to give each module in the application its own execution environment.

Basically, you would define a core environment that consists of a small kernel of the application, along with whatever dependencies are universally agreed on and all the interfaces that are necessary for modules to communicate with each other.  Then, each module you load gets its own classloader that can access (1) classes from the runtime environment, (2) classes from the application core, and (3) classes from that module and its direct dependencies. All inter-module communication goes through interfaces defined in the core so that no module directly depends on another.

This technique is used in application servers to allow applications to have dependencies that would otherwise clash, so you can see a working implementation of the technique, for example, in Tomcat (and, if you're lucky, you may be able to use Tomcat's implementation with little change).

Title: How do you approach transitive dependency conflicts that are only known at run-time?

Body:
How do you normally approach transitive dependency issues that occur at run-time in large software projects?

For the past three weeks, I have been trying to start a component of a large piece of software within another component of the software, but it intermittently dies due to transitive dependency issues that are only known at run-time.

By transitive dependency issues, I mean that certain dependencies of a given project's dependencies collide with other dependencies at run-time, causing instability, or instant failure.

There are hundreds, upon hundreds of dependencies in use, and there are approximately 50 sub-projects associated with the tool that are worked on in isolation by other teams, where all modules have deeply nested dependencies between each other. Nobody knows what all of the sub-projects are used for, given the scale, and complexity of the project.

In this situation, would you try to generate a visual representation of the DAG for each of the dependencies of the affected component, and attempt to determine where collisions may occur at run-time? I have no control over how dependencies are managed in other sub-projects, and cannot change any Java code that has been written by other developers

The solutions I've come up with only work for an hour, or two, and then they stop working due to changes in upstream components. An example of an upstream component is an artifact on which the project that I am working on is dependent on which is built at an earlier stage in the CI pipeline.

At other's requests, I am going to include information on what technology is being used, at the risk of having the question closed for providing too much information, or the body getting too long:

Maven is used for dependency management; and

Spring is used as a DI container;

Most of the dependency issues involve overlapping bean contexts as a result of the contexts of other modules being loaded at run-time

The product works properly, and there are smorgasbords of unit tests, and integration tests to elude to the functional correctness of the program

In general, I am looking for a language-agnostic approach to identifying ways of resolving dependency conflicts without enumerating through all possible combinations of a given project's dependencies.

I cannot re-architect the project, add additional quality gates, push for paradigm shifts across the company, or switch languages as a resolution.


答:
This is a big mistake because the time that I will spend in the refactor of the special and complicated login system will not be paid.

There is a big red flag showing you what has gone wrong.  The problem was embedded in this project before any changes were requested by the client, they were there before the code was even written...

Authentication and permissions are very well-known (and solved) problems even for exceptionally complex sets of requirements (2-factor authentication, time-locking, location restrictions for example).

The next step is to prevent recurrences...

You can reflect on the original development process and examine your design documents/process to understand the factors which led to those components being tightly-coupled and warning signs to look for.  Generally, when a common function is considered 'special' it's a good indication that the situation hasn't been fully understood for example.

Instead of taking this situation as a 'cost', take it as a wake-up call that you or whoever worked on the project might benefit from some professional development to better understand the development process - it's something good developers do all the time and using that knowledge to make sure that future projects are more amenable to extension and that code is easier to test/fix.  It has given you a chance to produce better code in the future.

As starting points the Single Responsibility Principle (SRP) and Separation of Concerns (SoC) should have kept unrelated code apart and mean that you shouldn't need complicated matrices of dependencies in the future.

Grab a couple of books on code quality and spend some time on them, it will not be wasted, and a few days of extra dev time is cheap compared to some projects that lose months due to issues that could have been avoided.

Title: What document/artifact should alert me when an old requirement changes the scope of new one?

Body:
I developed a software application a year ago, I delivered it with a simple documentation.

For example, it has an special and complicated login system as requirement.

Now the customer calls and ask me to change the application for support a new kind of users, then I review (quickly) the tables, views and code that I need to change to deliver the new requirement support a new kind of users and give an estimate time, but I forgot completely that I need to refactor the special and complicated login system.

This is a big mistake because the time that I will spend in the refactor of the special and complicated login system will not be paid.

What errors have I made? and how can I avoid it in the future?
A trace ability matrix gives me relations between test cases and requirements, but I need the track of old requirements in relation with new ones.


问:
Should create and edit be two separate user stories?
I often come across situations where creating and editing actions are very similar, but they are not exactly the same story. So should they be handled as separate user stories, or as one? For example, I could have:

Option A:

US A1: As a system administrator, I want to create new user accounts so that I can specify what services the users can access, and the users can access the system.

US A2: As a system administrator, I want to manage user accounts so that I can change what services the users can access and reset their passwords.

vs

Option B:

US B1: As a system administrator, I want to create and manage user accounts so that I can specify what services the users can access, and ensure that the users can make use of the system.

Is approach A or B correct, or is it simply a matter of personal preference or pragmatism depending on the complexity of the create vs edit functionality?

答:
I think that Option A, with separate user stories, would be preferred.

User stories are requirements. There are a set of characteristics of a good requirement that tend to be well accepted. Option A ensures that your user stories are cohesive (addresses one and only one thing), atomic (does not contain conjunctions), and more easily verifiable than Option B.

From an estimation standpoint, it's probably easier to estimate each one individually by walking through the workflows and use cases. You'll probably see commonalities and/or dependencies between them (for example, you need to create one before you can edit one), but you can give more realistic estimates if you break them up into smaller pieces.

From an implementation standpoint, though, you would likely need to deliver both pieces of functionality together to make a release actually useful to an end user. That can be managed in the iteration planning, though. Depending on your release cycle, they may end up in one release but in different iterations, if a release doesn't happen after every iteration. It's all up to planning and management.


答:
TL;DR They ought to be two separate, but related requirements.

The risk in running them as separate requirements is that you'll have duplicated code for the associated UI and underlying services.  But the risk in combining them as a single requirement is that the edit path has a slightly different setup to it.

A create path would look something like this:

Authorized user (AU) logs in to the system, opens create user panel

AU enters in and verifies details for new user

AU submits create request to system

System validates that business rules regarding user accounts are met

Systems stores user account (likely an insert statement)

An edit path would look something like this:

Authorized user (AU) logs in to the system, opens edit user panel

AU requests user details to be retrieved

System retrieves user details and presents information to AU

AU adjusts details for new user

AU submits edit request to system

System validates that business rules regarding user accounts are met

Systems stores user account (likely an update statement)

There's some obvious re-use with the create and edit user panels.  Likewise, the same routine to check business rules against the user account could be re-used.

But the create path does not need to retrieve existing user details, and it's possible that the create path will have slightly different prompts such as with password setup.

The final decision of which path to follow depends upon how your development team works.  From my experience, having two separate user stories does a better job at representing the workload involved to project management.  And generally the two tasks would be assigned to the same person which would reduce the need for additional communication / coordination while working on the requirements.

Looking at the broader perspective when you have closely related user stories, you need to take a moment and briefly sketch out what's involved for each story.  If there is a significant difference between the stories, then I think you're better off using separate stories.  This helps make sure the significant difference isn't buried within the combined story.

Title: Should create and edit be two separate user stories?

Body:
I often come across situations where creating and editing actions are very similar, but they are not exactly the same story. So should they be handled as separate user stories, or as one? For example, I could have:

Option A:

US A1: As a system administrator, I want to create new user accounts so that I can specify what services the users can access, and the users can access the system.

US A2: As a system administrator, I want to manage user accounts so that I can change what services the users can access and reset their passwords.

vs

Option B:

US B1: As a system administrator, I want to create and manage user accounts so that I can specify what services the users can access, and ensure that the users can make use of the system.

Is approach A or B correct, or is it simply a matter of personal preference or pragmatism depending on the complexity of the create vs edit functionality?


答:
I think it really depends on the stories themselves, are you going to differentiate the process or administration of the two tasks?

I could envision a scenario where there really is no difference beyond whether or not you are creating a new record.  This could be done as a single story.

I could also envision a scenario when only certain admins can create an account, but a larger group of application or service admins might be able to update their portions of the user account.  This sounds like two(or more) user stories.


答:
The key thing to consider here is whether your stories are manageable chunks of work.

To be manageable they need to be:

Unambiguously defined

Fairly easy to estimate

Completable within a sprint

So, if you find that merging two stories somehow compromises any of the above points, then don't do it.

Personally, I prefer working with many small stories as I find it easier to estimate that way.  The trade-off is that you then need to be careful about the ordering of related or dependent stories in your sprint (a fairly trivial task).


问:
How many story points should you allocate in an initial sprint?
When first implementing Scrum within a team, how should you go about determining the amount of story points that are in an initial sprint when you have no idea of the team's velocity?

Should you base this on an estimate of hours and only use the points at a later stage?

答:
You don't rely exclusively on point estimates for sprint planning anyway. During planning, your velocity can help you to quickly "propose" a sprint plan and/or assist with your sanity check before making the final commitment; but, no matter how much velocity data you have, the team ultimately needs to commit to stories, not points.

Bear in mind, 5 x 1-point stories do not equal 1 x 5-point story for exceptionally small values of 1. They are only roughly equivalent for the purpose of long-term planning.

And that's where the primary value of the points comes into play: when you need to guesstimate when an epic or release can be completed, or whether you have too much on your plate for a scheduled release-date.

That said, a successful team will eventually find itself planning about the same number of points each sprint. But, there will be variances based on the particular stories in that sprint. A successful team can articulate during planning why some 5-point stories don't actually offset all 5 of the initially proposed 1-point stories ...

ContentLicense: CC BY-SA 2.5


问:
How to write a good exception message
I'm currently doing a code review and one of the things I'm noticing are the number of exceptions where the exception message just seems to reiterate where the exception occurred. e.g.

```<code>throw new Exception("BulletListControl: CreateChildControls failed.");
</code>```

All three items in this message I can work out from the rest of the exception. I know the class and method from the stack trace and I know it failed (because I've got an exception).

It got me thinking about what message I put in exception messages. First I create an exception class, if one does not already exist, for the general reason (e.g. PropertyNotFoundException - the why), and then when I throw it the message indicates what went wrong (e.g. "Unable to find property 'IDontExist' on Node 1234" - the what). The where is in the StackTrace. The when may end up in the log (if applicable). The how is for the developer to work out (and fix)

Do you have any other tips for throwing exceptions? Specifically with regard to the creating new types and the exception message.

答:
I'll direct my answer more to what comes after an exception: what's it good for and how should software behave, what should your users do with the exception?  A great technique I came across early in my career was to always report problems and errors in 3 parts: context, problem & solution.  Using this dicipline changes error handling enormously and makes the software vastly better for the operators to use.

Here's a few examples.

```<code>Context: Saving connection pooling configuration changes to disk.
Problem: Write permission denied on file '/xxx/yyy'.
Solution: Grant write permission to the file.
</code>```

In this case, the operator knows exactly what to do and to which file must be affected.  They also know that the connection pooling changes didn't take and should be repeated.

```<code>Context: Sending email to 'abc@xyz.com' regarding 'Blah'.
Problem: SMTP connection refused by server 'mail.xyz.com'.
Solution: Contact the mail server administrator to report a service problem.  The email will be sent later. You may want to tell 'abc@xyz.com' about this problem.
</code>```

I write server side systems and my operators are generally tech savvy first line support.  I would write the messages differently for desktop software that have a different audience but include the same information.

Several wonderful things happen if one uses this technique.  The software developer is often best placed to know how to solve the problems in their own code so encoding solutions in this way as you write the code is of massive benefit to end users who are at a disadvantage finding solutions since they are often missing information about what exactly the software was doing.  Anyone who has ever read an Oracle error message will know what I mean.

The second wonderful thing that comes to mind is when you find yourself trying to describe a solution in your exception and you're writing "Check X and if A then B else C".  This is a very clear and obvious sign that your exception is being checked in the wrong place.  You the programmer have the capacity to compare things in code so "if" statements should be run in code, why involve the user in something that can be automated?  Chances are it's from deeper in the code and someone has done the lazy thing and thrown IOException from any number of methods and caught potential errors from all of them in a block of calling code that cannot adequately describe what went wrong, what the specific context is and how to fix it.  This encourages you to write finer grain errors, catch and handle them in the right place in your code so that you can articulate properly the steps the operator should take.

At one company we had top notch operators who got to know the software really well and kept their own "run book" that augmented our error reporting and suggested solutions.  To recognise this the software started including wiki links to the run book in exceptions so that a basic explanation was available as well as links to more advanced discussion and observations by the operators over time.

If you've had the dicipline to try this technique, it becomes much more obvious what you should name your exceptions in code when creating your own.  NonRecoverableConfigurationReadFailedException becomes a bit of shorthand for what you're about to describe more fully to the operator.  I like being verbose and I think that will be easier for the next developer who touches my code to interpret.

Title: How to write a good exception message

Body:
I'll direct my answer more to what comes after an exception: what's it good for and how should software behave, what should your users do with the exception?  A great technique I came across early in my career was to always report problems and errors in 3 parts: context, problem & solution.  Using this dicipline changes error handling enormously and makes the software vastly better for the operators to use.

Here's a few examples.

Context: Saving connection pooling configuration changes to disk.
Problem: Write permission denied on file '/xxx/yyy'.
Solution: Grant write permission to the file.

In this case, the operator knows exactly what to do and to which file must be affected.  They also know that the connection pooling changes didn't take and should be repeated.

Context: Sending email to 'abc@xyz.com' regarding 'Blah'.
Problem: SMTP connection refused by server 'mail.xyz.com'.
Solution: Contact the mail server administrator to report a service problem.  The email will be sent later. You may want to tell 'abc@xyz.com' about this problem.

I write server side systems and my operators are generally tech savvy first line support.  I would write the messages differently for desktop software that have a different audience but include the same information.

Several wonderful things happen if one uses this technique.  The software developer is often best placed to know how to solve the problems in their own code so encoding solutions in this way as you write the code is of massive benefit to end users who are at a disadvantage finding solutions since they are often missing information about what exactly the software was doing.  Anyone who has ever read an Oracle error message will know what I mean.

The second wonderful thing that comes to mind is when you find yourself trying to describe a solution in your exception and you're writing "Check X and if A then B else C".  This is a very clear and obvious sign that your exception is being checked in the wrong place.  You the programmer have the capacity to compare things in code so "if" statements should be run in code, why involve the user in something that can be automated?  Chances are it's from deeper in the code and someone has done the lazy thing and thrown IOException from any number of methods and caught potential errors from all of them in a block of calling code that cannot adequately describe what went wrong, what the specific context is and how to fix it.  This encourages you to write finer grain errors, catch and handle them in the right place in your code so that you can articulate properly the steps the operator should take.

At one company we had top notch operators who got to know the software really well and kept their own "run book" that augmented our error reporting and suggested solutions.  To recognise this the software started including wiki links to the run book in exceptions so that a basic explanation was available as well as links to more advanced discussion and observations by the operators over time.

If you've had the dicipline to try this technique, it becomes much more obvious what you should name your exceptions in code when creating your own.  NonRecoverableConfigurationReadFailedException becomes a bit of shorthand for what you're about to describe more fully to the operator.  I like being verbose and I think that will be easier for the next developer who touches my code to interpret.


问:
Should the ternary operator be used outside of assignment statements?
Edit This isn't a question of whether or not the ternary operator is harmful. It's about whether or not there's a consensus about whether or not it should be used outside of assignment statements. /Edit

Based on a boolean, I want to call one of two different functions (with no return value). I wrote this bit of javascript:

```<code>(condition) ? doThis(arg) : doThat(arg)
</code>```

Which I think looks cleaner than writing out an if-else statement:

```<code>if(condition) {
    doThis(arg);
}
else {
    doThat(arg);
}
</code>```

My colleagues strongly believe ternary statements should only be used in assignment statements. I can't find style guides that discuss this, probably because languages like Java and C# don't allow this at all (their compilers require ternary operators to return a value). Should this be considered a bad use of the ternary statement? Why?

答: Generally speaking, the conditional operator is intended to make an if statement with a value. w = x ? y : z. Thus, if you're using it for side effects, it's counter-intuitive. Valid, but counter-intuitive; and remember that you're writing code for your teammates to read.


问:
Creating menu structure using DB - is that fine?
I have an application that basically consists of a lot of screen so user needs to navigate a lot (like go from A>B>C>D) etc.

I have been thinking how to implement this (mainly hold the structure of the menu) as it needs to be on-screen menu (custom, no menu strips etc.) and did not find any solution.

Now I realized I could use a database for that, which would allow me also to change strings later with no impact.

My idea would be to have a table for each level (1-5) with options available. Once the user selects an option, the program will select any items in the table (CurrentLevel+1) based on its ID. Seems really a good solution to me but I am not a programmer (rather than an analyst).

Or even I could use specific table names and hold the table name in a specific column, for example:

User selects Settings

Program checks that with Settings, there is a table associated "SETTINGS" and query this table for all items available

Does this make sense?

答: You should NEVER keep those things in DB. There are other places where you can store the information. Pulling data from DB is expensive and much better solution would be to store it as XML or even separate class and including that object into other classes. Then you would only need to change the code on one place AND you would avoid torturing your DB.</p>


问:
btnBack vs backButtonField
For blackberry GUI developement.  I am using the name convention like backButtonField and some of my colleagues are using btnBack.

But sometimes I stuck with the names like loginVerticalFieldManager its a very long name.  At that time vfmLogin looks better

So for GUI components names what convention should I follow?

答: Never, ever be afraid of long names.  Other than for visual controls (where I still rather archaically use three letter prefixes of the btn variety to avoid confusion between the controls and the fields that back them) I never use abbreviations and try to make all my names as useful as possible - if that means they're long then so be it.  With copy & paste and code complete it's not like I ever type them again anyway  :-)</p>

Title: btnBack vs backButtonField


问:
How can I create an abstract parent class which uses data from an inherited class?
I'm getting my feet wet with Android app development and tying to find a good way to manage database interactions across multiple similar objects. My goal was to have a structure like:

```<code>public abstract class DatabaseObject{

    public static abstract String getTableName();
    public static abstract SQLiteDatabase getDB();
    public static void dropTable(){
        getDB().execSQL("DROP TABLE IF EXISTS " + getTableName());
    }
}

public class Book extends DatabaseObject{

    public static final String TABLE_NAME = "book";
    private String author;
    private static SQLiteDatabase _db;

    public static setDB(SQLiteDatabase db){
        _db = db;
    }

    @Override
    public static String getTableName(){
        return TABLE_NAME;
    }

    @Override
    public static SQLiteDatabase getDB(){
        return _db;
    }

    public String getAuthor(){
        return author;
    }

    public void getAuthor(String auth){
        author = auth;
    }
}
</code>```

Lately I've been working on a project that uses Hibernate, so I'm used to having a class that can be used throughout the application and also contains the ability to persist its data to the database. Unfortunately, "static abstract" isn't allowed in Java, so this wouldn't work.

My current plan is to have each of the classes like "Book" that I plan to use implement an interface and have an external class handle the common db interactions instead of the ancestor class.

Is there a better way to accomplish what I'm trying to do?

答:
This would work if you dropped all the statics from the base class, and the abstract from the method with an implementation. Think of how the methods would be called by clients: either aBook.dropTable() or Book.dropTable() makes sense, but DatabaseObject.dropTable() doesn't; which table did you want dropped?

Doubtless there are better ways to do things, e.g. http://developer.android.com/training/basics/data-storage/databases.html.


答:
If I follow you correctly, the issue is that the code you need to use has run-time dependencies on modules expressed in Spring XML, but maven is not told about them. So when you use them the things they need (the transitive dependencies) are not on your classpath, and they don't do what they should.

I'm guessing when you ask your colleagues 'how do i get this to work?', they say 'obviously you need this list of 35 modules and versions, how could you not know that?'

Presumably when integration testing is done, the required modules are declared as test dependencies. So the systematic solution is to set up inspections of integration test pom's to ensure they have nothing but 3rd-party test tools declared as test dependencies. This could even be automated by the maven enforcer plugin.

Apparently you can't do that, so your best option is likely found here.


问:
Thread synchronization for multiple threads accessing a message stream
My project has a single message stream (communicating with an external device) which is accessed via multiple client threads. The workflow is:

There is a thread (the "messaging thread") which reads the message stream and is able to dispatch received messages to clients. This works by waiting on a thread-safe queue which the message stream exposes.

Messages may be sent on the stream from any thread (the stream is thread-safe and handles concurrent send/receive)

A client thread sends a request across the message stream, and provides a callback function.

The client thread waits for responses. There may be multiple responses. The messaging thread knows how to match a received message to a client thread, based on the request sent by the client thread.  The messaging thread invokes the right callback function for each received message.

After sending the request, the client thread must block until all responses have been processed. This is normally indicated by the callback function returning a particular status, but it must also be possible to unblock a client thread and end the interaction by the messaging server receiving a particular message which it will recognize, or the application shutting down.

From time to time the messaging service may be unavailable (the messaging thread will know this); so the client threads must be able to wait for a certain time to see if the messaging service has become available.

Those are my requirements but I can't get my head around how to code the logic for the client threads "entering" and waiting; and how the client threads should communicate with the messaging thread. Which synchronization primitives to use, and so on.

I'm coding in C++ with the Poco libraries, and can use all the usual primitives (mutex, event, semaphore, condition variable etc.) as well as higher level constructs like a notification queue, notification centre, and event dispatcher.

答:
There are different ways to do it, but if you are inclined to stick with POCO, you may want to look at the macchina.io (OSP portion) WebEvent implementation - it is essentially a pub/sub messaging framework. There's more there than what you need but it's relatively simple and architecturally you should be able to quickly tailor it to your needs. I have used it in production for many years and it works well; it will also be ported in an OSP-independent form to Poco for one of the next releases.

Client can be either (1) a web socket endpoint or (2) an in-process observer which can send (i.e. post events) data and/or subscribe (i.e. receive notifications) to one or more subjects (topics). You'll probably need many in-process observers and one remote endpoint.

The framework runs in two threads handling:

Main queue - responsible for dispatching subscribe/unsubscribe request events from clients.

Worker queue - responsible for dispatching the data events (messages).

Each queue is dealt with in its own thread and there is a dotted-notation naming scheme for subject names, see here for details. Note that documentation only mentions WebSockets but naming works exactly the same for in-process observers and you may want or need a different naming scheme.


问:
What is a URI Scheme?
I have searched for this question, but I haven't found a good answer.

Even the Wikipedia Article on URIs does not explain it thoroughly. I thought it was the protocol for accessing a web page. e.g. HTTP/HTTPS/FTP, but the wiki article says otherwise.

Some URI schemes are not associated with any specific protocol (e.g.
  "file") and many others do not use the name of a protocol as their
  prefix (e.g. "news").

I know what part of the URL is the scheme. But my real question was what does it do?

答:
It's the part before the colon in a URI.

For example: the scheme for http://en.wikipedia.org/ is http. The scheme for file:///etc/passwd is file. The scheme for ftp://example.org/resource.txt is ftp.

Title: What is a URI Scheme?


问:
How do you check bugs on your client's PC's?
It seems like there are a plethora of methods for dialing in and checking out what's going on on a client's PC.  But they seem to boil down to just 2. Dialing in and checking it out with VNC and Remote Desktop.

VNC seems abysmal with more graphics laden OS's and it sometimes is too much to ask to get a access to a terminal server (especially when the client doesn't have one).

What other methods are out there for connecting with clients to diagnose and fix bugs they they can reproduce, but may not necessarily be able to adequately describe over the phone.

Alternatives to VNC and Remote Desktop are appreciated, but really looking for a better way to do it than just to dial in and check it out - or the most effective way to use VNc and Remote Desktop.

答:
If they're running Windows, depending what you're looking for (when I deal with thick-client [desktop] applications) I generally have them send me system information which Microsoft makes super easy. This is only useful for getting the system information, client configurations, registry settings, et al.

Windows XP/Windows 7:

Start > Run > msinfo32 (or msinfo32.exe)

File > Save As (This will save it as a .nfo> so you can view it using the same viewer on your system) or File > Export (Text) which is not so easily readable

This allows you to take a lot of things into account that generally everyone forgets to mention (like environment variables).


问:
Using private vs company devices for development at work
I'm employed at a mobile app development company since 4 months as Android developer. Currently I'm using my two private Android devices for development. Is it common practice that developers use their own hardware devices for development in mobile development companies, or should I ask for company devices?</p>

答:
I've encountered both scenarios. Previous company I worked we had a number of company devices but people also used their own in addition to that (AFTER the tests on the company devices showed the apps weren't going to cause mayhem, those private devices were mostly used to allow testing on more different screen sizes, OS versions, and hardware configurations).

Current environment I work in testing on personal devices is all but impossible because of access restrictions to the network. For a device to access the network at all it needs special software installed AND needs to be whitelisted at hardware level by the security department, which is just not going to be allowed for devices not owned by the organisation.

At most the user acceptance environment might be accessible for some apps (those that would be accessible to the general public after the system goes life) but that's it.

In general I'd be wary of using my personal devices to test software developed for a customer or employer, especially if I'm not one of the key coders on the project and can be fairly certain the app isn't going to do anything irreversible to my device. And that's before taking any legal problems into account, which are out of my field of expertise but may well exist.


答:
The quote from Wikipedia may be a bit misleading. What it means is that for example the file: URI scheme does not state what kind of way is used to accessing the data (or whatever it is pointing to). With http: you know there is the HTTP protocol being used. With file: it's whatever the applications wants to use.

With news: the protocol name is NNTP, but the name doesn't reflect that. Which is a good thing in my mind, since news: is a lot clearer.

So the URI scheme is just the first part including the colon.

Title: What is a URI Scheme?

Body:
I have searched for this question, but I haven't found a good answer.

Even the Wikipedia Article on URIs does not explain it thoroughly. I thought it was the protocol for accessing a web page. e.g. HTTP/HTTPS/FTP, but the wiki article says otherwise.

Some URI schemes are not associated with any specific protocol (e.g.
  "file") and many others do not use the name of a protocol as their
  prefix (e.g. "news").

I know what part of the URL is the scheme. But my real question was what does it do?


答:
I think you can adapt the visitor pattern for your requirement.

Your Book class should implement an interface, typically named Visitable.

```<code>public interface Visitable{
  public void accept(Visitor visitor);
}
</code>```

Now, to your book class you pass in a visitor which performs the necessary operations. Implement this method in book class.

```<code>public class Book implements Visitable{
  public void accept(Visitor visitor){
    visitor.visit(this);
  }
}
</code>```

Now, let's check the visitor part. If your set of actions are going to be common for all entities, implement a generic visitor.

```<code>public interface Visitor{
  public void visit(DatabaseObject dbo);
}
</code>```

Let's look at the visitor itself now.

```<code>public class DBOVisitor implements Visitor{
  public void visit(DatabaseObject dbo){
    String tableName = dbo.getTableName();
    String tableDropSQL = "DROP TABLE "+tableName;
    getDB().execSQL(tableDropSQL);
  }
}
</code>```

I hope you get the idea of it. Feel free to adapt it. Add specific methods if you want and as always, name the methods meaningfully. Hope this helps!

Title: How can I create an abstract parent class which uses data from an inherited class?

Body:
I'm getting my feet wet with Android app development and tying to find a good way to manage database interactions across multiple similar objects. My goal was to have a structure like:

```<code>public abstract class DatabaseObject{

    public static abstract String getTableName();
    public static abstract SQLiteDatabase getDB();
    public static void dropTable(){
        getDB().execSQL("DROP TABLE IF EXISTS " + getTableName());
    }
}

public class Book extends DatabaseObject{

    public static final String TABLE_NAME = "book";
    private String author;
    private static SQLiteDatabase _db;

    public static setDB(SQLiteDatabase db){
        _db = db;
    }

    @Override
    public static String getTableName(){
        return TABLE_NAME;
    }

    @Override
    public static SQLiteDatabase getDB(){
        return _db;
    }

    public String getAuthor(){
        return author;
    }

    public void getAuthor(String auth){
        author = auth;
    }
}
</code>```

Lately I've been working on a project that uses Hibernate, so I'm used to having a class that can be used throughout the application and also contains the ability to persist its data to the database. Unfortunately, "static abstract" isn't allowed in Java, so this wouldn't work.

My current plan is to have each of the classes like "Book" that I plan to use implement an interface and have an external class handle the common db interactions instead of the ancestor class.

Is there a better way to accomplish what I'm trying to do?

Body:
I think you can adapt the visitor pattern for your requirement.

Your Book class should implement an interface, typically named Visitable.

public interface Visitable{
  public void accept(Visitor visitor);
}

Now, to your book class you pass in a visitor which performs the necessary operations. Implement this method in book class.

public class Book implements Visitable{
  public void accept(Visitor visitor){
    visitor.visit(this);
  }
}

Now, let's check the visitor part. If your set of actions are going to be common for all entities, implement a generic visitor.

public interface Visitor{
  public void visit(DatabaseObject dbo);
}

Let's look at the visitor itself now.

public class DBOVisitor implements Visitor{
  public void visit(DatabaseObject dbo){
    String tableName = dbo.getTableName();
    String tableDropSQL = "DROP TABLE "+tableName;
    getDB().execSQL(tableDropSQL);
  }
}

I hope you get the idea of it. Feel free to adapt it. Add specific methods if you want and as always, name the methods meaningfully. Hope this helps!


答:
Don't create new types if you can help it. They can cause extra confusion, complexity and lead to more code to maintain. They may make your code had to extend. Designing an exception hierarchy requires a lot of though and testing. It's not an after thought. It's often best to use the built in language exception hierarchy.

The content of the exception message dependents on the receiver of the message - so you have to put yourself in that person's shoes.

A support engineer will need to be able to identify the source of the error as quickly as possible. Include a short descriptive string plus any data that can help troubleshoot the issue. Always include the stack trace - if you can - this will be the only true source of information.

Presenting errors to general users of your system depends on the type of the error: if the user can fix the problem, by providing different input for example, then a concise descriptive message is required. If the user can't fix the problem, then it's best to state an error has occurred and log/send an error to support (using guidelines above).

Also - don't throw up a big "HALT ERROR!" icon. It's an error - it's not the end of the world.

So in summary: think about the actors and use cases for your system. Place yourself in those user's shoes. Be helpful. Be nice. Think about this up front in your system design. From the perspective of your users - these exception cases and how the system handles them, are just as important as the normal cases in your system.

Title: How to write a good exception message

Body:
I'm currently doing a code review and one of the things I'm noticing are the number of exceptions where the exception message just seems to reiterate where the exception occurred. e.g.

```<code>throw new Exception("BulletListControl: CreateChildControls failed.");
</code>```

All three items in this message I can work out from the rest of the exception. I know the class and method from the stack trace and I know it failed (because I've got an exception).

It got me thinking about what message I put in exception messages. First I create an exception class, if one does not already exist, for the general reason (e.g. PropertyNotFoundException - the why), and then when I throw it the message indicates what went wrong (e.g. "Unable to find property 'IDontExist' on Node 1234" - the what). The where is in the StackTrace. The when may end up in the log (if applicable). The how is for the developer to work out (and fix)

Do you have any other tips for throwing exceptions? Specifically with regard to the creating new types and the exception message.


答:
The scheme is the first hierarchy of an URI and therefore the most 'prominent' part, which is used to identify the 'purpose' of the resource.
If you are interested in some 'kind' of resource (web links, news, files), you can tell by just using checking the scheme - not the whole resource string.

It's just a string repesenting a set of resources.

Title: What is a URI Scheme?


答:
The scheme indicates the addressing system used. URL's are really a unification of various disparate addressing systems. The part before the colon identifies the scheme in use, and everything after the colon is syntax specific for the scheme. Each scheme defines its own unique way of addressing resources. This makes the URL standard infinitely extensible through adding new schemes.

It is hard to say anything in general for schemes, because they are wildly different. In many cases the name of the scheme is the name of a protocol which can be used to fetch the resource (like http, https, ftp etc.) but that is not a hard rule, eg. the 'mailto' scheme indicates an e-mail address, but not a particular protocol. Some schemes don't correspond to any specific protocol, like the 'about' scheme used in web browsers, where the resource is not fetched via a protocol, but is built-in in the client.

Title: What is a URI Scheme?

ContentLicense: CC BY-SA 4.0


问:
Algorithm for determining transactions among weekly data series?
I'm trying to develop a small reporting tool (with sqlite backend). I can best describe this tool as a "transaction" ledger. What I'm trying to do is keep track of "transactions" from weekly data extract:

"new" (or add) - resource is new to my app since my app may not have tracked this resource before as it hasn't been seen via extracts.

"update" (or hit) - there is a recent use of that resource, update retention period by another week.

"delete" (or drop) - this item saw no use since last report (optional, but would be nice to have for graphing week-to-week changes in demand for resources).

All I've got is a weekly data extract (pipe-delimited flat file) coming from a legacy archiving/record-management system that I have no control over.

Each line can be distilled to basically this:

resource_id | resource info | customer_id | customer_info

Sample data:

```<code>10| Title X       | 1 | Bob
11| Another title | 1 | Bob
10| Title X       | 2 | Alice
</code>```

The goal is make it easy to report on resources that haven't seen use for X-months (based on last hit). There is a retention period where resources are kept around for ease of access if they're popular. A resource that hasn't seen use for 18 months is marked for long-term archival elsewhere.

This must be a common problem. Wondering if there a general-purpose algorithm to determine what's new/same/removed between data sets (db vs. latest extract)?

答:
Isn't this what HashTables are for ? If all you want to do is keep records of which resources have been used in the past months and delete resources that haven't been accessed in the last 18 months then you can use a HashTable where the Key is the resource_id and the value is the last access date.

For archiving the >18 months records you can go through all of the records in the hash table and just remove (or move) those specific records. (you can do this weekly when the report comes in)


问:
Delivering source code - refactor for clean up?
I'm in the middle of developing an asp.net webforms application to a customer, i've been using DataAccess and BusinessLogic layers in a folder structure within my application, in which my DataAccess classes use ordinary SQL queries to access the data. Then for certain reasons, for the remaining part of the project, I've decided to go for the entity framework and create separate DataAccess and Business Logic layer projects to retrieve the data.

I've been planning to move the whole folder structure of the old DataAccess and Business Logic layer to the newly created layer projects and use entity framework instead.

But at this moment, my client has decided to terminate the project and he would like to get the source code. I'm confused about what to deliver to him, since I haven't still adjusted my code to use entity framework only, so I would describe my code at this moment as "messy".

Should I just give him the code this way ? Or should I move all the old folder structure to the newly created projects and use entity framework instead, knowing that this would take almost 3 or 4 work days, which i doubt my boss would accept. Is there an intermediate solution ?

答:
The project is like the parrot - dead. So you will not get paid for working on it, so you zip it all up and deliver it as-is, nasties, bugs and everything.

You could add a quick readme if you want to salvage some professional pride explaining the intended migration path, but I wouldn't even attempt to fix up any more code. Worst case is that you deliver something that does not work like the customer's existing drops and that will only make them be very concerned that they didn't get the full release of source code (I assume they may have run pre-releases so far, and maybe that they will develop it further in-house)


答:
Okay, I know what part of the URL is the scheme. But my real question was what does it do?

It simply tells you how to interpret the part of the URL after the colon.

For example, in file://usr/share/doc, the file tells me the part after the colon should be interpreted as a locally-available filesystem path. This isn't identical to a protocol, because there is no transport layer or encoding - a client just uses regular local system calls to access it.

Conversely, https://programmers.stackexchange.com specifies a scheme (https, which in turn means "HTTP over TLS"), but still requires the client to make its own choices about the physical transport used to reach it.

Title: What is a URI Scheme?


答:
Explain, in detail, in terms your boss can understand, why, in your opinion this should be done.  Explain also the testing that would need to be done to make sure it really works.  Explain why spending the money / taking the time would make sense for your boss.  Remember that software changes should be justifiable to the business in terms they can understand and then they can make the decision about whether to spend money that way.  A "good thing, a good idea, a 'should be done'" need to come from the business, NOT just from your sense of "the right thing to do".  The right thing to do includes persuading the business that they should take this time and spend that money.  You should explain the positive and negative consequences of doing / not doing it.  The more impartially you are able to do this the more believable you will be.

I question your estimate of 3-4 days.  Does that include testing? qa? documentation?  Most project where I have felt there is 3-4 days of work have turned out in the end to be 3-4 weeks.  It's always assumed that this is an anomaly due to the business, the people, the project, the software, the infrastructure, the whatever.  After 30 years of doing this I've got to know that there are ALWAYS reasons why it takes much longer than anticipated.

Title: Delivering source code - refactor for clean up?

Body:
I'm in the middle of developing an asp.net webforms application to a customer, i've been using DataAccess and BusinessLogic layers in a folder structure within my application, in which my DataAccess classes use ordinary SQL queries to access the data. Then for certain reasons, for the remaining part of the project, I've decided to go for the entity framework and create separate DataAccess and Business Logic layer projects to retrieve the data.

I've been planning to move the whole folder structure of the old DataAccess and Business Logic layer to the newly created layer projects and use entity framework instead.

But at this moment, my client has decided to terminate the project and he would like to get the source code. I'm confused about what to deliver to him, since I haven't still adjusted my code to use entity framework only, so I would describe my code at this moment as "messy".

Should I just give him the code this way ? Or should I move all the old folder structure to the newly created projects and use entity framework instead, knowing that this would take almost 3 or 4 work days, which i doubt my boss would accept. Is there an intermediate solution ?


问:
Maximizing the amount of work not done in Agile?
Here's a quote from "Agile Principles, Patterns, and Practices in C#"
 By Micah Martin, Robert C. Martin

Simplicity the art of maximizing the amount of work not done is essential. Agile teams do not try to build the grand system in the sky. Rather, they always take the simplest path that is consistent with their goals. They don’t put a lot of importance on anticipating tomorrow’s problems; nor do they try to defend against all of them today. Rather, they do the simplest and highest quality work today, confident that it will be easy to change if and when tomorrow’s problems arise.

I really don't get that.

Does that means, instead of building a robust main engine which will be able to handle the features needed, one should just build one feature right ahead?

Because as far as I know this would most likely eventually turns out inefficient and less flexible.

Let's take an example:

Imagine ASP.Net without base Control/WebControl classes, because the .Net dev team would just have rushed doing "TextBox", "CheckBoxe", "Label", etc. immediatly. The .Net team dev would have taken the simplest path.

Woudln't that have made the whole framework's developpement a hell of trouble?

Can somebody tell me if I got the quote wrong of it's a really debatable rule?

答:
The concept of agile is that things change. So if you spend a very long time working on a super-engine, by the time you've finished and its ready to use, the requirements or technology may have changed and you'll have to start over.

In reality that's not likely to happen, but the requirements do change. So agile methodology works on the principle of getting something running and modifying it to make it fit, evolving it to be what you want.

Now this may sound dreadful, forever refactoring and never finishing (and some people do work like that, unfortunately) but if you have any experience then you'll be working on a design that can cope with a certain amount of change when you create the limited, initial releases.

ASP.NET is a bad example of up-front-design given that it is currently on release 6 and each version is very different to the other releases!

Its possible that you need experienced people in order to work efficiently in an agile way, or that experienced people will respond much better to agile than waterfall developments.


答:
There is some room for debate, but I think most people agree on the gist of it.

simplest path that is consistent with their goals

Simple is relative to the goals. A prototype for the .NET concept may have been built the way you described, but at some point, the goal involves a major framework that needs to be built with a lot of rigor and room for expansion. In agile development, the mess gets recognized much sooner and you go back to the drawing board.

they do the simplest and highest quality work today

So when the goal is a "robust main engine" that's what you start to build. And you'll probably build it one piece at a time. If you're agile, you build something that works every 2-4 weeks and repeat.

Simplest doesn't always mean simple. Your client may have delusions of being the next Facebook, but when you look at their budget, you either adjust their goals and build something not quite so scalable or start building a grand website and not get paid for it.

Title: Maximizing the amount of work not done in Agile?

Body:
Here's a quote from "Agile Principles, Patterns, and Practices in C#"
 By Micah Martin, Robert C. Martin

Simplicity the art of maximizing the amount of work not done is essential. Agile teams do not try to build the grand system in the sky. Rather, they always take the simplest path that is consistent with their goals. They don’t put a lot of importance on anticipating tomorrow’s problems; nor do they try to defend against all of them today. Rather, they do the simplest and highest quality work today, confident that it will be easy to change if and when tomorrow’s problems arise.

I really don't get that.

Does that means, instead of building a robust main engine which will be able to handle the features needed, one should just build one feature right ahead?

Because as far as I know this would most likely eventually turns out inefficient and less flexible.

Let's take an example:

Imagine ASP.Net without base Control/WebControl classes, because the .Net dev team would just have rushed doing "TextBox", "CheckBoxe", "Label", etc. immediatly. The .Net team dev would have taken the simplest path.

Woudln't that have made the whole framework's developpement a hell of trouble?

Can somebody tell me if I got the quote wrong of it's a really debatable rule?


问:
Why do arrays in .Net have Length but other collection types have Count?
In C# for example, arrays have Length property. But other collection types like lists, etc. have Count property. Is there a reason why these two are different? If so I would like to know.</p>

答:
They are named differently because semantically they are quite different:

A collection's Count is the number of items currently stored in it and can potentially change over time.

An array's Length is the maximum number of items it can hold (it will have a length of 10 even if you haven't stored that many items in it) and is immutable.

Example:

If I have a bucket that can fit a maximum of 100 balls in it it has a Length of 100. If I put 50 balls into it it then it has a Count of 50.

If I add 10 more balls the Count becomes 60 but the Length is still 100. In order to change the Length I need to get a different bucket.

Array probably uses the word Length because under the hood it's allocating a contiguous block (a length) of memory based on the capacity multiplied by the item size. Although the fact that the List class uses "Capacity" for a similar (though mutable) concept suggests array may use the word "Length" for historical reasons.


问:
C# try/finally for state cleanup
Is there any reason (for instance: performance) against moving state "cleanup" code in a finally state?
Example:

```<code>this.state.InProgress = true;
// logic here
this.state.InProgress = false;
</code>```

With finally state:

```<code>try
{
    this.state.InProgress = true;
    // logic here
}
finally
{
    this.state.InProgress = false;
}
</code>```

答:
No.

And even if the performance would be different (which it is not, see the link in the comment given by Sami), what do you think is more important, speed or correctness? A program which does not work correctly is pretty useless, how fast it may ever be.

The only reason I can think of is that you are 100% sure the "logic" part does not throw any exceptions (now and in the future). That makes the try/finally unneccesary "noise", which decreases readability a bit. Be aware that it's difficult to make predictions, especially about the future.

Title: C# try/finally for state cleanup


问:
Explaining new or uncommon syntax in comments
As per the title, should I be explaining syntax that I use in my code when I have a reasonable expectation that a developer looking at my code in the future will not be familiar with it? Short caveats or explanations could be added in-line while more complex constructions would be referred to by name and version number to allow a quick lookup in the documentation.

The two main reason they might not understand the syntax are because it's a new addition to the language or it's syntax that is rarely used by "average" developers. Assume that using this syntax is the recommended approach and not about me wanting to write fancy code. (No, I'm not XOR swapping in high-level languages.)

On the one hand, comments are there to facilitate maintenance and if I provide that explanation I could save a future developer a lot of effort and reading. On the other hand, I could argue that syntax documentation is readily available and that any decent developer could be expected to keep up to date on new developments or, failing that, shouldn't have any trouble figuring it out using the tools (IDE help) and documentaiton available to him.

For context, this question was prompted by recent updates to SAP's ABAP syntax which adds new grouping and filtering mechanics to loops and a number of other statements. Many legacy developers and client-side maintenance teams won't be familiar with this syntax for years (if ever).

For this question, assume that commenting your code is a good practice.

As csw comments, one option is to simply not use this new syntax until the maintainers have caught up, but as I hinted, some of those maintainers simply won't ever catch up. In my industry maintenance of the code is often handed over to small in-house developers once the project is delivered and they can be notorious for being stuck in "legacy mode". Writing functionally obsolete code as a crutch for out-of-touch programmers just doesn't seem like a good or defensible practice.

In my particular situation, the ABAP syntax updates offer some dramatic performance and readability improvements. They introduce a number of common modern operations to the ancient ABAP language like casting operators. The GROUP BY I linked is another good example that replaces complex, illegible and bug-prone code with a simple alternative. For a concrete syntax example, I can replace

```<code>READ TABLE itab WITH ... TRANSPORTING NO FIELDS.
IF sy-subrc = 0.
    ...
ENDIF.
</code>```

with:

```<code>IF line_exists( itab[ ... ] ).
    ...
ENDIF.
</code>```

For those interested, this PDF covers many of the new features. Slide 29 and 30 offer two good example of how drastic the difference can be.

Regarding the suggested duplicate, there are some useful answers there but my question covers a more specific case. You could probably summarise my question as "Should I ignore the document *why* rather than *how* paradigm when when doing so might greatly simplify maintenance for inexperienced developers?".

答:
I think it depends on the situation.

In this example, documentation like this belongs in a README file.*  If you consistently use the new syntax, your code will be virtually unrecognizable to a  programmer who only knows the older style.  Your maintainers will thank you if you warn them up front that they don't actually know this language.  I would:

Start every source file with a bold block comment that this file uses new syntax:

```<code>***********************************************
* ### This file uses the NEW ABAP SYNTAX  ### *
* ### introduced in NetWeaver 7.4.        ### *
* ### Please see README.html for details. ### *
***********************************************
</code>```

In the README, briefly explain the syntax changes and provide links (hence README.html) to tutorials and references.

This has two advantages:

You can reuse the README across multiple projects.  Don't repeat yourself!

Your code won't be half comments.  It appears the new syntax will be present throughout each file.  Explaining syntax, even briefly, wherever you use it will be tedious for you to do and difficult for your maintainer to read.

* Caveat: All I know about ABAP I learned from the links in your post.  Please don't consider this an expert opinion.

** By the way, the above sample block comment is hereby licensed CC0 1.0 :) .  Feel free to copy it if it is convenient to do so!

Body:
I think it depends on the situation.

In this example, documentation like this belongs in a README file.*  If you consistently use the new syntax, your code will be virtually unrecognizable to a  programmer who only knows the older style.  Your maintainers will thank you if you warn them up front that they don't actually know this language.  I would:

Start every source file with a bold block comment that this file uses new syntax:

***********************************************
* ### This file uses the NEW ABAP SYNTAX  ### *
* ### introduced in NetWeaver 7.4.        ### *
* ### Please see README.html for details. ### *
***********************************************

In the README, briefly explain the syntax changes and provide links (hence README.html) to tutorials and references.

This has two advantages:

You can reuse the README across multiple projects.  Don't repeat yourself!

Your code won't be half comments.  It appears the new syntax will be present throughout each file.  Explaining syntax, even briefly, wherever you use it will be tedious for you to do and difficult for your maintainer to read.

* Caveat: All I know about ABAP I learned from the links in your post.  Please don't consider this an expert opinion.

** By the way, the above sample block comment is hereby licensed CC0 1.0 :) .  Feel free to copy it if it is convenient to do so!


答:
To use your .NET analogy, the flow for an agile development of those controls would be:

TextBox: This text box is pretty awesome!

CheckBox: Hey, another one, wait a minute...

Label: Yeah, I'm seeing a trend here

BaseControl: That helps!

Essentially, instead of up front trying to look for your abstractions and designs, allow the design to emerge as you go. It's not that you aren't focusing on building quality software, it's just that you should not be trying to waste time predicting what you'll need and building up frameworks and abstractions until you actually need it.


问:
Should well-known business ID of an entity be represented with a dedicated type in DDD/OOP?
In practical terms it means using an custom (immutable) class over a string or some other primitive type.

Examples:

Publishing: International Standard Book Number.

Finance: International Securities Identification Number.

Advantages:

Can ensure the format of an identifier.

Becomes a first-class member of the model.

Disadvantages:

Adds persistence friction (e.g. Entity Framework).

More code.

答:
I would say go for it.  I would argue that the advantages outweigh the disadvantages in this case.  The extra code is likely to be pretty minimal and the persistence issue can be solved pretty easily be providing some sort of converter between your new Class and the type the database expects (I've never used Entity Framework but I know this is relatively painless in Hibernate).

One of the advantages you can get by defining your own class is that the compiler can ensure that any methods which want an ISBN or an ISIN will know at compile time if you try and pass in the wrong value. It will also be much harder to accidentally overwrite that field in your entity. We can avoid common errors like this entirely:

```<code>book.setAuthor(otherBook.getAuthorName());
book.setIsbn(otherBook.getAuthorName());
book.setPrice(otherBook.getPrice())
</code>```

If ISBN is a class rather than a primitive type then the above code won't even compile, saving a lot of debugging time later.

Body:
I would say go for it.  I would argue that the advantages outweigh the disadvantages in this case.  The extra code is likely to be pretty minimal and the persistence issue can be solved pretty easily be providing some sort of converter between your new Class and the type the database expects (I've never used Entity Framework but I know this is relatively painless in Hibernate).

One of the advantages you can get by defining your own class is that the compiler can ensure that any methods which want an ISBN or an ISIN will know at compile time if you try and pass in the wrong value. It will also be much harder to accidentally overwrite that field in your entity. We can avoid common errors like this entirely:

book.setAuthor(otherBook.getAuthorName());
book.setIsbn(otherBook.getAuthorName());
book.setPrice(otherBook.getPrice())

If ISBN is a class rather than a primitive type then the above code won't even compile, saving a lot of debugging time later.


问:
How much should a view know about model?
I am building an application in python with a python wrapper for WPF and with DAG support.  I am currently at a point where I have to decide a consistent way of interacting between the data and the view.

As far as I see there are currently two obvious solutions.

First one is similar to how Android Applications are structured. You have a controller which sets/populates the view. So the controller owns the view and pushes only the primitive data that will be displayed. The view is just a dumb layer and has no idea of what's happening and where that data is from. And then if user interacts with the view, it will send callbacks to the controller (if it registered).

UserInfoController.py

```<code>userInfoView = UserInfoView()
userInfoView.onGenderChangedCallback = self.onGenderChangedCallback
userInfoView.setUserGenderValue(user.getGender())
</code>```

UserInfoView.py

```<code>def setUserGenderValue(self, gender):
    self.userGender = gender

def getView(self):
    return ui.Label(self.userGender, onEditCallback=self.onGenderChangedCallback)
</code>```

Second one is passing a (reference of) model to the view and letting the view to retrieve and update the data. The view now contains the model and therefore it can update it without any additional callbacks to the controller.

UserInfoViewModel.py

```<code>self.gender = 'Male'
</code>```

UserInfoView.py

```<code>def getView(self):
    return ui.Label(self.ViewModel().getGender(), onEdited=self.genderEdited)

def genderEdited(self, newValue):
    self.ViewModel().setGender(newValue)
</code>```

So I guess what I am asking is, should I pass the very primitive data and keep the view as generic as possible, then work with callbacks and do the business specifics in the controller.

Or should I pass the whole model to the view and let the view to update the model directly. This means that there will be less code to type.

PS. Do not judge the code - it's just for visualization.

EDIT:

Also to add - this application will be written in python which supports ducktyping. This means that with the second approach, the view is still reusable as long as the model meeting the required interface.

答:
This is somewhat a generalized answer, but IMO view should do the least amount of work possible (e.g. validate user inputs).

This way you can expect all your logic to be in controller. This makes it a lot easier to maintain down the road, single responsibility principle, and all that.


答:
Agile doesn't necessitate an absence of high level design.  Before a story can be worked on by a developer, is a single user story going to completely capture everything needed to be defined before one can start sprinting?

As a user, I need to enter first name into a text input field on the X form, so that I can submit my first name as part of my profile information

One couldn't just start sprinting on this in a vaccuum.

What language did we decide to use?

What are the coding guidelines I should adhere to?

What are some use cases that I can test to?

Is the project skeleton and organization madeup?

How are software components organized?  Is there a component diagram describing the software component interactions?

Should we follow Transaction Script pattern on the server side or Rich Domain Model/MVC?

Did we create the Domain Model?

What are the non-functional requirements?  How quickly should I get a response back?  What about security?  Should I do XSS filtering and sanitize inputs?

What are our database development standards?  Do we have to adhere to certain naming conventions on schema objects?  Is there a class diagram describing the user profile table?

Do we have a framework established for proper unit testing of business logic?

Do we have a proper development environment and testing environment built so that the story can be tested by QA in isolation of ongoing development changes?

Did we implement Continuous Integration such that our builds are constantly occurring and being verified consistently.

When the story has passed testing and is accepted by the Product Owner, do we have a Continuous Delivery implementation such that software changes can be delivered to other environments?

Do we have source control in place with a proper source control and branching strategy decided on?

What web frameworks and design decisions have we decided on?  Angular?  Spring MVC, JSON over REST services?

Have User Interface guidelines been defined especially for how text boxes should appear?

Have any common web components been implemented (or need to be implemented as part of this story) to properly deliver this story per the high level design and with the goal of minimizing technical debt?

Anything else...

If you were just starting this one story, there is an infrastructure so to speak that needs to exist or you just bundle all of this complexity into this one seemingly small story.  It is required for a story that should ideally be a tiny vertical slice of an entire system.

As a post office customer, I want to send an overnight package from my home in Boston to my friend in San Francisco.

The infrastructure that is required for this story is that we need a system of roads, a pickup truck, a mail sorting machine, an express airplane, an airport with a runway and traffic control, etc...

If it sounds like a lot then that is because it is.  An enormous amount of work is necessary in terms of that development infrastructure that is required before one starts sprinting and directly delivering business value.

You really don't want to do this work in the sprint

There should be efforts before and between sprints to address and tune these processes and work.

Smoothing of Risk

The pursuit of minimum viable product and refactoring constantly to changing business needs is a smoothing of risk essentially.  You could spend a lot of time developing a Cadillac solution for the business to turn around and say that they actually needed a boat all along.

Think of it as paying insurance against that disaster scenario.  You spend two weeks and develop a skateboard.  Then you spend another and develop and electric wheelie.  Business decides they actually wanted a boat, you throw away your wheelie and create a paddle board in the next sprint.  You are down and out the time spent on a useless skateboard and wheelie, but you prevented yourself from wasting a lot of time building the high quality chasis for a Cadillac.

Yeah it kind of sucks to work hard on something that will probably get thrown away in a month, but just remember,

It is not about the developer!

Your ability to work on kick-ass high quality beautiful software and have pride in your work is not guaranteed.  It doesn't matter.  The only thing that matters is what the product owner wants, and delivering working software with quick turnaround.  That is it.


问:
Send more data, or do client processing?
I have a conceptual problem that I want feedback on. First and foremost, the layout of my system. It contains a server, with many clients connected to it.

The clients get fed data from the server at variable intervals. At the moment, this data contains: Faults, Warnings and Locations. Faults, Warnings and Locations all contain a variable for "Terminal". The terminal being a PC which may have a fault or warning attached to it.

Now. The admin console wishes to see how many terminals are on the system (essentially in the database) in total. Not a problem! I'm already sending information about all terminals in "Locations". This number is 2 for-loops and a count away (about 7 LOC).

However, here is my conundrum. Is it better to make the server do, essentially "return Terminals COUNT" and send it as part of the payload with Warnings, Errors and Locations, than have the client iterate through some arrays to get the information?

I've been thinking for a while, and while I'm of the impression the server should carry the work, it is some data being sent that is technically "unnecessary".

Is this correct?

答:
How much space would this count take? 10 bytes?

Unless you're trying to compress your payload to an absolute minimum, I would do calculations on a server, and keep logic that can be executed on a server on a server. Makes it a bit easier to maintain, less strain on client devices if it matters, etc.


答:
Contrary to other answers, I would say no. The code should be self-documented as much as possible. Such simple things should not need to be explained in the code.

I do not know SAP, but a simple google query pointed to the SAP reference page to the line_exists function.

If the maintainers and developers are not up to date, then the company needs to develop a strategy to keep them up to date.

Title: Explaining new or uncommon syntax in comments

Body:
As per the title, should I be explaining syntax that I use in my code when I have a reasonable expectation that a developer looking at my code in the future will not be familiar with it? Short caveats or explanations could be added in-line while more complex constructions would be referred to by name and version number to allow a quick lookup in the documentation.

The two main reason they might not understand the syntax are because it's a new addition to the language or it's syntax that is rarely used by "average" developers. Assume that using this syntax is the recommended approach and not about me wanting to write fancy code. (No, I'm not XOR swapping in high-level languages.)

On the one hand, comments are there to facilitate maintenance and if I provide that explanation I could save a future developer a lot of effort and reading. On the other hand, I could argue that syntax documentation is readily available and that any decent developer could be expected to keep up to date on new developments or, failing that, shouldn't have any trouble figuring it out using the tools (IDE help) and documentaiton available to him.

For context, this question was prompted by recent updates to SAP's ABAP syntax which adds new grouping and filtering mechanics to loops and a number of other statements. Many legacy developers and client-side maintenance teams won't be familiar with this syntax for years (if ever).

For this question, assume that commenting your code is a good practice.

As csw comments, one option is to simply not use this new syntax until the maintainers have caught up, but as I hinted, some of those maintainers simply won't ever catch up. In my industry maintenance of the code is often handed over to small in-house developers once the project is delivered and they can be notorious for being stuck in "legacy mode". Writing functionally obsolete code as a crutch for out-of-touch programmers just doesn't seem like a good or defensible practice.

In my particular situation, the ABAP syntax updates offer some dramatic performance and readability improvements. They introduce a number of common modern operations to the ancient ABAP language like casting operators. The GROUP BY I linked is another good example that replaces complex, illegible and bug-prone code with a simple alternative. For a concrete syntax example, I can replace

```<code>READ TABLE itab WITH ... TRANSPORTING NO FIELDS.
IF sy-subrc = 0.
    ...
ENDIF.
</code>```

with:

```<code>IF line_exists( itab[ ... ] ).
    ...
ENDIF.
</code>```

For those interested, this PDF covers many of the new features. Slide 29 and 30 offer two good example of how drastic the difference can be.

Regarding the suggested duplicate, there are some useful answers there but my question covers a more specific case. You could probably summarise my question as "Should I ignore the document *why* rather than *how* paradigm when when doing so might greatly simplify maintenance for inexperienced developers?".


答:
In this case, someone unfamiliar with the updates could simply look up line_exists and move along.

For something less searchable, you might want to leave a comment which simply names the new features you are using so that up-to-date documentation is easier to find. If you use these features in more than a few places, put such a notice in a readme file instead of in comments.

I would not bother explaining the syntax if there is already ample documentation from another source, save your effort for documenting the things you develop instead.


答:
In the context of ABAP you can rarely expect everyone to be familiar with all the newest features because:

ABAP has such a long history and the ancient language constructs are still encountered all the time (I am currently modifying a report which uses a logical database and makes excessive use of tables with header lines).

SAP themselves rarely uses the new features to ensure backward compatibility with systems not patched to newer releases yet, so you rarely encounter the new features "in the wild".

The SAP education courses are very expensive, so companies avoid sending people to any which they don't desperately needed for their work. The delta courses which explain new features are rarely considered essential enough.

When your organization is not up-to-date in the latest development practices, you might consider to make it your mission to get them up-to-date so that explanations of unusual syntax aren't necessary. When this is not an option (you have no time, no resources, and not feeling that this is your responsibility), you should either avoid the new features to not confuse the other teammembers or comment them.

Remember the rules of good comments:

The newbie explains the syntax

The apprentice explains what is happening

The expert explain why it is happening

Bad:

```<code>" This uses the new line_exist operator in 740 which replaces READ TABLE
IF line_exists( itab[ carrid = 'AE' ] ).
    PERFORM foobar.
ENDIF.
</code>```

When I know that operator this comment does not help me at all. Also, I might laugh at you for calling it "new" because this might be the year 2028 and that operator was declared obsolete years ago. When I don't know the operator, you just sent me on a 10 minute Googling spree instead of helping me understand your code.

Better:

```<code>" When any position has the carrier 'AE', we need to do the foobar operation
IF line_exists( itab[ carrid = 'AE' ] ).
    PERFORM foobar.
ENDIF.
</code>```

This tells me what is happening so I don't even need to understand what this new language feature does. When I didn't knew it before, you just demonstrated me what it does, so I learned something from you. And even when I already know it, your comment might be more readable than your code, helping me to understand your program.

Even better:

```<code>" Anytime there is at least one flight by carrier AE on the
" flight list, the foobar operation must be performed to prevent
" all the foobaz from getting confabulated.
IF line_exists( itab[ carrid = 'AE' ] ).
    PERFORM foobar.
ENDIF.
</code>```

It doesn't just tell me what is happening but also what purpose it fulfills.

Body:
In the context of ABAP you can rarely expect everyone to be familiar with all the newest features because:

ABAP has such a long history and the ancient language constructs are still encountered all the time (I am currently modifying a report which uses a logical database and makes excessive use of tables with header lines).

SAP themselves rarely uses the new features to ensure backward compatibility with systems not patched to newer releases yet, so you rarely encounter the new features "in the wild".

The SAP education courses are very expensive, so companies avoid sending people to any which they don't desperately needed for their work. The delta courses which explain new features are rarely considered essential enough.

When your organization is not up-to-date in the latest development practices, you might consider to make it your mission to get them up-to-date so that explanations of unusual syntax aren't necessary. When this is not an option (you have no time, no resources, and not feeling that this is your responsibility), you should either avoid the new features to not confuse the other teammembers or comment them.

Remember the rules of good comments:

The newbie explains the syntax

The apprentice explains what is happening

The expert explain why it is happening

Bad:

" This uses the new line_exist operator in 740 which replaces READ TABLE
IF line_exists( itab[ carrid = 'AE' ] ).
    PERFORM foobar.
ENDIF.

When I know that operator this comment does not help me at all. Also, I might laugh at you for calling it "new" because this might be the year 2028 and that operator was declared obsolete years ago. When I don't know the operator, you just sent me on a 10 minute Googling spree instead of helping me understand your code.

Better:

" When any position has the carrier 'AE', we need to do the foobar operation
IF line_exists( itab[ carrid = 'AE' ] ).
    PERFORM foobar.
ENDIF.

This tells me what is happening so I don't even need to understand what this new language feature does. When I didn't knew it before, you just demonstrated me what it does, so I learned something from you. And even when I already know it, your comment might be more readable than your code, helping me to understand your program.

Even better:

" Anytime there is at least one flight by carrier AE on the
" flight list, the foobar operation must be performed to prevent
" all the foobaz from getting confabulated.
IF line_exists( itab[ carrid = 'AE' ] ).
    PERFORM foobar.
ENDIF.

It doesn't just tell me what is happening but also what purpose it fulfills.


答:
The only "logic" a view should contain, should be the code responsible for changing the visible state of the GUI to the user. Any code that manipulates data or calculates a value should be handled somewhere else.

Your view should know what the model looks like, but should be ignorant of the behavior associated with any thing the model exposes.

Passing simple data types to your view makes it responsible for both manipulating the GUI and storing the view state, which can easily become unwieldy.

You should pass the model directly to the view if the model is built for manipulation by the view. If your model is the same one used by your data storage mechanism, that can cause problems down the road if your internal representation and view representation diverge (as the often do).

Basically, you should just have a View, View Model, Data Model and something to handle business logic. Then all your concerns are easily separated, you just have to glue them together.

Title: How much should a view know about model?

Body:
I am building an application in python with a python wrapper for WPF and with DAG support.  I am currently at a point where I have to decide a consistent way of interacting between the data and the view.

As far as I see there are currently two obvious solutions.

First one is similar to how Android Applications are structured. You have a controller which sets/populates the view. So the controller owns the view and pushes only the primitive data that will be displayed. The view is just a dumb layer and has no idea of what's happening and where that data is from. And then if user interacts with the view, it will send callbacks to the controller (if it registered).

UserInfoController.py

```<code>userInfoView = UserInfoView()
userInfoView.onGenderChangedCallback = self.onGenderChangedCallback
userInfoView.setUserGenderValue(user.getGender())
</code>```

UserInfoView.py

```<code>def setUserGenderValue(self, gender):
    self.userGender = gender

def getView(self):
    return ui.Label(self.userGender, onEditCallback=self.onGenderChangedCallback)
</code>```

Second one is passing a (reference of) model to the view and letting the view to retrieve and update the data. The view now contains the model and therefore it can update it without any additional callbacks to the controller.

UserInfoViewModel.py

```<code>self.gender = 'Male'
</code>```

UserInfoView.py

```<code>def getView(self):
    return ui.Label(self.ViewModel().getGender(), onEdited=self.genderEdited)

def genderEdited(self, newValue):
    self.ViewModel().setGender(newValue)
</code>```

So I guess what I am asking is, should I pass the very primitive data and keep the view as generic as possible, then work with callbacks and do the business specifics in the controller.

Or should I pass the whole model to the view and let the view to update the model directly. This means that there will be less code to type.

PS. Do not judge the code - it's just for visualization.

EDIT:

Also to add - this application will be written in python which supports ducktyping. This means that with the second approach, the view is still reusable as long as the model meeting the required interface.