问:
Is implementing an interface defined in a subpackage an anti-pattern?
Let's say I have the following:

```<code>package me.my.pkg;
public interface Something {
    /* ... couple of methods go here ... */
}
</code>```

and:

```<code>package me.my;
import me.my.pkg.Something;
public class SomeClass implements Something {
    /* ... implementation of Something goes here ... */
    /* ... some more method implementations go here too ... */
}
</code>```

That is, the class implementing an interface lives closer to the package hierarchy root than does the interface it implements but they both belong in the same package hierarchy.

The reason for this in the particular case I have in mind is that there is a previously-existing package that groups functionality which the Something interface logically belongs to, and the logical (as in both "the one you'd expect" and "the one where it needs to go given the current architecture") implementation class exists previously and lives one level "up" from the logical placement of the interface. The implementing class does not logically belong anywhere under me.my.pkg.

In my particular case, the class in question implements several interfaces, but that feels like it doesn't make any (or at least no significant) difference here.

I can't decide if this is an acceptable pattern or not. Is it or is it not, and why?

答:
Although formally legitimate, this may indicate a code smell. To find out whether this is so in your case, ask yourself three questions:

Are you gonna need it?

Why did you package it that way?

How do you tell if your package API is convenient to use?

Are you gonna need it?

If you don't see the reason to invest extra effort into code maintainability, consider leaving it as is. This approach is based on YAGNI principle

programmer should not add functionality until deemed necessary... "Always implement things when you actually need them, never when you just foresee that you need them."

Considerations provided below assume that investing effort into further analysis is justified, say you expect the code to be maintained in the long term, or are interested in practicing and honing skills to write maintainable code. If this doesn't apply, feel free to skip the rest - because you ain't gonna need it.

Why did you package it that way?

First thing worth noting is that neither of official coding conventions and tutorial give any guidance on that, sending strong signal that this kind decisions is expected to be at discretion of a programmer.

But if you look at the design implemented by developers of JDK, you will notice that "leaking" sub-packages API into higher level ones isn't practiced there. For an example, look at concurrent util package and to its sub-packages - locks and atomic.

Worth noting that using subpackages API inside is considered OK, for example ConcurrentHashMap implementation imports locks and uses ReentrantLock. It just doesn't expose locks API as public.

Okay, core API developers seem to avoid that, and to find out why it is so ask yourself, why did you package it that way? The natural reason for that would be desire to communicate to package users some sort of hierarchy, sort of layers, so that subpackage corresponds to lower level / more specialized / narrower usage concepts.

This is often done in order to make API easier to use and understand, to help API users operate within particular layer, avoiding to bother them with concerns belonging to other layers. If this is the case, exposing lower level API from sub-packages would sure go against your intent.

Side note, if you can't tell why do you package it this way, consider getting back to your design and thoroughly analyzing it until you understand this. Think of it, if it's hard to explain even to you, even now, how harder would it be to those who will maintain and use your package in the future?

How do you tell if your package API is convenient to use?

For that, I strongly recommend to write tests that exercise API provided by your package. Asking someone to review wouldn't hurt either, but experienced API reviewer most likely will ask you to provide such tests anyway. Thing is, it is hard to beat watching a real usage example when reviewing API.

One may look at the class with single method having single parameter and dream wow how simple, but if test to invoke it requires creation of 10 other objects, invoking like 20 methods with 50 parameters total, this breaks a dangerous illusion and reveals true complexity of the design.

Another advantage of having tests is these may greatly simplify evaluation of various ideas you consider to improve your design.

It sometimes happened to me that relatively minor implementation changes triggered major simplifications in tests, reducing amount of imports, objects, method invocations and parameters. Even prior to running tests, this serves a good indication of the way worth pursuing further.

Opposite happened to me too - that is, when large, ambitious changes in my implementations intended to simplify API were proven wrong by respective minor, insignificant impact on tests, helping me drop the fruitless ideas and leave code as is (with maybe just a comment added to help understand the background of design and help others learn about the wrong way).

For your concrete case, first thing that comes to mind is to consider changing inheritance to composition - that is, instead of making SomeClass directly implement Something, include an object implementing that interface inside the class,

```<code>package me.my;
import me.my.pkg.Something;
public class SomeClass {
    private Something something = new Something() {
        /* ... implementation of Something goes here ... */
    }
    /* ... some more method implementations go here too ... */
}
</code>```

This approach may pay back in the future, preventing a risk for some subclass of SomeClass to accidentally override a method of Something, making it behave in a way that you didn't plan for.

Body:
Although formally legitimate, this may indicate a code smell. To find out whether this is so in your case, ask yourself three questions:

Are you gonna need it?

Why did you package it that way?

How do you tell if your package API is convenient to use?

Are you gonna need it?

If you don't see the reason to invest extra effort into code maintainability, consider leaving it as is. This approach is based on YAGNI principle

programmer should not add functionality until deemed necessary... "Always implement things when you actually need them, never when you just foresee that you need them."

Considerations provided below assume that investing effort into further analysis is justified, say you expect the code to be maintained in the long term, or are interested in practicing and honing skills to write maintainable code. If this doesn't apply, feel free to skip the rest - because you ain't gonna need it.

Why did you package it that way?

First thing worth noting is that neither of official coding conventions and tutorial give any guidance on that, sending strong signal that this kind decisions is expected to be at discretion of a programmer.

But if you look at the design implemented by developers of JDK, you will notice that "leaking" sub-packages API into higher level ones isn't practiced there. For an example, look at concurrent util package and to its sub-packages - locks and atomic.

Worth noting that using subpackages API inside is considered OK, for example ConcurrentHashMap implementation imports locks and uses ReentrantLock. It just doesn't expose locks API as public.

Okay, core API developers seem to avoid that, and to find out why it is so ask yourself, why did you package it that way? The natural reason for that would be desire to communicate to package users some sort of hierarchy, sort of layers, so that subpackage corresponds to lower level / more specialized / narrower usage concepts.

This is often done in order to make API easier to use and understand, to help API users operate within particular layer, avoiding to bother them with concerns belonging to other layers. If this is the case, exposing lower level API from sub-packages would sure go against your intent.

Side note, if you can't tell why do you package it this way, consider getting back to your design and thoroughly analyzing it until you understand this. Think of it, if it's hard to explain even to you, even now, how harder would it be to those who will maintain and use your package in the future?

How do you tell if your package API is convenient to use?

For that, I strongly recommend to write tests that exercise API provided by your package. Asking someone to review wouldn't hurt either, but experienced API reviewer most likely will ask you to provide such tests anyway. Thing is, it is hard to beat watching a real usage example when reviewing API.

One may look at the class with single method having single parameter and dream wow how simple, but if test to invoke it requires creation of 10 other objects, invoking like 20 methods with 50 parameters total, this breaks a dangerous illusion and reveals true complexity of the design.

Another advantage of having tests is these may greatly simplify evaluation of various ideas you consider to improve your design.

It sometimes happened to me that relatively minor implementation changes triggered major simplifications in tests, reducing amount of imports, objects, method invocations and parameters. Even prior to running tests, this serves a good indication of the way worth pursuing further.

Opposite happened to me too - that is, when large, ambitious changes in my implementations intended to simplify API were proven wrong by respective minor, insignificant impact on tests, helping me drop the fruitless ideas and leave code as is (with maybe just a comment added to help understand the background of design and help others learn about the wrong way).

For your concrete case, first thing that comes to mind is to consider changing inheritance to composition - that is, instead of making SomeClass directly implement Something, include an object implementing that interface inside the class,

package me.my;
import me.my.pkg.Something;
public class SomeClass {
    private Something something = new Something() {
        /* ... implementation of Something goes here ... */
    }
    /* ... some more method implementations go here too ... */
}

This approach may pay back in the future, preventing a risk for some subclass of SomeClass to accidentally override a method of Something, making it behave in a way that you didn't plan for.


问:
Regarding little endian and big endian conversion
I have a query regarding big endian and little endian.

Basically the conversion is used to reverse the byte order in memory .

When we need to do the conversion, do we need convert each and every data types?

答:
the conversion itself is usually some fancy bit twiddler solution like: (for a 32 bit integer)

```<code>i = ((i&0xff000000) >>> 24) | ((i&0x00ff0000) >> 8) | ((i&0x0000ff00) << 8) | ((i&0x000000ff) <<24)
</code>```

why it is needed is that some architectures are big endian and some are little endian and if they want to communicate through a byte stream they need to agree on endianness on the byte stream so that a 1 doesn't become a 16,777,216 (2^24)

the conversion is only used for primitives that are larger than 1 byte; the other (composite) types are generally defined as a sequence of other composite types and/or primitives that will remain in order

for example the LAS file format is defined in little endian. this means the first header bytes in order are:

first char of signature, (L)

second char of signature, (A)

third char of signature, (S)

fourth char of signature, (F)

low byte of file source ID,

high byte of file source ID,

low byte of global encoding,

high byte of global encoding,

and so on

ContentLicense: CC BY-SA 3.0

Body:
the conversion itself is usually some fancy bit twiddler solution like: (for a 32 bit integer)

i = ((i&0xff000000) >>> 24) | ((i&0x00ff0000) >> 8) | ((i&0x0000ff00) << 8) | ((i&0x000000ff) <<24)

why it is needed is that some architectures are big endian and some are little endian and if they want to communicate through a byte stream they need to agree on endianness on the byte stream so that a 1 doesn't become a 16,777,216 (2^24)

the conversion is only used for primitives that are larger than 1 byte; the other (composite) types are generally defined as a sequence of other composite types and/or primitives that will remain in order

for example the LAS file format is defined in little endian. this means the first header bytes in order are:

first char of signature, (L)

second char of signature, (A)

third char of signature, (S)

fourth char of signature, (F)

low byte of file source ID,

high byte of file source ID,

low byte of global encoding,

high byte of global encoding,

and so on


答:
The answer is: it depends.

If you're sharing data with another platform, or (de)serializing some binary format with defined endianness, then you need to match that platform's or format's endianness.

Assuming that target endianness is well defined (and different from your native endianness), that will tell you what conversions you need.

Oh, and I'd suggest using htons, htonl and friends rather than twiddling the bytes manually - they're more likely to get optimized to a single BSWAP instruction or similar.

Title: Regarding little endian and big endian conversion

Body:
I have a query regarding big endian and little endian.

Basically the conversion is used to reverse the byte order in memory .

When we need to do the conversion, do we need convert each and every data types?


问:
How to keep your third party libraries up to date?
Let's say that I have a project that depends on 10 libraries, and within my project's trunk I'm free to use any versions of those libraries. So I start with the most recent versions. Then,  each of those libraries gets an update once a month (on average). Now, keeping my trunk completely up to date would require updating a library reference every three days.

This is obviously too much. Even though usually version 1.2.3 is a drop-in replacement for version 1.2.2, you never know without testing. Unit tests aren't enough; if it's a DB / file engine, you have to ensure that it works properly with files that were created with older versions, and maybe vice versa. If it has something to do with GUI, you have to visually inspect everything. And so on.

How do you handle this? Some possible approaches:

If it ain't broke, don't fix it. Stay with your current version of the library as long as you don't notice anything wrong with it when used in your application, no matter how often the library vendor publishes updates. Small incremental changes are just waste.

Update frequently in order to keep change small. Since you'll have to update some day in any case, it's better to update often so that you notice any problems early when they're easy to fix, instead of jumping over several versions and letting potential problems to accumulate.

Something in between. Is there a sweet spot?

答:
I'm currently setting up something like that :

1 mercurial repo for each extension of my application

a mercurial repo that gather specific versions of several 3rd party libraries

a SVN repo for graphic resources/works (but might change to something else)

a mercurial repo for my application, that uses the mercurial subrepos feature to use specific version of the 3rd pary repo, and some of the basic extensions

Now when I need to work on an extension that is not "basic" (implicitely included as a subrepo in the application repo), I simply get clone the repo in the extensions folder and let CMake generate the projects and solutions for the whole application.

That way, I can :

change the 3rd parties in a clone, check that it works with the app, push it in the 3rd pary repo, then update the subrepo version of the application repo to the new 3rd party repo version

work on extensions independently, all togeter or just pick some specific

not have to worry about having to link projects together, this is done by Cmake just by having the projects subrepos scanned with the whole application repo.

Don't have a lot of experience with this organization yet, but i think that's pretty useful.

ContentLicense: CC BY-SA 2.5


问:
How should a non-IT manager secure the long-term maintenance and development of essential legacy software?
We are a small, very specialized, benefits administration firm with an extremely useful, robust collection of software, some written in COBOL but most in BASIC. Two full-time consultants have ably maintained and improved this system over more than 30 years. Needless to say they will soon retire. (One of them has been desperate to retire for several years but is loyal to a fault and so hangs on despite her husband's insistence that golf should take priority.)

We started down the path of converting to a system developed by one of only three firms in the country that offer the type of software we use. We now feel that although this this firm is theoretically capable of completing the conversion process, they don't have the resources to do so timely, and we have come to believe that they will be unable to offer the kind of service we need to run our business. (There's nothing like being able to set one's own priorities and having the authority to allocate one's resources as one sees fit.)

Hardware is not a problem--we are able to emulate very effectively on modern servers. If COBOL and BASIC were modern languages, we'd be willing to take the risk that we could find replacements for our current consultants going forward.

It seems like there ought to be a business model for an IT support firm that concentrates on legacy platforms like this and provides the programming and software development talent to support a system like ours, removing from our backs the risks of finding the right programming talent and the job of convincing younger programmers that they can have a productive, rewarding career, in part in an old, non-sexy language like BASIC.

In short, as non-IT managers, how can we best manage this transition?

答:
It may seem that "there ought to be a business model for an IT support firm that concentrates on legacy platforms like this", but personally I think that is just wishful thinking on your part as it would "solve" the challenges you face in one fell swoop.

Staying stuck in old environments is not the way to go forward. And I for one wouldn't bet the life of any company on trying to stay stuck by finding some firm that, for now, would be willing to do what you apparently can't.

So not an answer to the actual quesion you asked, but sincere advice on how you could move forward while keeping the risks of a migration to the minimum.

Read "How to survive a ground-up rewrite wihtout losing your sanity"

Don't make the error of a long migration project with no real results for a long time. Read "How to survive a ground-up rewrite wihtout losing your sanity"

I cannot stress enough how the advice in that article has helped me in tackling/approaching similar problems after burning myself doing those kinds of projects the "old" way.

Set up automated tests

If you haven't got it in place already (why ever not?), get your current programmers to create an automated test harness for your applications.

The automated test suite should cover all functional areas of your applications. It sh/would document the current working specifications in "when_X_then_Y" rules of the individual test cases. This will help both in keeping changes in your current code from breaking existing functionality as well as support any migration to a new environment.

As you are dealing with COBOL and BASIC, the test suite should probably be on the level of integration tests: working off a "fixed" set of input files/databases and checking the output files/changed database contents of specific programs (COBOL) and/or applications. For the BASIC parts of your software this may mean adding command line parameters to make them exercise certain functions without (G)UI intervention, or getting a (G)UI based automated test tool.

Isolate calculations and other algorithms

Even Cobol supports the notion of sub programs callable from a main program. Isolate all import calculations and other algorithms in separate programs or modules. Goal is to create a library of programs/modules/whatever that do the grunt work isolated from everything that gathers input and creates output.

Adapt the test harness to test them both through your old applications as well as in isolation. This will ensure that the work you are doing on the "old" code to facilitate migration to a newer environment will introduce as few errors as possible.

Start a new set of applications in a "current" environment

Don't convert your current code. Converting one language to another means imposing the constraints of the old environment on the new. The result if often less than desirable (read: the result will be terrible and a pain to maintain). Migrate. Take the time to set up your applications in the new environment in a way that is considered best practice for that environment.

Get new programmers, well versed in your chosen environment, in to do so. Make it a priority from day one to isolate all important calculations and algorithms in separate classes and/or packages and hide them behind interfaces. Use dependency injection (the cheapest kind of DIY dependency injection will do) to tell your new application which classes to instantiate/use to do the calculations.

This is a good way to do things anyway and in your case will allow you to migrate those important parts on a per case basis. It will also hide the intricacies of calling basic and/or cobol programs from the calling functions in the new environment.

Don't go any further that setting up the applications and perhaps setting up the single most important input/output function that uses a calculation from your COBOL/BASIC "library".

Integrate your COBOL/BASIC "library"

Figure out how to call your COBOL/BASIC "library" from your new environment. This may involve setting up parameter files or database tables, executing a COBOL/BASIC program that wraps the COBOL/BASIC library you set up earlier. If you are lucky your version of BASIC may allow for the creation of DLL's that can be called directly.

Implement the class in your new environment that will call the COBOL/BASIC "library" and test the heck out of it using the same tests that are in test harness of the old environment, but now in the form of unit tests in the new environment.

Yes this means "duplicating" the tests, but it is a safety net you don't want to do without. If only because these unit tests will later serve as the tests to check the implementation of your calculations and algorithms when they are migrated to your new environment.

But again: don't go any further than adding the unit tests for the calculation(s) used by the single most important from the previous step.

Flesh out the new applications in iterations

Flesh out the new applications by repeating the previous two steps for all functions in your old applications. Keep adding those unit tests that check the calculations to your new applications' test harness. Use the integration test suite to check that the migrated functions function the same as your old applications.

Migrate the core library in iterations

And finally migrate the calculations and algorithms in your COBOL/BASIC "library", re-implementing them in your new environment. Again, do this iteratively using the (unit) tests as a way to keep your sanity.


答:
Rather than look for a firm to maintain your legacy software or for a firm to rewrite your legacy software, look for a firm to provide a continued benefits administration system service.  Outsource the problems of deciding whether or not to rewrite the software, what schedule to set, which language(s) or tools to use.

Yes, the obvious costs of this approach might exceed the obvious costs of hiring new programmers but, by your own admission you are a non-IT manager and it is easy to foresee scenarios in which you make decisions that ultimately cost your company more than the obvious costs of outsourcing.

Title: How should a non-IT manager secure the long-term maintenance and development of essential legacy software?

Body:
We are a small, very specialized, benefits administration firm with an extremely useful, robust collection of software, some written in COBOL but most in BASIC. Two full-time consultants have ably maintained and improved this system over more than 30 years. Needless to say they will soon retire. (One of them has been desperate to retire for several years but is loyal to a fault and so hangs on despite her husband's insistence that golf should take priority.)

We started down the path of converting to a system developed by one of only three firms in the country that offer the type of software we use. We now feel that although this this firm is theoretically capable of completing the conversion process, they don't have the resources to do so timely, and we have come to believe that they will be unable to offer the kind of service we need to run our business. (There's nothing like being able to set one's own priorities and having the authority to allocate one's resources as one sees fit.)

Hardware is not a problem--we are able to emulate very effectively on modern servers. If COBOL and BASIC were modern languages, we'd be willing to take the risk that we could find replacements for our current consultants going forward.

It seems like there ought to be a business model for an IT support firm that concentrates on legacy platforms like this and provides the programming and software development talent to support a system like ours, removing from our backs the risks of finding the right programming talent and the job of convincing younger programmers that they can have a productive, rewarding career, in part in an old, non-sexy language like BASIC.

In short, as non-IT managers, how can we best manage this transition?


问:
Implementing new required feature after software release
Fake Scenario

There is a software that was released 1 year ago. The software is to map and register all kind of animals on our planet. When the software was released, the client only needed to know the scientific name of the animal, a flag if it is in risk of extinction and a scale of dangerous(that is a fake software and specification, I don't want to discuss this here).

There are already 100.000 animals records saved on DB.

New Feature

One year later, the client wants a new feature. It is really important to him to know the animals classes, and this is a required field. So he asks me to put a field to input the animal class, and this field is required. Or maybe where this animal was discovered.

Problem

I have already 100.000 recorded animals without a class or where it was discovered, but I need to insert a new column to storage this information and this column can't be null. I don't have a default value for this situation (there isn't a default animal class or where it was discovered). I don't want to keep the requirement rule only on my software, my DB must have this requirement too(I like to keep business rules on DB too).

What are the alternatives to solve this situation?

I am on a situation that this new feature cannot be previewed or reviewed for the existing records. The time already passed and I can't go back on time to get it

答:
As others have suggested having your client supply the missing data is the best option.

Failing that, another idea would be to set a default -- such as "NOCLASS" that you could easily identify as invalid / default / pre-existing data. You could even wire the UI to force the user to update this if they update a record.


问:
Functional/nonfunctional requirements VS design ideas

Problem domain

Functional requirements defines what a system does.

Non-Functional requirements defines quality attributes of what the system does as a whole.(performance, security, reliability, volume, useability, etc.)

Constraints limits the design space, they restrict designers to certain types of solutions.

Solution domain

Design ideas , defines how the system does it.

For example a stakeholder need might be we want to increase our sales, therefore we must improve the usability of our webshop so more customers will purchase, a requirement can be written for this. (problem domain)

Design takes this further into the solution domain by saying "therefore we want to offer credit card payments in addition to the current prepayment option".

My problem is that the transition phase from requirement to design seems really vague, therefore when writing a software requirement specification I am often confused whether or not I incorporated design ideas in my requirements, that would make my requirement wrong.

Another problem is that I often write functional requirements as what a system does, and then I also specify in what timeframe it must be done. But is this correct? Is it then a still a functional requirement or a non functional one? Is it better to seperate it into two distinct requirements?

Here are a few requirements I wrote:

FR1 Registration of Organizer

FR1 describes the registration of an Organizer on CrowdFundum

FR1.1 The system shall display a registration form on the website.

FR1.2 The system shall require a Name, Username, Document number passport/ID card, Address, Zip code, City, Email address, Telephone number, Bank account, Captcha code on the registration form when a user registers.

FR1.4 The system shall display an error message containing: “Registration could not be completed” to the subscriber within 1 seconds after  the system check of the registration form was unsuccessful.

FR1.5 The system shall send a verification email containing a verification link to the subscriber within 30 seconds after the system check of the registration form was successful.

FR1.6 The system shall add the newly registered Organizer to the user base within 5 seconds after the verification link was accessed.

FR2 Organizer submits a Project

FR2 describes the submission of a Project by an Organizer on CrowdFundum

  - FR2 The system shall display a submit Project form to the Organizer accounts on the website.<
  - FR2.3 The system shall check for completeness the Name of the Project, 1-3 Photo’s, Keywords of the Project, Punch line, Minimum and maximum amount of people, Funding threshold, One or more reward tiers, Schedule of when what will be organized, Budget plan, 300-800 Words of additional information about the Project, Contact details within 1 secondin after an Organizer submits the submit Project form.
  - FR2.8 The system shall add to the homepage in the new Projects category the Project link within 30 seconds after the system made a Project webpage

  - FR2.9 The system shall include in the Project link for the homepage : Name of the Project, 1 Photo, Punch line within 30 seconds after the system made a Project webpage.

Questions:

FR 1.1 : Have I incorporated a design idea here, would " the system shall have a registration form" be a better functional requirement?

F1.2 ,2.3 : Is this not singular? Would the conditions be better written for each its own separate requirement

FR 1.4: Is this a design idea? Is this a correct functional requirement or have I incorporated non functional(performance) in it? Would it be better if I written it like this:
FR1 The system shall display an error message when check is unsuccessful.
 NFR: The system will respond to unsuccesful registration form checks within 1 seconds. Same question with FR 2.8 and 2.9.

FR2.3: The system shall check for "completeness", is completeness here used ambigiously? Should I rephrase it?

FR1.2: I added that the system shall require a "Captcha code" is this a functional requirement or does it belong to the "security aspect" of a non functional requirement.

I am eagerly waiting for your response.
Thanks!

答:
I'm going to rely upon the SWEBOK (Software Engineering Book Of Knowledge) to guide my answer.

In the Software Requirements* chapter, we're provided with more formal definitions of the terms needed for your question.

Functional requirements describe the functions that the software is to execute; for example, formatting some text or modulating a signal. They are sometimes known as capabilities.

Nonfunctional requirements are the ones that act to constrain the solution. Nonfunctional requirements are sometimes known as constraints or quality requirements.

I point those out because there appears to be some overlap in the way you have been requested to generate your document.  You stated: A SRS should only have functional, non functional and constraints and based upon the SWEBOK / IEEE definition you can see that non-functional requirements and constraints are one and the same.

And while some may protest of overkill, there are three main documents related to requirements work.

System Definition Document This document (sometimes known as the user requirements document or concept of operations) records the system requirements. It defines the high-level system requirements from the domain perspective.

System Requirements Specification In this view, system requirements are specified, the software requirements are derived from the system requirements, and then the requirements for the software components are specified.

Software Requirements Specification establishes the basis for agreement between customers and contractors or suppliers (in market-driven projects, these roles may be played by the marketing and development divisions) on what the software product is to do as well as what it is not expected to do.

So the problem with all of that is it appears clear cut when explained, but it ends up being muddy when implemented.  To help focus my answer, I'm going to ignore the System Reqs Spec as it's a huge topic and not quite necessary for your question.

The primary challenge you're encountering is that you are mixing your SDD and your SoftRS (software) documents.  Since the two documents are communication bridges between three camps, it's natural and unavoidable that you'll see some overlap between the two.  The SDD is a bridge between the client and the analysts, whereas the SRS is a bridge between the analysts and the developers.

So how do you draw the line between the SDD and the SRS?  Let's go back to the System's Engineering trinity:

what

why

how

And they really should go in that order because when we look at the V-model, we use those three in order to work our way through the layers.  You start with the what & why at the system layer.  As you capture those, you start generating ideas for the how, which goes into the next layer below in the V-Model.  "Eventually" you finish up with a particular layer and you start revising the layer below in the same manner.  The difference on the lower layers is that the upper layer's how becomes this layer's what.

Blah, blah, wall of text, let's tackle your questions.

FR 1.1 : Have I incorporated a design idea here, would " the system shall have a registration form" be a better functional requirement?

I'm going to start off with "meh" for an answer.  "shall display" vs "shall have" on a form that requires user interaction is kind of pointless.  If an argument erupted on a real project over the semantics between those two forms, I'd consider that a huge red flag and try to bail on the project.  Seriously.

"Shall display" implies "have" whereas "shall have" implies "display" in this case.  To be fully pedantic, you would need at least "shall have and display" to make it clear.  Any of those three variants is fine though.

F1.2 ,2.3 : Is this not singular? Would the conditions be better written for each its own separate requirement

They are certainly related, and it gets tricky on how you want to express those.  I rely upon team norms in this case as I have seen it go either way with equivalent results.  The important part is to be consistent in how you handle compound requirements like this.

FR 1.4: Is this a design idea? Is this a correct functional requirement or have I incorporated non functional(performance) in it? Would it be better if I written it like this:
FR1 The system shall display an error message when check is unsuccessful.
NFR: The system will respond to unsuccesful registration form checks within 1 seconds. Same question with FR 2.8 and 2.9.

I would probably break these out, yes.  Here's why:  The first is providing function (display error message) while the second provides the constraints (specific amount of time) in providing that function.  Constraints often change, but the functionality doesn't.  By moving the constraint to its own requirement, we can get up front agreement on the functionality and then deal with the constraints (how fast was the message delivered) when we get into implementation.

FR2.3: The system shall check for "completeness", is completeness here used ambigiously? Should I rephrase it?

Your close to explaining completeness with the list of items you provide.  However, you could be more clear in specifying what determines completeness or not in each of the items you listed.

FR1.2: I added that the system shall require a "Captcha code" is this a functional requirement or does it belong to the "security aspect" of a non functional requirement.

Depends upon what level of your design you are talking about.  At a high level, it's a non-functional requirement because it's a constraint.  At a low level, it's a functional requirement because it's specifying a function to be provided.

* SWEBOK is currently in a review state for the next release.  Except for the main link, some of the additional links may go stale.


问:
Are we queueing and serializing properly?
We process messages through a variety of services (one message will touch probably 9 services before it's done, each doing a specific IO-related function).  Right now we have a combination of the worst-case (XML data contract serialization) and best-case (in-memory MSMQ) for performance.

The nature of the message means that our serialized data ends up about 12-15 kilobytes, and we process about 4 million messages per week.  Persistent messages in MSMQ were too slow for us, and as the data grows we are feeling the pressure from MSMQ's memory-mapped files.  The server is at 16GB of memory usage and growing, just for queueing.  Performance also suffers when the memory usage is high, as the machine starts swapping.  We're already doing the MSMQ self-cleanup behavior.

I feel like there's a part we're doing wrong here.  I tried using RavenDB to persist the messages and just queueing an identifier, but the performance there was very slow (1000 messages per minute, at best).  I'm not sure if that's a result of using the development version or what, but we definitely need a higher throughput[1].  The concept worked very well in theory but performance was not up to the task.

The usage pattern has one service acting as a router, which does all reads.  The other services will attach information based on their 3rd party hook, and forward back to the router.  Most objects are touched 9-12 times, although about 10% are forced to loop around in this system for awhile until the 3rd parties respond appropriately.  The services right now account for this and have appropriate sleeping behaviors, as we utilize the priority field of the message for this reason.

So, my question, is what is an ideal stack for message passing between discrete-but-LAN'ed machines in a C#/Windows environment?  I would normally start with BinaryFormatter instead of XML serialization, but that's a rabbit hole if a better way is to offload serialization to a document store.  Hence, my question.

[1]: The nature of our business means the sooner we process messages, the more money we make.  We've empirically proven that processing a message later in the week means we are less likely to make that money.  While performance of "1000 per minute" sounds plenty fast, we really need that number upwards of 10k/minute.  Just because I'm giving numbers in messages per week doesn't mean we have a whole week to process those messages.

=============== edit:

Additional information

Based on the comments, I'll add some clarification:

I'm not sure serialization is our bottleneck.  I've benchmarked the application, and while serialization does show up in the heat graph, it's only responsible for maybe 2.5-3% of the service's CPU utilization.

I'm mostly concerned about the permanence of our messages and potential misuse of MSMQ.  We are using non-transactional, non-persistent messages so we can keep queueing performance up, and I would really like to have at least persistent messages so they survive a reboot.

Adding more RAM is a stopgap measure.  The machine has already gone from 4GB -> 16GB of RAM and it's getting harder and harder to take it down to continue adding more.

Because of the star routing pattern of the application, half the time an object is popped then pushed to a queue it doesn't change at all.  This lends itself again (IMO) to storing it in some kind of key-value store elsewhere and simply passing message identifiers.

The star routing pattern is integral to the application and will not change.  We can't application-centipede it because every piece along the way operates asynchronously (in a polling fashion) and we want to centralize the retry behavior in one place.

The application logic is written in C#, the objects are immutable POCOs, the target deployment environment is Windows Server 2012, and we are allowed to stand up additional machines if a particular piece of software is only supported in Linux.

My goals are to maintain current throughput while reducing memory footprint and increasing fault tolerance with a minimum outlay of capital.

答:
HP ProLiant ML350G5 system gets 82k transactions per minute - ie it has over 8x that "10k/minute" throughput you mentioned.

Performance:  82,774 tpmC

Also, to be honest, I'd have just gone with 64 or even 128 GB of RAM - RAM is cheap. Greenspun points out the difference between "throw RAM at it" and "get a smart MIT-educated guy to optimize it", and the RAM wins.

He ended up with a SQL Server machine equipped with 64 GB of RAM and a handful of front-end machines running ASP.NET pages... The site, swaptree.com, handles its current membership of more than 400,000 users (growing rapidly) without difficulty...

Note "the machine has already gone to 16 GB of RAM" is far from enough, with an article pointing out a server that was handling 400k users on 64 GB of RAM.


问:
Law of Demeter in MVC regarding Controller-View communication
The scenario: Having a Controller that controls a view composed of complex subviews.

Each one of those subviews is a separated class in a separate file. For example, one of those subviews is called ButtonsView, and has a bunch of buttons.

The Controller has to access those buttons.

Would accessing those buttons like this:

```<code>controllerMainView.buttonsView.firstButton.state();
</code>```

be a violation of the LOD?

On one hand, it could be yes because the controller is accessing the inner hierarchy of the view. On the other, a Controller should be aware of what happens inside the view and how is composed.

Any thoughts?

答:
a Controller should be aware of what happens inside the view

No it doesn't. Your buttons should send a command to the controller.


答:
The Controller has to access those buttons.

It should not.  A controller reacts to user actions sent by the view, then updates the model.   So the controller observes the view and controls the model.  The view observes the model.

The notifications sent by the view should be related to the model, not the view elements, e.g. "name-changed", not "name text box edited".  The controller should be completely ignorant of the view components.  This allows the view to change without requiring any change to the controller.  It allows one controller to work with different views of a model.

Dependencies:

```<code>Controller -> Model, View
View -> Model
</code>```

Control flow:

```<code>input event --> View -- view event -> Controller -- model change -> Model -- update notification -> View
</code>```

If you compose a view from sub-views, then the containing view should collect the notifications from the sub-views and, if necessary, translate them to a higher-level event and notify the controller:

```<code>input event --> SubView -- sub-view event -> View -- view event -> Controller
</code>```

Title: Law of Demeter in MVC regarding Controller-View communication

Body:
The scenario: Having a Controller that controls a view composed of complex subviews.

Each one of those subviews is a separated class in a separate file. For example, one of those subviews is called ButtonsView, and has a bunch of buttons.

The Controller has to access those buttons.

Would accessing those buttons like this:

```<code>controllerMainView.buttonsView.firstButton.state();
</code>```

be a violation of the LOD?

On one hand, it could be yes because the controller is accessing the inner hierarchy of the view. On the other, a Controller should be aware of what happens inside the view and how is composed.

Any thoughts?

Body:
The Controller has to access those buttons.

It should not.  A controller reacts to user actions sent by the view, then updates the model.   So the controller observes the view and controls the model.  The view observes the model.

The notifications sent by the view should be related to the model, not the view elements, e.g. "name-changed", not "name text box edited".  The controller should be completely ignorant of the view components.  This allows the view to change without requiring any change to the controller.  It allows one controller to work with different views of a model.

Dependencies:

Controller -> Model, View
View -> Model

Control flow:

input event --> View -- view event -> Controller -- model change -> Model -- update notification -> View

If you compose a view from sub-views, then the containing view should collect the notifications from the sub-views and, if necessary, translate them to a higher-level event and notify the controller:

input event --> SubView -- sub-view event -> View -- view event -> Controller


问:
High traffic chat - how to check if there is new message and show it for all users
I already had question about this but obviously it was not accepted very well, apparently too long when it's actually more information so you could have given me better answer.

Ok, I will be much clearer now. Best possible logic to develop scalable chat in terms of stability, storing/reading messages on chat, updating chat on new message for all users etc.? I have most of this developed, the logic I think I miss is --> check if there is new message and show it for all users. I have this implemented but it crashes the site due to its traffic of 300k-400k people, so that's my main question.

The chat is PHP based and uses Pusher (www.pusher.com) for instant messaging but it lacks what I need because it's more like a websocket.

I'm using hardcoded files to keep messages (want to avoid database as much as possible). It's a no extension type of file, I'm sure you know. I'm getting crash with

```<code>$fp = fopen(..., "w"); // pretend ... is the path and filename
fwrite($fp, $msg); //hardcode the message
fclose($fp);
</code>```

where $msg is the message itself. I'm having 1 file per message. I show last 150 messages = 150 file accesses and reads, yeah it's too much I guess. I have better logic now which I'm pursuing and that is 1 file with last 50-100 messages at all time. Sure it should be much better.

How does it crash, that's the trickiest part because everything seems ordinary, believe me it is difficult to determine what exactly crashes the site, but in like 5 minutes when I try to open the site it's gone, then I put the old content without chat and is back online again.

I'm having jquery post every 1 second to check if there is new message. I'm using timestamp in a special file where I keep the time last message was sent and if ((time() - time in file) <= 2) = reload last 150 messages including the last one. Too much input/output, write/read or however to say it I think is what crashes the site.

答:
What may be a good way to handle this is to insert data using php into a xml file that has the same structure as your mysql database.

Users would read the xml and thereby not force a php to do too much.

Every four days you could insert data from xml to database that is older than two days and clean up the xml file .


答: While agreeing with the other answer so far (aka "yes, so don't do that") I'd add that the notion of 'subview' implies the possibility of 'subcontroller', and assert that it's ok for the main controller to know of and talk to the subcontrollers, but only in circumstances where the information/effect communicated cannot be transmitted by (simple) changes the model state.</p>


答:
It varies depending things like on the libraries, what they're used for, how pervasive they are in your code, the cost (in terms of time and money) of performing the upgrade, and so on.

Ideally you would always have the latest all of the time, but if the new version isn't backward-compatible, what then?  You may have to shelve that update for a future release until you can handle the change carefully.  There could be some subtle change in behaviour (such as "you now need to set property X before calling method Y, or you get a slow memory leak") which is difficult to verify in testing.

On the other hand, the new version could have some serious security fixes, so you have to take that into account as well.

Short version:  take it on a case-by-case basis.

Title: How to keep your third party libraries up to date?

Body:
Let's say that I have a project that depends on 10 libraries, and within my project's trunk I'm free to use any versions of those libraries. So I start with the most recent versions. Then,  each of those libraries gets an update once a month (on average). Now, keeping my trunk completely up to date would require updating a library reference every three days.

This is obviously too much. Even though usually version 1.2.3 is a drop-in replacement for version 1.2.2, you never know without testing. Unit tests aren't enough; if it's a DB / file engine, you have to ensure that it works properly with files that were created with older versions, and maybe vice versa. If it has something to do with GUI, you have to visually inspect everything. And so on.

How do you handle this? Some possible approaches:

If it ain't broke, don't fix it. Stay with your current version of the library as long as you don't notice anything wrong with it when used in your application, no matter how often the library vendor publishes updates. Small incremental changes are just waste.

Update frequently in order to keep change small. Since you'll have to update some day in any case, it's better to update often so that you notice any problems early when they're easy to fix, instead of jumping over several versions and letting potential problems to accumulate.

Something in between. Is there a sweet spot?


答:
It sounds like this application is "core" to your business.  In cases where a system or process is what IS your business that is a case for having your own custom solution.

You alluded to this.  Unfortunately given the lengthly time you have gone since updating your technologies, this will be an extremely difficult undertaking.

I would recommend one of two routes.

Staff up an IT group of developers/project managers/QE/operations and build out your system incrementally, as noted in the rather technical answer above. This will however, be exceptionally expensive.

Rather than an off the shelf provider, look for a qualified custom developer consultant.  This group will handle all of the resources to build out your new system, then you can bring it in house with a small staff than option 1 to continue.  This option has a different set of risks however, selecting a good provider can be very difficult for the non-technical.  They can also be very high risk with cost overruns etc.  To mitigate this route, use your existing staff to craft a very detailed set of requirements (from the user perspective) for your bid.  Then ask for fixed price bids as well.

Good luck, you have about 20 years of legacy to overcome.  It will not be cheap, easy, or clean.


问:
I need to create an employee schedule/appointments program, but I don't know how to set it up
I work for a gym. I am the programmer, its just me, nobody else! Gets really frustrating when there's nobody to bounce conceptual ideas off of.

I'm getting rid of our archaic paper binder systems for tracking appointments and what not.

I've made a lot of things successfully already, now I'm trying to tackle the personal training department.

What I want:

Trainer information and work schedule

Appointment booking that can be done by time slot with all available trainers for that time, or by trainer with all available hours for that trainer

What I've tried so far:

I started with an 'appointments' database, a 'trainers' database, and a 'schedules' database. This became so complicated trying to fit the schedule in that I scrapped it.

Does anyone know know the best way to structure the tables for this and how to sort of make them communicate correctly? I don't need specific code, I just need help understand how to make this thing!

答:
It is better to buy or use something already in existance than to build something from scratch since this software is widely available.  Unless, of course you want to build a better product and sell it to more than 1 gym.  But if this is just for 1 gym or 1 customer, I would go the buy route and set it up for them.

Google "online appointment scheduler" and I am sure you will find something that suits your requirements.

If your set on building something, for the database schema:

Tables

Trainer

Customer

Gym

Appointment

Schedule (View)

Definitions

Trainer - All trainers

Customer - All customer (trained by trainers)

These two tables could be rolled up to a "Person" table if desired

Gym - All gyms

Appointment - Dual purpose (read below)

Schedule - A view that shows the calender by day, week, month

Appointment is dual purpose.  Trainers go in and schedule appointments at gyms for availability. Customers can search for trainer appointments and then schedule workout appointments based on the trainer appointments.  The schedule is a view of trainer availability versus scheduled customer appointments which can be aggregated by a certain time period.

In this case we are using appointments as a dual purpose to manage trainer availability and customer appointments.  If you think about it, trainer availability can be abstracted to an appointment at a gym, thus the same table (appointment) could be used for both trainers and customers.

Appointment would have relations to gym, trainer, and customer.  If you rolled Trainers and Customers into a person table it could be one relation, but it might be easier to separate then out.  Otherwise, you will need meta data to describe what kind of person it is (Trainer or Customer)

I would also consider data retention here and have an automated job to prune the appointment table.  No need to keep appointment from 6 months ago.  I am not sure of your retention requirements.


答: Here are some queue benchmarks you might be interested in.  MSMQ should be capable of handling 10K messages per second. Could it be a configuration issue or perhaps the clients aren't keeping up with reading the queue?  Also note how blazingly fast ZeroMQ is in those benchmarks(around 100K messages per second), it doesn't offer a persistence option but it should get you to where you want to be performance wise.</p>

Title: Are we queueing and serializing properly?

Body:
We process messages through a variety of services (one message will touch probably 9 services before it's done, each doing a specific IO-related function).  Right now we have a combination of the worst-case (XML data contract serialization) and best-case (in-memory MSMQ) for performance.

The nature of the message means that our serialized data ends up about 12-15 kilobytes, and we process about 4 million messages per week.  Persistent messages in MSMQ were too slow for us, and as the data grows we are feeling the pressure from MSMQ's memory-mapped files.  The server is at 16GB of memory usage and growing, just for queueing.  Performance also suffers when the memory usage is high, as the machine starts swapping.  We're already doing the MSMQ self-cleanup behavior.

I feel like there's a part we're doing wrong here.  I tried using RavenDB to persist the messages and just queueing an identifier, but the performance there was very slow (1000 messages per minute, at best).  I'm not sure if that's a result of using the development version or what, but we definitely need a higher throughput[1].  The concept worked very well in theory but performance was not up to the task.

The usage pattern has one service acting as a router, which does all reads.  The other services will attach information based on their 3rd party hook, and forward back to the router.  Most objects are touched 9-12 times, although about 10% are forced to loop around in this system for awhile until the 3rd parties respond appropriately.  The services right now account for this and have appropriate sleeping behaviors, as we utilize the priority field of the message for this reason.

So, my question, is what is an ideal stack for message passing between discrete-but-LAN'ed machines in a C#/Windows environment?  I would normally start with BinaryFormatter instead of XML serialization, but that's a rabbit hole if a better way is to offload serialization to a document store.  Hence, my question.

[1]: The nature of our business means the sooner we process messages, the more money we make.  We've empirically proven that processing a message later in the week means we are less likely to make that money.  While performance of "1000 per minute" sounds plenty fast, we really need that number upwards of 10k/minute.  Just because I'm giving numbers in messages per week doesn't mean we have a whole week to process those messages.

=============== edit:

Additional information

Based on the comments, I'll add some clarification:

I'm not sure serialization is our bottleneck.  I've benchmarked the application, and while serialization does show up in the heat graph, it's only responsible for maybe 2.5-3% of the service's CPU utilization.

I'm mostly concerned about the permanence of our messages and potential misuse of MSMQ.  We are using non-transactional, non-persistent messages so we can keep queueing performance up, and I would really like to have at least persistent messages so they survive a reboot.

Adding more RAM is a stopgap measure.  The machine has already gone from 4GB -> 16GB of RAM and it's getting harder and harder to take it down to continue adding more.

Because of the star routing pattern of the application, half the time an object is popped then pushed to a queue it doesn't change at all.  This lends itself again (IMO) to storing it in some kind of key-value store elsewhere and simply passing message identifiers.

The star routing pattern is integral to the application and will not change.  We can't application-centipede it because every piece along the way operates asynchronously (in a polling fashion) and we want to centralize the retry behavior in one place.

The application logic is written in C#, the objects are immutable POCOs, the target deployment environment is Windows Server 2012, and we are allowed to stand up additional machines if a particular piece of software is only supported in Linux.

My goals are to maintain current throughput while reducing memory footprint and increasing fault tolerance with a minimum outlay of capital.


答:
The internal storage of the native integer format is one aspect of the internal binary representation of numbers on various processors (two's complement vs. one's complement is another).  The position of the most-significant to least-significant bytes is an important aspect of data storage and transport.  For example byte order is a concern when transferring data between two systems using a binary data format (examples: XDR, Xupl, UBJson, etc).

We can examine 32-bit (b32) and 16-bit (b16) words on a machine.  They are stored in either four bytes (byte[4]) or two bytes (byte[2]), and can be examined as an array of bytes.  Consider the arrangement of the bytes in a 32-bit word (byte[4]).  Label the bytes A,B,C,D, and there are 4! = 24 possible permutations,

```<code>ABCD ABDC ACBD ACDB ADBC ADCB
BACD BADC BCAD BCDA BDAC BDCA
CABD CADB CBAD CBDA CDAB CDBA
DABC DACB DBAC DBCA DCAB DCBA
</code>```

Two of those permutations, ABCD and DCBA, are often used on processors, and we call these orderings the 'endianness' of the processor.  That is to say that the order of the bytes defines the endianness of the processor.  Suppose label A is most significant and D is least significant, then these two formats have special names,

Big-endian: ABCD, byte significance decreases as memory address increases

Little-endian: DCBA, byte significance increases as memory address increases

The 16-bit case is much simpler, only two permutations, AB and BA.

Other formats are used; the pdp-11 had a middle-endian layout, BADC.

There are many processors (ARM, PowerPC, Sparc9+, Alpha, Mips, Pa-Risc, IA-64) which can switch between big-endian and little-endian.

Here is a short C-program that will tell you the endianness of your processor,

```<code>#include <stdio.h>
#include <string.h>
typedef unsigned long ulong;
typedef unsigned char uchar;
int
main(int argc, char *argv[])
{
    uchar word[4] = {(uchar)0x01,(uchar)0x23,(uchar)0x45,(uchar)0x67};
    ulong be = 0x01234567;
    ulong le = 0x67452301;
    ulong me = 0x23016745;
    ulong we; ulong ue;
    memcpy(&we,word,4);
    if( we == be ) printf("Big-endian\n");
    if( we == le ) printf("Little-endian\n");
    if( we == me ) printf("Middle-endian\n");

    char UNIX[4+1]="UNIX";
    ue  = ((ulong)'U'); ue<<=8;
    ue += ((ulong)'N'); ue<<=8;
    ue += ((ulong)'I'); ue<<=8;
    ue += ((ulong)'X');
    printf("%s = %.4s\n",UNIX,(char*)&ue);

    int ndx;
    uchar *p = word;
    printf("@%x:\n", p );
    for( ndx=0; ndx<sizeof(we); ndx++ )
    {
        printf("[%02x] %03d:%02x\n", ndx, p[ndx], p[ndx] );
    }

}
</code>```

Body:
The internal storage of the native integer format is one aspect of the internal binary representation of numbers on various processors (two's complement vs. one's complement is another).  The position of the most-significant to least-significant bytes is an important aspect of data storage and transport.  For example byte order is a concern when transferring data between two systems using a binary data format (examples: XDR, Xupl, UBJson, etc).

We can examine 32-bit (b32) and 16-bit (b16) words on a machine.  They are stored in either four bytes (byte[4]) or two bytes (byte[2]), and can be examined as an array of bytes.  Consider the arrangement of the bytes in a 32-bit word (byte[4]).  Label the bytes A,B,C,D, and there are 4! = 24 possible permutations,

ABCD ABDC ACBD ACDB ADBC ADCB
BACD BADC BCAD BCDA BDAC BDCA
CABD CADB CBAD CBDA CDAB CDBA
DABC DACB DBAC DBCA DCAB DCBA

Two of those permutations, ABCD and DCBA, are often used on processors, and we call these orderings the 'endianness' of the processor.  That is to say that the order of the bytes defines the endianness of the processor.  Suppose label A is most significant and D is least significant, then these two formats have special names,

Big-endian: ABCD, byte significance decreases as memory address increases

Little-endian: DCBA, byte significance increases as memory address increases

The 16-bit case is much simpler, only two permutations, AB and BA.

Other formats are used; the pdp-11 had a middle-endian layout, BADC.

There are many processors (ARM, PowerPC, Sparc9+, Alpha, Mips, Pa-Risc, IA-64) which can switch between big-endian and little-endian.

Here is a short C-program that will tell you the endianness of your processor,

#include <stdio.h>
#include <string.h>
typedef unsigned long ulong;
typedef unsigned char uchar;
int
main(int argc, char *argv[])
{
    uchar word[4] = {(uchar)0x01,(uchar)0x23,(uchar)0x45,(uchar)0x67};
    ulong be = 0x01234567;
    ulong le = 0x67452301;
    ulong me = 0x23016745;
    ulong we; ulong ue;
    memcpy(&we,word,4);
    if( we == be ) printf("Big-endian\n");
    if( we == le ) printf("Little-endian\n");
    if( we == me ) printf("Middle-endian\n");

    char UNIX[4+1]="UNIX";
    ue  = ((ulong)'U'); ue<<=8;
    ue += ((ulong)'N'); ue<<=8;
    ue += ((ulong)'I'); ue<<=8;
    ue += ((ulong)'X');
    printf("%s = %.4s\n",UNIX,(char*)&ue);

    int ndx;
    uchar *p = word;
    printf("@%x:\n", p );
    for( ndx=0; ndx<sizeof(we); ndx++ )
    {
        printf("[%02x] %03d:%02x\n", ndx, p[ndx], p[ndx] );
    }

}


问:
Naming a predicate: "precondition" or "precondition_is_met"?
In my web app framework, each page can have a precondition that needs to be satisfied before it can be displayed to the user. For example, if user 1 and user 2 are playing a back-and-forth role-playing game, user 2 needs to wait for user 1 to finish his turn before he can take his turn. Otherwise, the user is displayed a waiting page.

This is implemented with a predicate:

```<code>def precondition(self):
    return user_1.completed_turn
</code>```

The simplest name for this API is precondition, but this leads to code like if precondition(): ..., which is not really obvious. Seems to me like it is more accurate to call it precondition_is_met(), but not sure about that either.

Is there a best practice for naming methods like this?

答:
The precondition seems to be part of the public API. Therefore, the naming should primarily reflect its usage by a consumer of your API. How your code handles that internally is another question all together.

I assume a user will provide a Page object that implements this precondition method. In that case, implementing a method precondition feels much more natural, declarative, and DWIMmy that the verbose (to the point of being Javaesque) precondition_is_met. Notice that the method is this precondition, and invoking it determines whether it was met.

If I am mistaken and the function is solely used in your internals, the longer name seems to be justified, although you could perhaps elide the is and use precondition_met or precondition_fulfilled.


问:
Best supporting argument for refactoring
Currently I am working on a code best described as C code living in C++ body. However I haven't been able to convince power that be to re-factor on ground of ease of maintenance. </p>

<p>What in your opinion is the best argument for refactoring the code. </p>

答:
I can think of three arguments for refactoring that I have used that have actually convinced sceptical directors.

Architectural change to allow additional types of desirable features.

Removing a block of code that has an established track record of bugs combined with a history of fixing a bug and a new bug appears.

Poor security / Poor performance that is affecting sales.

Using arguments like "the code is badly written" and "its really hard to understand the code" do not typically work.


问:
Is there a pattern to restrict which classes can update another class?
Say I have a class ImportantInfo with a public writable property Data. Many classes will read this property but only a few will ever set it. Basically, if you want to update Data you should really know what you're doing.

Is there a pattern I could use to make this explicit other than by documenting it? For example, some way to enforce that only classes that implement IUpdateImportantData can do it (this is just an example)? I'm not talking about security here, but more of a "hey, are you sure you want to do that?" kind of thing.

UPDATE

I've been faced with similar situations before, that's why I tried to keep the question more generic but it seems that a more concrete example is definitely required. So here it goes:

I have a Context class with a a property CurrentYear. Many classes use this Context object and, whenever CurrentYear changes, they need to react (reload themselves, for example). Now, there are some classes that can legitimately change CurrentYear. Of course, you don't want just everybody to change CurrentYear as that has an effect in many other classes. How would you go about that?

答: Unfortunately, I do not believe this is possible. I have tried the same approach and many hours of searching but was unsuccessful. The worse part is that comments for use of documentation can become a messy as well. I will do more research however and see what I can find. </p>


答:
One thing sort of comes to mind, if you switch to a private member and expose getters/setters..  Bear in mind I've never done .NET and am out of practice with Java, but this is the pseudocode I'm thinking of:

```<code>class SomeFickleClass {
   public interface IUpdateImportantData {
      public Data getData();
   }

   private Data myData;

   public function setData(IUpdateImportantData Thing) {
      myData = Thing.getData();
   }
   public function getData() {
      return myData;
   }
}
</code>```

And usage could be along the lines of:

```<code>final Data newData = ....
fickleClassInstance.setData(new SomeFickleClass.IUpdateImportantData() {
   public Data getData() {
      return newData;
   }
});
</code>```

So this does force an interface that requires IUpdateImportantData to do the update, and can do it on the fly with an anonymous class instance.  It's also a little awkward, which should discourage using it often.

Title: Is there a pattern to restrict which classes can update another class?

Body:
Say I have a class ImportantInfo with a public writable property Data. Many classes will read this property but only a few will ever set it. Basically, if you want to update Data you should really know what you're doing.

Is there a pattern I could use to make this explicit other than by documenting it? For example, some way to enforce that only classes that implement IUpdateImportantData can do it (this is just an example)? I'm not talking about security here, but more of a "hey, are you sure you want to do that?" kind of thing.

UPDATE

I've been faced with similar situations before, that's why I tried to keep the question more generic but it seems that a more concrete example is definitely required. So here it goes:

I have a Context class with a a property CurrentYear. Many classes use this Context object and, whenever CurrentYear changes, they need to react (reload themselves, for example). Now, there are some classes that can legitimately change CurrentYear. Of course, you don't want just everybody to change CurrentYear as that has an effect in many other classes. How would you go about that?

Body:
One thing sort of comes to mind, if you switch to a private member and expose getters/setters..  Bear in mind I've never done .NET and am out of practice with Java, but this is the pseudocode I'm thinking of:

class SomeFickleClass {
   public interface IUpdateImportantData {
      public Data getData();
   }

   private Data myData;

   public function setData(IUpdateImportantData Thing) {
      myData = Thing.getData();
   }
   public function getData() {
      return myData;
   }
}

And usage could be along the lines of:

final Data newData = ....
fickleClassInstance.setData(new SomeFickleClass.IUpdateImportantData() {
   public Data getData() {
      return newData;
   }
});

So this does force an interface that requires IUpdateImportantData to do the update, and can do it on the fly with an anonymous class instance.  It's also a little awkward, which should discourage using it often.


问:
From Java to Javascript?
I am primarily a Java programmer. Because of its OO principles and the general paradigm of Java programming, like wrapping things in static variables, and having things return specific types, heavily aids me in "visualizing" a program. Instead of thinking of a big program, I can, instead, focus on smaller organized parts of my eventual program, and add functionality and build up from there.

Thus, I have trouble programming in other languages. Or at least, I have not been able to program in the same ability as I do in Java compared to other languages.

I know Javascript has OO principles, so I'd like to learn this language in a OO-based like I would program with Java. Is this possible?

答:
They are nearly opposites in terms of how they are arranged:

Javascript is a dynamic, weakly typed language that can be used in a functional manner fairly easily. It helps to think of everything in Javascript as being an Object, even the functions (since they technically are, kinda).

Objects are effectively dictionaries of variables (which in turn can be other objects) and functions (methods). These can be added on the fly, much as you could add a new key and value to a HashMap in Java. You can even change existing methods on the fly.

A prototype is effectively a property that is attached to an object (dictionary) that says "These are the things that you should already have initialized when you are created" and then has a list of those variables and methods that it has and that the new object will be created with. You can then add additional properties to that new object and further extend it down the line.

The weak typing will probably cause the most problems, just remember that when in doubt, use === rather than ==.

In a more general sense, you generally want to adopt the idioms and quirks of a new language as your own. Programming language X in language Y is usually a recipe for disaster down the road. Additional general points are effectively covered by this question.

Title: From Java to Javascript?


答:
So, you currently have:

```<code>public class ImportantInfo {
    // constructor
    public ImportantInfo() { ... }

    // getter
    public Data getData() { ... }

    // dangerous setter
    public void setData(Data d) { ... }
}
</code>```

Managing Mutability

For one thing, maybe you don't want to include a set method by default.  For another, you probably don't want a public constructor.  Maybe you already have a factory, but your factory could return an immutable interface (that does not expose the set method).  The following interface has a method that returns the mutable implementation, but that requires work (so people won't do it by accident) and the name of the method provides a warning:

```<code>public interface ImportantInfo {
    public Data getData();

    // ... expose any other safe methods here ...

    public ImportantInfoImplementation getMutableImplementionButBeCareful();
}
</code>```

Now use a private constructor for ImportantInfo and a factory method that returns the immutable interface:

```<code>public class ImportantInfoImplementation {
    // constructor is now private so people can't instantiate this
    // willy-nilly.
    private ImportantInfoImplementation() { ... }

    // public factory method is now the way to get instances of this class
    // and you only get the interface which doesn't expose the dangerous
    // method.
    public static ImportantInfo of() {
        return new ImportantInfoImplementation();
    }

    // getter is mentioned in the interface
    @Override
    public Data getData() { ... }

    // dangerous setter is hidden by the interface.
    public void setData(Data d) { ... }

    // returns the mutable implementing class.
    @Override
    public ImportantInfoImplementation getMutableImplementionButBeCareful() {
        return this;
    }
}
</code>```

Now to use the dangerous method, clients have to call:

```<code>ImportantInfo ii = ImportantInfoImplementation.of();

// Living free and easy with safe immutable version.
someUntrustedMethod(ii);

// probably not messed up yet!
ii.getData();

// OK, I want it badly enough...
ii.getMutableImplementionButBeCareful().setData(d);
</code>```

I think @Izkata was shooting for something like the above, but I'm not really sure.

Leveraging Immutability

I'm not sure if your set method exposes some underlying danger, or if it makes the instance of this class unstable.  If the former, this won't help you, but if the latter, this may solve your problem: Make your class immutable:

```<code>public class ImportantInfo {
    private static final Data data;

    // constructor
    public ImportantInfo(Data d) {
        data = d;
    }

    // getter
    public Data getData() { return d; }

    // no-longer dangers setter returns a new ImportantInfo leaving
    // the old one unchanged.
    public ImportantInfo setData(Data d) {
        return new ImportantInfo(d);
    }
}
</code>```

Now if you call setData() your old ImportantInfo object is unchanged and the client code gets a new ImportantInfo object reflecting the changed state.  Of course, your Data object has to be immutable too for this to work properly.  If Data is, or holds a collection of some kind, you may find my tips on making collections immutable in Java to be helpful.  Update 2017-09-14: instead of that I've been using Paguro to eliminate or manage most mutation in Java.

Deprecation

If none of that makes you happy, you could deprecate the setData() method so that people have to suppress the warning to use it.  I don't like this quite as well, but then that may be because I'm not envisioning the reason why it's bad to call this method.

```<code>// Be careful when setting data because
//  1. first reason
//  2. second complication
//  3. ...
@Deprecated
public void setData(Data d) { ... }
</code>```

Conclusion

In any case, I like the idea of giving people easy access to the safe thing, but make them do more work to get the unsafe thing.  However you do this, please explain exactly what to be careful of, and why that is a problem so that people will know what they are getting into before they use it.

Body:
So, you currently have:

public class ImportantInfo {
    // constructor
    public ImportantInfo() { ... }

    // getter
    public Data getData() { ... }

    // dangerous setter
    public void setData(Data d) { ... }
}

Managing Mutability

For one thing, maybe you don't want to include a set method by default.  For another, you probably don't want a public constructor.  Maybe you already have a factory, but your factory could return an immutable interface (that does not expose the set method).  The following interface has a method that returns the mutable implementation, but that requires work (so people won't do it by accident) and the name of the method provides a warning:

public interface ImportantInfo {
    public Data getData();

    // ... expose any other safe methods here ...

    public ImportantInfoImplementation getMutableImplementionButBeCareful();
}

Now use a private constructor for ImportantInfo and a factory method that returns the immutable interface:

public class ImportantInfoImplementation {
    // constructor is now private so people can't instantiate this
    // willy-nilly.
    private ImportantInfoImplementation() { ... }

    // public factory method is now the way to get instances of this class
    // and you only get the interface which doesn't expose the dangerous
    // method.
    public static ImportantInfo of() {
        return new ImportantInfoImplementation();
    }

    // getter is mentioned in the interface
    @Override
    public Data getData() { ... }

    // dangerous setter is hidden by the interface.
    public void setData(Data d) { ... }

    // returns the mutable implementing class.
    @Override
    public ImportantInfoImplementation getMutableImplementionButBeCareful() {
        return this;
    }
}

Now to use the dangerous method, clients have to call:

ImportantInfo ii = ImportantInfoImplementation.of();

// Living free and easy with safe immutable version.
someUntrustedMethod(ii);

// probably not messed up yet!
ii.getData();

// OK, I want it badly enough...
ii.getMutableImplementionButBeCareful().setData(d);

I think @Izkata was shooting for something like the above, but I'm not really sure.

Leveraging Immutability

I'm not sure if your set method exposes some underlying danger, or if it makes the instance of this class unstable.  If the former, this won't help you, but if the latter, this may solve your problem: Make your class immutable:

public class ImportantInfo {
    private static final Data data;

    // constructor
    public ImportantInfo(Data d) {
        data = d;
    }

    // getter
    public Data getData() { return d; }

    // no-longer dangers setter returns a new ImportantInfo leaving
    // the old one unchanged.
    public ImportantInfo setData(Data d) {
        return new ImportantInfo(d);
    }
}

Now if you call setData() your old ImportantInfo object is unchanged and the client code gets a new ImportantInfo object reflecting the changed state.  Of course, your Data object has to be immutable too for this to work properly.  If Data is, or holds a collection of some kind, you may find my tips on making collections immutable in Java to be helpful.  Update 2017-09-14: instead of that I've been using Paguro to eliminate or manage most mutation in Java.

Deprecation

If none of that makes you happy, you could deprecate the setData() method so that people have to suppress the warning to use it.  I don't like this quite as well, but then that may be because I'm not envisioning the reason why it's bad to call this method.

// Be careful when setting data because
//  1. first reason
//  2. second complication
//  3. ...
@Deprecated
public void setData(Data d) { ... }

Conclusion

In any case, I like the idea of giving people easy access to the safe thing, but make them do more work to get the unsafe thing.  However you do this, please explain exactly what to be careful of, and why that is a problem so that people will know what they are getting into before they use it.


问:
"Whole-team" C++ features?
In C++, features like exceptions impact your whole program: you can either disable them in your whole program, or you need to deal with them throughout your code. As a famous article on C++ Report puts it:

Counter-intuitively, the hard part of coding exceptions is not the explicit throws and catches. The really hard part of using exceptions is to write all the intervening code in such a way that an arbitrary exception can propagate from its throw site to its handler, arriving safely and without damaging other parts of the program along the way.

Since even new throws exceptions, every function needs to provide basic exception safety — unless it only calls functions which guarantee throwing no exception — unless you disable exceptions altogether in your whole project.

Hence, exceptions are a "whole-program" or "whole-team" feature, since they must be understood by everybody in a team using them. But not all C++ features are like that, as far as I know.

A possible example is that if I don't get templates but I do not use them, I will still be able to write correct C++ — or will I not?. I can even call sort on an array of integers and enjoy its amazing speed advantage wrt. C's qsort (because no function pointer is called), without risking bugs — or not? It seems templates are not "whole-team".

Are there other C++ features which impact code not directly using them, and are hence "whole-team"? I am especially interested in features not present in C.

Update: I'm especially looking for features where there's no language-enforced sign you need to be aware of them. The first answer I got mentioned const-correctness, which is also whole-team, hence everybody needs to learn about it; however, AFAICS it will impact you only if you call a function which is marked const, and the compiler will prevent you from calling it on non-const objects, so you get something to google for. With exceptions, you don't even get that; moreover, they're always used as soon as you use new, hence exceptions are more "insidious". Since I can't phrase this as objectively, though, I will appreciate any whole-team feature.

Update 2: instead of C++ feature I should have written something like "C++-specific feature", to exclude things like multithreading which apply to a large amount of mainstream programming languages.

Appendix: Why this question is objective (if you wonder)

C++ is a complex language, so many projects or coding guides try to select "simple" C++ features, and many people try to include or exclude some ones according to mostly subjective criteria. Questions about that get rightfully closed regularly here on SO.

Above, instead, I defined (as precisely as possible) what a "whole-team" language feature is, provide an example (exceptions), together with extensive supporting evidence in the literature about C++, and ask for whole-team features in C++ beyond exceptions.

Whether you should use "whole-team" features, or whether that's a relevant concept, might be subjective — but that only means the importance of this question is subjective, like always.

答:
The obvious answer is const correctness: since const/volatile qualification is infectious, once one part of the code started using it, every (directly or indirectly) calling code must also be const correct, or cast away constness explicitly.

As with exceptions, however, this is obviously ultimately a good thing. More so even, because unlike exception safety it’s stringently verified by the compiler.

OwnerDisplayName: Blaisorblade

Title: "Whole-team" C++ features?


问:
What the best way to wire up Entity Framework database context (model) to ViewModel in MVVM WPF?
As in the question above: What the best way to wire up Entity Framework database model (context) to viewModel in MVVM (WPF)?

I am learning MVVM pattern in WPF, alot of examples shows how to implement model to viewModel, but models in that examples are just simple classes, I want to use MVVM together with entity framework model (base first approach). Whats the best way to wire model to viewModel.

Thanks for answers.

```<code>//ctor of ViewModel
public ViewModel()
{
db = new PackageShipmentDBEntities(); // Entity Framework generated class

ListaZBazy = new ObservableCollection<Pack>(db.Packs.Where(w => w.IsSent == false));
}
</code>```

This is my usual ctor of ViewModel, think there is a better way, I was reading about repository pattern, not sure if I can adapt this to WPF MVVM

答:
For simple scenarios I've used the following:</p>

```<code>public class ViewModel : IDisposable {

    private EntitiesContext _context = new EntitiesContext();

    private SomeEntity _model;
    public SomeEntity Model {
       get { return _model; }
    }

    public View(int id) {
        _model = _context.SomeEntity.Find(id);
    }

    private ICommand _saveCommand = new RelayCommand(() => _context.SaveChanges());
    public ICommand SaveCommand {
        get { return _saveCommand; }
    }

    public void Dispose() {
         _context.Dispose();
    }

}
</code>```

Body:
For simple scenarios I've used the following:

public class ViewModel : IDisposable {

    private EntitiesContext _context = new EntitiesContext();

    private SomeEntity _model;
    public SomeEntity Model {
       get { return _model; }
    }

    public View(int id) {
        _model = _context.SomeEntity.Find(id);
    }

    private ICommand _saveCommand = new RelayCommand(() => _context.SaveChanges());
    public ICommand SaveCommand {
        get { return _saveCommand; }
    }

    public void Dispose() {
         _context.Dispose();
    }

}


问:
Principles of an extensible data proxy
There is a growing industry now with more than 30 companies playing in the Backend-As-A-Service (BaaS) market.

The principle is simple: give companies a secure way of exposing data housed on premises and behind the firewall publicly.

This can include database data, as well as Legacy PC data through established connectors; SAP for example provides a connector for transacting with their legacy systems.

Early attempts were fixed providers for specific systems like SAP, IBM or Oracle, but the new breed is extensible, allowing Channel Partners and Consultants to build robust integration applications that can consume whatever data sources the client wants to expose.

I just happen to be close to finishing a Cloud Based HTML5 application platform that provides robust integration services, and I would like to break ground on an extensible data proxy to complete the system.

From what I can gather, I need to provide either an installable web service of some kind, or a Cloud service which the client can configure with VPN for interactions.

Then I can build in connectors, which can be activated with a service account, and expose those transactions via web services of some kind (JSON, SOAP, etc).

I can also provide a framework that allows people to build in their own connectors, and use some kind of schema to hook those connectors into the proxy.

The end result is some kind of public facing web service that could securely be consumed by applications to show data through HTML5 on any device.

My gut is, this isn't as hard as it sounds. Almost all of the 30+ companies (With more popping up almost weekly) have all come into existence in the last 18 months or so, which tells me either the root technology, or the skillset to create the technology is in abundance right now.

Where should I start on this? Are there some open source projects I can leverage? A specific group of developers I can hire? I'm confident someone here can set me on the right path and save me some time.

You don't see this many companies spring up this rapidly if they are all starting from scratch with proprietary technology.

The Register: WTF is BaaS

One Minute Video from Kony on their BaaS

答:
Have a look at the Usergrid stack, maintained (and subsequently owned) by Apigee. Apigee actually does most of this already. https://github.com/apigee/usergrid-stack

You may find yourself diving into a world of competition where the competitors have more capital and more resources than you, which would make it a difficult start.

What sets these large providers apart from the smaller firms, is that they can (and do) handle the support, scalability, and security concerns that are critical to a successful BaaS.

Title: Principles of an extensible data proxy


问:
Is "code that generates code" really all that great?
I was looking through CodePen's "popular pens" and I noticed this cool little spiral animation somebody made with a seemingly ridiculously small amount of code.

This is quite impressive until you click the headings for HTML and CSS to show the "compiled" versions of the same code.  Suddenly the 3 lines of HAML and ~40 lines of SCSS turns into a gigantic monster of repetition.  Here's where my question comes in:

Is it acceptable to do something like this in practice?  Don't get me wrong - I love using preprocessors to help me write code faster, but in some cases it looks like it's an automatic copy-paste machine.

答: HTML and CSS are not programming languages.  So HTML and CSS are not code in the same sense that the HAML and LESS compilers are code.  So the conversion from HAML to HTML and LESS to CSS is not 'code generating code'.  It is code generating data.  To get a browser to display a complex graphic, a lot of DOM elements must be created.  Using HAML and LESS allows them to be generated automatically from a simple specification.  This is good.</p>


答: Writing code is much like growing a garden - it needs to be pruned and tendered while growing often or it will just turn into an ugly mess which no one will want or even touch with fear some twig will break and crash the whole bush.</p>

Title: Best supporting argument for refactoring

Body:
Currently I am working on a code best described as C code living in C++ body. However I haven't been able to convince power that be to re-factor on ground of ease of maintenance. </p>

<p>What in your opinion is the best argument for refactoring the code. </p>


问:
Is this a typo in the Artistic License 2.0?
I'm not sure if this would fit better in StackExchange/English, but regardless, there is no practical use to the answer, other than to cure my curiosity.

Note this sentence at the end of the Artistic License 2.0:

THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS
  IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES.

It does not affect any legal aspects of the license, but is there a reason they mixed the use of single and double quotes on "AS IS'? The license is so new that this wouldn't have been for "command prompt friendly" reasons.

Is there special use or meaning behind this in the English language, or was it a typo?

答:
After some digging, I found the Artistic License 1.0, and looking in the same area, we see that the use of mixed quotes is not present:

10. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR
  IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
  WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.

This seems to point towards the fact that the single quote found in the Artistic License 2.0 is indeed a typo.


问:
Presenting agile estimates for Pivotal Tracker project
I've been developing for 6-7 years but never in a particularly agile way. With the latest project I'm trying to make our development process more professional, and more agile.

We're using Pivotal Tracker to track the project and have gathered some pretty well thought out stories. We're also trying to keep some of our (Prince2/Waterfall mindset) project managers happy.

So far I've got them to accept that

requirements always change

priorities always change

some of the requirements won't be delivered if you fix the time scale

you should fix the time scale

short sprints and regular review is good

However they still feel like they need to get a better grip of roughly how much will be delivered within a certain time.

I've come up with a spreadsheet to demonstrate what we might expect to get done in a range of 4 different timescales.

Questions

Are we setting ourselves up to fail

Are there better ways to do this

答:
The danger with this sheet is that can easily be read as a final planning with guarantees. People just overlook the small print (your notes at the bottom). Whereas even the green boxes are no guarantee.

In a project I'm working on we're struggling with the same. We're trying to hold on to not give any estimates; hard but not impossible. We've found a few things.

It is very dangerous to give estimations (or even guarantees) when something is done. People forget that you told them that nothing is guaranteed; "why would you otherwise say that it gets done next week?". When you don't make it, people get angry.

When people have a date, they communicate that to the outside world (read clients). Then it gives even more irritation when you don't make it, as they have to go back to the external person and say it won't be there (when they need it).

It is better, and easier, to give them insight in current progress. A common tool in agile of course is a burn down chart. In our project we use a Trello board, much a like this one. (Here's our Trello board, but it is in Dutch so you might not get everything.) We keep them updated on whether something is worked on and what outcomes it generates. We add notes, interaction designs, graphic designs, screenshots, etc. Sometimes we also ask for feedback or to help test along. This involves people in what is going.

As soon as possible, pass on the mantra that the product is already done and just getting improvements over time. This helps people not to wait for a specific moment. This one is most hard when the base of the product is not there yet. Although you have to watch out that "the base" is extended all the time.

No matter how good your stories are, there is a risk they take way longer or won't get there at all. It has happened to us quite a few times that we have to completely rethink a feature; find another solution for the underlying problem; or come to the conclusion that it doesn't have as high priority at all anymore. This all messes with the planning so much, that it is really hard to give estimations.