问:
Web interface with FastCGI or with direct HTTP?
Let's assume I want (for fun at start) to play with some new DSL (domain specific language) idea. And I really want its user[s] (probably only me at first) to interact thru a web interface. I'll probably implement it in C++ (probably using LLVM).

Should I use an HTTP server library (like libonion or microhttpd) to talk directly HTTP or should I use FastCGI? I could also use libraries doing both like cppcms or wt...

In particular, I am noticing that several recent web frameworks (Opa, Ocsigen, ...) do not have any FastCGI interface but only HTTP one....
(but Ur/Web seems to have both)

So my feeling is that FastCGI is really out of fashion....

Any opinions on that? Do you know recently started project using FastCGI ?
(and what about SCGI?)

答:
Few notes:

So my feeling is that FastCGI is really out of fashion....

Telling this is like to tell that TCP/IP is out of fashion in days of HTTP.

FastCGI is the protocol between web application and the web server - however it does not mean that you need to use it directly from your application.

Should I use an HTTP server library (like libonion or microhttpd) to talk directly HTTP or should I use FastCGI? I could also use libraries doing both like cppcms or wt...

See if you want to develop even a simple web site it is very hard to do it using HTTP alone - there are many factors to handle - this is why there are web frameworks that solve the problem for you, more than that many stuff like static files handing and some security considerations are passed to web server and the framework itself.

So I'd recommend you to use Web framework like CppCMS that allows to implement web application using C++ easily - so basically you work on busyness logic, the rest web framework does for you.

And as a bounce you get support of HTTP, FastCGI, SCGI protocols and you can use either your internal web server or any industry standard protocol with powerful web server.


问:
How do you regularly take advantage of VS2010's multi monitor support?
Although I like VS2010's multi monitor support, I seem to have too many accidental window drags, where I unsnap a window without intending to.  This behavior has made me still live in the mental model of vs200X's non-snappable windows.

1) Do you have a particular layout that works for general purpose work?

2) How have you optimised for specific scenarios (SQL, Debugging, Workflow, WPF)

3) Are you aware of any hotkey or utility that will jump to a particular window layout?

4) Are you aware of any way I can reduce the times I accidentialy undock a window?

答:
I have 2 screens but I don't use VS on both of them. I prefer to keep the other screen for the application being debugged because I want to see the effects of each instruction.

Sometimes I undock 2 windows code editor and put them side by side, on the same screen, for code comparison and similar operations.

ContentLicense: CC BY-SA 2.5


问:
DDD and Value Objects. Are mutable Value Objects a good candidate for Non Aggr. Root Entity?
Here is a little problem

Have an entity, with a value object. Not a problem. I replace a value object for a new one, then nhibernate inserts the new value and orphan the old one, then deletes it. Ok, that's a problem.

Insured is my entity in my domain.
He has a collection of Addresses (value objects). One of the addresses is the MailingAddress.
When we want to update the mailing address, let's say zipcode was wrong, following Mr. Evans doctrine, we must replace the old object for a new one since it's immutable (a value object right?).

But we don't want to delete the row thou, because that address's PK is a FK in a MailingHistory table. So, following Mr. Evans doctrine, we are pretty much screwed here. Unless i make my addressses Entities, so i don't have to "replace" it, and simply update its zipcode member, like the old good days.

What would you suggest me in this case? The way i see it, ValueObjects are only useful when you want to encapsulate a group of database table's columns (component in nhibernate). Everything that has a persistence id in the database, is better off to make it an Entity (not necessarily an aggregate root) so you can update its members without recreating the whole object graph, specially if that's a deep-nested object.

Do you concur? Is it allowed by Mr. Evans to have a mutable value object? Or is a mutable value object a candidate for an Entity?

Thanks

答:
IMO the address object is an entity in your domain. It's shared by multiple entities, has it's own identity and is unique accross the system.

Evans says:

An object defined primarily by its identity is called an entity.

ContentLicense: CC BY-SA 3.0


答:
Everything that has an identity should be an Entity, and everything that does not have an identity is a simple value, hence a value object.

To quote Martin Fowler (which in turn qoutes Eric Evans)

Entity: Objects that have a distinct identity that runs through time and different representations. You also hear these called "reference objects".

Value Object: Objects that matter only has the combination of their attributes.

Reason to make your address a Value Object:

If your address is mutable, you will likely screw up your mailing history in the end. For example, if you're shipping items to an customer, you can't be sure to which address you actually shipped something in the past if the address your MailingHistory table is referring to has been changed.

The MailingHistory entry We shipped A764 to address 657 could mean We shipped article A764 to Boston yesterday and We shipped article A764 to New York tomorrow.

If the mailing address has to been changed, there's no need to delete the old one. Keep it, and mark it as inactive, and the new one as active.

Of course you could treat your address as a Entity, but only when updating it would not change the actual place the address is referring to, hence only allowing the correction of typos.

If you're sure you could ensure that, than using an Entity would be possible.

But the best solution IMHO is to not referrence an address Entity in your mailing history, but rather save the specific address directly in your mailing history table (basically copying the data of the address).

This way, you always know where you shipped your stuff (or whatever you are mailing), and since you would use a mutable Entity, your address table won't be cluttered up.

I've worked with/on several ERP systems, and nearly all of them used this approach.

You will have some redundancy in your database, but it's the most pragmatic way IMHO.

Title: DDD and Value Objects. Are mutable Value Objects a good candidate for Non Aggr. Root Entity?

Body:
Here is a little problem

Have an entity, with a value object. Not a problem. I replace a value object for a new one, then nhibernate inserts the new value and orphan the old one, then deletes it. Ok, that's a problem.

Insured is my entity in my domain.
He has a collection of Addresses (value objects). One of the addresses is the MailingAddress.
When we want to update the mailing address, let's say zipcode was wrong, following Mr. Evans doctrine, we must replace the old object for a new one since it's immutable (a value object right?).

But we don't want to delete the row thou, because that address's PK is a FK in a MailingHistory table. So, following Mr. Evans doctrine, we are pretty much screwed here. Unless i make my addressses Entities, so i don't have to "replace" it, and simply update its zipcode member, like the old good days.

What would you suggest me in this case? The way i see it, ValueObjects are only useful when you want to encapsulate a group of database table's columns (component in nhibernate). Everything that has a persistence id in the database, is better off to make it an Entity (not necessarily an aggregate root) so you can update its members without recreating the whole object graph, specially if that's a deep-nested object.

Do you concur? Is it allowed by Mr. Evans to have a mutable value object? Or is a mutable value object a candidate for an Entity?

Thanks


答:
I see 2 things:

Is it ok for change of Zip code to affect a history record? I think it would be logical for the history record to point to the old, unchanged address, so you know you send it to wrong address.

The moment MailingHistory has FK on the address the address stopped being a value object and became entity. Value objects don't have identity, that allow other entities reference this identity. You can have addresses in single table with other tables pointing to it, but only effect is space saving. From domain point of view, if two entities have reference same type of value object, then they don't share any kind of information.


问:
Statistics for and Details About Open Source Swing Projects
I'm looking for process-relative information on open-source Swing projects:

how the task was described

how many developers were involved

how much time the solution was taken

etc.

Are there any open source (online) chronicles in that direction?  I strongly prefer projects that include the authors' names.

I watched this project and it seems fine but still I couldn't find any information concerning some current project task(s), its developers group, some chronicles (tips, milestones, feedbacks etc)

For example if I see this swing component I'd like to know the above information.

答:
You probably want to look at Ohloh

Ohloh provides statistics on a vast array of open source projects, many of which are categorized in terms of the technology that they use. For example, a simple search on Swing yields 241 pages of projects for you to data mine.


问:
Architecture Best Practice (MVC): Repository Returns Object & Object Member Accessed Directly or Repository Returns Object Member
Architecturally speaking, which is the preferable approach (and why)?

```<code>$validation_date = $users_repository->getUser($user_id)->validation_date;
</code>```

Seems to violate Law of Demeter by accessing member of object returned by method call

Seems to violate Encapsulation by accessing object member directly

$validation_date = $users_repository->getUserValidationDate($user_id);

Seems to violate Single Responsibility Principle as $users_repository no longer just returns User objects

答:
Sometimes, picking what's the most intuitive is the best rule of thumb.

Many people actually don't even agree with the laws/rules/principles you stated. I.e. the functional programming is clearly going away from OO and tries to separate data from processing, I think nobody cares about LoD for such trivial stuff, and the Single Responsibility stuff, although nice, is sometimes hard to achieve in the real world.

That being said, IMHO and this particular example, I find the first alternative the most direct and intuitive.


答:
The  technically 'correct' way to deal with this problem is to pass the correct User object into the method (or class) which is going to require "validation_date". Where possible, Dependency Injecting the exact object required should always be favoured over injecting Repositories, ServiceLocators and factories. The smallest required component should be passed in to the method that requires it. The code in the question doesn't really have a dependency on the repository but on the user.

It's not a Law of Demeter violation because, as the question suggests, the code needs access to the validation date. It's a Law of Demeter violation because the repository is only used as a gateway to other objects.

See http://misko.hevery.com/code-reviewers-guide/flaw-digging-into-collaborators/ for a detailed explanation of the problem and the best way to fix it.

Title: Architecture Best Practice (MVC): Repository Returns Object & Object Member Accessed Directly or Repository Returns Object Member

Body:
Architecturally speaking, which is the preferable approach (and why)?

```<code>$validation_date = $users_repository->getUser($user_id)->validation_date;
</code>```

Seems to violate Law of Demeter by accessing member of object returned by method call

Seems to violate Encapsulation by accessing object member directly

$validation_date = $users_repository->getUserValidationDate($user_id);

Seems to violate Single Responsibility Principle as $users_repository no longer just returns User objects


问:
What's a nice explanation for pointers?
In your own studies (on your own, or for a class) did you have an "ah ha" moment when you finally, really understood pointers? Do you have an explanation you use for beginner programmers that seems particularly effective?

For example, when beginners first encounter pointers in C, they might just add &s and *s until it compiles (as I myself once did). Maybe it was a picture, or a really well motivated example, that made pointers "click" for you or your student. What was it, and what did you try before that didn't seem to work? Were any topics prerequisites (e.g. structs, or arrays)?

In other words, what was necessary to understand the meaning of &s and *, when you could use them with confidence? Learning the syntax and terminology or the use cases isn't enough, at some point the idea needs to be internalized.

Update: I really like the answers so far; please keep them coming. There are a lot of great perspectives here, but I think many are good explanations/slogans for ourselves after we've internalized the concept. I'm looking for the detailed contexts and circumstances when it dawned on you.

For example:

I only somewhat understood pointers
  syntactically in C. I heard two of my
  friends explaining pointers to another
  friend, who asked why a struct was
  passed with a pointer. The first
  friend talked about how it needed to
  be referenced and modified, but it was
  just a short comment from the other
  friend where it hit me: "It's also
  more efficient." Passing 4 bytes
  instead of 16 bytes was the final
  conceptual shift I needed.

答:
I shall assume someone going to learn pointers knows what the normal variables are and how they work in C. Now, let's try to define pointers with some of it's attributes-

They are also variables, but of different nature. Assume there are two layers in the variable space. The normal variables of different types resides in the upper layer and pointers in the lower layer. Like this figure-

As the name 'Pointer' suggests, pointers can POINT to something. Like our finger can point to some object. What are the things they point to? These are the normal variables. In short, "Pointers point to normal variables".

Like normal variables, pointers also are of same number of types like int,char or float. And a pointer of a specific type can point to only same type of variables.

A pointer can point to one variable and later the same pointer can point to another variable. Just the type should be same. So, the a pointer's association with some variable is not permanent and can be changed.

So, how a pointer is declared? Almost like normal variables. You have to precede the name with an asterisk(*). Like-

```<code>int *pointer;
</code>```

Then, how a pointer is associated with a variable? Using the & operator before the variable like this statement-

```<code>pointer = &variable;
</code>```

How a pointer is used by pointing to a variable? This is also done by preceding the name with an asterisk(*). Then it can be used in the place of the variable it's pointing now-

```<code>*pointer = var1 + var2;
</code>```

instead of

```<code>variable = var1 + var2;
</code>```

Now, play with pointers with some code. Just get used to this characteristics of pointers now. Upto this point, we are talking about what pointers do. Once you are ok with it, then start studying how pointers are pointing to some variable and how they react if normal arithmetic operations are applied on them. Then go for the relation between pointers and arrays and pointers to pointers.

That is all I shall suggest about learning pointers.

Title: What's a nice explanation for pointers?

Body:
I shall assume someone going to learn pointers knows what the normal variables are and how they work in C. Now, let's try to define pointers with some of it's attributes-

They are also variables, but of different nature. Assume there are two layers in the variable space. The normal variables of different types resides in the upper layer and pointers in the lower layer. Like this figure-

As the name 'Pointer' suggests, pointers can POINT to something. Like our finger can point to some object. What are the things they point to? These are the normal variables. In short, "Pointers point to normal variables".

Like normal variables, pointers also are of same number of types like int,char or float. And a pointer of a specific type can point to only same type of variables.

A pointer can point to one variable and later the same pointer can point to another variable. Just the type should be same. So, the a pointer's association with some variable is not permanent and can be changed.

So, how a pointer is declared? Almost like normal variables. You have to precede the name with an asterisk(*). Like-

int *pointer;

Then, how a pointer is associated with a variable? Using the & operator before the variable like this statement-

pointer = &variable;

How a pointer is used by pointing to a variable? This is also done by preceding the name with an asterisk(*). Then it can be used in the place of the variable it's pointing now-

*pointer = var1 + var2;

instead of

variable = var1 + var2;

Now, play with pointers with some code. Just get used to this characteristics of pointers now. Upto this point, we are talking about what pointers do. Once you are ok with it, then start studying how pointers are pointing to some variable and how they react if normal arithmetic operations are applied on them. Then go for the relation between pointers and arrays and pointers to pointers.

That is all I shall suggest about learning pointers.


问:
Inheritance from the objects themselves
Making new inheritance hierarchy with the help of C++ I think about:

Why there is no inheritance from the class objects? Abstract example (on abstract C++):

```<code>struct Foo { int v; Foo(int a) : v(a) {} };
struct Buz : public Foo(2) { ... }
</code>```

So, the Buz is inherited only from instance of Foo - Foo(2).

Can such idea be useful? Is there any possible implementations or related ideas?

答:
You can also achieve this using templates.

template <int n>

``` <code>
class Foo
{
public:
  int _n;
  Foo():_n(n){}

};

class Der : public Foo
{
public:
  Der(){};
};

int main()
{
  Foo a;
  Der d;
  return 0;
};
  </code> ```

Title: Inheritance from the objects themselves

Body:
You can also achieve this using templates.

template <int n>

class Foo
{
public:
  int _n;
  Foo():_n(n){}

};

class Der : public Foo
{
public:
  Der(){};
};

int main()
{
  Foo a;
  Der d;
  return 0;
};


问:
How to identify a software development framework?
Based on what information, can we identify something as a software development framework? For example the Wikipedia article of 'software framework' claims it should include support programs, compilers, code libraries, etc. But there are some companies I know of which call a code library 'framework'!

What should a certain development environment contain to be considered as a 'framework'?

答:
The thing that distinguishes a framework from a library is inversion of control: you call a library, but you don't call a framework – a framework calls you.

Or to put it another way: when you write an application using a library, you write the application and leave "holes" in it for the boring details which you then "fill" using a library. (Such a boring detail might be "how to sort a list"; you won't write code for that, you'll just call the library's sort routine.)

When you write an application using a framework, the framework already provides the application for you and just leaves holes in it for the interesting details which you then have to fill out.


问:
When should I make the first commit to source control?
I'm never sure when a project is far enough along to first commit to source control. I tend to put off committing until the project is 'framework-complete,' and I primarily commit features from then on. (I haven't done any personal projects large enough to have a core framework too big for this.) I have a feeling this isn't best practice, though I'm not sure what could go wrong.

Let's say, for example, I have a project which consists of a single code file. It will take about 10 lines of boilerplate code, and 100 lines to get the project working with extremely basic functionality (1 or 2 features). Should I first check in:

The empty file?

The boilerplate code?

The first features?

At some other point?

Also, what are the reasons to check in at a specific point?

答:
Commit the empty project right away. Keep committing several times per hour you spend working on the project. Commit even if the code doesn't compile. I mark such commits with "WIP" in the commit massage to keep track of them.

I also have a script that automatically commits all my projects every 10 minutes to a backup repo, just in case I forget to commit manually. Let's call it my cloud-backed undo buffer.

Check in (aka. push) the project to a team repo when you need your team to see your code. Which is probably before your code is ready to be seen by your team, if you're anything like me.

If you want to be nice to your team, squash your commits before pushing them to the team repo.


问:
Is Clang/LLVM ready for prime time?
Clang is able to be used instead of gcc? What your experience on that? What disadvantages there are yet?

Performance of compilation is very better than gcc but about performance of code generated when executing it?

Are there good tools as front-end (IDE) to run on Linux or Windows?

EDIT: I mean C compiler. C++ it's not so good yet.

答:
Update: Now (2013) Clang is ready for prime time and used by some companies like Google. However it is not totally usable on Windows, work on this platform is a "work in progress".
LLVM/Clang is currently the default compilator on MacOSX/XCode but it's not exactly the same releases than the LLVM ones so beware of the minor differences (mostly difference of version numbers).

Well following the clang dev mailing list, recently the trunk version have been successfully building :

the linux kernel (a recent revision)

Qt (with it's special build process too, apparently)

Chromium (a recent revision)

So, I would say that the coming version (2.9) might be a good "ready for prime time" compiler.

However, if your project have a a planning and budget, maybe it's not a good idea to try a compiler that isn't heavily tested yet. If you're allowed to experiment and provide feedbacks to the Clang developers community, then go for it, it's win-win for everybody.
If not, maybe you should use a mature-and-heavily-used compiler like gcc (in its recent versions) to have a "stable ground" to rely on while working on your project.

Title: Is Clang/LLVM ready for prime time?


问:
Link between tests and user stories
I have not see these links explicitly stated in the Agile literature I have read. So, I was wondering if this approach was correct: Let a story be defined as "In order to [RESULT], [ROLE] needs to [ACTION]" then

RESULT generates system tests.

ROLE generates acceptance tests.

ACTION generates component and unit tests.

Where the definitions are the ones used in xUnit Patterns which to be fair are fairly standard.

Is this a correct interpretation or did I misunderstand something?

答:
Yes, that's a pretty solid approach.

Role generating the acceptance tests may be a bit of a stretch, but at least it links the validation requirements to the presumed user of the feature (story).

Result and Action capture differing layers of verification, focusing on integration and unit testing.  There can be a degree of overlap between those two aspects, but I think your approach works well enough.

Regarding xUnit Patterns book - if they are offering up templates, then they may well be within a hidden or secured site referenced within the book itself.

Title: Link between tests and user stories


问:
What made object oriented programming successful?
What is that feature according to you that has made object oriented programming so much successful ?

Message Passing

Inheritance

Polymorphism

Encapsulation

Or some other feature that you may like to introduce.

Also I would like to know that what is the connection between Abstract Data type and Object Oriented programming?

答:
In my opinion, the last three features are the most important once that impacted the wide spread usage of OOP:

```<code>2. Inheritance
3. Polymorphism
4. Encapsulation
</code>```

Edit: Another point would be IDE and graphical interface development environments like Visual studio and Eclipse. As they embrace OOP languages, thus more and more designs tended towards OOP.

And of course SOLID Principles are the once that make the software products ROCK solid deliverable :)

Body:
In my opinion, the last three features are the most important once that impacted the wide spread usage of OOP:

2. Inheritance
3. Polymorphism
4. Encapsulation

Edit: Another point would be IDE and graphical interface development environments like Visual studio and Eclipse. As they embrace OOP languages, thus more and more designs tended towards OOP.

And of course SOLID Principles are the once that make the software products ROCK solid deliverable :)


问:
Best way to protect website application code

Background

I have a web application that I host on my own server. I have clients who use the application as is, but some have asked if they can host the application on their own server. This enables them to have their own URLS rather than mine. The application only forms part of their website  so I'm assuming it will not be possible for my server to respond to a direct call to their domain etc

To give some examples, i currently have urls like www.mydomain.com/profile, www.mydomain.com/index.php?option=someoption&view=someview&id=1 What my clients' want is www.theirdomian.com/profile, www.theirdomian.com/index.php?option=someoption&view=someview&id=1 etc

Question

My question is, what is the best way for me to allow them to use their own URLs with my application, without giving them all the backend source code and databases to install on their server?

One way I thought would be to create a router.php file that sits on their server. The router then asks my server to output the html. When a link is clicked on the clients site, the router receives the request and forwards the request to get the data from my server etc.

Is this an effective way to achieve what I want, or is it way off the mark.

答:
Would it be an option for them to use a subdomain? So:

They create a subdomain like: accounts.theirdomain.com and in DNS set your server IP.
You accept those requests and show the data for their accounts.

Example: https://support.zendesk.com/entries/13976-mapping-a-host-name-of-your-own-to-zendesk-using-cname


答:
Well, it's certainly ready for primetime on Mac OS X, as many Mac OS X apps are compiled using clang. But even on other platforms, C support is pretty solid, and the team has made great strides with C++ support.

Generally speaking, clang compiles code faster than gcc, but gcc generates better-optimized code. (There are edge cases where this isn't true, but in general, that's the current status.)

Title: Is Clang/LLVM ready for prime time?

Body:
Clang is able to be used instead of gcc? What your experience on that? What disadvantages there are yet?

Performance of compilation is very better than gcc but about performance of code generated when executing it?

Are there good tools as front-end (IDE) to run on Linux or Windows?

EDIT: I mean C compiler. C++ it's not so good yet.


问:
Are factors such as Intellisense support and strong typing enough to justify the use of an 'Anaemic Domain Model'?
It's easy to accept that objects should be used in all layers except a layer nominated as a data layer. However, it's just as easy to end-up with an 'anaemic domain model' that is just an object representation of data with no real functionality ( http://martinfowler.com/bliki/AnemicDomainModel.html ).

However, using objects in this fashion brings the benefit of factors such as Intellisense support, strong typing, readability, discoverability, etc.

Are these factors strong arguments for an otherwise, anaemic domain model?

答:
What I understood from the article:

The programming language does not matter. So

factors such as Intellisense support, strong typing, readability, discoverability, etc.

do not matter to the authors opinion.

One problem I see is to distinct between your domain and your use-cases.

For me the domain belongs into the domain model and the use-cases into the services. But I have not much experience with large-software-developement.


问:
Should the 12-String be in its own class and why?
This question is regarding a homework project in my first Java programming class (online program).

The assignment is to create a "stringed instrument" class using (among other things) an array of String names representing instrument string names ("A", "E", etc).  The idea for the 12-string is beyond the scope of the assignment (it doesn't have to be included at all) but now that I've thought of it, I want to figure out how to make it work.

Part of me feels like the 12-String should have its own class, but another part of me feels that it should be in the guitar class because it's a guitar.  I suppose this will become clear as I progress but I thought I would see what kind of response I get here.

Also, why would they ask for a String[] for the instrument string names?  Seems like a char[] makes more sense.

Thank you for any insight.

Here's my code so far (it's a work in progress):

```<code>public class Guitar {

private int numberOfStrings = 6;
private static int numberOfGuitars = 0;
private String[] stringNotes = {"E", "A", "D", "G", "B", "A"};
private boolean tuned = false;
private boolean playing = false;

public Guitar(){
    numberOfGuitars++;
}

public Guitar(boolean twelveString){
    if(twelveString){
        stringNotes[0] = "E, E";
        stringNotes[1] = "A, A";
        stringNotes[2] = "D, D";
        stringNotes[3] = "G, G";
        stringNotes[4] = "B, B";
        stringNotes[5] = "E, E";
        numberOfStrings = 12;
    }
}

public int getNumberOfStrings() {
    return numberOfStrings;
}

public void setNumberOfStrings(int strings) {
    if(strings == 12 || strings == 6) {
        if(strings == 12){
            stringNotes[0] = "E, E";
            stringNotes[1] = "A, A";
            stringNotes[2] = "D, D";
            stringNotes[3] = "G, G";
            stringNotes[4] = "B, B";
            stringNotes[5] = "E, E";
            numberOfStrings = strings;
        }
        if(strings == 6)
            numberOfStrings = strings;
    }//if
    else
        System.out.println("***ERROR***Guitar can only have 6 or 12 strings***ERROR***");
}

public void getStringNotes() {
        for(int i = 0; i < stringNotes.length; i++){
            if(i == stringNotes.length - 1)
                System.out.println(stringNotes[i]);
            else
                System.out.print(stringNotes[i] + ", ");
        }//for
}
</code>```

答:
This goes a bit beyond an intro Java class, but...

Subclassing can send you down some pretty deep rabbit holes.  The number of strings is only the beginning.  Acoustic, electric, or acoustic-electric hybrid?  If electric, solid or hollow body?  How many pickups?  Single or double coil (humbuckers)?  Fixed or floating bridge?  If acoustic, classical or steel string (classicals have a wider neck and use nylon strings)?  And on and on and on.  Creating a separate class or subclass for every type of guitar quickly leads to madness (and we haven't even gotten into basses or other types of stringed instruments).

Instead of trying to track all that information by creating a bunch of subclasses of Guitar, a better approach is to delegate tracking that information to other classes.  For example, we can create a Tuning class which tracks the number of strings (or courses, thanks Blrfl) and their tunings.  We can create a Body class that tracks whether it's a solid or hollow body, a Pickup class to track the type of pickup, a Neck class to describe the width, radius, and scale length of the neck, etc.  We then compose all of these separate classes into a Guitar class1:

```<code>public class Guitar {
  Body bodyStyle;
  Neck neckStyle;
  Tuning tuning;
  ...
};
</code>```

Note that each of these classes may also delegate some information to other classes (for instance, the Tuning class could delegate tracking information about individual guitar strings (gauge (thickness), wound/unwound, composition, etc.) to a GuitarString class.

This way, we can use the same Guitar class to specify many different types of guitars:

```<code>Guitar g = new Guitar(new Body (/* body parameters */),
                      new Neck (/* neck parameters */),
                      new Tuning (/* tuning parameters */),
                      ...);
</code>```

In general, you want to keep your class hierarchies pretty shallow, and use delegation as much as possible (when you hear or read someone say "favor composition over inheritance", this is what they mean).  This gives you more flexibility and reduces your maintenance headaches.

Knowing where to draw the line is a matter of experience and the problem at hand.  It's possible to go overboard either way.  There are times where you want to subclass because you want to enforce a specific interface or behavior on all instances, and there are times where the effort of delegating to another class isn't worth it.

1: It's been over a year since I've had to write any Java, so I can't write any really detailed examples without screwing something up

Body:
This goes a bit beyond an intro Java class, but...

Subclassing can send you down some pretty deep rabbit holes.  The number of strings is only the beginning.  Acoustic, electric, or acoustic-electric hybrid?  If electric, solid or hollow body?  How many pickups?  Single or double coil (humbuckers)?  Fixed or floating bridge?  If acoustic, classical or steel string (classicals have a wider neck and use nylon strings)?  And on and on and on.  Creating a separate class or subclass for every type of guitar quickly leads to madness (and we haven't even gotten into basses or other types of stringed instruments).

Instead of trying to track all that information by creating a bunch of subclasses of Guitar, a better approach is to delegate tracking that information to other classes.  For example, we can create a Tuning class which tracks the number of strings (or courses, thanks Blrfl) and their tunings.  We can create a Body class that tracks whether it's a solid or hollow body, a Pickup class to track the type of pickup, a Neck class to describe the width, radius, and scale length of the neck, etc.  We then compose all of these separate classes into a Guitar class1:

public class Guitar {
  Body bodyStyle;
  Neck neckStyle;
  Tuning tuning;
  ...
};

Note that each of these classes may also delegate some information to other classes (for instance, the Tuning class could delegate tracking information about individual guitar strings (gauge (thickness), wound/unwound, composition, etc.) to a GuitarString class.

This way, we can use the same Guitar class to specify many different types of guitars:

Guitar g = new Guitar(new Body (/* body parameters */),
                      new Neck (/* neck parameters */),
                      new Tuning (/* tuning parameters */),
                      ...);

In general, you want to keep your class hierarchies pretty shallow, and use delegation as much as possible (when you hear or read someone say "favor composition over inheritance", this is what they mean).  This gives you more flexibility and reduces your maintenance headaches.

Knowing where to draw the line is a matter of experience and the problem at hand.  It's possible to go overboard either way.  There are times where you want to subclass because you want to enforce a specific interface or behavior on all instances, and there are times where the effort of delegating to another class isn't worth it.

1: It's been over a year since I've had to write any Java, so I can't write any really detailed examples without screwing something up


问:
Where to put custom validation while using Entity Framework
I am using MVC3 and Enitty Framework 4 with the Database first approach. It created the context template with its own validation for the fields based on the database. My question is where should I put the other validation based on the buisness logic. Should I put it in the Context.tt file, should it go in the controller or should it go in a seperate model? </p>

答:
At a minimum, business logic validation should go within the Controller for the framework you're using.  If the validation logic is portable, creating a separate validation module, called by the Controller, would also be okay.

In general, place the validation logic as close as possible to the layer it affects.  Likewise, validate items at the most appropriate layer (appropriate defined by what's being affected).  The concept is a related to encapsulation and the SOLID principles.  The goal is to allow changing out the individual components as needed, as well as making the validation logic more portable.

To be a little more clear, if there's validation logic to protect the database from errant changes, then that logic should be placed within (or called from) the Model.  Likewise, input validation belongs within the View.

Some validation logic can pull double (or triple) duty or would be common across multiple modules in the same layer.  It's appropriate to create a separate module for that logic.  At the risk / expense of duplicate checks, I would still have each layer validate for the aspects it is responsible for.


问:
How can I tell whether my computer is Harvard or von Neumann architecture?
I understand the difference between the two architectures is the separation of instructions from data in the Harvard architecture. But how do I know which type of system I'm on? Is it possible to write a program such that the program determines whether the system is von Neumann or Harvard? Could there be another architecture or are these architectures the only ones known?</p>

答:
When you program it: Modify a memory region and then jump there and execute it.

If it is Havard you can not do it.


问:
Best way to throw exception and avoid code duplication
I am currently writing code and want to make sure all the params that get passed to a function/method are valid. Since I am writing in PHP I don't have access to all the facilities of other languages like C, C++ or Java to check for parameters values and types

```<code>public function inscriptionExists($sectionId, $userId) // PHP
</code>```

vs.

```<code>public boolean inscriptionExists(int sectionId, int userId) // Java
</code>```

So I have to rely on exceptions if I want to make sure that my params are both integers.

Since I have a lot of places where I need to check for param validity, what would be the best way to create a validation/exception machine and avoid code duplication?

I was thinking on a static factory (since I don't want to pass it to all of my classes) with a signature like:

```<code>public static function factory ($value, $valueType, $exceptionType = 'InvalidArgumentException');
</code>```

Which would then call the right sub process to validate based on the type.

Am I on the right way, or am I going completely off the road and overthinking my problem?

答:
I think you are over-thinking your problem

In my opinion, dynamic typing is one of the features of PHP that makes it highly enjoyable to work with. Instead of enforcing strict typing rules, you can just document your function really well to indicate the parameters you expect. If the contract is not met, then results may vary and the fault is on the user of your function.

Plus if your code base is used only internally (by you and your team), you should have no problems with parameter types as you developped the code and should know how to use it. If your project is a library available to the public, good documentation is key. You should also have good unit tests to make sure your code behaves as expected and to provide examples on how to use your library.

I see you are trying to write Java code in PHP and that means that you still don't understand PHP well. When writing code in a given language, you should try to embrace the language features/philosophy instead of looking back to what you already know and trying to adapt.


问:
What do you optimize for?
Generally speaking, what type of optimizations do you typically slant yourself towards when designing software?

Are you the type that prefers to optimize your design for

Development time (i.e., quick to write and/or easier to maintain)?

Processing time

Storage (either RAM, DB, Disc, etc) space

Of course this is highly subjective to the type of problems being solved, and the deadlines involved, so I'd like to hear about the reasons that would make you choose one form of optimization over another.

答:
There is only one thing to optimize for and it is:

What your customers want

Do your customers need the fastest program possible? Optimize for speed.

Do your customers need absolute reliability? Optimize for that.

Do they need it delivered tomorrow or it will be useless? Optimize for speed of development.

Running on an incredibly tiny resource-constrained device? Optimize for those resources.

Title: What do you optimize for?


答: You could protect your code with a tool like Zend Guard, IonCube or something similar. Most hosts I've seen support the use of protected scripts.</p>

Title: Best way to protect website application code

Body:
Background

I have a web application that I host on my own server. I have clients who use the application as is, but some have asked if they can host the application on their own server. This enables them to have their own URLS rather than mine. The application only forms part of their website  so I'm assuming it will not be possible for my server to respond to a direct call to their domain etc

To give some examples, i currently have urls like www.mydomain.com/profile, www.mydomain.com/index.php?option=someoption&view=someview&id=1 What my clients' want is www.theirdomian.com/profile, www.theirdomian.com/index.php?option=someoption&view=someview&id=1 etc

Question

My question is, what is the best way for me to allow them to use their own URLs with my application, without giving them all the backend source code and databases to install on their server?

One way I thought would be to create a router.php file that sits on their server. The router then asks my server to output the html. When a link is clicked on the clients site, the router receives the request and forwards the request to get the data from my server etc.

Is this an effective way to achieve what I want, or is it way off the mark.


答:
Distribute your application in a virtual machine which runs on VMWare or VirtualBox or something similar. All your customer sees is a virtual server in their network. Everything inside is only accessible to you. Your customer does need to be able to support virtualization in their IT environment, but that is becoming more & more common these days.

You will have to do some extra configuration depending on whether they support DHCP or fixed IP addresses, if they insist on data backups, and if they need SSL certificates installed. But either way, they don't have to see anything inside the VM.


答:
"www" is a sub-domain.

foo.yourclient.com/profile <-- if the links are all relative to the root, then there's nothing to configure. Otherwise, set this for the BASE HREF.

The simple solution is to manage sub-domains, host the software yourself and market it as a SaaS solution. The only hurdle might be skinning the code on a sub-domain basis to match their main site.

Or you can take the overly complex path where you need to deploy obfuscated/compiled code onto their servers, fix any problems with how their servers are setup, coordinate with their IT people to update the software, handle database issues on their servers, etc.

Or you can convert your software to an API and build a RESTful layer that your clients can use from a website they build and maintain.


答:
PHP provides type hinting for objects and arrays. Unfortunately, not for scalar types such as string or int.

There are various approaches.  One is to use assert statements :

```<code>public function inscriptionExists($sectionId, $userId){
  assert(is_int($sectionId));
  assert(is_int($userId));
}
</code>```

One needs to ensure assert is active at least during development :

assert_options(ASSERT_ACTIVE, 1)

You could write a utility class along these lines

```<code>class Check{

  public static function int(& $param, $name){
    if( !is_int($param) ){
       throw new InvalidArgumentException($name.' is not an integer');
    }
  }
}
</code>```

and then

```<code>public function inscriptionExists($sectionId, $userId){
  Check::int($sectionId, 'sectionId');
  Check::int($userId, 'userId');
</code>```

Title: Best way to throw exception and avoid code duplication

Body:
I am currently writing code and want to make sure all the params that get passed to a function/method are valid. Since I am writing in PHP I don't have access to all the facilities of other languages like C, C++ or Java to check for parameters values and types

```<code>public function inscriptionExists($sectionId, $userId) // PHP
</code>```

vs.

```<code>public boolean inscriptionExists(int sectionId, int userId) // Java
</code>```

So I have to rely on exceptions if I want to make sure that my params are both integers.

Since I have a lot of places where I need to check for param validity, what would be the best way to create a validation/exception machine and avoid code duplication?

I was thinking on a static factory (since I don't want to pass it to all of my classes) with a signature like:

```<code>public static function factory ($value, $valueType, $exceptionType = 'InvalidArgumentException');
</code>```

Which would then call the right sub process to validate based on the type.

Am I on the right way, or am I going completely off the road and overthinking my problem?

Body:
PHP provides type hinting for objects and arrays. Unfortunately, not for scalar types such as string or int.

There are various approaches.  One is to use assert statements :

public function inscriptionExists($sectionId, $userId){
  assert(is_int($sectionId));
  assert(is_int($userId));
}

One needs to ensure assert is active at least during development :

assert_options(ASSERT_ACTIVE, 1)

You could write a utility class along these lines

class Check{

  public static function int(& $param, $name){
    if( !is_int($param) ){
       throw new InvalidArgumentException($name.' is not an integer');
    }
  }
}

and then

public function inscriptionExists($sectionId, $userId){
  Check::int($sectionId, 'sectionId');
  Check::int($userId, 'userId');


问:
What to do when a sprint is finished early?
What to do when a sprint is finished early?

At the moment our Scrum team works off stories from the backlog, if the sprint is finished early.

What happens with stories taken from the backlog? Will the stories be added to the current Sprint ? If yes, what if these stories won't be finished in time. Is the Sprint failed then?

答:
Bring something from the project backlog into the sprint (after discussions with scrum master and project owner).

The size of the item you undertake will depend on how much time you have. If there is nothing small enough create a sub-task of a bigger task to get it started (ie do some of the preliminary work).

Alternatively create some tasks that make the code base better. I have never seen a code base that could not be improved in some way. Review some code add more unit tests etc..


答:
Both Von Neumann and Harvard architectures belong to the Control flow paradigm.

There is another paradigm, which is Data flow.

A common example of dataflow computing, though implemented on control flow computers, is the spreadsheet (from Visicalc and Multiplan to Excel).

Neural networks also belong to this category.

FPGA are another example of dataflow architecture. They are programmed with hardware description languages such as VHDL.

Title: How can I tell whether my computer is Harvard or von Neumann architecture?

Body: I understand the difference between the two architectures is the separation of instructions from data in the Harvard architecture. But how do I know which type of system I'm on? Is it possible to write a program such that the program determines whether the system is von Neumann or Harvard? Could there be another architecture or are these architectures the only ones known?</p>


答:
For us a Sprint never ends early. We only increased our velocity or solved the problem in a way that makes us get more work done in the sprint.

Saying that we always have a backlog of items that are prioritized in order of importance by our product owners. When any team can fit more work into the sprint it is very easy for them to see what to do next on the list that will fit positively into the sprints remaining time given their velocity.

This avoids any downtime by the group waiting for discussions with Product Owner/Scrum Master on what should be done next. Our Product Owners and Scrum Masters keep on top of this list so there is always more work waiting to be put into the next sprint (or current one if time allowed.)

Body:
What to do when a sprint is finished early?

At the moment our Scrum team works off stories from the backlog, if the sprint is finished early.

What happens with stories taken from the backlog? Will the stories be added to the current Sprint ? If yes, what if these stories won't be finished in time. Is the Sprint failed then?


答:
When I first "learned" about pointers, I was sort of thrust in to it. My university had made the decision a long time before I enrolled to center the curriculum around Java, so when my Data Structures professor gave one lecture on C and asked us to implement an XOR-List with pointers I felt like I was getting in to something way over my head.

I understood the definition:

A pointer is a variable that contains
  an address of a variable

But I still didn't understand a large part of the concept. Looking back, I think it centered on three things:

What exactly is a memory location? (At the time I didn't take a Computer Organization class)

The awkward syntax (So um... why
exactly is it defined like "int *ip"
but then subsequently I refer to the
variable as "ip"?)

How exactly is it beneficial to store the address of a variable rather than just use the variable?

It wasn't until I purchased the K&R book and completed every problem that I really got a grasp for pointers. Besides the fact that I had long completed the Computer Organization class (that I think should be required before learning C), part of it had to do with the fact that I realized that pointers can be used for functions, arrays, structs... to do useful things and not merely as storage for addresses of ordinary variables.

But my "aha" moment by far was the way that K&R explained the awkward syntax of defining a simple pointer. I took notes throughout the book (in which I rephrase points made by the book in to my own words in order to further my understanding), and this is the one relating to that:

A pointer is a variable that contains
  an address to a variable. A pointer is
  both defined and dereferenced
  (yielding the value stored at the
  memory location that it points to)
  with the '*' operator; the expression
  is mnemonic.

```<code>Ex.:
   int a;      /* Variable 'a' is an integer */

   int *ip;   /* Variable ip is a pointer and dereferencing it gives an integer.
                 In other words, the expression *ip is an int, so ip is a pointer
                 to an int */
</code>```

I had always felt that I couldn't fully grasp the more advanced concepts of pointers until I had something so elementary ingrained in my head. It had bothered me endlessly after that assignment (which I didn't do too well on, by the way ;) ) why "*ip" did not exist right after I (thought I) defined "*ip". Mastering this is essential for more advanced concepts involving pointers, like function pointers and more complicated definitions like this:

```<code>char (*(x())[])()
</code>```

All in all, I think the concept of pointers requires:

A basic understanding of how memory
is laid out in a computer (and what
memory is).

Knowledge of how powerful
    pointers can be (real world usage,
    not just another abstract concept
    that they learn for the sake of
    learning).

Deciphering the
    hieroglyphics colloquially known as
    "a definition of a pointer"

So all in all, I think there should be at least 3 "aha" moments when learning about pointers. I'm still a student so I thought you'd appreciate the viewpoint of someone who's still (relatively) fresh off learning the concept.

Title: What's a nice explanation for pointers?

Body:
In your own studies (on your own, or for a class) did you have an "ah ha" moment when you finally, really understood pointers? Do you have an explanation you use for beginner programmers that seems particularly effective?

For example, when beginners first encounter pointers in C, they might just add &s and *s until it compiles (as I myself once did). Maybe it was a picture, or a really well motivated example, that made pointers "click" for you or your student. What was it, and what did you try before that didn't seem to work? Were any topics prerequisites (e.g. structs, or arrays)?

In other words, what was necessary to understand the meaning of &s and *, when you could use them with confidence? Learning the syntax and terminology or the use cases isn't enough, at some point the idea needs to be internalized.

Update: I really like the answers so far; please keep them coming. There are a lot of great perspectives here, but I think many are good explanations/slogans for ourselves after we've internalized the concept. I'm looking for the detailed contexts and circumstances when it dawned on you.

For example:

I only somewhat understood pointers
  syntactically in C. I heard two of my
  friends explaining pointers to another
  friend, who asked why a struct was
  passed with a pointer. The first
  friend talked about how it needed to
  be referenced and modified, but it was
  just a short comment from the other
  friend where it hit me: "It's also
  more efficient." Passing 4 bytes
  instead of 16 bytes was the final
  conceptual shift I needed.

Body:
When I first "learned" about pointers, I was sort of thrust in to it. My university had made the decision a long time before I enrolled to center the curriculum around Java, so when my Data Structures professor gave one lecture on C and asked us to implement an XOR-List with pointers I felt like I was getting in to something way over my head.

I understood the definition:

A pointer is a variable that contains
  an address of a variable

But I still didn't understand a large part of the concept. Looking back, I think it centered on three things:

What exactly is a memory location? (At the time I didn't take a Computer Organization class)

The awkward syntax (So um... why
exactly is it defined like "int *ip"
but then subsequently I refer to the
variable as "ip"?)

How exactly is it beneficial to store the address of a variable rather than just use the variable?

It wasn't until I purchased the K&R book and completed every problem that I really got a grasp for pointers. Besides the fact that I had long completed the Computer Organization class (that I think should be required before learning C), part of it had to do with the fact that I realized that pointers can be used for functions, arrays, structs... to do useful things and not merely as storage for addresses of ordinary variables.

But my "aha" moment by far was the way that K&R explained the awkward syntax of defining a simple pointer. I took notes throughout the book (in which I rephrase points made by the book in to my own words in order to further my understanding), and this is the one relating to that:

A pointer is a variable that contains
  an address to a variable. A pointer is
  both defined and dereferenced
  (yielding the value stored at the
  memory location that it points to)
  with the '*' operator; the expression
  is mnemonic.

Ex.:
   int a;      /* Variable 'a' is an integer */

   int *ip;   /* Variable ip is a pointer and dereferencing it gives an integer.
                 In other words, the expression *ip is an int, so ip is a pointer
                 to an int */

I had always felt that I couldn't fully grasp the more advanced concepts of pointers until I had something so elementary ingrained in my head. It had bothered me endlessly after that assignment (which I didn't do too well on, by the way ;) ) why "*ip" did not exist right after I (thought I) defined "*ip". Mastering this is essential for more advanced concepts involving pointers, like function pointers and more complicated definitions like this:

char (*(x())[])()

All in all, I think the concept of pointers requires:

A basic understanding of how memory
is laid out in a computer (and what
memory is).

Knowledge of how powerful
    pointers can be (real world usage,
    not just another abstract concept
    that they learn for the sake of
    learning).

Deciphering the
    hieroglyphics colloquially known as
    "a definition of a pointer"

So all in all, I think there should be at least 3 "aha" moments when learning about pointers. I'm still a student so I thought you'd appreciate the viewpoint of someone who's still (relatively) fresh off learning the concept.


问:
My father is a doctor. He is insisting on writing a database to store non-critical patient information, with no programming background
So, my father is currently in the process of "hacking" together a database using FileMaker Pro, a GUI based databasing tool for his small (4 doctor) practice. The database will be used to help ease the burden on reporting from medical machines, streamlining quite a clumsy process.

He's got no programming background, and seems to be doing everything in his power to not learn things correctly. He's got duplicate data types, no database-enforced relationships (foreign/primary key constraints) and a dozen other issues. He's doing it all by hand via GUI tool using Youtube videos.

My issue is, that whilst I want him to succeed 100%, I don't think it's appropriate for him to be handling these types of decisions. How do I convince him that without some sort of education in these topics, a hacked together solution is a bad idea? He's can be quite stubborn and I think he sees these types of jobs as "childs play"

How should I approach this? Is it even that bad an idea - or am I correct in thinking he should hire a proper DBA/developer to handle this so that it doesn't become a maintenance nightmare?

NB: I am a developer consultant of 4 years and I've seen my share of painful customer implementations.

Update:

So it's a few years later now, and I've had time to reflect on this question. My dad ended up implementing a solution using Google Docs, FileMaker Pro and some email hooks. He set the whole thing up himself, and he says he is getting immense value from it.

If you are an experienced developer, you are perhaps reading that description and cringing. But I learnt a pretty good lesson from the whole thing actually - that people only care about the results, and not the implementation. All my dad cares about is the fact he doesn't need to enter patient information down on paper manually, and can instead quickly fill out a Google docs form. What's great is he's looking to hire a junior dev/ops person to focus solely on automation within his practice.

答:
It's his business. And if he is determined, he'll make it work. And lots of folks have cobbled together solutions from various technologies to get stuff working.

Years ago, I reviewed the code of a friend of mine who put together a web application with PHP and some bulletin board software. He customized it heavily to meet his needs. The code was an abomination. Asides from barely being 1st normal form, he had HTML tags with data in his database. No MVC separation. But God bless him. His application worked, and he was able to pay his bills with the income from that web site.

My advice to him was this: If you are content to milk your application for revenues as long as possible, then don't refactor it using good software design techniques, and leave "well enough" alone.  If you want to evolve your application to offer more services and get more revenue, then you'll have to pay up and refactor the code. He elected to go with the former. C'est la vie.

If your dad doesn't feel the pain of data duplication and weak data integrity now, he will later, and only then will he learn the value of what you're saying.


问:
Did I Inadvertently Create a Mediator in my MVC?
I'm currently working on my first biggish project. It's a frontend facebook application that has, since last Tuesday, spanned some 6000-8000 LOC.

I say this because I'm using the MVC, an architecture I have never rigidly enforced in any of my hobby projects. I read part of the PureMVC book, but I didn't quite grasp the concept of the Mediator. Since I didn't understand and didn't see the need for it, my project has yet to use a single mediator.

Yesterday I went back to the design board because of some requirement changes and noticed that I could move all UI elements out of the View and into its own class. The View essentially only managed the lifetime of the UI and all events from the UI or Model.

Technically, the View has now become a 'Mediator' between the Model and UI. Therefore, I realized today, I could just move all my UI stuff back into the View and create a mediator class that handles all events from the view and model.

Is my understanding correct in thinking that I have devolved my View as it currently is (handling events from the Model and UI) into a Mediator and that the UI class is what should be the View?

答:
The View should be the code for the UI and the Mediator should handle the events from the View. The Model should be separate from the View and have its "events" handled by a Proxy.
Your Mediator can interact with your Proxy, but your Proxy or Model shouldn't interact with your view directly. See the PureMVC conceptual diagram for how things are supposed to interact within the framework. </p>


答:
Working on stretch or future sprint backlog items seems to be the common thing to do, which makes a lot of sense if your sprint backlog items are small enough and clearly defined. However, backlog items that may place the "done" code into a "no longer done" state should be avoided.

If the sprint is truly finished, tag it, prepare it for delivery, deliver it, and put your source code repositories into the "next sprint" state so there's no risk that late sprint changes will put delivery at risk.

Title: What to do when a sprint is finished early?


问:
When do domain concepts become application constructs?
I recently posted a question regarding recovering a DDD architecture that became an anemic domain model into a multitier architecture and this question is a follow-on of sorts.

My question is when do domain concepts become application constructs.

My application is a local client C# 4/WPF with the following architecture:

Presentation Layer

Views

ViewModels

Business Layer

???

Domain Layer

Classes that take the POCOs with primitive types and create domain concepts (e.g. image, layer, etc)

Sanity checks values (e.g. image width > 0)

Interfaces for DTOs

Interface for a repository that abstracts the filesystem

Data Access Layer

Classes that parse the proprietary binary files into POCOs with primitive types by explicit knowledge of the file format

Implementation of domain DTOs

Implementation of domain repository class

Local Filesystem

Proprietary binary files

When does the MyImageType domain class with Int32 width, height, and Int32[] pixels become a System.Windows.Media.ImageDrawing? If I put it in the domain layer, it seems like implemenation details are being leaked (what if I didn't want to use WPF?). If I put it in the presentation layer, it seems like it's doing too much. If I create a business layer, it seems like it would be doing too little since there are few "rules" given the CRUD nature of the application.

I think all of my reading has lead to analysis paralysis, so I thought fresh eyes might lend some perspective.

Update 1:

To clarify that the application is not a strictly CRUD, the domain layer would also contain signal processing functions and image transform settings. The signal processing functions must be applied on the raw pixel values directly from the DAL, while the image transform settings are stored with the domain objects to be applied by WPF as part of the presentation.

答:
Sounds to me DDD may a bit overkill for your type of application. Images, layers and such sounds like you'd have mostly to do with presentation logic.
I would not worry too much about the anemic part, if there is little business logic, it is as it is.

For the domain layer I would stick to names and terms your users would use. Does your user know what a MyImageType is and what it's supposed to do? No? Then it doesn't need to be part of the domain model.

It may help to just tell yourself you are not doing DDD, but just borrowing some of it's ideas and patterns.

If you are stuck in analysis try to focus on things you could do now without shutting too many doors. Postpone decisions as much as possible. Go for simple solutions that you can expand. Allow yourself some room to make mistakes. First make it work, then make it pretty.


问:
Is it ok to ignore poor performance for a resource that will be cached?
Let's say I have a web service that is poorly written and inefficient, but it's output is cached so there's no bottleneck. Do you just leave it? Would you go as far as to take deliberate shortcuts knowing that performance problems will be masked?</p>

答:
In the short term, yes, it's okay.

Knowing that over the long term, you're going to get burned.  So no, it's really not okay.

Yes | No really depends upon your shop; the amount of backlog that is present; and just how critical this particular function is.

Caching to mask performance issues is a crutch, and is a form of technical debt.  The real problem comes about when you have to start making changes or updates within that area.  The cache represents the first layer of band-aids to this problem.  Future changes will result in more and more band-aids until you fix the root of the problem.

If it can be reasonably easily fixed within the constraints of your environment, then it should be fixed.  Especially so if it's a volatile area.

If you're considering taking shortcuts knowing that you can use the crutch of caching, then you've already headed down the wrong path.


答:
It would be grossly inaccurate to tell you that it is or it isn't okay because it is ultimately a tradeoff between implementation time and how well you wish your program to perform.  I don't think it's fair to say that program performance always has priority over performance, because ultimately the software industry is a business like any other and some tradeoffs are acceptable.

However, I think the only time when it's okay to ignore poor performance for a resource that will be cached is if you plan on preloading a lot of resources you will use at the startup of the program and your cache isn't weak (you don't throw out old data in favor for new data).  Users tend to have little patience for waiting times, but they also tend to be more tolerable if they expect to have to wait, such as moments when you're opening a program or you're creating a report.  You can take advantage of this and load once and placing this resource in cache.  Just don't combine poor performance with lazy loading, since that will create unexpected delays when the user won't expect it.

And, of course, do be sure to get around to fixing that performance problem eventually.

Title: Is it ok to ignore poor performance for a resource that will be cached?

Body: Let's say I have a web service that is poorly written and inefficient, but it's output is cached so there's no bottleneck. Do you just leave it? Would you go as far as to take deliberate shortcuts knowing that performance problems will be masked?</p>


问:
NLP - Queries using semantic wildcards in full text searching, maybe with Lucene?
Let's say I have a big corpus (for example in english or an arbitrary language), and I want to perform some semantic search on it. For example I have the query:

"Be careful: [art] armada of [sg] is coming to [do sg]!"

And the corpus contains the following sentence:

"Be careful: an armada of alien ships is coming to destroy our planet!"

It can be seen that my query string could contain "semantic placeholders", such as:

[art] - some placeholder for articles (for example a / an in English)
[sg], [do sg] - some placeholders for NPs and VPs (subjects and predicates)
I would like to develop a library which would be capable to handle these queries efficiently. I suspect that some kind of POS-tagging would be necessary for parsing the text, but because I don't want to fully reimplement an already existing full-text search engine to make it work, I'm considering that how could I integrate this behaviour into a search engine like Lucene?

I know there are SpanQueries which could behave similarly in some cases, but as I can see, Lucene doesn't do any semantic stuff with stored texts.

It is possible to implement a behavior like this? Or do I have to write an own search engine?

答:
Not a Lucene expert but:

You could create your own tokenizers that indexes e.g. [ART] as a token. That way you might be able to do phrase searches like the example above. This won't work if 'armada' is sometimes a [SG] or some other token. You'd need a specialized wildcard search if that is the case.

Perhaps a conventional wildcard search through Lucene will allow you to gather at least a pretty good result set to start with. With a second pass you could parse out the [ART] qualifiers and such to come to a final result set.


问:
OOP Design: relationship between entity classes
I have at first sight a simple issue but can't wrap my head around on how to solve. I have an abstract class Compound. A Compound is made up of Structures. Then there is also a Container which holds 1 Compound.

A "special" implementation of Compound has Versions. For that type of Compound I want the Container to hold the Versionof the Compound and not the Compound itself.

You could say "just create an interface Containable" and a Container holds 1 Containable. However that won't work. The reason is I'm creating a framework and the main part of that framework is to simplify storing and especially searching for special data type held by Structure objects. Hence to search for Containers which contain a Compound made up of a specific Structure requires that the "Path" from Containerto Structure is well defined (Number of relationships or joins).

I hope this was understandable. My question is how to design the classes and relationships to be able to do what I outlined.

EDIT:

Kind of translation issue. with version i did not mean in terms of "versioning" but more in terms of "different variety" but fundamentally the same. There is no active / inactive. All are active.

EDIT 2:

Also note that these classes are entity classes and hence complex inheritance and hierarchies can be problematic.

EDIT 3:

Just don't see how either pattern (Composite, decorator) can work. I tried but the problem is the "path traversal", eg. implementing it in the context of Spring-data and QueryDSL.

I've created Class diagramm with comments that might help to understand the issue. Batch = Version.

答:
... to search for Containers which contain a Compound made up of a specific Structure requires that the "Path" from Container to Structure is well defined (Number of relationships or joins).

Not if you are asking the container if it has such a structure yes or no, then only the container needs to know the path. You can keep it an implementation detail in such a case.

Implement a container class for version-less compounds, and an implementation for version-ed compounds. You indirectly traverse the structures through delegation.


问:
What's your favourite quote about programming?
What's your favourite quote about programming?

One quote per answer, and please check for duplicates before posting!

答:
Good code is its own best documentation. As you're about to add a comment, ask yourself, 'How can I improve the code so that this comment isn't needed?' Improve the code and then document it to make it even clearer.

-Steve McConnell

LastEditorDisplayName: Roger Pate


问:
IEEE SRS documents: lightweight version when working with outside contractors?
Typically we follow an Agile development process that tends not to put an emphasis on writing requirements and technical documents that nobody will read.  We tend to focus our limited manpower to development and testing activities with collaborative design and whiteboarding as a key focus.

There is a mostly standalone web component that will take quite a few weeks to develop, but this work can be mostly parallel with other project work going on.  To try and catch up time I was given a budget for hiring a developer on oDesk to complete this work.

While my team isn't accustomed to working off of a firm SRS document, I realize that with outsourced development that it is a good idea to be as firm and specific as possible so I realize that I need to provide a detailed Requirements and Technical Specification document for this work to be done correctly.

When I do write a Requirements document I typically utilize the standard IEEE SRS document template but I think this is too verbose and probably overkill for what I need to communicate to a developer.  Is there another requirements document that is more lightweight and also accepted by a major standards organization like the IEEE?

Further, as what will be developed as a software module that will interact with other software modules, my requirements really need to delve into technical specifications for things to work correctly.  In this scenario does it make sense to merge technical and requirements specifications into a single document, and if not, what is a viable alternative?

答:
The best option is probably to take an existing template or two (for purchase - also found in the appendices of Software Requirements) or three and tailor them. Remove sections that are irrelevant to your needs or add new sections that you like from one template into the rest of another template. Merge sections together if that makes sense. When combined, these would probably cover every possible type of question that might be asked, it's just a matter of filling in the details where they are needed.

Tailoring would make it not match templates by major standards organizations, but tailoring is a key component of process improvement and deployment programs. I don't think that anyone would have a problem with a tailored template, in most cases. To me, the explicit removal of sections makes for a nicer and more reader-friendly document than text that says "does not apply".

As far as providing specifications, I'd be hesitant on what is provided. If you will be providing inputs in a specified format, provide that format. If another system will be consuming outputs, provide the expected output format. These could be railroad diagrams, XML schemas, byte layout maps, and any sample inputs/outputs (sanitized, if necessary). If you're specifying something that needs to be a drop-in replacement for another system, specifying the public interface may be necessary as well. However, I'd recommend leaving as much leeway to the developer as possible to design and build a system around your requirements.

In my experiences, there's often a separation of the requirements of the system and a detailed description of the interfaces between components. I don't think this is always necessary, though. Conformance to a specified interface is, technically, a communication or environment requirement ("the system shall provide output in XML that conforms to the schema defined in schema file"). Separating the two is probably more appropriate when describing a system of related components rather than a single component, where I'd argue that having a single, comprehensive resource for what I'm expected to produce is better.

I'd recommend approaching this as defining only what you need from this system, leaving as much as possible up to the developer. If you spend too much time doing the specification such that there's only one or two solutions, then you've done most of the time intensive work (in my experience). As a developer yourself, you probably know what questions you might ask if you were presented with the general scope of the system you want - answer those as clearly and specifically as possible and hope the developer will ask any other questions you might not have thought of.


问:
Optimization of a hybrid pagination scheme
I'm working on a Web Application using node.js in which I'm building a partial copy of the database on the client-side to decrease the load on my server. Right now, I have a function like this (expressed as python-style pseudocode, but implemented in JavaScript):

```<code>get(table_name,primary_key):
    if primary_key in cache[table_name]:
        return cache[table_name][primary_key]
    else:
        x = get_data_from_server(table_name,primary_key) # socket.io
        return cache[table_name][primary_key] = x
</code>```

While this scheme works perfectly well for caching individual rows, I'd like to extend it to support the creation of paginated tables ordered according to the primary_key, and loading additional data using the above function for only the current and possibly the adjacent pages. Now, I don't want to keep the list of primary keys on the server to be retrieved every time I need to change the page (which, for reasons beyond the scope here, will be very frequent), and keeping it on the client side, subject to real-time create/delete events from the server, doesn't seem that good an idea, even after compression (using ranges, instead of individual values).

What is the best way to calculate which items are to be displayed on a random page, minimizing the space requirements & the need for communication with the server?

答:
If the server does the pagination isn't it already returning a small subset?

You could let the server return only an a list of primary-keys for the requested page. Materialize as many as you can from your cache, then bulk fetch the remaining identities from the server in one call.


问:
JavaScript and callback nesting
A lot of JavaScript libraries (notably jQuery) use chaining, which allows the reduction of this:

```<code>var foo = $(".foo");
foo.stop();
foo.show();
foo.animate({ top: 0 });
</code>```

to this:

```<code>$(".foo").stop().show().animate({ top: 0 });
</code>```

With proper formatting, I think this is quite a nice syntactic capability. However, I often see a pattern which I don't particularly like, but appears to be a necessary evil in non-blocking models. This is the ever-present nesting of callback functions:

```<code>$(".foo").animate({
    top: 0,
}, {
    callback: function () {
        $.ajax({
            url: 'ajax.php',
        }, {
            callback: function () { ... }
        });
    }
});
</code>```

And it never ends. Even though I love the ease non-blocking models provide, I hate the odd nesting of function literals it forces upon the programmer.

I'm interesting in writing a small JS library as an exercise, and I'd love to find a better way to do this, but I don't know how it could be done without feeling hacky. Are there any projects out there that have resolved this problem before? And if not, what are the alternatives to this ugly, meaningless code structure?

答:
Just because you can use anonymous functions (lambdas) for this kind of construct doesn't mean you have to. Just like it's good practice to pull complex value construction syntax out of a function call and into its own variable, you can do the same with your function literals. Observe:

```<code>// Your example:
$(".foo").animate({
    top: 0,
}, {
    callback: function () {
        $.ajax({
            url: 'ajax.php',
        }, {
            callback: function () { ... }
        });
    }
});

// Can be rewritten as:
var animateProps = { top: 0 };
var animateCallback = function() {
    var ajaxProps = { url: 'ajax.php'; }
    var ajaxCallback = function () { ... }
    $.ajax(ajaxProps, {callback: ajaxCallback});
};
$(".foo").animate(animateProps, {callback: animateCallback});

// Or even, depending on what you do inside the ajax callback:
var animateProps = { top: 0 };
var ajaxProps = { url: 'ajax.php'; }
var ajaxCallback = function () { ... }
var animateCallback = function() {
    $.ajax(ajaxProps, {callback: ajaxCallback});
};
$(".foo").animate(animateProps, {callback: animateCallback});
</code>```

And all the ugly nested syntax is gone!

Note, however, that the nested-anonymous-function style isn't all that bad; after all, if your function calls follow a logical structure, then so will the function call nestings. Example:

```<code>doAsyncSomething(
    function(successData){
        alert("All is well!");
    },
    function(errorMessage){
        alert("Oh no! Something went wrong! Namely: " + errorMessage);
    });
</code>```

In this example, the code nesting follows the logical structure quite nicely.

Title: JavaScript and callback nesting

Body:
Just because you can use anonymous functions (lambdas) for this kind of construct doesn't mean you have to. Just like it's good practice to pull complex value construction syntax out of a function call and into its own variable, you can do the same with your function literals. Observe:

// Your example:
$(".foo").animate({
    top: 0,
}, {
    callback: function () {
        $.ajax({
            url: 'ajax.php',
        }, {
            callback: function () { ... }
        });
    }
});

// Can be rewritten as:
var animateProps = { top: 0 };
var animateCallback = function() {
    var ajaxProps = { url: 'ajax.php'; }
    var ajaxCallback = function () { ... }
    $.ajax(ajaxProps, {callback: ajaxCallback});
};
$(".foo").animate(animateProps, {callback: animateCallback});

// Or even, depending on what you do inside the ajax callback:
var animateProps = { top: 0 };
var ajaxProps = { url: 'ajax.php'; }
var ajaxCallback = function () { ... }
var animateCallback = function() {
    $.ajax(ajaxProps, {callback: ajaxCallback});
};
$(".foo").animate(animateProps, {callback: animateCallback});

And all the ugly nested syntax is gone!

Note, however, that the nested-anonymous-function style isn't all that bad; after all, if your function calls follow a logical structure, then so will the function call nestings. Example:

doAsyncSomething(
    function(successData){
        alert("All is well!");
    },
    function(errorMessage){
        alert("Oh no! Something went wrong! Namely: " + errorMessage);
    });

In this example, the code nesting follows the logical structure quite nicely.


问:
Testing controller logic that uses ISession directly
I have just read this blog post from Jimmy Bogard and was drawn to this comment.

Where this falls down is when a component doesn’t support a given
  layering/architecture. But even with NHibernate, I just use the
  ISession directly in the controller action these days. Why make things
  complicated?

I then commented on the post and ask this question:-

My question here is what options would you have testing the controller logic IF you do not mock out the NHibernate ISession.

I am curious what options we have if we utilise the ISession directly on the controller?

答:
Use a light weight in-memory database that's NHibernate supported.

Or you can use seams on the controller, extract code that uses ISession to a separate method, make it virtual. Override it in a class on which you run your tests.

If you do these methods you may as well put them on a repository interface though.


答:
As always, it depends. Caching can improve performance anywhere between "whopping" and "not at all", or even reduce performance.

If your resource it read often but seldom changed, caching is usually a good idea, especially when generating it is non-trivial. If, however, it changes every few requests, there is no point caching it.

Also, it can be beneficial to use several layers of caching - e.g., a response cache at the HTTP level that serves identical responses to identical requests, a memory cache holding readily-processed data sets, another cache that holds chunks of raw data for further processing, and of course the caching that comes with your databases and filesystems. The reason why you want to cache at several levels is that there are different points at which you can match identical conditions with identical results, and you want to cache at each of these whenever it makes sense.

Another factor you need to keep in mind is that most data does not have to be available in real-time. It is often acceptable to present data that is, say, an hour old or so, even when newer data exists. If this is the case, you can generate your resource in a separate process, serving the previous version until the new one is done, then doing a fast atomic replace (e.g. by renaming a file or through an atomic database operation). This way, you always get maximum performance at all times, while you can still afford to take some time generating the resource. And, better yet, the generator can run on a different machine if necessary, so as not to bog down the web server itself. Of course it doesn't hurt to add a layer of caching on top of that; after all, serving from RAM is still an order of magnitude faster than serving from disk.


问:
Saving all hits to a web app
Are there standard approaches to persisting data for every hit that a web app receives? This would be for analytics purposes (as a better alternative to log mining down the road).

Seems like Redis would be a must. Is it advisable to also use a different DB server for that table, or would Redis be enough to mitigate the impact on the main DB?

Also, how common is this practice? Seems like a no brainer for businesses who want to better understand their users, but I haven't read much about it.

答:
I think it's far more common to just use conventional logging to a textfile. Most webservers can log all the requests. You can analyze those external to any application that handles the requests.

Just keep it cheap and simple. You could still use Redis when making a reporting solution by importing the log files.

Title: Saving all hits to a web app


问:
Best way to protect website application code

Background

I have a web application that I host on my own server. I have clients who use the application as is, but some have asked if they can host the application on their own server. This enables them to have their own URLS rather than mine. The application only forms part of their website  so I'm assuming it will not be possible for my server to respond to a direct call to their domain etc

To give some examples, i currently have urls like www.mydomain.com/profile, www.mydomain.com/index.php?option=someoption&view=someview&id=1 What my clients' want is www.theirdomian.com/profile, www.theirdomian.com/index.php?option=someoption&view=someview&id=1 etc

Question

My question is, what is the best way for me to allow them to use their own URLs with my application, without giving them all the backend source code and databases to install on their server?

One way I thought would be to create a router.php file that sits on their server. The router then asks my server to output the html. When a link is clicked on the clients site, the router receives the request and forwards the request to get the data from my server etc.

Is this an effective way to achieve what I want, or is it way off the mark.

答:
There are a few technical solutions to this:

Have them point their domain to your server, and configure your server to accept such requests; this is a simple DNS change, but it does mean that their entire domain now runs on your server.

Have them set up a reverse proxy on their end that rewrites the desired requests to your domain. Apache, for example, has modules for this (see https://httpd.apache.org/docs/2.2/mod/mod_proxy.html), including filters to rewrite URLs inside the documents you serve; this is kind of a hassle to set up, and it doesn't work for everything, but it may be worth giving a shot - if it does work, your application will run transparently under their domain, served through their servers, but running on your own servers. The basic idea is that their server matches request URLs against a certain pattern, forwards them to your server, and then changes the URLs in the response it receives before sending it back to the client. (Basically, this is your router.php solution, only at the web server level, thus with less hassle.)

Have them put an iframe into their page, in which they just put your page. If the iframe has 100% width and height, the user won't see the difference (except that navigation does not change the visible URL). This is by far the easiest solution.

Split up your application into a service layer and a front end. Deliver the front end, but keep the service layer on your server. This way, they can only make use of your service through your server; the front-end without the service layer is relatively useless.

Install and maintain a server (physical or virtual) on their network that runs your application; set it up so that they cannot access it (strong passwords, full-disk crypto, etc.).

However, the problem is a social one, not a technical one, and the proper social solution is to set up a proper contract (hint: you do need a lawyer for this) that clearly states what they can and cannot do with it, and deliver the code. Yes, you need to trust them not to violate the contract in clever ways; but that's just the way of the world.

If you absolutely cannot trust them not to be criminals, then maybe you should just decline the offer and make your money elsewhere.


问:
Continous Delivery TFS
Is it possible to achieve Continuous Delivery using TFS e.g. Windows Service? There are > 1000 posts on how to use msdeploy with TFS for WEB projects.

I am trying to understand why there are no resources such as blogs, articles, msdn or best practises for Continuous Delivery for Windows service using TFS.

I am not sure tow to achieve the following without any working reference materials. This is so frustrating.

Archive existing codebase on Remote server for Service as well for Web project not on Integration Server please!

How To Stop services on Remote server not on Integration Server

Copy New code Base on Remote Server

Start Services

答:
I decided to ignore msdeploy altogether. Largely for the same reasons you mention. Lack of documentation and noone seems to be using it (successfully).

My impression is that it only makes something that is not that hard complicated.

I stick with simple xcopy deploy methods. Most services like IIS have fine management interfaces, I just script against those.

Title: Continous Delivery TFS


问:
What are some good End-User Programming solutions you have seen?
End-User Programming is where regular end users, i.e. non-programmers, are able to customize a program, or create a new one, with minimal training or instruction.

App Inventor for Android is one recent example, but perhaps the most popular example of end-user programming is the spreadsheet.

What examples of end-user programming have you seen used, or believe to be useful? What's the philosophy of the system? What challenges remain?

答:
mIRC

Back in the day, mIRC scripting was a relatively harmless way of exposing end-users to simple variables and event handling.  It probably still is, really.


问:
Alternatives to sql like databases
These days computers usually have 2GB or 4GB memory.

I like to use some secure client server model, and well an sql database is likely candidate.

On the other hand I only have about 8000 records, who will not frequently be read or written in total they would consume less then 16 Megabyte.

And it made me wonder what would be good secure options in a windows environment to store the data work with it multi-client single server model, without using SQL or mysql?

Would for well such a small amount of data maybe other ideas better?

Because I like to keep maintenance as simple as possible (no administrators would need to know sql maintenance, as they dont know databases in my target environment).

Maybe storing in xml files or.. something else.

How others would go if ease of administration is the main goal?

Oh and it should be secure to, the client server data must be a bit secure (maybe NTLM files shares https or...etc)

Maybe I should say something of the use, it would be like client ask for a single record and retrieves an answer a single byte is returned those clients won't launch complex questions, only the maintenance server side might require record editing, clients will only ask not change records. And clients wont perform advanced queries.

答:
Very first thing that comes to mind is SQLite. Have you considered giving that a shot? Very light weight and ubiquitous. Easy to use too.

SQLite (in addition to the comments below) is easily backed up and transportable across systems, mobile devices, client machines, embedded systems, servers all because it is a file. It does behave like a SQL system and often is used like a very lite one.

In our corporation we use them as mini databases from major ERP systems were we replicate this data down to mobile devices for offline access. This allows the same logic in our apps on mobile devices regardless of whether they are connected to a beefy server or in some remote location with no network access.

This data can also be encrypted and secure as you would like it to be. Again everything is securely encrypted on the mobile devices and in transmission.

Maintenance on the SQLite db file is very easy. There are many functions that you can use to keep the database light and optimize. I refer to this FAQ often. One command that has helped us in the mobile and embedded world to transfer our database faster is vacuum command for instance. SQLite makes it easy.

One other use of SQLite that I recently saw online (but can't find the link btu will include it once I do) is that it can be used as a portable filesystem for various computers. It is easy to store and pack searchable data and then easily move it. I gather from your question this might also be of benefit.

I hope this gives a clearer answer and of some of the possibilities for SQLite.

Title: Alternatives to sql like databases