问:
In Java, what are some good ways to separate APIs from implementation of entire projects?
Context: Imagine you're writing a plugin to a program (let's say Foobar Plugin for Eclipse) and you want it to have an API which other people - such as the creators of Barbaz Plugin for Eclipse - can call in order to provide integration. ("Whenever a foo is barred, our plugin also bazzes it automatically! ... if the foobar plugin is actually installed, that is.")

If Barbaz just uses classes from Foobar, they'll crash if Foobar isn't actually installed. For licensing or other reasons, Barbaz also wants to be able to work without Foobar. Foobar might not be free-as-in-beer, or it might just be a very large or complicated plugin which users don't want to install.

You might solve this by distributing a small "API plugin", perhaps with just interface declarations IFoobarPlugin. If Foobar is installed, Barbaz can acquire a real instance of IFoobarPlugin - otherwise, they get a null object (or at least a null pointer). Either way, the class IFoobarPlugin is still installed, so Barbaz Plugin doesn't crash with a NoClassDefFoundError.

In short, instead of this dependency graph:

```<code> Barbaz
   |
   V
 Foobar
</code>```

the developers of both plugins would prefer this:

```<code>Barbaz   Foobar
   \       /
    V     V
   FoobarAPI
</code>```

The question is: How does Barbaz get a reference to the real instance of IFoobarPlugin?

FoobarAPI directly wraps the Foobar classes.

This relies on NoClassDefFoundError being thrown in a predictable location (e.g. the first time a method is called which references the non-existent class). It's conceivable that on some platforms, you can't even load FoobarAPI

FoobarAPI cannot be compiled from source without Foobar.

Typically, the client must not call getFoobarPlugin until it detects that Foobar is actually installed.

```<code>package com.foobar.api;
import com.foobar.internal.FoobarPlugin;
public class FoobarPluginAPI {
    public static IFoo createFoo() { // may throw NoClassDefFoundError
        return FoobarPlugin.createFoo();
    }
}
</code>```

FoobarAPI gets the plugin instance via reflection.

The API can be compiled without the implementation.

It is easy to predict what happens when Foobar isn't installed.

The use of reflection may cause a performance hit, if the function is called repeatedly. (This can be avoided by returning a factory object)

```<code>package com.foobar.api;
public class FoobarPluginAPI {
    public static IFoo createFoo() {
        try {
            return (IFoobarPlugin)Class.forName("com.pluginx.internal.FoobarPlugin").getMethod("createFoo").invoke(null);
        } catch(ReflectiveOperationException e) {
            return new NullFoobarPluginImpl(); // or null, or throw an exception, etc
        }
    }
}
</code>```

Foobar registers itself in the API when it initializes.

The API is completely separate from the implementation.

There is no string-typing with reflection. The compiler can type-check everything here.

Alternative plugins ("Open Foobar") can register the same API.

If the client doesn't find an instance of Foobar, it might not know whether none is installed, or whether it is installed but hasn't been registered yet.

```<code>package com.foobar.api;
public abstract class FoobarPluginAPI {
    public abstract IFoo createFoo();

    private static FoobarPluginAPI instance;
    public static FoobarPluginAPI getInstance() {return instance;}
    public static void setInstance(FoobarPluginAPI newInstance) {
        if(instance != null)
            throw new IllegalStateException("instance already set");
        else
            instance = newInstance;
    }
}
</code>```

The same as above, but the client code needs to get the initial reference from the plugin system itself.

No special considerations needed in the API module

However, the client code is much more verbose.

```<code>// API
package com.foobar.api;
public interface FoobarPluginAPI {
    IFoo createFoo();
}

// Implementation
package com.foobar;
import org.eclipse.blahblah.Plugin;
import com.foobar.api.FoobarPluginAPI;
public class FoobarPlugin extends Plugin implements FoobarPluginAPI {
    @Override
    public IFoo createFoo() { ... }
}

// Client code uses it like this
FoobarPluginAPI foobar = (FoobarPluginAPI)EclipsePluginManager.getPluginByID("com.foobar");
if (foobar != null) {
    Foo foo = foobar.createFoo();
    // ...
}
</code>```

Don't. Make it the client's problem. The client (Barbaz Plugin) will probably end up making their own wrapper which acts like one of the above.

答:
From what I understand people often use the factory pattern for this.

They put the API interfaces into separate module (say a jar file), and then when the clients want to use the API and has access to an implementation of the API, the implementation of the API will have a factory entry point for the clients to start creating concrete objects implementing that API.

This means that your first idea from the above is the closest resemblance.


问:
Why shouldn't you develop on production database?
I need help with organizing my arguments for why it's MADNESS to develop against production data.

Backstory: I started working here six months ago and I noticed we're developing directly against production data. The codebase is local, but the database we're connected to is live data! So i have to be super careful constantly when doing update/store operations, so that I don't break anything.

We have an annual software meeting soon and I want to raise my concerns, and come loaded with arguments but I have a really hard time coming up with good solid points to something that's should be obvious as this. It's as if they would ask me to come up with arguments to why I need to breathe.

My Question: What arguments are there for NOT developing on production database directly?

答:
Even if you are super careful, everyone has sometimes a weak moment. Back in the days we also developed against a production database and at the end of a long day, I needed to change something super simple in a user-table update query, but forgot the where id = '$id' part. So all users had my data as their data. Luckily we had a recent backup, but that are mistakes you don't want to make, even when most of the time nothing goes wrong. It only needs just one mistake to take the whole DB down.

Everyone makes mistakes, even if you're super careful. The best way to develop (and test) is a copy of the DB structure filled with fake data.

OwnerDisplayName: Weblurk

ContentLicense: CC BY-SA 3.0


问:
How to handle enums in an indirection with functionpointers at ANSI-C?
Moinsen,

I am somehow stucked in a design problem. Language is ANSI-C.

Lets assume we have a tinkerbox of software-modules:

one module for the logic Logic

(at least) one module doing some logging Logger

two modules, both giving a "frame" to let the program run, lets say

one with a GUI

one for commandline

...

Therefore, the same logic could used in a comandline- and a graphic-version of the software. The Logic has to log some errors but should not know anything about the specific logger as it could be dependent on the "frame". It is obvious to give Logic a function pointer that has to be filled by the frame to bind the used Logger to the Logic.

At Logging-Module (all code Pseudo-ANSI-C):

```<code>    void Logger_Log(char *sLogText)
    {
      //do some stuff
    }
</code>```

At Logic-Module:

```<code>    void Logic_PseudoLog(char *sLogText)
    {
      printf(sLogText);
    }

    void(* Logic_Log)(char *sLogText) = &Logic_PseudoLog;

    void Logic_SetLogger(void(* LogFct)(char *sLogText))
    {
      Logic_Log = LogFct;
    }
</code>```

At GUI/Cmd-Line:

```<code>    #include "Logger.h"
    #include "Logic.h"
    Logic_SetLogger(&Logger_Log);
</code>```

Now I want to introduce different severity levels for logging and implement them as an enum in Logger:

```<code>    //Logger.h:
    typedef enum {
      DEBUG,
      INFO,
      ERROR
    } teLogLevel;

    void Logger-Log(char *sLogText, teLogLevel eLevel);
</code>```

And here the problem rises: The function-pointer at Logic needs to have the correct signature. To do so, it has to know about teLogLevel. Therefore Logic has to know about the Logger, exactly the case I wanted to avoid with the indirection in the first place.

```<code>    #include "Logger.h"
    void(* Logic_Log)(char *sLogText, teLogLevel eLevel);
</code>```

The situation as layed out is just an example. Please don't solve it by saying something like "use int instead of enum" or "build three functions for the levels". The bottemline question is:

How to handle enums in an indirection with functionpointers at ANSI-C?

How to "inject" enums into a module, that should not now about the origin of the enums?

答:
In your current design, the Logic module already has a dependency on the Logger module, but that dependency is hidden.
The dependency lies in the fact that both Logic and Logger must agree on the set of functions used for logging (one function) and their signatures (void (char*)).

The way out of here is to clearly separate the interface from the implementation. In particular, the Logger module only provides the logging interface. The implementations are either provided by the GUI/Cmd-Line modules, or by separate Logger-Implementation modules that can depend on the GUI/Cmd-Line modules.

The Logger module would only consist of a single header file, like this

```<code>/* File: Logger.h */
typedef enum {
  DEBUG,
  INFO,
  ERROR
} teLogLevel;

typedef void (*LoggerFuncT)(char *sLogText, teLogLevel eLevel);

/* Logger function that discards all logging. Can be used as a safe default. */
static void NullLogFunc(char*, teLogLevel) {}
</code>```

All other modules that either use or implement logging functionality need to refer to this header to know the correct function signatures and other types (including enums).

For example, the Logic module would use it like this:

```<code>#include "Logger.h"
LoggerFuncT Logic_Log = NullPseudoLog;

void Logic_SetLogger(LoggerFuncT LogFct)
{
  Logic_Log = LogFct;
}

void Logic_DoSomething()
{
  Logic_Log("Entering Logic_DoSomething()", DEBUG);
  //...
  Logic_Log("Leaving Logic_DoSomething()", DEBUG);
}
</code>```

In the GUI module, you could have an implementation like this:

```<code>void GUI_LogToDebugWindow(char* sText, teLogLevel eLevel)
{
    //...
}

/* Let the Logic module use this function as logger.
 * The compiler will complain here if the logger signatures don't match. */
Logic_SetLogger(GUI_LogToDebugWindow);
</code>```

Body:
In your current design, the Logic module already has a dependency on the Logger module, but that dependency is hidden.
The dependency lies in the fact that both Logic and Logger must agree on the set of functions used for logging (one function) and their signatures (void (char*)).

The way out of here is to clearly separate the interface from the implementation. In particular, the Logger module only provides the logging interface. The implementations are either provided by the GUI/Cmd-Line modules, or by separate Logger-Implementation modules that can depend on the GUI/Cmd-Line modules.

The Logger module would only consist of a single header file, like this

/* File: Logger.h */
typedef enum {
  DEBUG,
  INFO,
  ERROR
} teLogLevel;

typedef void (*LoggerFuncT)(char *sLogText, teLogLevel eLevel);

/* Logger function that discards all logging. Can be used as a safe default. */
static void NullLogFunc(char*, teLogLevel) {}

All other modules that either use or implement logging functionality need to refer to this header to know the correct function signatures and other types (including enums).

For example, the Logic module would use it like this:

#include "Logger.h"
LoggerFuncT Logic_Log = NullPseudoLog;

void Logic_SetLogger(LoggerFuncT LogFct)
{
  Logic_Log = LogFct;
}

void Logic_DoSomething()
{
  Logic_Log("Entering Logic_DoSomething()", DEBUG);
  //...
  Logic_Log("Leaving Logic_DoSomething()", DEBUG);
}

In the GUI module, you could have an implementation like this:

void GUI_LogToDebugWindow(char* sText, teLogLevel eLevel)
{
    //...
}

/* Let the Logic module use this function as logger.
 * The compiler will complain here if the logger signatures don't match. */
Logic_SetLogger(GUI_LogToDebugWindow);


答: Have you had a look at the ServiceLoader Mechanisms in Java? Basically you can specify the implementation of an interface via the manifest file in a jar. Oracle also provides some further information about plugins in Java programs.</p>

ContentLicense: CC BY-SA 4.0

Title: In Java, what are some good ways to separate APIs from implementation of entire projects?

Body:
Context: Imagine you're writing a plugin to a program (let's say Foobar Plugin for Eclipse) and you want it to have an API which other people - such as the creators of Barbaz Plugin for Eclipse - can call in order to provide integration. ("Whenever a foo is barred, our plugin also bazzes it automatically! ... if the foobar plugin is actually installed, that is.")

If Barbaz just uses classes from Foobar, they'll crash if Foobar isn't actually installed. For licensing or other reasons, Barbaz also wants to be able to work without Foobar. Foobar might not be free-as-in-beer, or it might just be a very large or complicated plugin which users don't want to install.

You might solve this by distributing a small "API plugin", perhaps with just interface declarations IFoobarPlugin. If Foobar is installed, Barbaz can acquire a real instance of IFoobarPlugin - otherwise, they get a null object (or at least a null pointer). Either way, the class IFoobarPlugin is still installed, so Barbaz Plugin doesn't crash with a NoClassDefFoundError.

In short, instead of this dependency graph:

```<code> Barbaz
   |
   V
 Foobar
</code>```

the developers of both plugins would prefer this:

```<code>Barbaz   Foobar
   \       /
    V     V
   FoobarAPI
</code>```

The question is: How does Barbaz get a reference to the real instance of IFoobarPlugin?

FoobarAPI directly wraps the Foobar classes.

This relies on NoClassDefFoundError being thrown in a predictable location (e.g. the first time a method is called which references the non-existent class). It's conceivable that on some platforms, you can't even load FoobarAPI

FoobarAPI cannot be compiled from source without Foobar.

Typically, the client must not call getFoobarPlugin until it detects that Foobar is actually installed.

```<code>package com.foobar.api;
import com.foobar.internal.FoobarPlugin;
public class FoobarPluginAPI {
    public static IFoo createFoo() { // may throw NoClassDefFoundError
        return FoobarPlugin.createFoo();
    }
}
</code>```

FoobarAPI gets the plugin instance via reflection.

The API can be compiled without the implementation.

It is easy to predict what happens when Foobar isn't installed.

The use of reflection may cause a performance hit, if the function is called repeatedly. (This can be avoided by returning a factory object)

```<code>package com.foobar.api;
public class FoobarPluginAPI {
    public static IFoo createFoo() {
        try {
            return (IFoobarPlugin)Class.forName("com.pluginx.internal.FoobarPlugin").getMethod("createFoo").invoke(null);
        } catch(ReflectiveOperationException e) {
            return new NullFoobarPluginImpl(); // or null, or throw an exception, etc
        }
    }
}
</code>```

Foobar registers itself in the API when it initializes.

The API is completely separate from the implementation.

There is no string-typing with reflection. The compiler can type-check everything here.

Alternative plugins ("Open Foobar") can register the same API.

If the client doesn't find an instance of Foobar, it might not know whether none is installed, or whether it is installed but hasn't been registered yet.

```<code>package com.foobar.api;
public abstract class FoobarPluginAPI {
    public abstract IFoo createFoo();

    private static FoobarPluginAPI instance;
    public static FoobarPluginAPI getInstance() {return instance;}
    public static void setInstance(FoobarPluginAPI newInstance) {
        if(instance != null)
            throw new IllegalStateException("instance already set");
        else
            instance = newInstance;
    }
}
</code>```

The same as above, but the client code needs to get the initial reference from the plugin system itself.

No special considerations needed in the API module

However, the client code is much more verbose.

```<code>// API
package com.foobar.api;
public interface FoobarPluginAPI {
    IFoo createFoo();
}

// Implementation
package com.foobar;
import org.eclipse.blahblah.Plugin;
import com.foobar.api.FoobarPluginAPI;
public class FoobarPlugin extends Plugin implements FoobarPluginAPI {
    @Override
    public IFoo createFoo() { ... }
}

// Client code uses it like this
FoobarPluginAPI foobar = (FoobarPluginAPI)EclipsePluginManager.getPluginByID("com.foobar");
if (foobar != null) {
    Foo foo = foobar.createFoo();
    // ...
}
</code>```

Don't. Make it the client's problem. The client (Barbaz Plugin) will probably end up making their own wrapper which acts like one of the above.


答:
There are several reasons.

The first reason is the risk, if you're working on a system with live customer's email addresses there's a risk (no matter how small) that you could end up emailing them (for example) - the same logic could be applied to texts/bank details etc. If you don't have this data there is no way you can accidentally charge a member for access to your development site.

Second (perhaps minor) is the ability to recognise which system you're on. If you have several versions of the software open (live/dev) and they run off the same data then how will you know which is which? You may accidentally end up performing actions on the real system you meant to do in dev.

The third reason is the most important. Your company has a legal duty to protect the personal information of your clients. Your live database may contain names, addresses, contact information and bank details of your members. This should be treated with the utmost security. Leaving it lying around on a developers machine (dare I say laptop!?) is not safe. What happens if your office is burgled? Are your backups all stored securely? What happens when you dispose of the machines?

Live systems are expensive not only because of their redundancy but because of their restricted access. It's much harder to break into a hosting facility than it is an office! Imagine the crushing blow to your business's reputation of an unauthorised person gained access to this information.

Your customers' personal information is some of your most sensitive information - it shouldn't be lying around on desktop machines!

Title: Why shouldn't you develop on production database?

Body:
I need help with organizing my arguments for why it's MADNESS to develop against production data.

Backstory: I started working here six months ago and I noticed we're developing directly against production data. The codebase is local, but the database we're connected to is live data! So i have to be super careful constantly when doing update/store operations, so that I don't break anything.

We have an annual software meeting soon and I want to raise my concerns, and come loaded with arguments but I have a really hard time coming up with good solid points to something that's should be obvious as this. It's as if they would ask me to come up with arguments to why I need to breathe.

My Question: What arguments are there for NOT developing on production database directly?


问:
Select design pattern - user stage
I'm struggling to point a finger into the right design pattern.

I have a web site which user can register and interact with the system.
I want to add the following abilities to a user:

Each user will be in a stage. Let's say that we have 5 stages.
when user is register, he will be in the 1-st stage.

User will be able to climb to the next stage.
To do so, he will need to complete X tasks.
(There will be 20 tasks in the system).

In each stage, the user will be able to buy benefits with the points that he gain in each task that he completed.

What's the appropriate design pattern to use here?

Thanks.

答:
"I'm trying to do X, which design pattern should I use?" is usually the wrong question to ask.

A design pattern is a proven solution to a recurring problem, but its value as a pattern lies largely in its name: once you've solved similar requirements in similar ways several times, you can more easily remember the combination of classes and relationships that did the job, and you can more easily communicate the decision to other practitioners who also know the name and the pattern.

But when you don't know what to do for a set of requirements, simply being told the name of a pattern will do almost nothing for you. You will have to follow the details of the situation, understand the pressures involved and why one decision is preferable to another in order to take away any benefit from learning the pattern. It's almost always better to attempt your own solution to understand the trade-offs involved, and then compare your code to the example code given in the pattern literature. Then, either you will have reinvented a pattern - congratulations, you've added a useful tool to your tool kit. Or you might suddenly "see the light" and understand why this other arrangement of classes and methods works better - congratulations, you've acquired a new tool and found a solution to your task. (Or you might find that your own solution actually works better. Double congratulations! You've succeeded better than others, and perhaps you can eventually extend it a new pattern of your own.)

In any case, you usually do better by writing code for your problem and then comparing it to example solutions than by choosing a design pattern and recreating it for your use case simply because it's a well-known pattern. You don't know whether or not a pattern is a good fit for your situation until you've had a go at it and understand what makes it tricky. Immediately seeing "Ah, I need to construct a Bridge for this" only works when you already know both your problem and the design pattern from experience.

So far, you haven't described anything that would require a complicated arrangement of cooperating classes at all. Users can solve tasks and advance through stages, and they can buy benefits. That doesn't sound like anything more complicated than an entity with three attributes, or maybe n:m relations for tasks and benefits. What's giving you trouble so that you think the straightforward implementation won't work?

Title: Select design pattern - user stage


答:
You can't really decide on a specific design pattern at this stage. Your description is too high level.

To be able to get to deciding on a design pattern you should first construct a doman model which shows the main entities in your system, and associated cardinalities.

From reading your description there are three main entities that jump out :

User, Task, Stage

And to a lesser extent, which may require some clarification :

Point, Benefit

Once you have a domain model (which is basically a UML class model), you can start to analyze interactions, and if you like create some sequence diagrams.

Only after this analysis can you really start to look at whether or not you need a strategy pattern, command pattern, bridge pattern etc etc...

Title: Select design pattern - user stage

Body:
I'm struggling to point a finger into the right design pattern.

I have a web site which user can register and interact with the system.
I want to add the following abilities to a user:

Each user will be in a stage. Let's say that we have 5 stages.
when user is register, he will be in the 1-st stage.

User will be able to climb to the next stage.
To do so, he will need to complete X tasks.
(There will be 20 tasks in the system).

In each stage, the user will be able to buy benefits with the points that he gain in each task that he completed.

What's the appropriate design pattern to use here?

Thanks.

OwnerDisplayName: Oliver Watkins


答:
Because as a developer you just can't work efficiently.

Does this SQL query to update all statuses for a given condition work?

You have now just updated status fields in your table.

Does this SQL query to update from version X to Y work?

You have now just modified your database. What if your status fields with allowed values 0...3 were updated to 0...5 with new values inserted? What if a field has to be removed from a table?

"Let's see if the code sees the password change"

You have now changed a password in your DB.

"From now on were going to salt all database passwords"

You have now changed ALL passwords in your DB. Oops.

"Let's delete the records for this client."
Oops, the SQL where clause was incorrect.

In all these examples it is possible to come up with counter-arguments ("Use a fictitious client to test with", "Wrap your work in transactions", "We can do that between midnight and 1 o'clock when nobody is using the database") but they all result in extra work and they are all precautions against accidents (which will fail from time to time)

The way you phrase it in your question is correct: it is MADNESS to develop against a  production database. Sooner or later your company is going to have a disaster on its hands. I bet there have already been incidents in the past that you do not know about.


答:
TL;DR: make sure you consider the advantages if you want to convince others to change their stance.

Working on production data in development has numerous downsides:

Privacy:  Leakage of unnecessary data to the developers.  However, given the devops movement this may be inevitable because they're also the sysadmins; and often people just don't care as long the number of devs is limited.

Security: connecting to the production database implies that any hacked developer machine fairly trivially can do really nasty things.  Hacks require attack targets, and a fully-loaded workstation with one of those unreliable meatbags in charge adds a lot of surface area.  It's bad enough if devs can access source control; but it takes more than a script kiddy to exploit that, and it's not always easy to hide infiltration via the code.  By contrast, if you can just access the servers, even an automated hack tool has a good chance of taking control of your server.

Reliability: Working on the live data is bad for two reasons here: Firstly, you can't experiment with data changes (outside of tricky limited scenarios) which means your code will be less well tested when the dev finishes it. Secondly, bugs can have catastrophic consequences because they can make large-scale changes to the most important bits of data you have.

These three downsides have knock-on effects.  Because it's risky, work takes more time and attention, which increases the cost of any development.  Your network may need fancier firewalling and routing because you suddenly have these "priviledged" machines you need to secure.  External assistence is a little trickier because you can't just give every temp the keys to the kingdom.

However...

The various downsides of working on live databases are fairly obvious. People at your workplace surely realize that working with production data takes care and care costs money - even if they don't focus on it.  You may clarify and highlight the dangers, and that might help you - but you're probably not telling them anything particularly new, which makes it hard to make a case.  You might want to flesh out how the downsides are realistic risks to the specific business you're doing.

However, if you really want to win this argument, you should focus at least as much on the ADVANTAGES of working with production data.  You're going to need to understand why they do this, even unstated gut feelings.  In short: my real answer is that I think you're asking the wrong question :-).

Once you understand why they do this, you can make a case why your alternative is sufficient.

I don't know your workplace, but I can take a wild stab at the dark:

Spagetti data-code: The code depends on the data. E.g. something like an accounting period may be a row in an sql table, and without a valid accounting period, (and a valid user, and a valid sales item, and a valid sales rep...) you can't add a bill, which is what you're currently developing.  If you've always had production data to play with, it may not be trivial to even run any code without a fairly realistic database because there can be complex interrelated constraints your mock data needs to satisfy.

Mock data isn't representative: When the problem domain is large and complicated, you mock data is probably not representative of real-world data in some way.  This means that code can be less well tested in scenarios that matter.  For example, you may have exceptional accounting periods that overlap due to legacy or changes in the legal framework, or just due to old now unresolvable bugs.  All those all corner cases are unlikely to be in your mock data once things get complex.

Mock data is expensive: Creating mock data can be (or seem like) an insurmountable task.  If your data model is sufficiently complex, you may need to spend a lot of time creating mock data, and once you're finished, you still need to maintain and update this mock data as code evolves.  You've just signed up for even more maintenance duty.

Conservative mindset: Changing development practices is risky.  If it works now, why change and risk making things worse?  There's probably dozen of subtle differences you haven't thought of, and any one of those could cost us business.  Stick with a proven recipe.

Learning Curve:  Even if the new way is better, it's not worth the investment (and there's always something new in IT, why not pick some other more valuable improvement to make first?)

I bet there are more reasons - but again, I don't know your team.  If you want to change their minds, you'll need to consider whatever advantages they think the status quo has, and convincingly demonstrate the new way isn't (much) worse.


问:
Why is a private member accessible in a static method?
The following is pseudo code, I tried it in Java and PHP and both worked:

```<code>class Test {

    private int a = 5;

    public static function do_test(){
        var t = new Test();
        t.a = 1;
        print t.a // 1
    }

}

Test::do_test();
</code>```

Why can you do this in OOP paradigm and what's the use of it?

答:
In Java, private variables are visible to the whole class. They can be accessed from static methods and from other instances of the same class.

This is, for example, useful in factory methods. A factory method usually does initializations to an object which are so complex that you do not want to leave them to the application code. In order to do the initialization, the factory method often needs access to the class-internals you don't want to expose. Being able to access the private variables directly makes your life much easier.

However, when you would like to hide the implementation details of a class even from static methods or from other instances of that class, you could follow the private class data pattern. Put all private variables of a class into a private inner class and delegate any getters or setters to getters and setters of that inner class.

Another option is to define an interface for the class which declares all the public methods of the class and then only reference the class under that interface whereever possible. A reference to the interface-type can not be used to directly access anything not declared in the interface, no matter where (except with reflection, of course). When your use an object-oriented programming language which has no interfaces (like C++, for example), they can be simulated with an abstract base-class which is inherited by the actual class.

```<code>interface ITest {
     public int getA();
}

class Test implements ITest {

    private int a = 5;

    public int getA() { return a; } // implementation of method declared in interface

    public static void main(){
        ITest t = new Test();
        t.a = 1; // syntax error: Interface ITest has no "a"
        System.out.println(t.getA()); // calls Test.getA, visible because ITest declares it
    }

}
</code>```

Body:
In Java, private variables are visible to the whole class. They can be accessed from static methods and from other instances of the same class.

This is, for example, useful in factory methods. A factory method usually does initializations to an object which are so complex that you do not want to leave them to the application code. In order to do the initialization, the factory method often needs access to the class-internals you don't want to expose. Being able to access the private variables directly makes your life much easier.

However, when you would like to hide the implementation details of a class even from static methods or from other instances of that class, you could follow the private class data pattern. Put all private variables of a class into a private inner class and delegate any getters or setters to getters and setters of that inner class.

Another option is to define an interface for the class which declares all the public methods of the class and then only reference the class under that interface whereever possible. A reference to the interface-type can not be used to directly access anything not declared in the interface, no matter where (except with reflection, of course). When your use an object-oriented programming language which has no interfaces (like C++, for example), they can be simulated with an abstract base-class which is inherited by the actual class.

interface ITest {
     public int getA();
}

class Test implements ITest {

    private int a = 5;

    public int getA() { return a; } // implementation of method declared in interface

    public static void main(){
        ITest t = new Test();
        t.a = 1; // syntax error: Interface ITest has no "a"
        System.out.println(t.getA()); // calls Test.getA, visible because ITest declares it
    }

}


答:
People make mistakes.  It only takes one little mistake, and you've trashed the company database.  That's especially true if your application modifies the database, rather than just querying it.

You need to test corner cases.  If it's a customer database, can you handle customers with no middle names, customers with accented characters or punctuation marks in their names, customers with no phone number, customers with overseas addresses, and so on?  The only way to test this is to add such customers to the database.  But what then happens when the marketing department decide to send a mailshot to all the company's existing customers?


问:
What does "(int) value & 0x1, (int) value & 0x2, (int) value & 0x4, (int) value & 0x8" mean?"

The "value" ranges from 0 to 15 (its possible values). When will those 4 "if" conditions be met? If my (int)value = 2 does this mean 0010?

```<code>            if  ((int)value & 0x1)
            {
                //statement here
            }
            if  ((int)value & 0x2)
            {
                //statement here
            }
            if  ((int)value & 0x4)
            {
                //statement here
            }
            if  ((int)value & 0x8)
            {
                //statement here
            }
</code>```

答:
Each number can be expressed as value = b0*2^0 + b1*2^1 + b2*2^2 + b3*2^3 + ... with each b being either 0 or 1 (these are the bits of the representation). This is the binary representation.

The binary AND (&) takes each of those b pair wise and performing AND on them. This has the following outputs:

```<code>0 & 0 = 0
0 & 1 = 0
1 & 0 = 0
1 & 1 = 1
</code>```

Using powers of 2 (which have only a single bit on) we can isolate and test the individual bits:

value & 1 is true when value is odd {1, 3, 5, 7, 9, 11, 13, 15}.

value & 2 is true when value/2 is odd {2, 3, 6, 7, 10, 11, 14 ,15}.

value & 4 is true when value/4 is odd {4, 5, 6, 7, 12, 13, 14 ,15}.

value & 8 is true when value/8 is odd {8, 9, 10, 11, 12, 13, 14 ,15}.

The 0x prefex on the numbers means it should be interpreted as a hexadecimal number. It is a bit superfluous when you only go up to 0x8 but tells maintainers it is probably used as a bitmask.

OwnerDisplayName: patr

Body:
Each number can be expressed as value = b0*2^0 + b1*2^1 + b2*2^2 + b3*2^3 + ... with each b being either 0 or 1 (these are the bits of the representation). This is the binary representation.

The binary AND (&) takes each of those b pair wise and performing AND on them. This has the following outputs:

0 & 0 = 0
0 & 1 = 0
1 & 0 = 0
1 & 1 = 1

Using powers of 2 (which have only a single bit on) we can isolate and test the individual bits:

value & 1 is true when value is odd {1, 3, 5, 7, 9, 11, 13, 15}.

value & 2 is true when value/2 is odd {2, 3, 6, 7, 10, 11, 14 ,15}.

value & 4 is true when value/4 is odd {4, 5, 6, 7, 12, 13, 14 ,15}.

value & 8 is true when value/8 is odd {8, 9, 10, 11, 12, 13, 14 ,15}.

The 0x prefex on the numbers means it should be interpreted as a hexadecimal number. It is a bit superfluous when you only go up to 0x8 but tells maintainers it is probably used as a bitmask.


答:
Is the live system supposed to be highly available? In your situation availability can easily be compromised by a bug during development or a human error.

Were there problems in the past? Precedence is often an easy way to convince people.

Is the company legally obliged to protect this data? Developers can export all data and sell it or send it to the competition.

I think developer productivity arguments are not likely to get you far here. Obviously, nobody thinks this is a problem for developers. I'd rather argue with business goals like HA and legal obligations. These are terms that management can understand.


问:
How to convince co-workers the merits of local development enviroments
I'm trying to convince my co-workers about the merits of developing on local environments, but so far have had little luck in my quest. Outside of myself, the other developers with my company develop on seperate folders on the same server as our development server, using the same DB/DB Server/Web Server for all folders, with your standard text editor on the local machines. I've mentioned the benefits of any mistakes (like say the stray while loop misconfiguration) localized to one machine, network or server issues having no relevance or effect on work, and able to use xdebug (although you can use it on a shared server, the issues with sessions I've been told are problematic...and not having a fulltime sys admin to keep things happy doesn't hurt either). So far, no dice.

So I ask you the SO community what could be done to convince others to do so, or if I'm the one that is on the wrong path. The current environment that we have is your typical WAMP environments, but I wanted to keep the question language and environment agnostic as possible.

Thanks in advance!

答:
Typically the reason you have an entirely separate system is so you can alter shared libraries.

On your common development environment, you will almost certainly have something that is common to everybody, a system service or a version of some component (eg a database) that cannot be changed. So when you want to make changes to that shared component,everyone else is impacted until you're done, and even then - you simply cannot revert to an older version of the codebase without reverting (ie re-installing) the shared component.

On your own dev box though, you can do what you like without interrupting the guy doing bugfixes on the old code, or the guy just updating a feature that uses the existing system.

For example, at an old place we had a few PHP devs who coded on a shared linux box that was 'controlled' by a sysadmin guy. All was good if they only updated application code (which they could do in their home directory), but there were some shared services that could not be updated... and so never were, ever. When it eventually came time to update the OS, one dev had a new box built for him and everything migrated so he could make whatever changes were required - notice that this is effectively a box for himself, a situation that wouldn't have been as disruptive as it was had he been running locally anyway.


问:
Should I be using a composite key for this table?
My database is going to store words, so the Word table is the most important. The Rhyme table lists which words a particular word perfectly rhymes with. It consists of three fields:

```<code>RhymeID - primary key.
WordID - foreign key linking to Word table
Rhyme - a non key integer which refers to a different record in the Word table.
</code>```

E.g. 'cat' has WordID 009, 'bat' has WordID 014 and 'fat' has WordID 035, two records in the Rhyme table might look like this

```<code>RhymeId - WordId - Rhyme
001 - 009 (cat) - 014 (bat)
002 - 009 (cat) - 035 (fat)
</code>```

The question is, should I make WordId a primary key to form a composite key with RhymeId? Do I need it to uniquely identify each record? I have no practical experience with databases, this one is still in the planning stage.

答:
Two concepts from the DB design world apply here.  They are "natural keys" and "surrogate keys".  A natural key is that combination of columns, the values of which can be used to distinguish the row which contains them from all other rows in the table i.e. that combination of values is unique in the table.  Importantly these columns appear "naturally" in the user's understanding of the problem.  A surrogate key is a value invented to stand in for the natural key, usually for technical or performance reasons.  Once you create a surrogate key it is normal practice to use that as the foreign key in all other tables.

In your example "cat" wold be the natural key of the Word table and "009" is the surrogate key for that natural key.

So, for your Rhyme table the natural key would be WordID and Rhyme (yes, even though they are both themselves surrogate keys from another table) and RhymeID is the surrogate key.

If other tables will have a foreign key pointing back to Rhyme then I would definietly suggest giving it a surrogate key.  If it won't then the surrogate is 50% bloat for zero value in what is likely to be an exceedingly large table; I would suggest omitting it.


问:
How to transfer code responsibility to another developer
I'm in a situation at work where I have to transfer responsibility of a large code base that I inherited, re-factored and enhanced to another developer. This is the first time that I have to do such a thing and although I always thought it would be trivial the actual steps I have to follow seem vague.

The code base I maintain is a module that includes a lot of stuff such as

A persistence layer

A service layer

A presentation layer which sadly has a lots of business code in it

An interface for module interaction

I also have very good knowledge of the business assumptions made when it was developed as well as its technical foundation.

I know that I can go with my mind's flow and give it my best but I prefer to do it in the most professional manner I can. So, I would like to ask you for advice on how I should approach this situation. Are there any standard procedures and good practices that I could follow?

答:
Transferring responsibility for a code base is not that different from getting another developer assigned to your team, working together for some time and then leaving the team yourself. The biggest difference would be in the time that you work together, which is likely to be very short to non-existent when talking about a transfer.

When preparing the code base (and everything around it) for the transfer, picture in your mind how you would like to find the project if you come fresh to it and try to put the project in that state. That typically means:

The design is documented, if possible with reasons why the design is as it is and why the alternatives don't work

The business assumptions are documented

If there are any project accounts, their login details are available

Depending on the reasons for the code transfer, it might be expected or create goodwill to be available after the transfer to answer questions from the new guy.


问:
Webcam software for both Windows and Linux – possible?
my visually impaired sister uses a webcam with DIY stand as a digital magnifier to read printed texts.

We wanted to initiate a project to create a software - in fact only a modified webcam viewer (like Cheese in Linux). Is it possible to have one SW for both platforms (Windows and Linux) = almost the same code, same filters and GUI, and just use the video stream using some standard protocol? Because most people use Win, but we would like to support Linux primarily.

I am not sure if this is possible in windows. We need the software to take the video stream and apply some color and other effects like those described in this article.

The idea is to maintain only one application (best would be open-source) with a small differences for both platforms. For the GUI, the GTK seems to be optimal as it is accessible for ScreenReader SW. Such app would not only help the visually impaired but also the elderly people.

So, is this possible or is this idea really stupid?

thanks :-D

答:
While I realise that this answer is a bit late, my suggestion would be QT. QT is a C++ library that allows for cross-platform development and runs well on Windows, Mac, Linux and Android. This would allow for the same code to be used for the GUI and the webcam access on all the platforms you require.

The webcam access API, for example, is documented here:

http://qt-project.org/doc/qt-5/cameraoverview.html


答:
These if-statements check if a specific bit of value is set.

The hexadecimal value 0x4, for example, has the 3rd bit from the right set to 1 and all other bits set to 0. When you use the binary-and operator (&) with two operants, the result will have all bits set to 0 except for those bits which are 1 in both operants.

So when you do the calculation value & 0x4, you either get binary 00000000 or binary 00000100, depending on whether or not the 3rd bit of value is 1 or 0. The first evaluates to false, and the second to true, so the if-block is only executed for values where the 3rd bit is set.

Title: What does "(int) value & 0x1, (int) value & 0x2, (int) value & 0x4, (int) value & 0x8" mean?"

Body:
The "value" ranges from 0 to 15 (its possible values). When will those 4 "if" conditions be met? If my (int)value = 2 does this mean 0010?

```<code>            if  ((int)value & 0x1)
            {
                //statement here
            }
            if  ((int)value & 0x2)
            {
                //statement here
            }
            if  ((int)value & 0x4)
            {
                //statement here
            }
            if  ((int)value & 0x8)
            {
                //statement here
            }
</code>```


问:
Why is the finalize method included in Java?
According to this post, we should never rely on the finalize method to be called. So why did Java include it in the programming language at all?

It seems like a terrible decision to include in any programming language a function that might get called.

答:
The Java Language Specification (Java SE 7) states:

Finalizers provide a chance to free up resources that cannot be freed automatically by an automatic storage manager. In such situations, simply reclaiming the memory used by an object would not guarantee that the resources it held would be reclaimed.


问:
Entirely separate business logic layer from MVC
We are currently refactoring our controller methods in ASP.NET MVC application.

At the beginning we've separated data access layer (our goal was to remove LINQ from controllers entirely). Now we are thinking about another step - how to create a business logic layer to reduce number of lines and logic in controller. Currently we have something like this:

```<code>public ActionResult CustomerProjects(some parameters)
{
    var collectionOfSomeType = this.CustomerRepository.GetSomeData();
    var anothercollection = this.ProjectsRepository.GetAnotherData(collectionOfSomeType);

    var viewModel = CreateSomeViewModel(anotherCollection);

    return View("Index", viewModel);
}
</code>```

Of course it's just an example with four lines of code. We have some methods which are bigger (but still IMO not so bad). We injected our helper classes through IoC container, more complex logic sits there. But now we'd like to remove even that parts.

Is it worth our time to create another layer which would be our 'last gate' before controllers? The final result would be:

```<code>public ActionResult CustomerProjects(some parameters)
{
    var viewModel = someSource.PrepareCustomerProjectsViewModel(params);

    return View("Index", viewModel);
}
</code>```

What do you think?

答:
For me there is no question to be answered here, you should always strive to separate out your components as much as possible.

At a bare minimum, for every new project I create I do the exact following steps:

1) Create a blank visual studio solution

2) Add an MVC project to it

3) Add a class library to it called the Business layer

4) Add a class library to it called the Data layer

By doing this your following the good principles of n-Tier design.  Add into this some form of AOP (For example post-sharp or MVC Attributes) to handle any elements that are cross-cutting the layers, and you have a good solid architecture to work from.

NO RAW Data from your data layer should ever make it into your presentation layer (The MVC App) everything should be combined and flattened in your business layer.

The business layer should only ever handle DTO objects between itself and presentation, with raw data that it brings in from the data layer and then applies various rules too that are specific to your application domain.

With EF code first, and Nu-get packages such as auto-mapper, all of this is incredibly easy these days.

Use EF in your DAL to get your data using Linq, ADO or whatever you need.

Use auto-mapper to transform that data into DTO's to be passed to the business layer, then do any work you need before finally using auto-mapper to pass the resulting DTO up to your presentation.

Even if your NOT using MVC, adopting this strategy is win/win , even for WPF, Webforms, Winforms and much more.

If you do it correctly then the MVC portion essentially becomes a brain dead display of what the business layer is doing, and the ease with which you can remove your MVC app and put another UI on in it's place is frighteningly simple.

Update 14/11/2014

After reading the most recent comment added to this thread, I felt that adding this additional part to my answer was well warranted.

Good Architecture is about much more than just "Pretty Code".

If you get your architecture wrong it can be the difference between crashing and burning and flying high in a blaze of glory.

I've been doing I.T & Software development in one form or another now since about 1979, and believe me I've seen my fair share of failures and successes in that time.

When I first started, and I was still wet behind the ears, Object Oriented Programming wasn't even a thing, you lumped EVERYTHING into one source file, then you ran it through a compiler, then a linker with no kind of GUI stuff to help you.

Some of the code I wrote during these times, was incredibly messy, inefficient and completely horrible. As I grew, and learned however, I began to understand why this kind of code caused the problems it did, and while writing nice easy to read code is certainly an important skill, it's also very important to make sure that your surface area is also minimal and follows good standards.

I've seen so many great projects fail (or at the very least struggle greatly) over the years, and each time it's been because of bad choices made at the architecture design level, I can't stress just how important it is to get the design and the plans right before you even touch a single line of code.

And while I'm on the subject, code generators are just as dangerous.  If your code generator creates code from templates that YOU control, then great guns, but IF you depend on templates, where you have no control over how the output is generated, then your asking for trouble.  Visual Studio is a great tool, and amazing for creating fast solutions, but please make sure you know EXACTLY what it's creating behind the scenes when you click that button to do something.

If I get a library to develop against, the last thing I want to do, is to have to delve into the sources to tell me how it works, I depend on the architect who designed it, to guide me, by making logical choices, that are formed from a knowledge of great solid software craftsmanship practices.

I simply wouldn't trust anything that passed strings and discreet values around as though they where candy at a Christmas party, because... well how can I be sure what the type and responsibility of the variable/property/method actually is.

Who would you trust more to buy a house off?  A professional company who hired an Architect to survey, plan and design a complete set of plans, which a professional team of Builders, Roofers, Plasterers etc then worked as a team to implement, or the guy that lives at the end of your street who works in the building trade and knows a thing or two about building houses?

I know which my choice would be.


答:
The answer to your question depends on the definition of "good" in the question "what are some good ways to separate APIs from implementation of ..."

If "good" means "pragmatic easy to implement for you as manufecturer of the api" this might be helpful:

since you are using java where jar-libraries are loaded at runtime i would suggest a slightly different alternative:

The API consists only of interfaces plus a dummy implementation of these interfaces that has no real function.

the customer using your api can compile against this dummy-jar and at runtime you can replace the dummy-jar with the licensed one.

something similar is done with slf4j where the actual logging-implementation to be used with your application will be chosen by replacing the logging-jar


答:
My preferred responsibility by object:

Controller handles the building of the viewmodel/viewbag.

Logic unrelated to the rendering of the page gets shipped off to the BL.

Thus personally I would compose the viewmodel within the controller, and not create a separate layer. The layer that you would create to compose the viewmodel, what would you call it? The Controller layer?

Title: Entirely separate business logic layer from MVC

Body:
We are currently refactoring our controller methods in ASP.NET MVC application.

At the beginning we've separated data access layer (our goal was to remove LINQ from controllers entirely). Now we are thinking about another step - how to create a business logic layer to reduce number of lines and logic in controller. Currently we have something like this:

```<code>public ActionResult CustomerProjects(some parameters)
{
    var collectionOfSomeType = this.CustomerRepository.GetSomeData();
    var anothercollection = this.ProjectsRepository.GetAnotherData(collectionOfSomeType);

    var viewModel = CreateSomeViewModel(anotherCollection);

    return View("Index", viewModel);
}
</code>```

Of course it's just an example with four lines of code. We have some methods which are bigger (but still IMO not so bad). We injected our helper classes through IoC container, more complex logic sits there. But now we'd like to remove even that parts.

Is it worth our time to create another layer which would be our 'last gate' before controllers? The final result would be:

```<code>public ActionResult CustomerProjects(some parameters)
{
    var viewModel = someSource.PrepareCustomerProjectsViewModel(params);

    return View("Index", viewModel);
}
</code>```

What do you think?


答:
There are two interesting things to note here.

First, this is a common pattern for checking each of the low-order 4 bits of an integral value. The if condition is met if the corresponding bit is set. For the value 2 the bit pattern is indeed 0010.

The other more interesting question is why the (int) cast? Apart from the bad style of using C-casts in C++, no integer or character values require this cast. A bool makes no sense, a double/float would be converted to an integer temporary and it would be unusual to use literal values to test an enum. It might make sense with a pointer, but that would be a very specialised use. Conclusion: the cast makes no sense.


问:
In-memory datastore in Haskell
I want to implement an in-memory datastore for a web service in Haskell. I want to run transactions in the STM monad.

When I google hash table steam Haskell I only get this: Data. BTree. HashTable. STM. The module name and complexities suggest that this is implemented as a tree. I would think that an array should be more efficient for mutable hash tables.

Is there a reason to avoid using an array for an STM hashtable?
Do I gain anything with this steam hash table or should I just use a steam ref to an IntMap?

答:
The implementation you reference is part of a package for implementing a concurrent B-Tree. The HashTable itself is implemented as an array of TVars of Data.Map objects.

The quoted complexity values are worst-case. Remember that hashtables are usually O(N) worst case for lookup, insertion, and deletion. Using Map for the buckets brings it down to O(log(N)).

Title: In-memory datastore in Haskell


问:
Managing database schema for a C++ app
I have an open source project (Cockatrice) that uses mysql for the server component. I'm planning some changes to the schema, but right now the only management I have is a script that runs the proper CREATE TABLE statements.

Before I start rolling out changes I'd like to get a schema management solution in place. The app is written in C++ with Qt, and I haven't been able to find anything like rails migrations or play evolutions for C++. I could just use those, but it would introduce a completely unrelated dependency that I'm reluctant to use for this.

I've come up with an approach and I'd like some feedback on whether it makes sense or has any drawbacks.

Add a new table to manage the schema, with a version column.

New migrations would get added with a version up, down, and full creation script (eg 2.up.sql, 2.down.sql, and 2.full.sql). The up script would contain the sql to perform the upgrade, the down script would reverse it, and the full would create a database from scratch at that version.

I was thinking I'd write a script runnable by the administrator that would do something like the following:

Read current version from db

scan for new patches

lock whole db

snapshot db minus volatile tables

start transaction

apply each sql file in order to bring it to the latest version

create a scratch db and apply the full create sql

compare updated schema against the scratch db

if schema doesn't match, error out and abort transaction

if it matches, drop the scratch schema

unlock

答:
y primary thought on DB management is not to bundle it into the application, but to bundle it into the installer. Admittedly all the project I work on have an ops team (of some sort or other) to do the install so maybe I'm a little blinkered here.

Nevertheless the steps are sensible. I tend to create an upgrade script for each version upgrade rather than many small upgrade steps, but Rails seems to do well with a numbered set of upgrade scripts for each feature.

Given the sql is self-contained, I still think an app to run it is unnecessary - a batch file will happily open the DB and run the sql in. We do this in SQLServer command line tools all the time, MySQL runs on the command line, using the source command to run a sql file directly.

Title: Managing database schema for a C++ app


答: Finalizers exist because they were expected to be an effective means of ensuring that things get cleaned up (even though in practice they aren't), and because when they were invented, better means of ensuring cleanup (such as phantom references and try-with-resources) didn't exist yet.  In hindsight, Java would likely be better if the effort spent on implementing its "finalize" facility had been spent on other means of cleanup, but that was hardly clear during the time Java was initially being developed.</p>

Title: Why is the finalize method included in Java?

Body:
According to this post, we should never rely on the finalize method to be called. So why did Java include it in the programming language at all?

It seems like a terrible decision to include in any programming language a function that might get called.


问:
Testing of personal projects
I'm developing a web based personal project that will hopefully be used by thousands.  Obviously prior to releasing it in the wild as Beta I was wondering,  are there any communities out there that will test my web app and provide feedback?  Free would be great, but I'm open to suggestions.</p>

答:
People here perhaps? And users at other stackexchange sites.

Maybe also people from a non-technical background, if, as you say potentially 1000s of users, some of those are likely to be non-technical and will have different issues regarding usability.

Friends? Family?

You might want to think of some incentives to motivate people to test your site: rewards, founder membership etc.

And also a criteria to test against.

Maybe you're already aware of the established user-acceptance testing discipline so forgive me if I've told you what you might already know so I won't say too much, except to say there are books, discussions and evangelists on the subject. O'Reilly - oreilly.com the book publish would be a good place to look for more ideas.

Edit:

Check out this book: "Effective UI: The Art of Building Great User Experience in Software"
http://oreilly.com/catalog/9780596154783/

ContentLicense: CC BY-SA 2.5

Title: Testing of personal projects


问:
File exists vs. File does not exist. Is there a difference in performance?
Let's say I am checking a directory for the existence of a file, and then depending on whether or not the file exists, I act accordingly. For example, see the two Python snippets below.

```<code>if os.path.isfile(file_name):
    # do task A
else:
    # do task B
</code>```

or

```<code>if not os.path.isfile(file_name):
    # do task B
else:
    # do task A
</code>```

Is there a difference between the two or is it just semantics? While the example I gave uses Python, would the rules apply the same to other languages?

答:
It is considered to be best practice to arrange the condition such that it is most probable to be entering your if clause.  The <50% condition should be your else clause.  In this instance,  it depends on what you're expecting.  If you expect to find the file, then you should use if os.path.isfile(file_name):.

This reason stems back to optimization of branching, though nowadays the difference is so subtle that unless performance were very important, you wouldn't do it to optimize but rather to provide a convention to the programmer that this is the expected behavior.

Another reason you may want to switch the if and else clauses is if you're being forced to awkwardly word your condition.  An example of this is if you already have isNotOpen, and you want to check the more probable condition that isNotOpen is false, then it would be ugly to write if not isNotOpen:.  One solution could be to switch the if and the else clause and just write if isNotOpen:, though I think in such circumstances, it would be better still to name variables according to the condition you expect to be true.  In other words, you wouldn't have a variable named isNotOpen, but rather isOpen.  When you hit the if statement, your most probable condition is not the negated variable but the variable itself, so if isOpen: which both ensures that it is readable and that the most probable condition is in the if clause.

In this respect, there are those that would not add "not" in the name at all, though I don't have a problem with this so long as it is a condition you're expecting (and hence you won't ever have to test the negation of that condition).

I think that other than this, there is no reason why you should do one over the other, however I would expect (expect in this context being a loose term) the more probable condition to be in the if clause in any language, not only in Python.  But that's just my 10 cents.


答:
You might consider creating the tables as part of the installation.

Alternatively, your C++ program could issue CREATE TABLE IF NOT EXISTS Mysql statements. Then it would work when the tables exist (usual case) or when they don't exist.

And you could query the existence and the columns of older tables with e.g. SHOW TABLES & SHOW COLUMNS and/or SHOW CREATE TABLE -or use the Information Schema (then later ALTER TABLE if needed)

Title: Managing database schema for a C++ app

Body:
I have an open source project (Cockatrice) that uses mysql for the server component. I'm planning some changes to the schema, but right now the only management I have is a script that runs the proper CREATE TABLE statements.

Before I start rolling out changes I'd like to get a schema management solution in place. The app is written in C++ with Qt, and I haven't been able to find anything like rails migrations or play evolutions for C++. I could just use those, but it would introduce a completely unrelated dependency that I'm reluctant to use for this.

I've come up with an approach and I'd like some feedback on whether it makes sense or has any drawbacks.

Add a new table to manage the schema, with a version column.

New migrations would get added with a version up, down, and full creation script (eg 2.up.sql, 2.down.sql, and 2.full.sql). The up script would contain the sql to perform the upgrade, the down script would reverse it, and the full would create a database from scratch at that version.

I was thinking I'd write a script runnable by the administrator that would do something like the following:

Read current version from db

scan for new patches

lock whole db

snapshot db minus volatile tables

start transaction

apply each sql file in order to bring it to the latest version

create a scratch db and apply the full create sql

compare updated schema against the scratch db

if schema doesn't match, error out and abort transaction

if it matches, drop the scratch schema

unlock


答:
There is 0 difference. However, there are some guidelines about what you put in the if and what - in the else.

One is that you should try to put a "positive" result in the if. Many languages have shorter negation than " not " (Java has "!" that shouldn't have whitespace around it), and it's easy to overlook them, especially if you're looking at a verbose method name right next to it.

Another is that you should put the expected result first, and unexpected later.

A third one I can remember off the top of my head is that if one of the branches allow you to terminate early - put that first and the rest of the code outside an if whatsoever. (I seem to recall there also being one that is the direct opposite of this...)

TL;DR:

No difference to compiler. Only convention and readability.

Title: File exists vs. File does not exist. Is there a difference in performance?

Body:
Let's say I am checking a directory for the existence of a file, and then depending on whether or not the file exists, I act accordingly. For example, see the two Python snippets below.

```<code>if os.path.isfile(file_name):
    # do task A
else:
    # do task B
</code>```

or

```<code>if not os.path.isfile(file_name):
    # do task B
else:
    # do task A
</code>```

Is there a difference between the two or is it just semantics? While the example I gave uses Python, would the rules apply the same to other languages?


问:
Relation between objects
For a few weeks I’ve been thinking about relation between objects – not especially OOP’s objects. For instance in C++, we’re used to representing that by layering pointers or container of pointers in the structure that needs an access to the other object. If an object A needs to have an access to B, it’s not uncommon to find a B *pB in A.

But I’m not a C++ programmer anymore, I write programs using functional languages, and more especially in Haskell, which is a pure functional language. It’s possible to use pointers, references or that kind of stuff, but I feel strange with that, like “doing it the non-Haskell way”.

Then I thought a bit deeper about all that relation stuff and came to the point:

“Why do we even represent such relation by layering?

I read some folks already thought about that (here). In my point of view, representing relations through explicit graphes is way better since it enables us to focus on the core of our type, and express relations later through combinators (a bit like SQL does).

By core I mean that when we define A, we expect to define what A is made of, not what it depends on. For instance, in a video game, if we have a type Character, it’s legit to talk about Trait, Skill or that kind of stuff, but is it if we talk about Weapon or Items? I’m not so sure anymore. Then:

```<code>data Character = {
    chSkills :: [Skill]
  , chTraits :: [Traits]
  , chName   :: String
  , chWeapon :: IORef Weapon -- or STRef, or whatever
  , chItems  :: IORef [Item] -- ditto
  }
</code>```

sounds really wrong in term of design to me. I’d rather prefer something like:

```<code>data Character = {
    chSkills :: [Skill]
  , chTraits :: [Traits]
  , chName   :: String
  }

-- link our character to a Weapon using a Graph Character Weapon
-- link our character to Items using a Graph Character [Item] or that kind of stuff
</code>```

Furthermore, when a day comes to add new features, we can just create new types, new graphs and link. In the first design, we’d have to break the Character type, or use some kind of
work around to extend it.

What do you think about that idea? What do you think is best to deal with that kind of issues in Haskell, a pure functional language?

答:
You have actually answered your own question you just don't know it yet. The question you're asking is not about Haskell but about programming in general. You're actually asking yourself very good questions (kudos).

My approach to the problem you have at hand divides basically in two main aspects: the domain model design and trade-offs.

Let me explain.

Domain Model Design: This is how you decide to organize the core model of your application. I can see you're already doing that by thinking of Characters, Weapons and so on. Plus you need to define the relations between them. Your approach of defining objects by what they are instead of what they depend on is totally valid. Be careful though because it's not a silver bullet for every decision regarding your design.

You're definitely doing the right thing by thinking of this in advance but at some point you need to stop thinking and start writing some code. You'll see then if your early decisions were the right ones or not. Most likely not since you don't have yet full knowledge of your application. Then don't be afraid of refactoring when you realize certain decisions are becoming a problem not a solution. It's important to write code as you think of those decisions so you can validate them and avoid having to rewrite the entire thing.

There are several good principles you can follow, just google for "software principles" and you'll find a bunch of them.

Trade-offs: Everything is a trade-off. On one hand having too many dependencies is bad however you'll have to deal with extra complexity of managing dependencies somewhere else rather than in your domain objects. There's no right decision. If you have a gut feeling go for it. You'll learn a lot by taking that path and seeing the result.

Like I said, you're asking the right questions and that's the most important thing. Personally I agree with your reasoning but it looks you've already put too much time thinking about it. Just stop being afraid of making a mistake and make mistakes. They are really valuable and you can always refactor your code whenever you see fit.

Title: Relation between objects


答: If you are doing the upgrade within the client application like that, your approach will work.  I'd go so far as to say its unnecessary to do anything more than check the schema version in the database and apply the relevant SQL statements to update the schema.  So I'd skip the step where you try to compare the schema to another scratch database. </p>

Title: Managing database schema for a C++ app


问:
Let applications share a database or keep them in sync with web services?
We have decided to build separate applications for user authentication and user management.  The reason is that the the former is a "this just needs to always work, and do so instantly" style service, and the latter includes a much-larger user-interface component with many requirements and features.

Unfortunately, while white-boarding, prototyping, and getting more information about required features, we discovered that they need to share several types of information. For example, both apps need to know whether a user is locked out or needs to reset their password.

We are considering connecting the applications to the same database.  We considered using web services for communication, but that has a higher up-front cost, is more complex, and will have worse performance (assuming the same query will be made in either case). We'd have to keep some pieces of information in sync across two database instances, which is obviously not an optimal setup.

On the other hand, sharing the database instance would require the ORM's entity schemas to stay in sync somewhat (even if we weren't using one, we'd still need to make sure our queries still worked in both apps whenever the database schema changed).  It creates a shared dependency. In addition, the database becomes a single-point of failure/poor performance. In addition, I'm not sure it would be possible to hide irrelevant data from either app, so encapsulation is reduced.

Has anyone here worked this dilemma before and gained any insights? I'm sure there are other considerations here that I haven't thought of yet.  It's not exactly unusual to have different applications connect to a central database.

Edit (much later):

The outcome of this story almost two years later is that we ended up merging the applications into one (which thankfully was easy because they were both just modules using the same framework). The reasoning for splitting them into two made sense at the time, but in retrospect they shared too many responsibilities to make it practical.

答:
I used to work on a similar application, but the anticipated situation in my application would be very different from the way this site, facebook, twitter, or your application would work.

This is just in case, this can somewhat give you some insight.
I put both authentication data and business data in the same SQL database.
The reasons are:

When the application grows big enough that a single server is not enough, enterprise SQL vendors always provide a cluster solution which abstracts away how your DB works in distributed manner. You wouldn't have to worry about single point of failure or poor performance.

The schema has to be stable, if you want to make sure things work even when you change the data schema. You are asking for too much.

Having both in the same SQL server service saves you all the headaches you have to deal with concurrent changes in user access right. Think about somebody changing access control values for a user when a request from that user comes to the back-end service.

Note that in my application, I expect a small number of users and huge amount of data. Not in the way of this web site, or facebook, or twitter, or even your application when the number of users is huge (even when compared with business data)


问:
How to take over sizable codebase, without having access those who implemented?
I've started a job as mobile lead in a 100employee company. Their Mobile products (iOS and Android) has been developed by external teams, and now they have decided to assemble internal teams, so I'm heavily involved in hiring ATM, both for iOS and Android. I will have teams of 5 people for each of the platforms. I've been manager before, but it's the first time I'm not starting code from scratch.

My question is how to handle taking over code? The iOS code is about 50 classes, many of them over 700 lines. The code quality is around 5/10. What should be my first steps for taking over the code base? Little by little or major restructure first, or both using different resources?

答:
First, I do not know the average programmer, but at my current job I have inherited, alone, some 100 classes, many with more than 2k lines (and didn't have the luxury of 5/10 code quality). So I would not overworry about it.

That said, before deciding between "I will make little changes or a major restructure first", maybe you should know what you have and what you need.

Search for documentation from the previous developers, including testsuites.

Document the classes and their responsabilities. Single out classes that smell bad (too many responsabilities, unneeded inheritance, whatever).

Get to know what the stakeholders expect from the software (in its current state and in the future). If something is not going to be changed much, no sense in doing a full refactoring. Make them decide the priorities (which software will need to be updated first).

Gain expertise. For each app, get one developer to investigate it and get to be the product owner. Way better than having all developers know just a little of every application.

Listen to Joel (well, actually read him). The temptation of getting the code "your way" is high, but the risks and costs may be so (unless the original structure is utter crap).


问:
Why does F# Core define generic array types?
I just noticed that the FSharp.Core namespace includes generic array types of up to 4 dimensions, i.e. Core.[]<'T>, Core.[,]<'T>, etc. C# and VB seem to be doing just fine with System.Array - although it's not clear to me how they manage to support strongly-typed specialized array types like int[], string[].

I guess this becomes two questions then:

How does C# support strongly-typed specialized array types like int[]
based on the non-generic System.Array?

Given that C# manages to do this, why does F# define generic array types?

答:
How does C# support strongly-typed specialized array types like int[] based on the non-generic System.Array?

Very likely, by generating a specialized class that inherits from System.Array since generics weren't available in 1.0. The behavior has likely been kept around for compatibility.

Given that C# manages to do this, why does F# define generic array types?

Because F# didn't have the same compability constraints that C# 2.0 had with existing code. Based on what I know, C# 2.0 would have had generic array types if it was the first release of C#.


答: Speaking from experience. Find your target audience. Find people you know, people who will be honest. You have to have a pain in the butt friend who would love to tear your app to shreds. Though this answer seems light, watching a user use your app is the most beneficial thing i have ever done. My favorite test is to sit them down and give them no instruction. Figure out what they WANT to do.</p>

Title: Testing of personal projects

Body: I'm developing a web based personal project that will hopefully be used by thousands.  Obviously prior to releasing it in the wild as Beta I was wondering,  are there any communities out there that will test my web app and provide feedback?  Free would be great, but I'm open to suggestions.</p>


答:
F# doesn't define generic array types per se. Arrays in F# are the same array type rest of .NET uses, and despite all syntactic evidence pointing to the contrary, they're not generic.

This can sometimes backfire on you when you're using reflection in F# - even if you have an array<int> which appears to be a perfectly valid generic type, when you inspect it you get a false from IsGenericType, a true from IsArray, and you get the type argument with GetElementType rather then GetGenericArguments.

Like Telastyn noted in his answer, this is likely the legacy baggage of .NET 1.0 that we'll have to live with. But it's just one of many things that makes using reflection API in F# a real minefield.

What F# does define, are the [], [,] ... type abbreviations/aliases/operators and modules with corresponding functions, but they all ultimately refer to the same Array type beneath.

You can look at the source code on github here and here to see it for yourself.

Title: Why does F# Core define generic array types?

Body:
I just noticed that the FSharp.Core namespace includes generic array types of up to 4 dimensions, i.e. Core.[]<'T>, Core.[,]<'T>, etc. C# and VB seem to be doing just fine with System.Array - although it's not clear to me how they manage to support strongly-typed specialized array types like int[], string[].

I guess this becomes two questions then:

How does C# support strongly-typed specialized array types like int[]
based on the non-generic System.Array?

Given that C# manages to do this, why does F# define generic array types?


答:
Python optimizer is pretty stupid by design, but this is one case that the optimizer happens to be capable of detecting:

```<code>>>> def a():
...     if foobar:
...         pass
...
>>> dis.dis(a)
  2           0 LOAD_GLOBAL              0 (foobar)
              3 POP_JUMP_IF_FALSE        9

  3           6 JUMP_FORWARD             0 (to 9)
        >>    9 LOAD_CONST               0 (None)
             12 RETURN_VALUE
>>> def b():
...     if not foobar:
...         pass
...
>>> dis.dis(b)
  2           0 LOAD_GLOBAL              0 (foobar)
              3 POP_JUMP_IF_TRUE         9

  3           6 JUMP_FORWARD             0 (to 9)
        >>    9 LOAD_CONST               0 (None)
             12 RETURN_VALUE
</code>```

For which you should use, write readable code rather than worrying about little details like this.

Body:
Python optimizer is pretty stupid by design, but this is one case that the optimizer happens to be capable of detecting:

>>> def a():
...     if foobar:
...         pass
...
>>> dis.dis(a)
  2           0 LOAD_GLOBAL              0 (foobar)
              3 POP_JUMP_IF_FALSE        9

  3           6 JUMP_FORWARD             0 (to 9)
        >>    9 LOAD_CONST               0 (None)
             12 RETURN_VALUE
>>> def b():
...     if not foobar:
...         pass
...
>>> dis.dis(b)
  2           0 LOAD_GLOBAL              0 (foobar)
              3 POP_JUMP_IF_TRUE         9

  3           6 JUMP_FORWARD             0 (to 9)
        >>    9 LOAD_CONST               0 (None)
             12 RETURN_VALUE

For which you should use, write readable code rather than worrying about little details like this.


答:
In general, it's easier for people to understand the conditional without the negation - it's one less thing to think about when deciphering the meaning of the condition. The performance difference will probably be negligible, and worrying about it is premature optimization. (Besides, if you're working in Python, this kind of micro-optimization is worthless; if you really had a performance problem, you'd solve it by using better algorithms or implementing the critical code in C.)

However, in this case both of your options are potentially race conditions if task A or B involves acting on the file. The file may appear/disappear between checking the if condition and executing either task. Generally you proceed with task A as if the file is there and handle the exception if it turns out to not be there. File I/O is a form of concurrency and you should assume that things can change between any two program statements.


问:
Using mocks to set up object even if you will not be mocking any behavior or verifying any interaction with it?
When building a unit test, is it appropriate to use a mocking tool to assist you in setting up an object even if you will not be mocking any behavior or verifying any interaction with that object?

Here is a simple example in pseudo-code:

```<code>//an object we actually want to mock
Object someMockedObject = new Mock(Object.class);
EqualityChecker checker = new EqualityChecker(someMockedObject);

//an object we are stubbing/mocking only to avoid figuring out how to instantiate or
//tying ourselves to some constructor that may be removed in the future
ComplicatedObject someObjectThatIsHardToInstantiate = new Mock(ComplicatedObject.class);

//set the expectation on the mock
When(someMockedObject).equals(someObjectThatIsHardToInstantiate).return(false);
Assert(equalityChecker.check(someObjectThatIsHardToInstantiate)).isFalse();

//verify that the mock was interacted with properly
Verify(someMockedObject).equals(someObjectThatIsHardToInstantiate).oneTime();
</code>```

Is it appropriate to mock ComplicatedObject in this scenario?

答:
You don't really want a mock object. You want a stub. Basically you want a dumb object that takes the place of something complex so you can control that complex process without needing to validate that it works.

Mocks Aren't Stubs (Martin Fowler)


问:
Why is a private member accessible in a static method?
The following is pseudo code, I tried it in Java and PHP and both worked:

```<code>class Test {

    private int a = 5;

    public static function do_test(){
        var t = new Test();
        t.a = 1;
        print t.a // 1
    }

}

Test::do_test();
</code>```

Why can you do this in OOP paradigm and what's the use of it?

答:
Some languages and runtime frameworks (e.g. Java, .NET) make the assumption that anyone who is compiling the code for a particular class can be trusted not to use any private members of any instance of that class in ways which would be detrimental to its correct operation.  Other languages and frameworks are more restrictive in that regard, and do not allow access to private members of an instance except by code running on that instance.  Both designs have advantages and disadvantages.

The biggest advantage of allowing any code within a class to access private members of any instance is that there are cases where that level of access is appropriate, and having private work that way eliminates the need to either have a different access qualifier available for that purpose or else force code to expose members more broadly than would otherwise be ideal.

An advantage of disallowing such access (as was the case in the Microsoft Common Object Model (COM)) is that it allows outside code to treat classes as interfaces.  If a class ImmutableMatrix contains a private or protected double[][] backing field, and if code within the class examines the backing array of other instances, then it will not be possible to define a non-array-backed class (e.g. ZeroMatrix, IdentityMatrix) which outside code could use as an Immutable2dMatrix, without that class having to including the backing field.  If nothing within Immutable2dMatrix uses private members of any instance other than this, then it would be possible to rename the class to ImmutableArrayBackedMatrix, and define a new abstract ImmutableMatrix class which could have ImmutableArrayBackedMatrix as well as the aforementioned non-array-backed classes as subtypes.

Note that such refactoring would not be prevented by having the language "allow" ImmutableMatrix to examine the backing array for instances other than this, unless the language took advantage of that ability and actually did examine outside instances.  The primary effect of having a language restrict such usage is that it will make the compiler squawk immediately at any attempt to write code which would not be amenable to such refactoring.


问:
Is hierarchical product backlog a good idea in TFS 2012-2013?
I'd like to validate I'm not in the wrong way.

My team project is using Visual Studio Scrum 2.x. Since each area/product has a lot of kind of requirements (security, user interface, HTTP/REST services...), I tried to manage this creating "parent backlogs" which are "open forever" and they contain generic requirements.

Those parent backlogs have other "open forever" backlogs, and/or sprint backlogs.

For example:

HTTP/REST Services (forever)

Profiles API (forever)
*POST profile (forever)

We need a basic HTTP/REST profiles' API to register new user profiles (sprint backlog)

Is it the right way of organizing the product backlog?

Note: I know there're different points of view and that would be right for some and wrong for others. I'm looking for validation about if this is a possible good practice on TFS with Visual Studio Scrum.

答:
As far as I understood hierarchical backlogs:
They are not meant to be organized by technical topics, but rather organized by abstraction level of the work item. The lowest levels are supposed to be the most technical, the highest the most business-value/business-goal related.

In the MSDN documentation there is an example with the following hierarchy:

World-class customer support

Mitigate impact of low-coverage areas

Data cache improvements

To me this way of using the different levels seems to be useful for:

Capturing high-level goals - even if they are currently out of scope for development and without having to specify technical, detailed tasks

Documenting the presumed link between the technical detail and the expected business outcome

The the similar abstraction levels within each level and the context of the upper layers provide a good framework to discuss alternatives or prioritization


问:
Moving our web application from a windows development environment to linux environment seamlessly
I am trying to develop a web application on a windows machine using apache wicket, java, jquery etc. Apache wicket comes with an embedded jetty server. I am using eclipse as the IDE.

The application needs to access some resources like configuration files etc that are present on remote machine (linux server) to which we could ssh, once development is complete we would like to deploy this application on a tomcat server hosted on this linux server. How to move seamlessly from the windows development environment to the linux server deployment?

Right now we do the development by copying over the latest config files from the server, however this is error prone as it becomes difficult to keep track of the latest config files, this leads to unexpected behavior when the application is deployed.

Our team is located in India and our servers are located in US, mapping the config files and accessing them do not have good response times.

答:
I understand you are trying to solve two key problems here

Syncing configuration files to between two locations

Deploying applications from development to production.

To answer your first question:
There a number of sync tools that are available you can use to sync a bunch of directories to across multiple systems my favorite is rsync.
[1]http://rsync.samba.org/examples.html

So you can use it to sync configuration files in your production linux server and a development linux server.

To answer your second question:
I am assuming you are using some sort of version control system for your code,If so then you can use any of the continuous integration systems like jenkins to do an automated build for you and push the built project to the remote server once the build is successful.The good thing about using a continuous integration servers is once a developer commits the code it can automatically kick off new builds (if you configure it to do so) and you will have quick feedback on the status of your build and fix the issue.


问:
How does the "Fourth Dimension" work with arrays?
Abstract:

So, as I understand it (although I have a very limited understanding), there are three dimensions that we (usually) work with physically:

The 1st would be represented by a line.

The 2nd would be represented by a square.

The 3rd would be represented by a cube.

Simple enough until we get to the 4th -- It is kinda hard to draw in a 3D space, if you know what I mean...  Some people say that it has something to do with time.

The Question:

Now, though that doesn't all make much sense, that is all great with me.  My question isn't about this, or I'd be asking it on MathSO or PhysicsSO.  My question is: How does the computer handle this with arrays?

I know that you can create 4D, 5D, 6D, etc... arrays in many different programming languages, but I want to know how that works.

答:
Fortunately, programs aren't limited by the physical constraints of the real world. Arrays aren't stored in physical space, so the number of dimensions of the array doesn't matter. They are flattened out into linear memory. For example, a single dimensional array with two elements might be laid out as:

```<code>(0) (1)
</code>```

A 2x2 dimensional array might then be:

```<code>(0,0) (0,1) (1,0) (1,1)
</code>```

A three dimensional 2x2x2 array might be:

```<code>(0,0,0) (0,0,1) (0,1,0) (0,1,1) (1,0,0) (1,0,1) (1,1,0) (1,1,1)
</code>```

You can hopefully see where this is going. Four dimensions might be:

```<code>(0,0,0,0) (0,0,0,1) (0,0,1,0) (0,0,1,1) (0,1,0,0) (0,1,0,1) (0,1,1,0) (0,1,1,1)
(1,0,0,0) (1,0,0,1) (1,0,1,0) (1,0,1,1) (1,1,0,0) (1,1,0,1) (1,1,1,0) (1,1,1,1)
</code>```

Body:
Fortunately, programs aren't limited by the physical constraints of the real world. Arrays aren't stored in physical space, so the number of dimensions of the array doesn't matter. They are flattened out into linear memory. For example, a single dimensional array with two elements might be laid out as:

(0) (1)

A 2x2 dimensional array might then be:

(0,0) (0,1) (1,0) (1,1)

A three dimensional 2x2x2 array might be:

(0,0,0) (0,0,1) (0,1,0) (0,1,1) (1,0,0) (1,0,1) (1,1,0) (1,1,1)

You can hopefully see where this is going. Four dimensions might be:

(0,0,0,0) (0,0,0,1) (0,0,1,0) (0,0,1,1) (0,1,0,0) (0,1,0,1) (0,1,1,0) (0,1,1,1)
(1,0,0,0) (1,0,0,1) (1,0,1,0) (1,0,1,1) (1,1,0,0) (1,1,0,1) (1,1,1,0) (1,1,1,1)


答:
An array is only a block of continous memory.
Memory addressing is one-dimensional, you can either go forward or backward. So assuming you have an array with 5 elements, 5 memory blocks will be reserved. If you have a 2-dimensional array with 5 elements in each dimension, 25 memory blocks will be reserved.</p>

Title: How does the "Fourth Dimension" work with arrays?

Body:
Abstract:

So, as I understand it (although I have a very limited understanding), there are three dimensions that we (usually) work with physically:

The 1st would be represented by a line.

The 2nd would be represented by a square.

The 3rd would be represented by a cube.

Simple enough until we get to the 4th -- It is kinda hard to draw in a 3D space, if you know what I mean...  Some people say that it has something to do with time.

The Question:

Now, though that doesn't all make much sense, that is all great with me.  My question isn't about this, or I'd be asking it on MathSO or PhysicsSO.  My question is: How does the computer handle this with arrays?

I know that you can create 4D, 5D, 6D, etc... arrays in many different programming languages, but I want to know how that works.


答:
The dimensions are whatever you want to be, the 4th dimension doesn't necessarily have to be time. If you think of three dimensions as a cube, you can think of 4 dimensions as a row of cubes. 5 dimensions, a grid of cubes, and so on.

You could also have a 3d collection of voxels, with a 4th dimension being color, or density, or some other property.

When you allocate the memory for your multidimensional array, it just simply allocates the product of each dimensions maximum for your data type. If you have a 3d array or 'cube' of 10 elements in each dimension, you'll have 1,000 elements allocated. If you make that a 4d array with 10 elements in the 4th dimension, the computer will just allocate 10,000. Bump it up to 5 dimensions, and it will allocate 100,000.

The computer doesn't care about any sort of meaning about what each dimension represents.
To select where in the list of elements a single point is, it's just multiplication to select a memory address.


答:
Java is not strictly an object-oriented language, but a class based language - the class determines the operations and behaviour access rather than the instance.

So don't be overly surprised that it lets you do things which are not strictly object-oriented.

Since the method is in the same class-scope as the instance, it has full access to private members. Similar rules govern instances of inner classes accessing data from instances of outer classes - an instance of an inner class can access private members of the outer class.

This is inherited from C++, where it is useful for creating copy and move constructors. It also is useful for comparing or combining two objects where their value depends on members which are not publically accessible in an efficient manner ( for example, the getter for an array in Java should copy the array so that the client code cannot modify it, changing the internal state of the object, but having to copy arrays to compare object equality is not efficient )

Title: Why is a private member accessible in a static method?

Body:
The following is pseudo code, I tried it in Java and PHP and both worked:

```<code>class Test {

    private int a = 5;

    public static function do_test(){
        var t = new Test();
        t.a = 1;
        print t.a // 1
    }

}

Test::do_test();
</code>```

Why can you do this in OOP paradigm and what's the use of it?