问:
Refactor an old model of a LastUser Modification on every Object?
I have a software requirement, that needs to store the user that made the last modification to another object, for every object (assume that all objects are already mapped and into a BD).

So we have the ParamBase an object that holds the basic data for every object, this will be a super class, every other parameter in the system will Inherit this class, (Using @MappedSuperClass)

```<code>@MappedSuperclass
ParamBase {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Version
    private Long version;

    @Temporal(value = TemporalType.TIMESTAMP)
    private Date timeStampLastModification;

    @Column
    private User userOfLastModification;
    //constructors, getter setters, other stuff, etc
}
</code>```

The User object, this will represent the user, also mapped into a BD, for now is just simple Object mapped as Entity, all other Parameters will have to store this User into a field.

```<code>@Entity
User {
   //User stuff, cons, get, seters, etc
}

@Entity
Country extends ParamBase {
    //This class extends ParamBase so will have a field to hold the
    //userOfLastModification
}
</code>```

In an EJB I have business logic that will work with several operations and objects, when in this case a parameter is updated, the userSession (assigned at login) will update the userOfLastModification field.

THE PROBLEM:
All of the objects will have a relation with User, so all other Objects have a mapped field userOfLastModification_id, this creates a massive dependency of all clases to User.
To give you an idea, just picture on an Entity Relation diagram ER, all tables related to one single User Table, it's a mess!!!

THE REFACTOR!:
I think this model is wrong, I think breaks the equilibrium of software design  I don't think you need to create a relation between all the tables/object to one table (User) to accomplish this requirement, I will like some feedback or ides on how to:
1. Explain the design error, if there is one? (I always think that I can be wrong, and there's no problem with that)

Is there a better way to do this?

Thanks for your help!

答: Refactoring with DougM approach to handle it with a Java String had the best result posible as only getters and setters where changed, with little amount of efford.</p>


问:
Is it acceptable to ask management for pseudo code?
I'm a developer in the IT department of a large oil company. I received a spec document, basically in plain English, about business rules that need to be implemented in a new application. The rules are really difficult to translate into code, since I don't know all of the inner workings of the business.

Is it acceptable to ask management (the people who gave me the spec) for the rules in more of a pseudo code fashion or would I be looked at as if I had two heads?

"Management" in this case refers to guys who were once developers, but now have more of a management role here in IT.

答:
The essence of delivering products for customers is figuring out the communication process.   Often the specifics are not initially clear and you'll have to move things in that direction.  You will need to ask every question necessary until you understand the business process as it relates to your use case.  Often this means you speak with an expert (usually a business analyst).

If you cannot be made to understand the specifics of the process you have little hope of writing proper code.  Ultimately, your code should clearly articulate the process.  In other words, write the code so that it demonstrates and understanding of what is supposed to happen.  Normally, you want to use named variables to express the transitions from a starting state to a final state.  Most processes are state machines of one form or another whether or not state machine is explicit in the code.

ContentLicense: CC BY-SA 3.0


答:
If you think it will help, yes, ask them for pseudo-code.  Or, perhaps, more specific lower level descriptions of processes.  Or a flow chart, even.  If they are managers with a vested interest in your successfully finishing a project,  why would they have a problem with the request?  </p>

<p>If, though, you find that you need pseudo-code often, then there is clearly a communication issue between you and them.  Either they are not being clear enough, and/or you are not very good at converting requests into code.  </p>

Title: Is it acceptable to ask management for pseudo code?

Body:
I'm a developer in the IT department of a large oil company. I received a spec document, basically in plain English, about business rules that need to be implemented in a new application. The rules are really difficult to translate into code, since I don't know all of the inner workings of the business.

Is it acceptable to ask management (the people who gave me the spec) for the rules in more of a pseudo code fashion or would I be looked at as if I had two heads?

"Management" in this case refers to guys who were once developers, but now have more of a management role here in IT.

Body:
If you think it will help, yes, ask them for pseudo-code.  Or, perhaps, more specific lower level descriptions of processes.  Or a flow chart, even.  If they are managers with a vested interest in your successfully finishing a project,  why would they have a problem with the request?

If, though, you find that you need pseudo-code often, then there is clearly a communication issue between you and them.  Either they are not being clear enough, and/or you are not very good at converting requests into code.


问:
Is my websocket session idea practical?
In a situation where all communication (including logging in) between a client (web browser) and server is done over a persistent TLS encrypted websocket, would there be anything inadvisable about having the server attach the client's log-in state to the connection itself as custom properties?

ie,

```<code>WSconnection.loggedIn = true;
WSconnection.timeout = Date.now() + 360000;
</code>```

By doing this you'd actually be authenticating the connection not the user. However, the connection is a persistent TLS encrypted point to point connection.

答:
That is how HornetQ's websocket implementation works (Stomp doesn't necessarily have to work over WebSockets but HornetQ exposes both naked TCP and WebSocket options).

StompConnection.java

Essentially the connection object is wrapped with the metadata of the HornetQ session ID and the login credentials and flagged "isValid".

So yes, it's certainly a practical and workable method.

Title: Is my websocket session idea practical?


问:
When should I implement authentication in a database?
I'm currently embarking on a MongoDB project (a simple user login system), and I notice that there is an option for authentication. Here is the server string, with the userinfo shown as optional information.

```<code>mongodb://[username:password@]host1[:port1][,host2[:port2:],...]/db
</code>```

From the MongoDB Manual:

Before gaining access to a system all clients should identify themselves to MongoDB. This ensures that no client can access the data stored in MongoDB without being explicitly allowed.

Why would I choose to use this feature? Shouldn't it be up to the server programmers (i.e. the ones implementing the PHP, Python, or whatever have you) to authenticate the user to determine which information to display?

答:
You would use that feature to log into the database. Your program (whether it runs on the server or the client) is going to have to identify and authenticate itself--either to the (MongoDB) database itself, or possibly to a proxy service.

In either case, it will need at least a userid and password to do so. (Cryptographic keys or trusted tokens are even stronger, safer identifying and authenticating credentials. But that's another level for later.)

So if your "simple" user login system wants/needs to contact the DBMS directly, it will have to construct something similar to the URL template you posted. (That's true of other databases like MySQL as well.)

If you don't provide credentials such as this, the DBMS will not recognize your program as one that can legitimately access data, and it won't let your program "in." (Note, this is separate from the user login process, which presumably relies on the data in MongoDB to navigate.)

As @Matthew points out, your DBMS user accounts/credentials are best kept separate from the user accounts/credentials you're managing.

A final, important note: There are no simple user login systems. Little issues like security exposures make them rather complicated and tricky to get right. When they're simple, they're usually woefully insecure--subject to spoofing, wiretapping, and other exploits. You may get away with it on a local, private network with low probability that others will want to attack your system. But if it's on the wider Internet, or protects anything of value, security hardening is essential. There's a 99.99999999% chance you're not going to get that with a "simple" homegrown solution; especially not the first time out of the barn.


问:
Why implement a lexer as a 2d array and a giant switch?
I'm slowly working to finish my degree, and this semester is Compilers 101. We're using the Dragon Book. Shortly into the course and we're talking about lexical analysis and how it can be implemented via deterministic finite automata (hereafter, DFA). Set up your various lexer states, define transitions between them, etc.

But both the professor and the book propose implementing them via transition tables which amount to a giant 2d array (the various non-terminal states as one dimension, and the possible input symbols as the other) and a switch statement to handle all of the terminals as well as dispatch to the transition tables if in a non-terminal state.

The theory is all well and good, but as someone who's actually written code for decades, the implementation is vile. It's not testable, it's not maintainable, it's not readable, and it's a pain and a half to debug through. Worse yet, I can't see how it would be remotely practical if the language was UTF capable. Having a million or so transition table entries per non-terminal state gets unweildy in a hurry.

So what's the deal? Why is the definitive book on the subject saying to do it this way?

Is the overhead of function calls really that much? Is this something that works well or is necessary when the grammar isn't known ahead of time (regular expressions?)? Or perhaps something that handles all cases, even if more specific solutions will work better for more specific grammars?

(note: possible duplicate "Why use an OO approach instead of a giant switch statement?" is close, but I don't care about OO. A functional approach or even saner imperative approach with standalone functions would be fine.)

And for the sake of example, consider a language that only has identifiers, and those identifiers are [a-zA-Z]+. In the DFA implementation, you'd get something like:

```<code>private enum State
{
    Error = -1,
    Start = 0,
    IdentifierInProgress = 1,
    IdentifierDone = 2
}

private static State[][] transition = new State[][]{
    ///* Start */                  new State[]{ State.Error, State.Error (repeat until 'A'), State.IdentifierInProgress, ...
    ///* IdentifierInProgress */   new State[]{ State.IdentifierDone, State.IdentifierDone (repeat until 'A'), State.IdentifierInProgress, ...
    ///* etc. */
};

public static string NextToken(string input, int startIndex)
{
    State currentState = State.Start;
    int currentIndex = startIndex;
    while (currentIndex < input.Length)
    {
        switch (currentState)
        {
            case State.Error:
                // Whatever, example
                throw new NotImplementedException();
            case State.IdentifierDone:
                return input.Substring(startIndex, currentIndex - startIndex);
            default:
                currentState = transition[(int)currentState][input[currentIndex]];
                currentIndex++;
                break;
        }
    }

    return String.Empty;
}
</code>```

(though something that would handle end of file correctly)

Compared to what I would expect:

```<code>public static string NextToken(string input, int startIndex)
{
    int currentIndex = startIndex;
    while (currentIndex < startIndex && IsLetter(input[currentIndex]))
    {
        currentIndex++;
    }

    return input.Substring(startIndex, currentIndex - startIndex);
}

public static bool IsLetter(char c)
{
    return ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'));
}
</code>```

With the code in NextToken refactored out into its own function once you have multiple destinations from the start of the DFA.

答:
The inner loop of:

```<code>                currentState = transition[(int)currentState][input[currentIndex]];
                currentIndex++;
                break;
</code>```

has a lot of performance advantages.  There are no branches in that at all, because you do exactly the same thing for every input character.  The performance of the compiler can be gated by the lexer (which must operate on a scale of every character of input).  This was even more true when the Dragon Book was written.

In practice, besides CS students studying lexers, no one has to implement (or debug) that inner loop because it is part of the boilerplate that comes with the tool that builds the transition table.

Body:
The inner loop of:

                currentState = transition[(int)currentState][input[currentIndex]];
                currentIndex++;
                break;

has a lot of performance advantages.  There are no branches in that at all, because you do exactly the same thing for every input character.  The performance of the compiler can be gated by the lexer (which must operate on a scale of every character of input).  This was even more true when the Dragon Book was written.

In practice, besides CS students studying lexers, no one has to implement (or debug) that inner loop because it is part of the boilerplate that comes with the tool that builds the transition table.


答:
The main technical reason is that most databases require you to authenticate in order to figure out which "schema" or "application" you are connecting to. Otherwise, it doesn't know who you are.

The main security reason is that connections from the local network should not be trusted. If another node on your network is compromised (a PC, a server, a wifi guest, the teenage sys-admin in the back room downloading warez), then so is your unauthenticated database. Of course your database and app server should reside behind a firewall either way.

You can limit the connections to localhost (same computer), but in many architectures, the app code runs on a different node from the database. If your app is co-resident with your DB, and you have a single dedicated DB for your app, then you can get away with this.

With databases that support schemas / multiple accounts, users are often dedicated to unique applications. MongoDB encourages this. This ensures multiple applications can safely share a single database infrastructure. I often host multiple web applications with a single physical database. App1 should not be able to freely connect to App2's data store.

Lastly, for auditing / compliance reasons, users must authenticate in order to identify who did what, retroactively. If you are in any business covered by regulatory controls, HIPAA, SOX, etc. accurate auditing is a requirement. Generic or shared users are not compliant.

As far as who is responsible? It is every programmer's responsibility, but especially the app programmer and database administrator. Often those are one and the same.

Maybe some of these don't apply to your app, but its a good practice nonetheless.

Title: When should I implement authentication in a database?

Body:
I'm currently embarking on a MongoDB project (a simple user login system), and I notice that there is an option for authentication. Here is the server string, with the userinfo shown as optional information.

```<code>mongodb://[username:password@]host1[:port1][,host2[:port2:],...]/db
</code>```

From the MongoDB Manual:

Before gaining access to a system all clients should identify themselves to MongoDB. This ensures that no client can access the data stored in MongoDB without being explicitly allowed.

Why would I choose to use this feature? Shouldn't it be up to the server programmers (i.e. the ones implementing the PHP, Python, or whatever have you) to authenticate the user to determine which information to display?


问:
Unit test private method in c++ using a friend class
I know that this is a debated practice, but let's suppose that this is the best option for me. I am wondering about what is the actual technique to do this. The approach that I see is this:

1) Make a friend class that of the class who's method I want to test.

2) In the friend class, create a public method(s) that call the private method(s) of the tested class.

3) Test the public methods of the friend class.

Here is a simple example to illustrate the above steps:

```<code>#include <iostream>

class MyClass
{
  friend class MyFriend; // Step 1

  private:
  int plus_two(int a)
  {
    return a + 2;
  }
};

class MyFriend
{
public:
  MyFriend(MyClass *mc_ptr_1)
  {
    MyClass *mc_ptr = mc_ptr_1;
  }

  int plus_two(int a) // Step 2
  {
    return mc_ptr->plus_two(a);
  }
private:
  MyClass *mc_ptr;
};

int main()
{
  MyClass mc;
  MyFriend mf(&mc);
  if (mf.plus_two(3) == 5) // Step 3
    {
      std::cout << "Passed" << std::endl;
    }
  else
    {
      std::cout << "Failed " << std::endl;
    }

  return 0;
}
</code>```

Edit:

I see that in the discussion following one of the answers people are wondering about my code base.

My class has methods that are called by other methods; none of these methods should be called outside the class, so they should be private. Of course they could be put into one method, but logically they are much better separate. These methods are complicated enough to warrant unit testing, and due to performance issues I will very likely have to re-factor these methods, hence it would be nice to have a test to make sure that my re-factoring didn't break anything. I am not the only one working on the team, though I am the only one who is working on this project including the tests.

Having said the above, my question was not about whether it is a good practice to write unit tests for private methods, though I appreciate the feedback.

答:
If it's hard to test, it's badly written

If you have a class with private methods complex enough to warrant their own test, the class is doing too much.  Inside there is another class trying to get out.

Extract the private methods that you want to test into a new class (or classes) and make them public.  Test the new classes.

In addition to making the code easier to test, this refactoring will make the code easier to understand and maintain.


问:
Function has two sets of arguments, the latter of which calls a nested function?
The function foo, has a nested function; bar. Calling foo with a second set of arguments feeds them into bar if bar is returned at the end of foo. How does this work and what is it called?

Are there any uses for it over simply having a single set of arguments that calls the function normally?

```<code>def foo(arg1):
    print(arg1)
    def bar(arg2,arg3):
        print (arg2,arg3)
    return bar

foo("hello")("hello","world")

>>>
hello
hello world
</code>```

答:
This is called higher-order programming, or, using functions as first-class values. In this case, a function returning a function.

The use of it compared to simply having a single set of arguments only becomes apparent when the "second set of arguments" is not provided, i.e. when foo("hello") is used by itself (passed into another function or stored in a variable). This is usually only useful if, unlike in the example in the original question, arg1 is used inside of bar. The answer involving getErrorHandler illustrates this more useful case, which can also be thought of as forming a closure.

Though "having second set of arguments" may be a helpful mental model, and corresponds to the way it looks when "fully called" (saturated), these extra arguments don't really belong to foo, they belong to bar.


问:
Shipping unmodified open source applications with closed source apps
I am creating a closed source application whose task is to launch other open source applications (similar to start menu of windows).

So i have included various opensource applications under licences like :

GNU-GPL

LGPL

MIT license

Apple Public Source License Version 2.0

Apache creative commons

CeCILL

I have not modified the opensource applications and i am ready to publish source of the opensource applications,
but i do not want to disclose the source code of my launcher application.

I intend to offer the whole stuff free with a commercial hardware.  i.e. i am charging only for hardware and not for software. Can i do so ?

Further in future i intend to sell the whole software bunch by including only the cost incurred for developing the closed source module, can i do so ?

I have gone through the gpl documentation but i am not able to relate the scenario with the information in docs.

Please explain the answer w.r.t. the individual licence, so that i can exclude the applications incase their license does not permit me to do so!

答:
For the use case of an application launcher, it is definitely allowed, but there are terms, which vary depending on whether it's GPL2 or GPL3. For the GPL2, you must ship the source code on the same server that is used to download the binary (section 3a).

The GPL3 (section 6d) is more permissive, but you have to be prepared in case the 3rd party website goes down or stops hosting the particular version of the source.


问:
What is the benefit of a function without parameters which only calls another function
A tutorial (for Javascript) I'm doing suggests we write a function like this one:

```<code>function sayHello() {
   //Some comments explaining the next line
   window.alert("Hello");
}
</code>```

Other than obfuscation are there benefits to writing something like this in real life? If so, what are the benefits?

答: As Doval said, this example is probably just trying to introduce you to functions. I'm general, though, it is useful. Especially by specifying some but not all do the arguments, and passing the other ones through, you can make a more case-specific function from a more general function. As a somewhat trivial example, consider a sorting function that takes an array to sort and a comparator function to sort with. By specifying a comparator function that compares by numerical value, I can make a sortByNumericalValue function, and calls to that function are much more clear and concise.</p>


答:
I think its useful sometimes for hiding implementation.

```<code> function sayHello() {
  window.alert("Hello");
 }
</code>```

And this gives you the flexibility to change it later

```<code> function sayHello() {
  console.log("Hello");
 }
</code>```

Title: What is the benefit of a function without parameters which only calls another function

Body:
A tutorial (for Javascript) I'm doing suggests we write a function like this one:

```<code>function sayHello() {
   //Some comments explaining the next line
   window.alert("Hello");
}
</code>```

Other than obfuscation are there benefits to writing something like this in real life? If so, what are the benefits?

Body:
I think its useful sometimes for hiding implementation.

 function sayHello() {
  window.alert("Hello");
 }

And this gives you the flexibility to change it later

 function sayHello() {
  console.log("Hello");
 }


问:
Debug symbols change application execution
I have to set up remote debugging for a multi threaded application running on a embedded device. C++ is the language.

I've gotten so far and got the remote debugging working for a simple application, but when applying the same procedures on the multi threaded giant just don't work (the application starts behaving unpredictably when built with debug). There was no stopping of the execution (no breakpoints), just a continuous standard run, just with debug symbols.

What would cause a failure in debug mode in this environment? (once again, no breakpoints in debug mode, just continuous running)

答:
Not really enough information to go on, but anyway...

First and foremost, properly written and bug-free code does not fail when build in debug mode. The likelihood is that you have uncovered bugs you didn't know where there.

Generically, across all kinds of applications, the commonest reason for a debug build failing is the difference in memory layout (triggering an otherwise silent bug). Different initialisation values (debug code often fills unused space with strange bit patterns) or different spacing or placement will all do it. A less common reason is the different level of optimisation.

Specifically, for multi-threaded applications, the commonest reason is timing. Debug code runs slower and either exposes or covers up race conditions.

Bottom line: you've got bugs to fix. Be thankful that debug mode has exposed them for you.


答:
Please pardon my memory if I have this incorrect... Javascript isn't my preferred implementation language.

There are several reasons why one would want to have a no arg function wrap another function call.  While the simple call to window.alert("Hello"); is something that you could imagine just instead calling directly instead of sayHello().

But what if there is more to it?  You've got a dozen places where you want to call sayHello() and have written window.alert("Hello"); instead.  Now you want it to do a window.alert("Hello, it is now " + new Date()).  If you wrapped all those calls as sayHello() you change it one place.  If you didn't, you change it in a dozen places.  This touches on Don't Repeat Yourself.  You do it because you don't want to have to do it a dozen times in the future.

I worked with an i18n / l10n library in the past that used functions to do client side localization of the text.  Consider the sayHello() function.  You could have it print out hola when the user is localized to a Spanish language.  This could look something like:

```<code>function sayHello() {
  var language = window.navigator.userLanguage || window.navigator.language;
  if(language === 'es') { window.alert('Hola'); }
   else { window.alert("Hello"); }
}
</code>```

Though, this isn't how the library worked.  Instead, it had a set of files that looked like:

```<code># English file
greeting = hello
</code>```

```<code># Spanish file
greeting = hola
</code>```

And then the library would detect the browser language setting and then create dynamic functions with the appropriate localization as the return value for a no-arguemnt function call based on the appropriate localization file.

I'm not enough of a Javascript coder to say if that is good or bad... just that it was and can be seen as a possible approach.

The point being, wrapping the call to another function in a function of its own is often quite useful and helps with the modularization of the application and may also result in easier to read code.

All that bit aside, you are working from a tutorial.  It is necessary to introduce things as simply as possible at the start.  Introducing varargs style function calls from the start can result in some very confusing code for a person who is unfamiliar with coding in general.  It is much easier to go from no argument, to arguments, to varargs style - with each building on the previous examples and understanding.

Body:
Please pardon my memory if I have this incorrect... Javascript isn't my preferred implementation language.

There are several reasons why one would want to have a no arg function wrap another function call.  While the simple call to window.alert("Hello"); is something that you could imagine just instead calling directly instead of sayHello().

But what if there is more to it?  You've got a dozen places where you want to call sayHello() and have written window.alert("Hello"); instead.  Now you want it to do a window.alert("Hello, it is now " + new Date()).  If you wrapped all those calls as sayHello() you change it one place.  If you didn't, you change it in a dozen places.  This touches on Don't Repeat Yourself.  You do it because you don't want to have to do it a dozen times in the future.

I worked with an i18n / l10n library in the past that used functions to do client side localization of the text.  Consider the sayHello() function.  You could have it print out hola when the user is localized to a Spanish language.  This could look something like:

function sayHello() {
  var language = window.navigator.userLanguage || window.navigator.language;
  if(language === 'es') { window.alert('Hola'); }
   else { window.alert("Hello"); }
}

Though, this isn't how the library worked.  Instead, it had a set of files that looked like:

# English file
greeting = hello

# Spanish file
greeting = hola

And then the library would detect the browser language setting and then create dynamic functions with the appropriate localization as the return value for a no-arguemnt function call based on the appropriate localization file.

I'm not enough of a Javascript coder to say if that is good or bad... just that it was and can be seen as a possible approach.

The point being, wrapping the call to another function in a function of its own is often quite useful and helps with the modularization of the application and may also result in easier to read code.

All that bit aside, you are working from a tutorial.  It is necessary to introduce things as simply as possible at the start.  Introducing varargs style function calls from the start can result in some very confusing code for a person who is unfamiliar with coding in general.  It is much easier to go from no argument, to arguments, to varargs style - with each building on the previous examples and understanding.


答:
Here's a questionable suggestion for a questionable question. I don't like the coupling of friend as then released code has to know about the test. Nir's answer is one way to alleviate that, but I still don't much like changing the class to conform to the test.

Since I don't rely on inheritance often, I sometimes just make the otherwise private methods protected and have a test class inherit and expose as needed. The reality is that the public API and the testing API can differ and still be distinct from the private API, which leaves you in sort of a bind.

Here's a practical example that's of the sort I resort to this trick for. I write embedded code, and we rely on state machines quite a bit. The external API doesn't necessarily need to know about the internal state machine state, but the test should (arguably) test conformance to the state machine diagram in the design doc. I might expose a "current state" getter as protected and then give the test access to that, allowing me to test the state machine more fully. I often find this type of class hard to test as a black box.

Title: Unit test private method in c++ using a friend class

Body:
I know that this is a debated practice, but let's suppose that this is the best option for me. I am wondering about what is the actual technique to do this. The approach that I see is this:

1) Make a friend class that of the class who's method I want to test.

2) In the friend class, create a public method(s) that call the private method(s) of the tested class.

3) Test the public methods of the friend class.

Here is a simple example to illustrate the above steps:

```<code>#include <iostream>

class MyClass
{
  friend class MyFriend; // Step 1

  private:
  int plus_two(int a)
  {
    return a + 2;
  }
};

class MyFriend
{
public:
  MyFriend(MyClass *mc_ptr_1)
  {
    MyClass *mc_ptr = mc_ptr_1;
  }

  int plus_two(int a) // Step 2
  {
    return mc_ptr->plus_two(a);
  }
private:
  MyClass *mc_ptr;
};

int main()
{
  MyClass mc;
  MyFriend mf(&mc);
  if (mf.plus_two(3) == 5) // Step 3
    {
      std::cout << "Passed" << std::endl;
    }
  else
    {
      std::cout << "Failed " << std::endl;
    }

  return 0;
}
</code>```

Edit:

I see that in the discussion following one of the answers people are wondering about my code base.

My class has methods that are called by other methods; none of these methods should be called outside the class, so they should be private. Of course they could be put into one method, but logically they are much better separate. These methods are complicated enough to warrant unit testing, and due to performance issues I will very likely have to re-factor these methods, hence it would be nice to have a test to make sure that my re-factoring didn't break anything. I am not the only one working on the team, though I am the only one who is working on this project including the tests.

Having said the above, my question was not about whether it is a good practice to write unit tests for private methods, though I appreciate the feedback.


问:
Static controllers
I have built myself a PHP MVC framework to meet my needs. As pretty much all of the core classes are static, I just stumbled upon the idea of having static controllers.  I know that for some reason static classes are not perceived well by programmers, however if a class makes no sense to have an instance I really can't see any good reason to create one.

For example the System class ( b.k.a. App in other frameworks ) that initializes the whole framework includes configuration files and calls the front controller. There cannot be two instances of this class - the system is only initialized once. Yes it does have other functions as well but none of them relate to an instance - getClientIP, handleException, handleError etc.

So following the same path of logic, my controllers have no properties and are generally used once per request. However when I think about it, I have never seen a framework with static controllers. Static library classes - yes, but static controllers - never. Is there any good reason not to have static controllers in an MVC framework?

P.S.: And yes I know there's no such thing as static classes in PHP yet, basically what I call a static class is a class with private constructor and only static methods.

答:
In a complex routing system, generally a controller should be looked up by a name that is based on what its job is or what route it handles. When your app "boots up" you register controllers under those names so that the class name isn't hard coded everywhere, allowing you to swap out controllers easily. This is what the App facade in Laravel does.

There is nothing wrong with using static classes (abstracts with final private constructors) in place of singletons (I personally think they are preferable to singletons), and if you know your core won't grow too much then this is fine. The drawback is if you ever want to switch to the more dynamic way of doing it you're going to have to refactor.

An ideal MVC is thin. As Laravel's creator Taylor Otwell put it, be careful not to box yourself in to a "pure MVC" paradigm. A web service consists of more than MVC; MVC is just a pattern, not an architecture.

Title: Static controllers


问:
How should I connect to my php framework to use methods written in the framework, in a framework agnostic environment?
My company runs 2 websites, a public facing website for clients, and an employee intranet. The intranet is used as a backend for employees to edit and maintain various parts of the public website. Both are written in PHP. The intranet is years older, and was designed using an inhouse framework. We have recently created a new public website, and because of the opportunity to "start from scratch" with it, we designed it using a PHP framework (Kohana). We knew from the beginning that there would be implementation issues with getting the intranet to interact with the public site, and vice-versa. We are now at that point.

There are a few different ways we have been able to make things work: For direct data manipulation, both use mysql, so the query builder in Kohana can manipulate the same data as the straight mysqli queries of the intranet. But beyond that, when the public site needs to use certain auditing methods written on the intranet framework, or when the intranet needs to send an automatic email written in Kohana, or use any number of other methods and functions, we have

1- Included one framework within the other, to have access to both. Problems with this are:

a. Both rely on object buffering to prepare output, and are constantly starting and ending buffers at odd times.

b. Conflicting class names being autoloaded

c. autoloaders overwriting each other

d. errors designed to be handled in one way are being handled improperly by the other framework's error handler.

e. any number of other incompatibility issues

We have gotten around these on a case by case basis, but it has been a nightmare

2- Using a remote API. We have written webservice methods on each server, and the other framework makes a cURL request of the other server. Problems with this are:

a. The added work of protecting the API and authenticating requests

b. the need to write service methods

c. The overhead of having to make http requests instead of loading files locally

3- Using a local api. Similar to the above, except the framework is included on the same server, and the api methods are written in shell scripts which output data to be read by the calling script via shell_exec.
This alleviates the need for authentication, but it seems like an ugly, hacky way of doing things

We don't want to rewrite the intranet using a proper framework. It would take an incredible amount of time that we do not have. Is there a better way to do this, or at least a more "standard" or "conventional" way of dealing with this problem? Or are we stuck hacking away at it like we currently have been?

答:
I would suggest expanding on 2. You can secure your endpoints by IP whitelisting.

There is not much overhead involved in making HTTP requests. Worry about other bottlenecks like inefficient SQL and file I/O.

Having two incompatible systems talk to one another requires an agreed upon API. This is a fundamental fact. Sandboxing one inside the other is just going to give you the runaround.


问:
User Generated Content and Hotlink Protection
I have a website that allows for users to paste content (like snippets of code, etc) for sharing.  Like Pastebin and Github, I also have a "raw" link that will display the raw contents of those posts.

However, some users are posting up code and then using our service as a host for distributing content that violates our TOS (for example, javascript code and then linking to that code from external sites).

Running on NGINX and PHP, what is the best way to manage this?

I have a feature that when reported, I can disable the raw version of a particular post.  However, it is not feasible to monitor each and every post (and then be sure that I understand what is good / what is bad).

Is my only solution to disable raw functionality across the board?  Should I block the raw versions from sites like facebook (using referrer maybe)?  I played around with hotlink protection, but in all truth, it doesn't really appear to work all that well (or it could be just my configuration of it).

答:
Output raw content in plain text and tell (modern) browsers to honor it.

```<code>header("Content-Type: text/plain");
header('X-Content-Type-Options: nosniff');
</code>```

You can also do a referrer check, but that will disable all external linking to the raw content.

Body:
Output raw content in plain text and tell (modern) browsers to honor it.

header("Content-Type: text/plain");
header('X-Content-Type-Options: nosniff');

You can also do a referrer check, but that will disable all external linking to the raw content.


答: Maybe every time you get a request for a raw version of a file with a Referer header that's not your site, log it. Then it's pretty easy to build a list of "top suspicious content in the last X hours that admins should check". You can't check every bit of content, but maybe keeping on top of that would be ok? You could even weight the chart so it's by bandwidth (requests x size), that way you know you are dealing with the most troublesome ones first.</p>

Title: User Generated Content and Hotlink Protection

Body:
I have a website that allows for users to paste content (like snippets of code, etc) for sharing.  Like Pastebin and Github, I also have a "raw" link that will display the raw contents of those posts.

However, some users are posting up code and then using our service as a host for distributing content that violates our TOS (for example, javascript code and then linking to that code from external sites).

Running on NGINX and PHP, what is the best way to manage this?

I have a feature that when reported, I can disable the raw version of a particular post.  However, it is not feasible to monitor each and every post (and then be sure that I understand what is good / what is bad).

Is my only solution to disable raw functionality across the board?  Should I block the raw versions from sites like facebook (using referrer maybe)?  I played around with hotlink protection, but in all truth, it doesn't really appear to work all that well (or it could be just my configuration of it).


问:
How big sites scale up and optimize to massive traffic?
How do sites like Facebook and Twitter optimize their sites for massive traffic. Aside from spending big bucks on getting the best servers, what can be optimized in your code to accommodate massive traffic?

I've read about caching your pages to static HTML, but that's impractical for social networking sites where the pages are constantly updated.

答:
Facebook is a particularly extreme example of load, but in general, high-traffic sites:

use a content delivery network (CDN) for distributing static assets (CSS and JavaScript) and media (images, videos, etc.).

use in-memory caches like Memcached whenever possible to reduce load on the database.

have a load balancer that distributes traffic to a pool of web servers

cache generated HTML fragments (e.g. parts of your profile page) and include them when generating a full response

ContentLicense: CC BY-SA 2.5


问:
Optimal Database design for 3-way relationship
All right, I know this sounds complicated, but all relationships are, lemme clarify. Well, I have three entities in my database which are tied to each other in a string of relationships, the app is for restaurants, and the tables are as follows:

```
<b>Customers</b>
Id
Name
Email
```

```
<b>Packages</b>
Id
Name
ImageUrl
Price
Description
Products (One package may have 1 to many products)
```

```
<b>Products</b>
Id
Name
ImageUrl
Price
Description
```

```
<b>Orders</b>
Id
CustomerId
Address
```

The one extra table mentioned is just for clarification, as customer can place an order. Here goes, now the relationships are defined as follows:

Customer can place multiple orders, One order is only associated with one customer, one-to-many(this one is for clarification)

One package can contain multiple products, one product can belong to multiple packages(consider packages as deals in a restaurant, like deals have the same items/products that the restaurant already offers), many-to-many

One order can contain multiple products, One product may have multiple orders, many-to-many

One order can contain multiple packages, One package can have multiple orders, many-to-many

The last three are the main we need to focus on, now the thing is how to design this in the database. Like for many-to-many we shall use referencing or relationship tables, like for e.g. in the case of packages and products a table could be created package_products and that is all fine coz we are ready to take that query cost to the new table in exchange for good methodology. And the same needs to be done for the orders and products table, a new table order_products catering to their many-to-many needs. Also, the same for the two entities, orders and packages, that is all fine. But now on the query side, we have to optimize this, like the solutions already exist, the one I mentioned, u may have something similar, what I want is something better.

If I want to for e.g. get the details of an order, which can have many packages and products at the same time, will have to query orders table, then the reference table for the orders and products to get single products, then will have to separately query the reference table for orders and packages to get the packages in it. Now that said, and fine at the moment, but if you have noticed by now, packages are made up of products, so basically orders are storing the info for a bunch of products some of whom were part of a deal/package and the other, well not. As we open up the packages in an order we basically wind up at the same product table, a kind of circle back motion. Questions:

Is this technique bad even ? I began to think so

How do I avoid this if it is ?

How to eventually avoid the extra query cost as well, on the order package table and so on ?

Is the technique which puts an extra package ID in order_products table bad, if not what would that ternary relationship be called and is that even permissible ?

Thank you in advance for reading and answering with the great virtue of patience.

答:
SQL has a "JOIN" syntax for doing what you want.

This is relational databases are all about. They are designed to filter ( "WHERE" ) and combine (" FULL|OUTER|INNER JOIN ") sets of data.

Any RDBMS should handle your join requirements with no problems as they are optimized for this. On no account should you do you joins in program code as this is horribly inefficient.


答:
Three points:

First, you need to use JOIN to good advantage, so as to retrieve the joined data that you want with one trip to the database, instead of repetitive trips to the database.  As James Anderson correctly pointed out, this is what relational databases are all about.

However, if you are just learning how to use a database in SQL, then using a database of your own design may take you down the wrong trail. The database needs to be designed well to exploit the full power of JOIN, and of two other relational operators, known as restrict and project in relational math.  The SQL buzzwords are WHERE, DISTINCT, and GROUP BY.

Second, the relationship between packages and products is your basic bill-of-materials case.  This case has been extensively studied in practice over the last forty years.  There's no need for you to reinvent the wheel.  However, if you add the possibility that packages can be composed of other packages, then the BOM problem becomes a recursive one.  SQL is not built for recursion, but there are workarounds.

If you come up to speed on the nested-set technique for designing containment hierarchies,  like BOM,  then you reduce what would have been a recursive query into a simple SQL query that the database server can decompose into a simple reiterative process for you.  Nested-set is not ultimately complicated, but there is a learning curve here.

Third, the relationship between order details and products or packages is not really a ternary relationship, in the way that term is usually used.  Each order detail references an order (the parent), and either a product or a package.  This either-or situation is your typical class-subclass (type-subtype) situation, rather than a true ternary relationship.   Unfortunately,  vanilla SQL is not good at inheritance.  You could use extensions to SQL peculiar to your DBMS, if it has them,  or you could use one of two techniques, called "single table inheritance"  or "class table inheritance".  I like Fowler's treatment of this subject.

There's plenty to learn here.  You sound like a smart programmer, so you should be able to learn it fast.  Just don't assume you already know it.  Maybe you do, maybe you don't.

Title: Optimal Database design for 3-way relationship

Body:
All right, I know this sounds complicated, but all relationships are, lemme clarify. Well, I have three entities in my database which are tied to each other in a string of relationships, the app is for restaurants, and the tables are as follows:

```
<b>Customers</b>
Id
Name
Email
```

```
<b>Packages</b>
Id
Name
ImageUrl
Price
Description
Products (One package may have 1 to many products)
```

```
<b>Products</b>
Id
Name
ImageUrl
Price
Description
```

```
<b>Orders</b>
Id
CustomerId
Address
```

The one extra table mentioned is just for clarification, as customer can place an order. Here goes, now the relationships are defined as follows:

Customer can place multiple orders, One order is only associated with one customer, one-to-many(this one is for clarification)

One package can contain multiple products, one product can belong to multiple packages(consider packages as deals in a restaurant, like deals have the same items/products that the restaurant already offers), many-to-many

One order can contain multiple products, One product may have multiple orders, many-to-many

One order can contain multiple packages, One package can have multiple orders, many-to-many

The last three are the main we need to focus on, now the thing is how to design this in the database. Like for many-to-many we shall use referencing or relationship tables, like for e.g. in the case of packages and products a table could be created package_products and that is all fine coz we are ready to take that query cost to the new table in exchange for good methodology. And the same needs to be done for the orders and products table, a new table order_products catering to their many-to-many needs. Also, the same for the two entities, orders and packages, that is all fine. But now on the query side, we have to optimize this, like the solutions already exist, the one I mentioned, u may have something similar, what I want is something better.

If I want to for e.g. get the details of an order, which can have many packages and products at the same time, will have to query orders table, then the reference table for the orders and products to get single products, then will have to separately query the reference table for orders and packages to get the packages in it. Now that said, and fine at the moment, but if you have noticed by now, packages are made up of products, so basically orders are storing the info for a bunch of products some of whom were part of a deal/package and the other, well not. As we open up the packages in an order we basically wind up at the same product table, a kind of circle back motion. Questions:

Is this technique bad even ? I began to think so

How do I avoid this if it is ?

How to eventually avoid the extra query cost as well, on the order package table and so on ?

Is the technique which puts an extra package ID in order_products table bad, if not what would that ternary relationship be called and is that even permissible ?

Thank you in advance for reading and answering with the great virtue of patience.


答:
Other than obfuscation are there benefits to writing something like this in real life? If so, what are the benefits?

centralization: although the implementation is a single line long, if it is a line that changes often, you probably prefer to change it in a single place, than wherever sayHello is called.

minimizing/hiding of dependencies: your client code no longer needs to know there is a window object, and you may even change the whole implementation without affecting client code at all

contract fulfillment: client code may expect a module that has a sayHello function. In this case, even if trivial, then function must be there.

consistence of abstraction levels: if client code uses high level operations, it is in your interest to write client code in terms of 'sayHello, sayBye' and some other 'sayXXX' function(s), instead of window objects. Infact, in client code you may not even want to know there is such a thing as a 'window' object.


答:
Asking for pseudocode, in my opinion, stems out of frustration that requirements are ambiguous and not clear enough.

I agree with Robert Harvey that properly written requirements would - should - nullify the need of having pseudocode at hand.

Writing pseudocode could be sort of a practical exercise for the management to make them realize how unprecise they have been.

Maybe a great exercise, but we are not in a position to teach them, and it smells of homework as punishment to me ("I will not be giving ambiguous guidelines, I will not be giving..."). Writing pseudocode enforces precision, but at the cost of imposing certain formality.

What pseudocode would that be, anyway?

Of the implementation they want you to deliver?

Or of the hypothetical unit test of this implementation?

This is a very important distinction.

This isn't really their job. They have no business in designing, or even knowing what's inside the blackbox, as long as the box does the trick. The same business logic could have very different algorithmic representations and it is up to the programmer to pick the one they like.

I agree! Now you can write your implementation any way you seem fit, as long as it passes their test. Like TDD / BDD.

So now we're in the ballpark.

Because a properly written test suite reads like a good spec.

In fact, some frameworks really blur the distinction between specs and a test. Take a look at Cucumber, for instance (mind you, I am in no way affiliated with the product).

1: Describe behaviour in plain text

2: Write a step definition in Ruby

3: Run and watch it fail (TBC)


问:
How can I test a method which aggregates data from a database?
I'm developing the web Java application and come across the following issue:

I'm using jUnit 4.5.

Suppose that I have a method which aggregates data from a database for the rendering their to a markup. Is it make a sense to testing an sql query in the way that I simple write a series of sql-queries and compare expected and real results?

答:
A unit test should test the unit you are dealing with and not other units (that's what integration, regression, load, or acceptance tests are for).

The method you are testing has the job to issue SQL queries and receive the results. Therefore, its unit test should exercise that behaviour and verify it. Whether that means using a real database, an in-memory test database or a completely fake mock database that does nothing but respond with canned results depends on which is easiest to do. The important point is that you verify "a SELECT ID FROM PUPILS WHERE... goes out, and the results are stored or returned".


答:
I would say it is a combination of the answers given by @MichaelT and @Sleiman Jneidi.

Perhaps there are a number of places in the code where you want to greet the user with a Hello message so you pack that idea in a method. In the method you can translate it or expand on a simple 'Hello' by displaying a longer text. Also you might want to use a nice JQuery dialog in place of an alert.

The point is that the implementation is in one place. You just need to change the code in one place. (SayHello() is perhaps a too simple example)


问:
What is the difference between uninitialized object variable and object variable initialized to null in Java
I have the following two object variables

```<code>Date a;
Date b=null;
</code>```

Definitely both 'a' and 'b' are not referring to any objects.

Now if I invoke following statement

```<code>System.out.println(a.toString());
</code>```

There will be a compile time error, whereas if I invoke the following statement

```<code>System.out.println(b.toString());
</code>```

There will be no compile time error but there will be a runtime error. What is the reason for this and what value will be actually stored in 'b' to represent a null value?

答:
There is no difference for class fields. They are null by default for objects, 0 for numeric values and false for booleans.

For variables declared in methods - Java requires them to be initialized. Not initializing them causes a compile time error when they are accessed.

What's the reason? Class fields can be modified by any method. In any order the method is invoked. All non-private fields may be modified by other classes and/or classes extending that class. Hence, there is no point in notifying about an uninitialized variable, since it may be assigned in many, many places.

Variables inside methods, however, are local and can be modified only inside the method itself. Hence it is both possible and rational to point possible mistakes. And the compiler tries to do it. If it knows the field is not initialized, it will show an error, because that's never what you want. If it is not sure - it will give a warning, so that you can make sure.

```<code>public static class Test {
    Date a; // ok
    Date b = null; // ok

    public void test() {
        Date c;
        Date d = null;

        System.out.println(a.toString());
        System.out.println(b.toString());
        System.out.println(c.toString()); // error
        System.out.println(d.toString()); // warning
    }
}
</code>```

Body:
There is no difference for class fields. They are null by default for objects, 0 for numeric values and false for booleans.

For variables declared in methods - Java requires them to be initialized. Not initializing them causes a compile time error when they are accessed.

What's the reason? Class fields can be modified by any method. In any order the method is invoked. All non-private fields may be modified by other classes and/or classes extending that class. Hence, there is no point in notifying about an uninitialized variable, since it may be assigned in many, many places.

Variables inside methods, however, are local and can be modified only inside the method itself. Hence it is both possible and rational to point possible mistakes. And the compiler tries to do it. If it knows the field is not initialized, it will show an error, because that's never what you want. If it is not sure - it will give a warning, so that you can make sure.

public static class Test {
    Date a; // ok
    Date b = null; // ok

    public void test() {
        Date c;
        Date d = null;

        System.out.println(a.toString());
        System.out.println(b.toString());
        System.out.println(c.toString()); // error
        System.out.println(d.toString()); // warning
    }
}


问:
Databases: Where should the application logic run?
http://highscalability.com/blog/2010/11/9/facebook-uses-non-stored-procedures-to-update-social-graphs.html talks about how Facebook moved logic out of the database into the application in order to improve ease of development (scaling better across employees instead of across databases).

Are there any studies/articles/benchmarks that evaluate the business and technical tradeoffs of running as much of the logic in the database versus in the application?

Specifically, I'm wondering what scales better (both in terms of the database performance and ease of development as the business grows):

Scenario 1 (Logic in database)

Running as much of the logic on the database end.

Using database-specific SQL extensions/features.

Using stored procedures.

Few queries over short transactions, low network overhead.

Scenario 2 (Logic in application)

Running as much of the logic on the application end.

Limiting oneself to features which are common across all major databases.

Not using stored procedures.

Many queries over long transactions, high network overhead.

What kind of people-scaling overhead can one expect in Scenario 1?

What kind of database-scaling overhead can one expect in Scenario 2?

答:
I tend to recommend / prefer:

Logging

App level for application logic ("delete user", "change password", "add customer").

For compliance / audit, apply directly to database (since this will catch any other indirect means of access, such as DBAs)

Security / Permissions

Security should be implemented within the application.

Within the DBRMS, security can be implemented a dozen different ways (SQL Admins, often Local Admins are SQL Admins (not that they should be), DB owner, DB roles, object rights)... this can easily lead to confusion ("who has rights to X?", "how does Jane Doe have permission to Y?")... avoid wherever possible. And, rights directly to the DB can be dangerous, since there are so many tools to access databases (Excel, Access, etc)... too easy for users to hit the DB directly, and do things that bypass the app's process.

Let's face it, most apps DON'T use integrated authentication (NTLM / Kerberos). WebApps require Kerberos, which is annoying and confusing to many, plus it means that permissions within the DB can cause problems to the app (if for example, the app doesn't know how to handle when a specific call fails due to the user not being in the correct group)... plus, there are too many ways to apply permissions directly to SQL, to enforce good consistency... PLUS, apps aren't going to scan the DB for such misconfigurations ("gee, user can run things because they're SA, when in fact they SHOULD be a member of this DB role").

(MSSQL) Application roles are rarely used, but SHOULD BE (looking at the devs here). Great way to enforce app permissions within SQL.

Queries

simple queries (SELECT *, SELECT by ID) can be handled by ORMs writing dynamic SQL

Complex queries tend to be written better by hand, so write a sproc and map within the ORM

INS/UPD/DEL

no specific preference.

on one hand, passing an app object to a sproc makes the INS/UPD transaction across tables easier

on the other hand, scaling out may mean that some tables are moved to other servers, so the transactions aren't contained to a single server

also, transaction locking requires tuning to ensure that locks won't become performance impediments. The alternative "NOSQL" / "eventual consistency" model is high performance, but involves more code, and more sysadmin effort (since there are usually more systems involved to track and propogate the data between the databases / cache servers).

SDL

should only run during deployment... presumably an installation / upgrade process runs the SDL code

OwnerDisplayName: Gili


答:
Thats because the state of local variables is controlled within its scope

```<code> // method/loop/if/try-catch etc...
 {
   Date d; // if it's not intialised in this scope then its not intialised  anywhere
 }
</code>```

Which  is not the case for fields

```<code>class Foo{
 Date d; // it could be intialised anywhere, so its out of control and java will set to null for you
}
</code>```

Now, why its fine to set a variable to null and use it immediately? maybe that is a historical mistake that sometimes leads to horrible mistakes

```<code> {
  Date d = null;
  try{
  }catch{ // hide it here
  }
  return d;
 }
</code>```

Now what's the semantic difference?

```<code>Date d;
</code>```

just declares variable that can hold a reference that points to an object of type Date, however

```<code>Date d= null;
</code>```

does exactly the same but the reference is pointing to null this time, null is like any reference, it takes a space of a native pointer, that is 4 byte on 32-bit machines and 8 bytes on 64-bit machines

Title: What is the difference between uninitialized object variable and object variable initialized to null in Java

Body:
I have the following two object variables

```<code>Date a;
Date b=null;
</code>```

Definitely both 'a' and 'b' are not referring to any objects.

Now if I invoke following statement

```<code>System.out.println(a.toString());
</code>```

There will be a compile time error, whereas if I invoke the following statement

```<code>System.out.println(b.toString());
</code>```

There will be no compile time error but there will be a runtime error. What is the reason for this and what value will be actually stored in 'b' to represent a null value?

Body:
Thats because the state of local variables is controlled within its scope

 // method/loop/if/try-catch etc...
 {
   Date d; // if it's not intialised in this scope then its not intialised  anywhere
 }

Which  is not the case for fields

class Foo{
 Date d; // it could be intialised anywhere, so its out of control and java will set to null for you
}

Now, why its fine to set a variable to null and use it immediately? maybe that is a historical mistake that sometimes leads to horrible mistakes

 {
  Date d = null;
  try{
  }catch{ // hide it here
  }
  return d;
 }

Now what's the semantic difference?

Date d;

just declares variable that can hold a reference that points to an object of type Date, however

Date d= null;

does exactly the same but the reference is pointing to null this time, null is like any reference, it takes a space of a native pointer, that is 4 byte on 32-bit machines and 8 bytes on 64-bit machines


问:
Do I need EventAggregator here?
I'm learning MVVM pattern with C#, WPF and .NET Framework 4.5.1.

I'm using MVVM Light framework to do it and now I have a doubt. Reading the book Windows 8 MVVM Patterns Revealed I see that the author uses Event Aggregator Pattern.

I'm not sure if I need it, because in the following ViewModel I would have to raise the event to EventAggregator and handle it on the same ViewModel.

Here is my ViewModel:

```<code>public class MainViewModel : ViewModelBase
{
    private RelayCommand doLoginCommand;

    /// <summary>
    /// The <see cref="UserName" /> property's name.
    /// </summary>
    public const string UserNamePropertyName = "UserName";

    private string _userName = null;

    /// <summary>
    /// Sets and gets the UserName property.
    /// Changes to that property's value raise the PropertyChanged event.
    /// </summary>
    public string UserName
    {
        get
        {
            return _userName;
        }

        set
        {
            if (_userName == value)
            {
                return;
            }

            RaisePropertyChanging(UserNamePropertyName);
            _userName = value;
            RaisePropertyChanged(UserNamePropertyName);
        }
    }

    /// <summary>
    /// The <see cref="UserPassword" /> property's name.
    /// </summary>
    public const string UserPasswordPropertyName = "UserPassword";

    private string _userPassword = null;

    /// <summary>
    /// Sets and gets the UserPassword property.
    /// Changes to that property's value raise the PropertyChanged event.
    /// </summary>
    public string UserPassword
    {
        get
        {
            return _userPassword;
        }

        set
        {
            if (_userPassword == value)
            {
                return;
            }

            RaisePropertyChanging(UserPasswordPropertyName);
            _userPassword = value;
            RaisePropertyChanged(UserPasswordPropertyName);
        }
    }

    public RelayCommand DoLoginCommand
    {
        get { return doLoginCommand; }
    }

    /// <summary>
    /// Initializes a new instance of the MainViewModel class.
    /// </summary>
    public MainViewModel()
    {
        ////if (IsInDesignMode)
        ////{
        ////    // Code runs in Blend --> create design time data.
        ////}
        ////else
        ////{
        ////    // Code runs "for real"
        ////}

        this.doLoginCommand = new RelayCommand(ExecuteDoLogin);
    }

    private void ExecuteDoLogin()
    {
        Debug.WriteLine(_userName);
    }
}
</code>```

And its XAML:

```<code><Window x:Class="WPFMvvmApress.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525"
        DataContext="{Binding MainViewModel, Source={StaticResource Locator}}">
    <Grid>
        <StackPanel x:Name="loginPanel" HorizontalAlignment="Center" Height="159" Margin="0" VerticalAlignment="Center" Width="349">
            <TextBox
                x:Name="userName"
                HorizontalAlignment="Left"
                Height="23"
                TextWrapping="Wrap"
                VerticalAlignment="Top"
                Width="231"
                Margin="10,10,0,5"
                Text="{Binding Path=UserName, Mode=TwoWay}"/>
            <TextBox
                x:Name="userPassword"
                HorizontalAlignment="Left"
                Height="23"
                TextWrapping="Wrap"
                VerticalAlignment="Top"
                Width="231"
                Margin="10,5,0,5"/>
            <Button
                x:Name="loginButton"
                Content="Login"
                HorizontalAlignment="Left"
                VerticalAlignment="Top"
                Width="75"
                Margin="10,5"
                Command="{Binding Path=DoLoginCommand}"/>
        </StackPanel>

    </Grid>
</Window>
</code>```

What do you think?

答:
The general idea of MVVM is to use the ViewModel to model the View so that the ViewModel data-binds to elements on the View which usually includes the Model (for more information, see my answer to this question: How do I know if I'm violating MVVM with WPF?).

The event aggregator or mediator is used to transmit events between the layers that should not be aware of each other. In your example above, data-binding to a command on the ViewModel is the preferred way to handle events that can be bound to a command.

Title: Do I need EventAggregator here?


问:
How do I design my application to use REST for itself?
I'm not sure how to ask this.  I know this is simplistic, but I understand (I think):

REST is an architecture, not required, simply a way to build

REST is a style and a community standard for transfer of data

REST uses verbs and nouns, mostly the latter, GET, POST, PUT,
DELETE...

As I read I only see the architecture from the consumers point of view and the creator of the API for the consumer.

What I cannot find is how to do this for just my application.  What if I'm not sharing anything with anyone at the moment.  I want to build my application to follow this architecture for the future.

What do I do now?  If I want to use this type of construct:

Examples:

PUT http://www.example.com/customers/12345

PUT http://www.example.com/customers/12345/orders/98765

PUT http://www.example.com/buckets/secret_stuff

I my application, when I create a new person, I use an HTML <form action="something.php" method=POST>  Now how do I do this with PUT?  Where does this go?

If I use http://www.example.com/customers/12345 how do I know within my application that I want to PUT or GET or whatever?

I'm using MVC, where's my action?  I realize the consumer might use my architecture/service with nouns, but this is for only me.  How do I know what to do, if I can't use PUT in a form tag?

Right now I use my PHP page to grab the query string based upon a RewriteRule:

```<code>require_once("database\\adapters\\PDO\\Database.bootstrap.php");
class App {
    protected $_controller = 'Welcome';
    protected $_method = 'index';
    protected $_params = [];
    protected $_model = 'Welcome';

    public function __construct(){
    $url = $this->parseURL();
    //This works because I put the rewrite rules in IIS;
    //Our RewriteRule in IIS (or Apache) is ^(.+)$  This is any character saved to a variable.
    //The new location is index.php?url=$1 [QSA, L].  This will look a little different after you import it into IIS.

    if (file_exists('app\\controllers\\' . $url[0] . '.controller.php')){
        $this->_controller = $url[0];
        $this->_model = $url[0];
        unset($url[0]);  //Unset removes that element from the array;
        //var_dump($url);
    }

    //Get the controller and model.  All done by convention over configuration;
    require_once 'app\\controllers\\' . $this->_controller . '.controller.php';
    require_once 'app\\models\\Parent.model.php';

    //get a new Database object from the bootstrap;
    $_DB = new DatabaseBootstrap();

    $this->_controller = $this->_controller . "Controller";

    $this->_model = new ParentModel($_DB->getAdapter());
    $this->_controller = new $this->_controller($this->_model);

    //This checks to see if our method from the url exists;
    //Your querystring will look like this - http://server/virtualdirectory/controller/action/variables1/variable2.....

    if(isset($url[1])){
        if(method_exists($this->_controller,$url[1])){
            $this->_method = $url[1];
            unset($url[1]);
        }
    }

    $this->_params = $url ? array_values($url) : [];

    //This calls your controller and your method and sends over your array of parameters
    call_user_func_array([$this->_controller, $this->_method],$this->_params)
}

public function parseURL(){
    if(isset($_GET['url'])){
        return $url = explode('/',filter_var(rtrim($_GET['url'],'/'),FILTER_SANITIZE_URL));
        }
    }
</code>```

EDIT:  Based upon my reading of the answers, it appears I cannot use REST natively as in using HTTP verbs.  I either have to use the name of the types in AJAX or I have to have a hidden field that contains my REST method like so (example from cakePHP):

```<code><form id="RecipeEditForm" method="post" action="/recipes/edit/5">
<input type="hidden" name="_method" value="PUT" />
</code>```

And it seems this is done for the "greater good."  That is, so that others can consume my API services using libraries such as curl or using AJAX where one can create any request method they wish (?).  Since we are using a REST architecture, the consumer using the API would simply put PUT, DELETE, etc.  Some future architecture might not use those verbs, so we make up new keywords.  It's just that PUT, etc. are in the w3 specs for HTTP, which are not very well supported.?

答: HTML forms can only be submitted by GET and POST. Many applications that use REST services don't rely on HTML forms because of these limitations, and instead submit data by AJAX where you are not limited to just two verbs. There are endless existing libraries for doing this in Javascript (jQuery, Angular $http, etc). Additionally you are not limited to form-encoded data over AJAX - for example you can send JSON or XML from your page if that's more convenient.</p>


问:
When does it make sense to compile my own language to C code first?
When designing an own programming language, when does it make sense to write a converter that takes the source code and converts it to C or C++ code so that I can use an existing compiler like gcc to end up with machine code? Are there projects that use this approach?</p>

答:
It depends on what Operating System you are using if you are using Windows there is a Microsoft IL (Intermediate Language) Which converts your code into intermediate language so that it takes no time to get compiled into machine code. Or If you are using Linux there is a separate compiler for that

Coming back to your question is when you when designing your own language you should have a separate compiler or interpreter for that because machine does not know the high level language . Your code should be compiled into machine code to make it useful for machine


问:
Is it acceptable to ask management for pseudo code?
I'm a developer in the IT department of a large oil company. I received a spec document, basically in plain English, about business rules that need to be implemented in a new application. The rules are really difficult to translate into code, since I don't know all of the inner workings of the business.

Is it acceptable to ask management (the people who gave me the spec) for the rules in more of a pseudo code fashion or would I be looked at as if I had two heads?

"Management" in this case refers to guys who were once developers, but now have more of a management role here in IT.

答:
You have received tangled requirements, with business logic not entirely clear, and contexts still very vague. The problem is, that asking for "pseudo-code" will go half-way at most, without too much love, and then even hamper you in development; by half understood or not well tought out decisions. It will probably backfire even.

Make a story-board from it, part of the code design, and try to bring concrete details to bear. Structured little scenes, stories. Communicate that you are doing just that, and after a while communicate with the people on the material.

Best in document form, with depicted screens.
Now documentation should not have much overhead, but my ideal would be a format like docbookx, that is versionable, conserves diagrams separately. But it should not take extra time and mind power, so go for docx / odt otherwise. Unzippable and then versionable.

If you then can bring structure in the whole, you have done half of the implementation. You know what's in it. You should be able to get feedback on most of the issues. Priorization for instance.

During implementation, you can give an overview of the work done.


答:
It makes sense when the time to generate full machine code outweighs the inconvenience of having an intermediate step of compiling your "IL" into machine code using a C compiler.

Typically domain-specific languages are written in this way, a very high level system is used to define or describe a process that is then compiled into an executable or dll. The time taken to produce working/good assembly is much greater than generating C, and C is quite close the assembly code for performance, so it makes good sense to generate C and re-use the skills of the C compiler writers. Note that it isn't just compiling, but optimising too - the guys who write gcc or llvm have spent a lot of time making optimised machine code, it'd be daft to try to reinvent all their hard work.

It might be more acceptbale to re-use LLVM's compiler backend which IIRC is language neutral, so you generate LLVM instructions instead of C code.

Title: When does it make sense to compile my own language to C code first?

Body: When designing an own programming language, when does it make sense to write a converter that takes the source code and converts it to C or C++ code so that I can use an existing compiler like gcc to end up with machine code? Are there projects that use this approach?</p>


答:
Tranlating to C code is a very well established habit. The original C with classes (and the early C++ implementations, then called Cfront) did that successfully. Several implementations of Lisp or Scheme are doing that, e.g. Chicken Scheme, Scheme48, Bigloo. Some people translated Prolog to C. And so did some versions of Mozart (and there have been attempts to compile Ocaml bytecode to C). J.Pitrat's artificial intelligence CAIA system is also bootstrapped and generates all its C code. Vala also translates to C, for GTK related code. Queinnec's book Lisp In Small Pieces have some chapter about translation to C.

One of the issues when translating to C is tail-recursive calls. The C standard does not guarantee that a C compiler is translating them properly (to a "jump with arguments", i.e. without eating call stack), even if in some cases, recent versions of GCC (or of Clang/LLVM) do that optimization.

Another issue is garbage collection. Several implementations just use the Boehm conservative garbage collector (which is C friendly...). If you wanted to garbage collect code (like several Lisp implementations do, e.g. SBCL) that might be a nightmare (you would like to dlclose on Posix).

Yet another issue is dealing with first-class continuations and call/cc. But clever tricks are possible (look inside Chicken Scheme). Accessing the call-stack could require a lot of tricks (but see GNU backtrace, and libbacktrace etc....). Orthogonal persistence of continuations (i.e. of stacks or threads) would be difficult in C.

Exception handling is often a matter to emit clever calls to longjmp etc...

You may want to generate (in your emitted C code) appropriate #line directives. This is boring and takes a lot of work (you'll want that to e.g. produce more easily gdb-debuggable code).

My obsolete GCC MELT lispy domain specific language (to customize or extend GCC) is translated to C (actually to poor C++ now). It has its own generational copying garbage collector. (You might be interested by Qish or Ravenbrook MPS). Actually, generational GC is easier in machine generated C code than in hand-written C code (because you'll tailor your C code generator for your write-barrier and GC machinery). The Bismon static source code analyzer (described in this DRAFT report) also generates C code.

I don't know any language implementation translating to genuine C++ code, i.e. using some "compile-time garbage collection" technique to emit C++ code using a lot of STL templates and respecting the RAII idiom. (please tell if you know one). But RefPerSys aims to generate C++ code (or C code, perhaps also machine code).

What is funny today is that (on current Linux desktops) C compilers may be fast enough to implement an interactive top level read-eval-print-loop translated to C: you'll emit C code (a few hundred lines) at every user interaction, you'll fork a compilation of it into a shared object, which you would then dlopen. (MELT is doing that all ready, and it is usually fast enough). All this might take a few tenths of a second and be acceptable by end-users.

When possible, I would recommend translating to C, not to C++, in particular because C++ compilation is slow. However, C++ has today powerful standard containers, exceptions,  λ-expressions, etc .... and is used or required by interesting C++ libraries or frameworks such as Qt, POCO, Tensorflow, and all these features is what motivates the choice of generating C++ code in a pet project of mine called RefPerSys. If generating C++ dynamically, either accept to wait more than a second for compiling every generated C++ file (e.g. into a temporary plugin, see for Linux the C++ dlopen mini howto) or use clever tricks (e.g. ccache and/or GCC pre-compiled headers, etc....) while minimizing if possible the total amount of #include-d material) to decrease the C++ compilation time.

If you are implementing your language, you might also consider (instead of emitting C code) some JIT libraries like libjit, GNU lightning, asmjit, or even LLVM or GCCJIT. If you want to translate to C, you might sometimes use tinycc: it compiles very quickly the generated C code (even in memory) to slow machine code. But in general you want to take advantage of the optimizations done by a  real C compiler like GCC

If you translate to C your language, be sure to build the entire AST of the generated C code in memory first (this also makes easier to generate first all the declarations, then all the definitions and function code). You would be able to do some optimizations/normalizations this way. Also, you could be interested in several GCC extensions (e.g. computed gotos). You'll probably want to avoid generating huge C functions - e.g. of a hundred thousands line of generated C - (you'll better split them into smaller pieces) since optimizing C compilers are very unhappy with very big C functions (in practice, and experimentally, gcc -O compilation time of large functions is proportional to the square of the function code size). So limit the size of your generated C functions to a few thousand lines each.

Notice that both Clang (thru LLVM) and GCC (thru libgccjit) C & C++ compilers offer some way to emit some internal representations suited for these compilers, but doing so might (or not) be harder than emitting C (or C++) code, and is specific to each compiler.
Also, recent GCC are extensible thru dlopen-ed plugins.

If designing a language to be translated to C, you probably want to have several tricks (or constructs) to generate a mixture of C with your language. My DSL2011 paper MELT:  a Translated Domain Specific Language
Embedded in the GCC Compiler should give you useful hints.

Generating C code might be done with GNU m4 (like GNU autoconf does). But you could also consider using GNU guile, Bigloo, SBCL, Ocaml, Python, GNU bison, GPP, etc... when coding your own C code generator.

ContentLicense: CC BY-SA 4.0


答:
How do I know what to do, if I can't use PUT in a form tag?

There seems to be some confusion between your application (the server) and one possible client of your application (the web browser talking to the server). You most certainly can use PUT on the server.

As vrostu says web browsers use HTML and HTML has not kept up well with HTTP. HTTP has had these verbs since the late 1990s but HTML has not been updated to allow easy construction of web site forms that use these verbs. I think HTML 5 is changing this, slowly.

When designing your server it is best to ignore what client will be using to communicate and just design it correctly the way you want to design it, using all the HTTP verbs. You can use other tools to communicate with it rather than HTML web forms.

When you are happy the server is working well then look to using a javascript library to hack the web page to send the correct HTTP request.

Title: How do I design my application to use REST for itself?

Body:
I'm not sure how to ask this.  I know this is simplistic, but I understand (I think):

REST is an architecture, not required, simply a way to build

REST is a style and a community standard for transfer of data

REST uses verbs and nouns, mostly the latter, GET, POST, PUT,
DELETE...

As I read I only see the architecture from the consumers point of view and the creator of the API for the consumer.

What I cannot find is how to do this for just my application.  What if I'm not sharing anything with anyone at the moment.  I want to build my application to follow this architecture for the future.

What do I do now?  If I want to use this type of construct:

Examples:

PUT http://www.example.com/customers/12345

PUT http://www.example.com/customers/12345/orders/98765

PUT http://www.example.com/buckets/secret_stuff

I my application, when I create a new person, I use an HTML <form action="something.php" method=POST>  Now how do I do this with PUT?  Where does this go?

If I use http://www.example.com/customers/12345 how do I know within my application that I want to PUT or GET or whatever?

I'm using MVC, where's my action?  I realize the consumer might use my architecture/service with nouns, but this is for only me.  How do I know what to do, if I can't use PUT in a form tag?

Right now I use my PHP page to grab the query string based upon a RewriteRule:

```<code>require_once("database\\adapters\\PDO\\Database.bootstrap.php");
class App {
    protected $_controller = 'Welcome';
    protected $_method = 'index';
    protected $_params = [];
    protected $_model = 'Welcome';

    public function __construct(){
    $url = $this->parseURL();
    //This works because I put the rewrite rules in IIS;
    //Our RewriteRule in IIS (or Apache) is ^(.+)$  This is any character saved to a variable.
    //The new location is index.php?url=$1 [QSA, L].  This will look a little different after you import it into IIS.

    if (file_exists('app\\controllers\\' . $url[0] . '.controller.php')){
        $this->_controller = $url[0];
        $this->_model = $url[0];
        unset($url[0]);  //Unset removes that element from the array;
        //var_dump($url);
    }

    //Get the controller and model.  All done by convention over configuration;
    require_once 'app\\controllers\\' . $this->_controller . '.controller.php';
    require_once 'app\\models\\Parent.model.php';

    //get a new Database object from the bootstrap;
    $_DB = new DatabaseBootstrap();

    $this->_controller = $this->_controller . "Controller";

    $this->_model = new ParentModel($_DB->getAdapter());
    $this->_controller = new $this->_controller($this->_model);

    //This checks to see if our method from the url exists;
    //Your querystring will look like this - http://server/virtualdirectory/controller/action/variables1/variable2.....

    if(isset($url[1])){
        if(method_exists($this->_controller,$url[1])){
            $this->_method = $url[1];
            unset($url[1]);
        }
    }

    $this->_params = $url ? array_values($url) : [];

    //This calls your controller and your method and sends over your array of parameters
    call_user_func_array([$this->_controller, $this->_method],$this->_params)
}

public function parseURL(){
    if(isset($_GET['url'])){
        return $url = explode('/',filter_var(rtrim($_GET['url'],'/'),FILTER_SANITIZE_URL));
        }
    }
</code>```

EDIT:  Based upon my reading of the answers, it appears I cannot use REST natively as in using HTTP verbs.  I either have to use the name of the types in AJAX or I have to have a hidden field that contains my REST method like so (example from cakePHP):

```<code><form id="RecipeEditForm" method="post" action="/recipes/edit/5">
<input type="hidden" name="_method" value="PUT" />
</code>```

And it seems this is done for the "greater good."  That is, so that others can consume my API services using libraries such as curl or using AJAX where one can create any request method they wish (?).  Since we are using a REST architecture, the consumer using the API would simply put PUT, DELETE, etc.  Some future architecture might not use those verbs, so we make up new keywords.  It's just that PUT, etc. are in the w3 specs for HTTP, which are not very well supported.?


答:
One popular php framework allows faking PUT/DELETE requests by adding a _method=PUT argument to your form action:

```<code><form method="POST" action="/customers/12345?_method=PUT">
</code>```

Internally, the framework converts the POST request to a PUT request.

http://symfony.com/doc/current/cookbook/routing/method_parameters.html#faking-the-method-with-method

Easy enough to implement.  But I would follow @vrostu's advice and look into a javascript REST framework instead of trying to use forms.

Body:
One popular php framework allows faking PUT/DELETE requests by adding a _method=PUT argument to your form action:

<form method="POST" action="/customers/12345?_method=PUT">

Internally, the framework converts the POST request to a PUT request.

http://symfony.com/doc/current/cookbook/routing/method_parameters.html#faking-the-method-with-method

Easy enough to implement.  But I would follow @vrostu's advice and look into a javascript REST framework instead of trying to use forms.


问:
Should I denote that a method satisfies an interface?
When writing a class which has ("satisfies") 1 or more interfaces, should I note somehow (e.g. in an XML comment, or with an attribute) that a particular method was added for one of the interfaces?

For example, the IComparable interface requires an int CompareTo(Object) method.

I know I don't need to do anything other than implement the appropriate methods, but for maintainability and ease of understanding are there any "best practices" for letting others know why the method exists?

答:
Put the methods that satisfy the interface into a #region.

```<code>#region IMyInterface Members

// methods that satisfy interface

#endregion
</code>```

Visual Studio even has a shortcut for creating this region and method prototypes for each method in the interface, available by right-clicking on the "inherits from" declaration in the class definition, and selecting "Implement Interface."

In other words, Microsoft sees this as a best practice.

Naturally, nothing prevents you from putting in an XML comment that says "This method satisfies the Iinterface1 and Iinterface2 interfaces."

Body:
Put the methods that satisfy the interface into a #region.

#region IMyInterface Members

// methods that satisfy interface

#endregion

Visual Studio even has a shortcut for creating this region and method prototypes for each method in the interface, available by right-clicking on the "inherits from" declaration in the class definition, and selecting "Implement Interface."

In other words, Microsoft sees this as a best practice.

Naturally, nothing prevents you from putting in an XML comment that says "This method satisfies the Iinterface1 and Iinterface2 interfaces."


问:
Should fields still be private when you need to restructure the data?
I was taught that an object should know how to do everything with itself. So I've built an application trying to keep fields private and have a lot of methods like these:

DisplayGraphically()

DisplayAsText()

WriteToFile()

Apply()

Edit() (shows a dialog box to edit it)

ErrorCheck()

Now I want to save the data to another file format whose structure doesn't closely correspond to my object structure. It would feel easy if all the data was public. Then a single method could collect all the various bits of data from the objects and reorganize it to suit the file format. But this means exposing private fields (through getters). On the other hand, that's what an API would provide and surely doing this job through an API would be quite clean.

To sum up, which is better in what cases?

Fields are private. Objects have lots of methods to deal with many different uses.

Fields have public getters and setters which maintain correct internal state. New functionality that involves many objects can be encapsulated in its own class and doesn't require any modification of the existing code.

答:
Fields are private. Objects have lots of methods to deal with many different uses.

Keep fields private (getters & setters are evil), but also reduce the specific things each object is doing by using other specialized objects.

To give an example no object should have both these methods

```<code>DisplayGraphically()
DisplayAsText()
</code>```

They should have at most a single display method. It is not the objects job to figure out where they are displaying to. Instead you should have a Display object that does the grunt work and can either be a graphic display or a console display. This class should have a clear interface that the your object expects and understand.

So instead of the two different messages above replace with

```<code>myobj.display_myself(display_to_use)
</code>```

Your object knows only how to use this Display object to display itself, most likely by simply calling the Display object with internal state of the object.

It is the display object itself knows how to display that information. You could have a thousand types of Display classes but your original object still only needs one method.

So say you are saving your objects data to a DB. Your object shouldn't care. It just has

```<code>myobj.persist_myself(persistence_to_use)
</code>```

where persistence_to_use can be an object that knows how to write to a database, or an object that knows about files, or an object that knows about back up tape disks etc.

You want to completely change the file format you use to persist your data. Great, your object doesn't care a bit. You simply create a new Persistence object that does what ever new fancy file system stuff you want and pass that object instead of your old persistence object. myobj doesn't even notice this change.

Body:
Fields are private. Objects have lots of methods to deal with many different uses.

Keep fields private (getters & setters are evil), but also reduce the specific things each object is doing by using other specialized objects.

To give an example no object should have both these methods

DisplayGraphically()
DisplayAsText()

They should have at most a single display method. It is not the objects job to figure out where they are displaying to. Instead you should have a Display object that does the grunt work and can either be a graphic display or a console display. This class should have a clear interface that the your object expects and understand.

So instead of the two different messages above replace with

myobj.display_myself(display_to_use)

Your object knows only how to use this Display object to display itself, most likely by simply calling the Display object with internal state of the object.

It is the display object itself knows how to display that information. You could have a thousand types of Display classes but your original object still only needs one method.

So say you are saving your objects data to a DB. Your object shouldn't care. It just has

myobj.persist_myself(persistence_to_use)

where persistence_to_use can be an object that knows how to write to a database, or an object that knows about files, or an object that knows about back up tape disks etc.

You want to completely change the file format you use to persist your data. Great, your object doesn't care a bit. You simply create a new Persistence object that does what ever new fancy file system stuff you want and pass that object instead of your old persistence object. myobj doesn't even notice this change.