答:
For my environment, I built a dedicated tool for managing database updates.  I created several database tables to track schema (table, field, index, indexField, history) and a screen to manage those tables.  I also track meta-data such as when changes were made, the last time a schema change was applied, etc.

Our developers now use this program whenever they want to modify our database.  First they make any required changes to the tables. Then they open up an apply schema screen which shows a list of changed tables and they can select which ones to apply to the database.  We can then create the update script and apply the update script.

When we're building a production release, the developers can then go in and flag which table updates they want to be included in the release. Our release process will then create & apply the schema changes for those tables.


问:
Which user-story estimation technique is better?
I found two techniques for estimating user stories:

by the size of the story, which is unit-less

by the time estimate, which is measured by days

The first uses relative comparison between stories to infer time, and it should be independent on developer experience, while the second depends on developer experience.

I tried the first which is good, but I believe the second is more developer-friendly, and I want to see the pros and cons of each of them from practical experience. Any idea?

答: Most production projects are run based on a schedule of some sort. The PM usually needs to know when something will finish, at least approximately. If I tell you that this item has a complexity of x, the PM can't put that on a Gantt chart unless there is a way to translate complexity to time units. That is why, INMHO, using time estimates is good for planning (I assume you use estimates for that). Now choosing the unit of days is kind of debatable. You may want to see Agile Planning: ‘Ideal Day’ – User Story Estimation.</p>

ContentLicense: CC BY-SA 3.0


问:
How to include database changes during application publish
I am maintaining a WinForms application, which talks to a SQL Server database. Sometimes I have to change database schema (for example to alter a sql procedure or add new one). For this purpose I have a SchemaChange.sql file, where I put the corresponding sql code.

When I create an installer for my project, the msi package is created. It contains my application, referenced assemblies, COM+ assemblies,... Alongside the msi package I provide an SchemaChange.sql file, which has to be run on the production sql server.

But sometimes I forget to add something to SchemaChange.sql file during development or I forget to execute it on production server after upgrading my application on client machines. Any advice how to automate this to avoid further problems?

答: Go give LiquidBase a try. I've also gone the route of manually creating sequentially numbered SQL scripts, but now having used a database change management system like LiquidBase makes me never want to go back.</p>


问:
Alternatives to the singleton pattern
I have read different opinions about the singleton pattern.
Some maintain that it should be avoided at all costs and others
that it can be be useful in certain situations.

One situation in which I use singletons is when I need a factory
(let's say an object f of type F) to create objects of a certain class A.
The factory is created once using some configuration parameters and then
is used each time an object of type A is instantiated. So every part of
the code that wants to instantiate A fetches the singleton f and create
the new instance, e.g.

```<code>F& f                   = F::instance();
boost::shared_ptr<A> a = f.createA();
</code>```

So the general my scenario is that

I need only one instance of a class either for optimization reasons (I do not need multiple factory objects) or for sharing common state (e.g. the factory knows how many instances of A it can still create)

I need a way to have access to this instance f of F in different places of the code.

I am not interested in the discussion whether this pattern is good or bad,
but assuming I want to avoid using a singleton, what other pattern can I use?

The ideas I had were (1) to get the factory object from a registry or
(2) to create the factory at some point during program start up and then
pass the factory around as a parameter.

In solution (1), the registry itself is a singleton, so I have just shifted
the problem of not using a singleton from the factory to the registry.

In case (2) I need some initial source (object) from which the factory object
comes so I am afraid that I would again fall back to another singleton
(the object that provides my factory instance).
By following back this chain of singletons I can maybe reduce the problem
to one singleton (the whole application) by which all other singletons
are directly or indirectly managed.

Would this last option (using one initial singleton that creates all other
unique objects and injects all other singletons at the right
places) be an acceptable solution?
Is this the solution that is implicitly suggested when one advises not to
use singletons, or what are other solutions, e.g. in
the example illustrated above?

EDIT

Since I think the point of my question has been misunderstood by some,
here is some more information. As explained e.g. here, the word
singleton can indicate (a) a class with a single instance object and
(b) a design pattern used to create and access such an object.

To make things clearer let us use the term unique object for (a) and
singleton pattern for (b). So, I know what the singleton pattern
and dependency injection are (BTW, lately I've been using DI heavily
to remove instances of the singleton pattern from some code I am working on).

My point is that unless the whole object graph is instantiated from
a single object living on the stack of the main method, there will always be
the need to access some unique objects through the singleton pattern.

My question is whether having the complete object graph creation and
wiring depend on the main method (e.g. through some powerful DI framework
that does not use the pattern itself) is the only
singleton-pattern free solution.

答:
Singletons Encapsulation

Case scenario. Your application is Object Oriented, and requires 3 or 4 specific singletons, even if you have more classes.

Before Example (C++ like pseudocode):

```<code>// network info
class Session {
  // ...
};

// current user connection info
class CurrentUser {
  // ...
};

// configuration upon user
class UserConfiguration {
  // ...
};

// configuration upon P.C.,
// example: monitor resolution
class TerminalConfiguration {
  // ...
};
</code>```

One way is to partially remove some (global) singletons, by encapsulating all of them into a unique singleton, that has as members, the other singletons.

This, way, instead of the "several singletons, approach, versus, no singleton at all, approach", we have the "encapsulate all singletons into one, approach".

After Example (C++ like pseudocode):

```<code>// network info
class NetworkInfoClass {
  // ...
};

// current user connection info
class CurrentUserClass {
  // ...
};

// configuration upon user
// favorite options menues
class UserConfigurationClass {
  // ...
};

// configuration upon P.C.,
// example: monitor resolution
class TerminalConfigurationClass {
  // ...
};

// this class is instantiated as a singleton
class SessionClass {
  public: NetworkInfoClass NetworkInfo;
  public: CurrentUserClass CurrentUser;
  public: UserConfigurationClass UserConfiguration;
  public: TerminalConfigurationClass TerminalConfiguration;

  public: static SessionClass Instance();
};
</code>```

Please note, that the examples are more like pseudocode, and ignore minor bugs, or syntax errors, and consider the solution to the question.

There is also other thing to consider, because, the programming language used, may affect how to implement your singleton or non singleton implementation.

Cheers.

Title: Alternatives to the singleton pattern

Body:
Singletons Encapsulation

Case scenario. Your application is Object Oriented, and requires 3 or 4 specific singletons, even if you have more classes.

Before Example (C++ like pseudocode):

// network info
class Session {
  // ...
};

// current user connection info
class CurrentUser {
  // ...
};

// configuration upon user
class UserConfiguration {
  // ...
};

// configuration upon P.C.,
// example: monitor resolution
class TerminalConfiguration {
  // ...
};

One way is to partially remove some (global) singletons, by encapsulating all of them into a unique singleton, that has as members, the other singletons.

This, way, instead of the "several singletons, approach, versus, no singleton at all, approach", we have the "encapsulate all singletons into one, approach".

After Example (C++ like pseudocode):

// network info
class NetworkInfoClass {
  // ...
};

// current user connection info
class CurrentUserClass {
  // ...
};

// configuration upon user
// favorite options menues
class UserConfigurationClass {
  // ...
};

// configuration upon P.C.,
// example: monitor resolution
class TerminalConfigurationClass {
  // ...
};

// this class is instantiated as a singleton
class SessionClass {
  public: NetworkInfoClass NetworkInfo;
  public: CurrentUserClass CurrentUser;
  public: UserConfigurationClass UserConfiguration;
  public: TerminalConfigurationClass TerminalConfiguration;

  public: static SessionClass Instance();
};

Please note, that the examples are more like pseudocode, and ignore minor bugs, or syntax errors, and consider the solution to the question.

There is also other thing to consider, because, the programming language used, may affect how to implement your singleton or non singleton implementation.

Cheers.


答:
If you are using a multiparadigm language like C++ or Python, one alternative to a singleton class is a set of functions/variables wrapped in a namespace.

Conceptually speaking, a C++ file with free global variables, free global functions, and static variables used for information hiding, all wrapped in a namespace, gives you nearly the same effect as a singleton "class".

It only breaks down if you want inheritance.  I've seen a lot of singletons that would have been better off this way.

Title: Alternatives to the singleton pattern

Body:
I have read different opinions about the singleton pattern.
Some maintain that it should be avoided at all costs and others
that it can be be useful in certain situations.

One situation in which I use singletons is when I need a factory
(let's say an object f of type F) to create objects of a certain class A.
The factory is created once using some configuration parameters and then
is used each time an object of type A is instantiated. So every part of
the code that wants to instantiate A fetches the singleton f and create
the new instance, e.g.

```<code>F& f                   = F::instance();
boost::shared_ptr<A> a = f.createA();
</code>```

So the general my scenario is that

I need only one instance of a class either for optimization reasons (I do not need multiple factory objects) or for sharing common state (e.g. the factory knows how many instances of A it can still create)

I need a way to have access to this instance f of F in different places of the code.

I am not interested in the discussion whether this pattern is good or bad,
but assuming I want to avoid using a singleton, what other pattern can I use?

The ideas I had were (1) to get the factory object from a registry or
(2) to create the factory at some point during program start up and then
pass the factory around as a parameter.

In solution (1), the registry itself is a singleton, so I have just shifted
the problem of not using a singleton from the factory to the registry.

In case (2) I need some initial source (object) from which the factory object
comes so I am afraid that I would again fall back to another singleton
(the object that provides my factory instance).
By following back this chain of singletons I can maybe reduce the problem
to one singleton (the whole application) by which all other singletons
are directly or indirectly managed.

Would this last option (using one initial singleton that creates all other
unique objects and injects all other singletons at the right
places) be an acceptable solution?
Is this the solution that is implicitly suggested when one advises not to
use singletons, or what are other solutions, e.g. in
the example illustrated above?

EDIT

Since I think the point of my question has been misunderstood by some,
here is some more information. As explained e.g. here, the word
singleton can indicate (a) a class with a single instance object and
(b) a design pattern used to create and access such an object.

To make things clearer let us use the term unique object for (a) and
singleton pattern for (b). So, I know what the singleton pattern
and dependency injection are (BTW, lately I've been using DI heavily
to remove instances of the singleton pattern from some code I am working on).

My point is that unless the whole object graph is instantiated from
a single object living on the stack of the main method, there will always be
the need to access some unique objects through the singleton pattern.

My question is whether having the complete object graph creation and
wiring depend on the main method (e.g. through some powerful DI framework
that does not use the pattern itself) is the only
singleton-pattern free solution.


答:
How about using IoC container? With some thought you can end up with something on the lines of:

```<code>Dependency.Resolve<IFoo>();
</code>```

You would have to specify which implementation of IFoo to use at a startup, but this is a one off configuration which you can easily replace later. Lifetime of a resolved instance can be normally controlled by an IoC container.

Static singleton void method could be replaced with:

```<code>Dependency.Resolve<IFoo>().DoSomething();
</code>```

Static singleton getter method could be replaced with:

```<code>var result = Dependency.Resolve<IFoo>().GetFoo();
</code>```

Example is relevant to .NET, but I'm certain very similar can be achieved in other languages.

Title: Alternatives to the singleton pattern

Body:
How about using IoC container? With some thought you can end up with something on the lines of:

Dependency.Resolve<IFoo>();

You would have to specify which implementation of IFoo to use at a startup, but this is a one off configuration which you can easily replace later. Lifetime of a resolved instance can be normally controlled by an IoC container.

Static singleton void method could be replaced with:

Dependency.Resolve<IFoo>().DoSomething();

Static singleton getter method could be replaced with:

var result = Dependency.Resolve<IFoo>().GetFoo();

Example is relevant to .NET, but I'm certain very similar can be achieved in other languages.


答:
Your original requirements:

So the general my scenario is that

I need only one instance of a class either for optimization reasons (I do not need >multiple factory objects) or for sharing common state (e.g. the factory knows how many >instances of A it can still create)

I need a way to have access to this instance f of F in different places of the code.

Do not line up with the definition of a singleton (and what you rather refer to later). From GoF (my version is 1995) page 127:

Ensure a class only has one instance, and provide a global point of access to it.

If you only need one instance, that does not preclude you from making more.

If you want a single, globally accessible instance then make a single globally accessible instance. There is no need to have a pattern named for everything you do. And yes, single globally accessible instances are usually bad. Giving them a name doesn't make them less bad.

To avoid global accessibility, the common 'make an instance and pass it along' or 'have the owner of two objects glue them together' approaches work well.

Title: Alternatives to the singleton pattern


问:
Where are null values stored, or are they stored at all?
I want to learn about null values or null references.

For example I have a class called Apple and I created an instance of it.

```<code>Apple myApple = new Apple("yummy"); // The data is stored in memory
</code>```

Then I ate that apple and now it needs to be null, so I set it as null.

```<code>myApple = null;
</code>```

After this call, I forgot that I ate it and now want to check.

```<code>bool isEaten = (myApple == null);
</code>```

With this call, where is myApple referencing? Is null a special pointer value? If so, if I have 1000 null objects, do they occupy 1000 object memory space or 1000 int memory space if we think a pointer type as int?

Body:
Quick example (note varible names are not stored):

void main()
{
  int X = 3;
  int *Y = X;
  int *Z = null;
} // void main(...)

...........................
....+-----+--------+.......
....| &X  |   X    |.......
....+-----+--------+.......
....| 100 |   3    |<---+..
....+-----+--------+....|..
........................|..
....+-----+--------+....|..
....| &Y  |   Y    |....|..
....+-----+--------+....|..
....| 102 |  100   +----+..
....+-----+--------+.......
...........................
....+-----+--------+.......
....| &Z  |   z    |.......
....+-----+--------+.......
....| 104 |   0    |.......
....+-----+--------+.......
...........................

Cheers.

ContentLicense: CC BY-SA 4.0


答:
There are a few alternatives:

Dependency Injection

Every object has its dependencies passed to it when it was created. Typically either a framework or a small number of factory classes are responsible for creating and wiring the objects

Service Registry

Every object is passed a service registry object. It provides methods to request various different objects which provide different services. The Android framework uses this pattern

Root Manager

There is a single object which is the root of the object graph. By following the links from this object any other object can be eventually found. Code tends to look like:

```<code>GetSomeManager()->GetRootManager()->GetAnotherManager()->DoActualThingICareAbout()
</code>```

Title: Alternatives to the singleton pattern

Body:
There are a few alternatives:

Dependency Injection

Every object has its dependencies passed to it when it was created. Typically either a framework or a small number of factory classes are responsible for creating and wiring the objects

Service Registry

Every object is passed a service registry object. It provides methods to request various different objects which provide different services. The Android framework uses this pattern

Root Manager

There is a single object which is the root of the object graph. By following the links from this object any other object can be eventually found. Code tends to look like:

GetSomeManager()->GetRootManager()->GetAnotherManager()->DoActualThingICareAbout()


问:
Is Ubuntu workable as a laptop for an IT consultant?
I work as a consultant programmer, typically in large businesses. I use a Windows Laptop, and many of my colleagues use a Mac.

My personal preference would be to run Ubuntu if I could have complete control over my development environment. But I will have occasional need for Microsoft specific products, especially IE.

My colleagues that use a Mac often run Windows on a virtual machine for these situations.

My question is: Is Ubuntu a workable solution for the laptop of an enterprise programmer? For example, is it as easy to run Windows on a VM on Ubuntu as it is on a Mac? Has anyone out there tried this? Is there any particular reason why Ubuntu would not serve as well as a Mac for development in this environment?

Note that I am not doing .NET development, so I am typically dealing with Java that is going to be run on an Apache server and used by clients running Windows.

答:
I do this a little differently.  I use Windows 7, but have VMWare workstation and create a virtual machine for the environment I want to develop under.  I have a virtual machine for Ubuntu, Fedora, FreeBSD and Open Solaris.  If there is an operating system that I want to use, then I just create another VM.  I hope to be able to use OSX this way at some point, but last time I checked you were not allowed to do this by Apple.

I did try to do this the other way around (VM for windows under and Ubuntu desktop), but it was a mess.  VMware had many, many issues with this (mostly crashing the whole machine) and was generally slower.  Also, the kernel updates for Linux when trying to use VMware was a real pain.

Yes, this is anecdotal, but is just my experience with it.


问:
A Huge Database: Picking the right schema and data model
We want to store some genomic variant data but there are some problems, more important ones like problem of the data's immense size and variability.

Variant data can be huge.  For example, a single individuals variant data could feasibly some day require a million rows of data in a table, or require of a gigabyte of raw storage on disk.  Multiply this over several thousand individuals, and you could potentially end up with terabytes worth of information that you need to make sense of.

Each client and/or system we integrate with, will expose or want to see data slightly differently depending on their needs and use cases.  This can potentially lead to hundreds of fields that we might need to store, all of which might need to be in different configurations based on the clients needs. So this variant data model will need to keep this in mind in order to remain easy to use, expandable and most
importantly, scalable in the long term.

What do you think is better for such a problem? We were thining of having some coulmns in each table that point to an external database or even a file, where we save the huge BLOB data?

答: I have made use of external files and link to them. This will greatly reduce the strain on the DB. You will need to find a way to get the data back out of the file, but it can be done pretty simply with JavaScript or PHP.</p>


问:
Is C#-4.0 an open standard?
The Ecma-334 (ISO/IEC 23270:2006) standard corresponds to the version 2.0 of the language.

Specification of version 4.0 is freely available from Microsoft, but Microsoft's open specifications list only lists the Ecma (version 2.0) version.

So what about all the good features added in the later versions (LINQ, lambda functions, etc)? Can one implement them in his compiler?

答:
C# 4.0 does not have a published ECMA standard yet.

However, Mono actively adds the latest C# and .NET Framework features to its compiler, using the specifications published by Microsoft.

Title: Is C#-4.0 an open standard?


问:
Wrong use of CSS3 Animations or not?
Well, I started using some CSS3 animations a couple of days ago. After hardcoding I've started trying different tools like Adobe Edge Preview version.

I made a short animation to get the functionality of the tool
http://things.eyemade.ch/css3edge/

After that someone at Twitter took a look at it and said that it is wrong using divs to paint things like these. But I'm not sure about that. Things changed over the last years and if we keep in mind this stuff is going to be used in many web/mobile games, is it really wrong to use divs this way nowadays?

答:
Web and mobile games will probably use canvas. It allows to do much more advanced visual effects and animations, with better hardware acceleration compared to
s moving around.

Keep
s for, well, the sections of text, where there are no other, more appropriate elements (such as
). This also means that for those
s, you must use the animations with moderation, to enhance user interactivity, not to create full-scale animations.

Title: Wrong use of CSS3 Animations or not?

Body:
Web and mobile games will probably use canvas. It allows to do much more advanced visual effects and animations, with better hardware acceleration compared to <div/>s moving around.

Keep <div/>s for, well, the sections of text, where there are no other, more appropriate elements (such as <h1/>). This also means that for those <div/>s, you must use the animations with moderation, to enhance user interactivity, not to create full-scale animations.


问:
Why not Spring framework?
Are there any disadvantages in tying my application to Spring framework?

I'm not talking about bugs or issues like that, if any. I'm talking about strategic, architectural things that will influence my application lifecycle.

Should I prefer Spring over Java EE core features supported by EE container? What are the advantages?

答: Spring really is good. Spring Core is fine. I would add to the other points, if you are in the niche category where performance is truly a concern, you'll want to avoid the other Spring modules, only if you are in the hands of top developers. This is only a concern if you are running a system where performance really is critical. In the hands of average to good developers, Spring will probably actually give you a performance boost by helping to write clean simple code.</p>

Title: Why not Spring framework?


问:
introducing pointers to a large software project
I have a fairly large software project written in c++.

In there, there is a class foo which represents a structure (by which i don't mean the programmers struct) in which foo-objects can be part of a foo-object.

Here's class foo in simplest form:

```<code>class Foo
{
    private:
        std::vector<unsigned int> indices;
    public:
        void addFooIndex(unsigned int);
        unsigned int getFooIndex(unsigned int);
};
</code>```

Every foo-object is currently stored in an object of class bar.

```<code>class Bar
{
    private:
        std::vector<Foo> foos;
    public:
        void addFoo(Foo);
        std::vector<Foo> getFoos();
}
</code>```

So if a foo-object should represent a structure with a "inner" foo-object, I currently do

```<code>Foo foo;
Foo innerFoo;
foo.addFooIndex(bar.getFoos().size() - 1);
bar.addFoo(innerFoo);
</code>```

And to get it, I obviously use:

```<code>Foo foo;
for ( unsigned int i = 0; i < foo.getFooIndices().size(); ++i )
{
    Foo inner_foo;
    assert( foo.getFooIndices().at(i) < bar.getFoos().size() );
    inner_foo = bar.getFoos().at(foo.getFooIndices().at(i));
}
</code>```

So this is not a problem. It just works. But it's not the most elegant solution.

I now want to make the inner foos to be "more connected" with the foo-object. It would be obviously to change class foo to:

```<code>class Foo
{
    private:
        std::vector<Foo*> foo_pointers;
    public:
        void addFooPointer(Foo*);
        std::vector<Foo*> getFooPointers();
};
</code>```

So now, for my question: How to gently change this basic class without messing up the whole code? Is there a "clean way"?

答:
I don't think having the foo object be responsible for its index in a container is a good idea. It should be blissfully unaware of the container(s) it is in. Maintaining these indices is the job of the container (if it is applicable for that container).

Your current code requires a foo to retrieve the inner foos from bar so why not just retrieve them directly from foo?

```<code>for (unsigned int index = 0; index < foo.getFooPointers().size(); ++index)
{
    Foo* inner_foo = foo.getFooPointers().at(index);
}
</code>```

Why do you need the inner foos stored in bar? If there is some situation where you want to loop through all foos, including inner ones, you could create an iterator.

As a side note I would probably call the member function something like getInnerFoos() or getChildren() instead of getFooPointers(). The signature already tells you that it returns pointers of type foo.

Body:
I don't think having the foo object be responsible for its index in a container is a good idea. It should be blissfully unaware of the container(s) it is in. Maintaining these indices is the job of the container (if it is applicable for that container).

Your current code requires a foo to retrieve the inner foos from bar so why not just retrieve them directly from foo?

for (unsigned int index = 0; index < foo.getFooPointers().size(); ++index)
{
    Foo* inner_foo = foo.getFooPointers().at(index);
}

Why do you need the inner foos stored in bar? If there is some situation where you want to loop through all foos, including inner ones, you could create an iterator.

As a side note I would probably call the member function something like getInnerFoos() or getChildren() instead of getFooPointers(). The signature already tells you that it returns pointers of type foo.


答:
I don't know enough about your system but you need to look at the following:

1-How you obtain the data and in what format? Answering this will give options of how to store it and load it initially if you will end-up using a database.

2-How do you process this raw data? Answering this, will help you figure the 'active' set size. This will help in deciding how to store and how to load the data also. You may find that you don't need the entire input record and all you need is few fields of it only. If most of the fields are not used, you can keep them in a separate archived storage.

3-How do you inquire this data (online/batch and what criteria is most likely to be used)? Answering this will be the key factor in answering how to store the data what parts to keep on-line and what parts to keep off-line. Oracle for example allows you to run SQL on text files without loading the files in first. This could be a huge time saver, but of course it depends on your scenario.

as per your point:

single individuals variant data could feasibly some day require a million rows of data in a table

I really don't understand how this is possible. If it is accurate, I am not sure how it will be used. Maybe you need to separate the concepts of mere data storage from the concept of which parts of the data will be used. If you understand more about how the data will be used, you may be able to cut down the number of rows by aggregation or a similar technique.

In short much analysis is required for before a solution can be found. The guiding principles are:

1-Know your data well

2-Cut down on row size by keeping the needed columns only and linking to off-line storage when possible

3-Cut down on total row numbers by aggregation when possible

4-Use table partitioning and avoid excessive indexing

5-Know how the users need to use this data

6-Consider loading data as it arrives

7-You are probably going to need a star schema (fact and dimensions) to speed queries, but we can't tell by just the information provided

Title: A Huge Database: Picking the right schema and data model

Body:
We want to store some genomic variant data but there are some problems, more important ones like problem of the data's immense size and variability.

Variant data can be huge.  For example, a single individuals variant data could feasibly some day require a million rows of data in a table, or require of a gigabyte of raw storage on disk.  Multiply this over several thousand individuals, and you could potentially end up with terabytes worth of information that you need to make sense of.

Each client and/or system we integrate with, will expose or want to see data slightly differently depending on their needs and use cases.  This can potentially lead to hundreds of fields that we might need to store, all of which might need to be in different configurations based on the clients needs. So this variant data model will need to keep this in mind in order to remain easy to use, expandable and most
importantly, scalable in the long term.

What do you think is better for such a problem? We were thining of having some coulmns in each table that point to an external database or even a file, where we save the huge BLOB data?


答: It probably won't be the typical use people have for moving these things around, but.. it works, doesn't it?

Title: Wrong use of CSS3 Animations or not?

Body:
Well, I started using some CSS3 animations a couple of days ago. After hardcoding I've started trying different tools like Adobe Edge Preview version.

I made a short animation to get the functionality of the tool
http://things.eyemade.ch/css3edge/

After that someone at Twitter took a look at it and said that it is wrong using divs to paint things like these. But I'm not sure about that. Things changed over the last years and if we keep in mind this stuff is going to be used in many web/mobile games, is it really wrong to use divs this way nowadays?


问:
Is it common to use arrays everywhere with PHP?
I'm a fresh grad, and I just started workingin real world projects. I'm basically using PHP most of the time. I just figured out that most of the solutions I came out with for most of the problems, is involving using an array in somehow. What Am I doing wrong here? How could I unlearn this and always think of something else? Or is it the fault of the language?</p>

答:
Most programming is going to involve manipulating a collection of some sort, of which the array is the most basic type.  Other languages use Lists, Vectors and Dictionaries\Associative arrays a lot as well but PHP utilizes the same syntax for both associate arrays and numeric arrays.

Do you want to use other data types?  Sure, when you have a demonstrated performance problem or need a particular structure like a stack or queue.  Using a lot of various search structures and various sort and search algorithms for large data sets is often unnecessary due to databases.  This is of course provided you understand how to structure and index your tables properly.  If it helps, a few Fortran programmers used to think about various data structures as types of arrays.


答:
I've been using PHP for, I think, around 6 or 7 years now.  I find myself using arrays quite a bit. With built in sorting and looping functions, they are easy to work with and help manipulate data the way I need to.

Where you say "...or is it the fault of the language?" It's only a fault if it causes some problem, prevents you from solving a problem, or uses more resources than you might otherwise use, so I'd say there's likely no fault to be had.

Title: Is it common to use arrays everywhere with PHP?

Body: I'm a fresh grad, and I just started workingin real world projects. I'm basically using PHP most of the time. I just figured out that most of the solutions I came out with for most of the problems, is involving using an array in somehow. What Am I doing wrong here? How could I unlearn this and always think of something else? Or is it the fault of the language?</p>


问:
What to do when you find a security hole in your company's site
I have found a major security hole in one of my company's public facing site. This is our first public facing site that was converted from an intranet site. I brought this issue up to my boss and they essentially shrugged it off, saying that it would take a good deal of work to re-architecture the site to make it secure.

This has really bothered me and I have thought about exploiting the hole to show the effects that this could happen if an actual hacker got to it. This is probably not the best idea as the effects could cost me my job if not something worse.

What are some things I can do to show the magnitude of the situation to management?

答:
A manager's responsibility is to manage risk.

When a cross-scripting security hole was discovered in Gmail, this presented a very critical risk that the team quickly worked to resolve. Because there are millions of Gmail users, if I wrote a Web application that exploited this flaw, there would be a good chance that users of my Web application may be using Gmail and may have it open in another tab. Thus, as a phisher, it may be worth it to me to build such an application to gain access to user data.

The question your manager may be asking himself or herself is this:  How risky is this security hole? What is the likelihood that there is a Web application out there that is targeting this particular security hole on this particular site? What is the risk that employees who are visiting our Website are also using this third-party website?

In my experience, if your site isn't getting a ton of traffic, then there isn't a ton of risk.

Your boss may be thinking that the opportunity cost of not fixing this particular security hole which may or may not be a problem, is that he or she instead can focus resources on activities that will help grow the business and generate revenue.

With that said, there was an issue very similar to this where Github was hacked, and there is a question on Project Management SE that covers this topic from a project management perspective.  The user who hacked Github was in a similar situation as you, and his Github privileges were suspended for a time period.

My question to you is this: What happens to your business if the site does go down? What is the likelihood that you'll even see this security hole exploited?

If you do choose to pursue this, you'll need to objectively obtain evidence that this is a very real, imminent threat to the viability of the business.

Here are some suggestions for obtaining evidence that this is a real problem:

Perform Google searches looking for news articles, blogs or other experiences of companies that have experienced major issues as a result of a similar, related security hole. Demonstrate that this is indeed a risk that is worth addressing in lieu of other business opportunities.

Discuss with other technical personnel on the team and get their insight. If the issue is really severe, you should be able to find others who can back you up as well. If not, then either your concerns are not warranted or you have major issues in security in your company culture.

Discuss other options with your IT department for patching the hole that involve quicker-fix solutions that -- although not ideal -- may mitigate the risk and give you some peace of mind without breaking the corporate piggy bank. Sometimes a small amount of work can help eliminate some of the risk, if not all.

If the above points don't work, then my consider letting this go, and know that these issues are just going to be a normal part of business risk management.


问:
How to speak to a computer
I am a self-taught, novice programmer. The language I chose was Objective-C, so that I can write Apple applications and software. I have learned the hard way that Objective-C has a steep learning curve, but I have forced myself to look at it over and over until I get it right.

I feel I am completing one major step, and that is becoming very comfortable with the syntax. Now as I enter the next big step - finding out what is possible with a computer programming language - I am thinking that all software is just developed within the confines of:

classes

loops

booleans

IF/OR statements

variables

etc.

Is that a true assessment? When thinking of software in my head do I just need to learn to convert it all to the above? Right?

Sorry if this question sounds funny, but I am just learning how to take the language in and talk (what I think is) the language of a computer. Is there a good book or tutorial that helps illustrate how to "speak as a computer would"?

答:
First-Class Functions

Another useful feature that a programming language can have is first-class functions.  A first-class function is a function that can be used as data.

In a language in which you can treat functions as data, you can create variables that refer to them, pass them around as arguments to functions, and return them from functions.  Once case where you might use this is the famous map function.

Say that I just got some string from a file or something and that the string contains a series of integers separated by spaces.  Say I use a string-splitting function to get an array of strings containing each of the integers (still as strings).  I have access to a library function to parse an integer from a string, and I want to use it to convert each of these strings containing integers to actual integer values.  I create the new array and write a loop to convert each string and store the resulting integer in the new array.

Now say I want to take a different array of integers and find the absolute value of each and store the results in a new array.  I can use another loop to do this.  However, I have this pattern showing up in my code: start with an array, perform some transformation of each value in the array, and store all of the results in a new array.  I could just write out the code to do this each time, but there is a way to abstract out the process of creating the new array, looping, transforming, and storing.

I can write a function that takes as arguments

an array of type x

a function for somehow transforming objects of type x into objects of type y (possibly the same type as x)

and have it create an array of elements of type y of the correct length, loop over the values in the original array, call the function argument to do the transformation, store the results in the new array, and return the new array.

After I've written this function, map, I don't have to write this code out by hand any more.

Objective-C should have function pointers because C has them.

The way I described map also took advantage of some sort of generic typing.

Closures

Another feature is closures.  A closure is a function object that captures some of the variables that existed in the scope in which it was created.  What does that mean?

Some languages let you write function literals, functions that don't (necessarily) have names and just appear in you code without a special separate declaration.  When you write a function literal in another function, there might be variables in the same scope as the function literal.  There are situations where you might find it useful to use those variables inside of the function literal and have those variables stay with the function object.  Such a function object would be a closure.

Here's an example of code that I wrote that creates a closure (written in Common Lisp):

```<code>(defun exponential-change (function constant)
  (lambda (time)
    (* (expt constant time) (funcall function time))))
</code>```

(Don't ((let (the) parentheses) scare you)).  Think of it as being written like this:

```<code>function exponential_change (function, constant) {
    return function (time) {
        return exponent(constant, time) * function(time);
    };
}
</code>```

I wrote this for synthesizing sound.  I represent a sound as a function of time that returns amplitude samples (-1 to 1).  This function, exponential-change, transforms a sound by making the amplitude increase or decrease (depending on the constant) in an exponential fashion.  exponential-change creates returns a function of time based on another function of time.  The fact that the new function keeps track of what function it needs to modify prevents other code from having to keep track of that detail.

Closures not only keep track of the values of the variables they capture but also the variables themselves.  This means that you could create a function that modifies those variables.

Title: How to speak to a computer

Body:
First-Class Functions

Another useful feature that a programming language can have is first-class functions.  A first-class function is a function that can be used as data.

In a language in which you can treat functions as data, you can create variables that refer to them, pass them around as arguments to functions, and return them from functions.  Once case where you might use this is the famous map function.

Say that I just got some string from a file or something and that the string contains a series of integers separated by spaces.  Say I use a string-splitting function to get an array of strings containing each of the integers (still as strings).  I have access to a library function to parse an integer from a string, and I want to use it to convert each of these strings containing integers to actual integer values.  I create the new array and write a loop to convert each string and store the resulting integer in the new array.

Now say I want to take a different array of integers and find the absolute value of each and store the results in a new array.  I can use another loop to do this.  However, I have this pattern showing up in my code: start with an array, perform some transformation of each value in the array, and store all of the results in a new array.  I could just write out the code to do this each time, but there is a way to abstract out the process of creating the new array, looping, transforming, and storing.

I can write a function that takes as arguments

an array of type x

a function for somehow transforming objects of type x into objects of type y (possibly the same type as x)

and have it create an array of elements of type y of the correct length, loop over the values in the original array, call the function argument to do the transformation, store the results in the new array, and return the new array.

After I've written this function, map, I don't have to write this code out by hand any more.

Objective-C should have function pointers because C has them.

The way I described map also took advantage of some sort of generic typing.

Closures

Another feature is closures.  A closure is a function object that captures some of the variables that existed in the scope in which it was created.  What does that mean?

Some languages let you write function literals, functions that don't (necessarily) have names and just appear in you code without a special separate declaration.  When you write a function literal in another function, there might be variables in the same scope as the function literal.  There are situations where you might find it useful to use those variables inside of the function literal and have those variables stay with the function object.  Such a function object would be a closure.

Here's an example of code that I wrote that creates a closure (written in Common Lisp):

(defun exponential-change (function constant)
  (lambda (time)
    (* (expt constant time) (funcall function time))))

(Don't ((let (the) parentheses) scare you)).  Think of it as being written like this:

function exponential_change (function, constant) {
    return function (time) {
        return exponent(constant, time) * function(time);
    };
}

I wrote this for synthesizing sound.  I represent a sound as a function of time that returns amplitude samples (-1 to 1).  This function, exponential-change, transforms a sound by making the amplitude increase or decrease (depending on the constant) in an exponential fashion.  exponential-change creates returns a function of time based on another function of time.  The fact that the new function keeps track of what function it needs to modify prevents other code from having to keep track of that detail.

Closures not only keep track of the values of the variables they capture but also the variables themselves.  This means that you could create a function that modifies those variables.


问:
Are Java applets worth learning?
I'm on the way of learning Java myself. I find most of texts giving emphasis to Java applets. I got confused about the importance. Is it something widely used?  Do I need to spend more time on it?</p>

答:
Generally no, unless you have tried all other GUI platforms/frameworks and itching for something different.

Academically speaking, can provide a different perspective of GUI development whether it is for teaching or demostrations (some might say -ve demo :P ).

Title: Are Java applets worth learning?

ContentLicense: CC BY-SA 2.5


问:
Why do so many developers believe performance, readability, and maintainability cannot coexist?
While responding to this question, I began to wonder why so many developers believe a good design should not account for performance because doing so would affect readability and/or maintainability.

I believe that a good design also takes performance into consideration at the time it is written, and that a good developer with a good design can write an efficient program without adversely affecting readability or maintainability.

While I acknowledge that there are extreme cases, Why do many developers insist an efficient program/design will result in poor readability and/or poor maintainability, and consequently that performance should not be a design consideration?

答:
Because experienced programmers have learned that it's true.

We've worked with code that is lean and mean and doesn't have performance issues.

We've worked on a lot of code that, to address performance issues is VERY complex.

One immediate example that comes to mind is that my last project included 8,192 manually sharded SQL tables.  This was needed because of performance issues.  The setup to select from 1 table is a lot simpler than to select from and maintain 8,192 shards.


答:
If you have equity, push to schedule a weekly or monthly meeting to review security concerns and then this can just be an item on that agenda.  Moving the focus from the particular issue to the general area is often an effective technique.

If you don't have equity, move on.

You've raised the issue to management and they've passed.  You can try again if it's important to you.  And again if it's really important.  If it's really really really important, get another job and tell potential employers why.  The ones that value ethics the most will probably appreciate it.

Also bear in mind that if you've raised the issue and got a no you are now faced with changing people's mind which is very hard.  I would go down the path of getting them to agree with you and give you yes's.  e.g. "we both want the company to success". Yes.  "I know we both care about security". Yes.  "We know we've got a very limited budget to address such items". Yes.  Get a few of these then start steering towards some schedule for making the security fixes.

Another 'softer' approach is to agree that you don't have the time/resources to do this now.  But can you push for agreement on a date that it will be addressed.  It can be in a week, or a month, or 6 months.  Usually time flies and then you're there.

Title: What to do when you find a security hole in your company's site

Body:
I have found a major security hole in one of my company's public facing site. This is our first public facing site that was converted from an intranet site. I brought this issue up to my boss and they essentially shrugged it off, saying that it would take a good deal of work to re-architecture the site to make it secure.

This has really bothered me and I have thought about exploiting the hole to show the effects that this could happen if an actual hacker got to it. This is probably not the best idea as the effects could cost me my job if not something worse.

What are some things I can do to show the magnitude of the situation to management?


问:
How can Scrum be adapted to an academic environment?
I'm currently working with a professor at my university to develop new curricula for the Software Engineering and Capstone Design courses offered in my college.

Up until recently, both courses used the waterfall model exclusively, and thus students spent a majority of their time writing lengthy reports. After much pressure from me, my professor decided to include Scrum in the Software Engineering curriculum this past semester.

The first half of the semester was still waterfall-esque, with students writing 40-page design reports and software specification documents. Mid-semester, all teams were required to release a demo of their applications. At that point, the course switched to Scrum, with two 3-week sprints. We are now trying to figure out how to eliminate waterfall altogether and create an exclusively Scrum-based curriculum.

Unfortunately, we encountered a few incompatibilities between Scrum and the students:

Daily Scrum meetings are nearly impossible for students. Even during the class itself, it's inconvenient for students to hold Scrum meetings since the professor is usually lecturing.

Estimating points/hours is difficult, since students are inexperienced and therefore can't accurately predict how long something will take.

Scrum works best with full-time, co-located developers, but students are neither. At most, students dedicate 15-20 hours per week to the course, and organizing work meetings can be extremely difficult. Teams can have up to 10 students (and there's always one or two slackers).

Professors crave documentation! I haven't heard of any Scrum reports—just the backlogs and burndown charts (which I'm not sure will be enough to appease the academics).

Students often assume that agile means "Jump right in and start coding without looking back". This leads to some of the most horrible code imaginable. Therefore, I'm looking for a way to enforce proper design without requiring a 50-page document or a pile of UML diagrams.

Given these problems, how do you think my professor and I can adapt Scrum to function in an academic environment (and should we even bother with Scrum in the first place)? Also, is there still value to teaching the waterfall model?

Thanks in advance for any feedback!

答: Scrum works if you have a term/semester long project and the class is divided into 6 to 10 person groups. Then you could dedicate the last 10 minutes of class time to the scrum meeting.</p>


问:
UML, Dependency, and Martin Fowler's Data Mapper Diagram
I'm trying to get a better understanding of Dependency.

In Martin Fowler's explanation of the Data Mapper pattern, http://martinfowler.com/eaaCatalog/dataMapper.html, the UML diagram shows the Mapper being dependent on both the Domain Object and the Database.

It seems to me, however, that the Domain Object is dependent on the Mapper. For example, if the interface of the Mapper changes, the Domain Object may need to change.  I would have expected a dependency to be shown from the Domain to the Mapper.

At another level, I can see that the Mapper is dependent on the Domain Objects.  Domain Objects, of all classes, are likely to change, and sure, this is likely to cause changes in the Mapper.

I guess I'd feel happier if the Domain/Mapper dependency was bi-directional.  Am I missing something?  Or do I just need to loosen up a bit?  Perhaps Martin only shows the dependency in one direction because it is the overwhelmingly more important direction?

答:
Your domain object and the database should have no idea that a mapper exists.
Your mapper is created after the domain and the database has been created.  Hence the mapper is dependent on both the database and the object.

If you designed your domain object to have a "notion" that a mapper is in place,  It may mean that your domain object is highly coupled with the mapper which should not be the case.


问:
How is a "Software Developer" different from a "Software Consultant"? What makes a consultant?
I have seen a lot of people claiming themselves to be a "software consultant". These consultants do what a normal software developer does, write code, estimate tasks, fix bugs and attend meetings etc. The only difference being the financials, consultants end up earning more. Then how is a software developer different from a "consultant"?

In addition to the main question, I would like to know how can a software developer become a consultant? Are there any specific guidelines for a consultant? Do they need to amass certifications and write up research papers? Please do not confuse the software consultant with a management consultant. Software consultants I have seen are not managers.

答:
I know there are some companies that call themselves consulting companies but from what I understand they don't do much consulting in the traditional sense.

The only difference seems to be that they only employ experienced developers and are contracted out to large companies to do the work that they themselves could do in house but hopefully to a higher standard.


答:
Agree with mjfgates. Convention exists for a reason. If you think the reason is outdated, feel free to experiment. That said, convention also exists to make it easier for others to read your code. If you're making it harder for the rest of us to understand how you're doing what you're doing, then either

have a very good reason,

document it extremely well,

don't release it to the public,

or don't do it at all.

Title: Wrong use of CSS3 Animations or not?


问:
How to include database changes during application publish
I am maintaining a WinForms application, which talks to a SQL Server database. Sometimes I have to change database schema (for example to alter a sql procedure or add new one). For this purpose I have a SchemaChange.sql file, where I put the corresponding sql code.

When I create an installer for my project, the msi package is created. It contains my application, referenced assemblies, COM+ assemblies,... Alongside the msi package I provide an SchemaChange.sql file, which has to be run on the production sql server.

But sometimes I forget to add something to SchemaChange.sql file during development or I forget to execute it on production server after upgrading my application on client machines. Any advice how to automate this to avoid further problems?

答:
I like using Migrator.NET (and fluent migrator.net) for my projects.  All db schema changes are part of the solution, complete with rollback logic.  Each change or logic change is implemented as a 'migration' class, then it's simply a matter of upgrading to the latest version or rolling back to a specific version.

Migrator.NET stores the current migration version in your sql server database, so knows which set of migrations to apply to any database to bring it up to date.


答:
The way we do it is

The database schema is all stored in source code repository.

When a build is done a database is built from the scripts and a
backup is made of the empty schema and included in the installation
MSI.

When the MSI is run by the client we use the RedGate Compare
API to compare the packaged backup to the clients database. It then
dynamically creates an upgrade script and run on the client.

There are a couple more steps, like backing up the client database before running the scripts, but this is the gist of it.

The most important thing is version control the scripts and automating the upgrade process. Then not much can go wrong.

Title: How to include database changes during application publish

Body:
I am maintaining a WinForms application, which talks to a SQL Server database. Sometimes I have to change database schema (for example to alter a sql procedure or add new one). For this purpose I have a SchemaChange.sql file, where I put the corresponding sql code.

When I create an installer for my project, the msi package is created. It contains my application, referenced assemblies, COM+ assemblies,... Alongside the msi package I provide an SchemaChange.sql file, which has to be run on the production sql server.

But sometimes I forget to add something to SchemaChange.sql file during development or I forget to execute it on production server after upgrading my application on client machines. Any advice how to automate this to avoid further problems?


答:
Linux is an excellent environment for an enterprise programmer. You can configure and control your entire system from bits and pieces without any hassles of virus, malware, etc. Unlike windows, It doesn't suffer from an obsession to reboot after installing software and also, applications and environments tend to run better/efficiently on Linux. These days Ubuntu has made it possible that users can configure and use Linux as easily as a Mac or a Windows.

For a programmer it is even more better. C, C++, Python are pre installed. Be it java, groovy/grails, ruby/rails, or smalltalk. All of them run flawlessly on a Linux machine. If it is inevitable that you need to test your windows specific applications, you can always run wine and configure the dlls to get it running.

Within my Ubuntu system, I run Virtual box to manage Tiny core Linux and Bodhi Linux. I never installed Windows on virtual box but I have experienced it on one of my colleague's machine. It runs very smoothly without any hassles.

Title: Is Ubuntu workable as a laptop for an IT consultant?

Body:
I work as a consultant programmer, typically in large businesses. I use a Windows Laptop, and many of my colleagues use a Mac.

My personal preference would be to run Ubuntu if I could have complete control over my development environment. But I will have occasional need for Microsoft specific products, especially IE.

My colleagues that use a Mac often run Windows on a virtual machine for these situations.

My question is: Is Ubuntu a workable solution for the laptop of an enterprise programmer? For example, is it as easy to run Windows on a VM on Ubuntu as it is on a Mac? Has anyone out there tried this? Is there any particular reason why Ubuntu would not serve as well as a Mac for development in this environment?

Note that I am not doing .NET development, so I am typically dealing with Java that is going to be run on an Apache server and used by clients running Windows.


问:
Manual memory allocation and purity
Language like Haskell have concept of purity. In pure function, I can't mutate any state globally. Anyway Haskell fully abstracts memory management, so memory allocation is not a problem here.

But if languages can handle memory directly like C++, it's very ambiguous to me. In these languages, memory allocation makes visible mutation. But if I treat making new object as impure action, actually, almost nothing can be pure. So purity concept becomes almost useless.

How should I handle purity in languages have memory as visible global object?

答: Purity is a concept that doesn't become useless just because the programming language doesn't enforce it. Haskell may well be your best bet if you're looking for absolute assurance of purity, but that doesn't mean the concept is useless in C++. You can certainly increase the purity of code in C++, and that can certainly have a positive effect on its quality.</p>

Title: Manual memory allocation and purity


问:
Why does the Java collections APIs not have a last method?
This is for ordered collections e.g. java.util.List. Why did the language designers not include a last method? The only reasons I can think of are:

ambiguity when the collection is empty (return null or throw exception)

API bloat

Any other reasons?

答: The java.util.LinkedList defines the getLast() and getFirst() methods. Unfortunately these methods are not defined in one of it's interfaces, so you have to use the LinkedList type. If you are only interested in the last element you might consider to use the java.util.Queue interface's peek() method. LinkedList implements Queue.


问:
In agile environment, how is bug tracking and iteration tracking consolidated.
This topic stemmed from my other question about management-imposed waterfall-like schedule. From the responses in the other thread, I gathered this much about what is generally advised:

Each story should be completed with no bugs.  Story is not closed until all bugs have been addressed.  No news there and I think we can all agree with this.

If at a later date QA (or worse yet a customer) finds a bug, the report goes into a bug tracking database and also becomes a story which should be prioritized just like all other work.

Does this sum up general handling of bugs in agile environment?

If yes, the part I'm curious about is how do teams handle tracking in two different systems? (unless most teams don't have different systems).

I've read a lot of advice (including Joel's blog) on software development in general and specifically on importance of a good bug tracking tool. At the same time when you read books on agile methodology, none of them seem to cover this topic because in "pure" agile, you finish iteration with no bugs. Feels like there's a hole there somewhere.

So how do real teams operate? To track iterations you'd use (whiteboard, Rally...), to track bugs you'd use something from another set of products (if you are lucky enough, you might even get stuck with HP Quality Center).  Should there be 2 separate systems? If they are separate, do teams spend time creating import/sync functionality between them? What have you done in your company? Is bug tracking software even used? Or do you just go straight to creating a story?

答:
I think so the best way is to add bugs to your sprints and release that way you can track your bugs.

I got this idea from a new tool Yodiz it allows you to add bugs to sprints and releases


答:
C++ has the capability to provide such constructs/forms.

You could implement these abstraction layers, if you choose.

To enforce this, you might start by adding const to everything, then use objects' constructors to define their state, then introduce smart pointers, then probably realize it was slow and create thread local allocators, and so on…

Apparently, GHC will also output C programs -- perhaps this output would help visualize how it can be approached using C or C++?

Title: Manual memory allocation and purity

Body:
Language like Haskell have concept of purity. In pure function, I can't mutate any state globally. Anyway Haskell fully abstracts memory management, so memory allocation is not a problem here.

But if languages can handle memory directly like C++, it's very ambiguous to me. In these languages, memory allocation makes visible mutation. But if I treat making new object as impure action, actually, almost nothing can be pure. So purity concept becomes almost useless.

How should I handle purity in languages have memory as visible global object?


答:
Applets aren't used widely these days, so the knowledge won't be that useful.  That said, there is little in Java that is applet-specific.  It makes no difference if you learn AWT and Swing by writing applets or by writing desktop applications.  It's fairly easy to write an application that will also function as an applet.

The main distinction is that you use a different top-level container for applets than for applications.  Unsigned applets also have some security restrictions, particularly around IO and networking.

Title: Are Java applets worth learning?

Body: I'm on the way of learning Java myself. I find most of texts giving emphasis to Java applets. I got confused about the importance. Is it something widely used?  Do I need to spend more time on it?</p>


问:
Is overloading an example of the Open/closed principle?
Wikipedia says

"software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification"

The word functions caught my eyes, and I now wonder if we can assume that creating an overload for a method can be regarded as an example of the Open/closed principle or not?

Let me explain an example. Consider that you have a method in your service layer, which is used in almost 1000 places. The method gets userId and determines whether user is admin or not:

```<code>bool IsAdmin(userId)
</code>```

Now consider that somewhere it's necessary to determine if the user is admin or not, based on username, not userId. If we change the signature of the above-mentioned method, then we've broken code in 1000 places (functions should be closed to modification). Thus we can create an overload to get the username, find the userId based on username, and the original method:

```<code>public bool IsAdmin(string username)
{
    int userId = UserManager.GetUser(username).Id;
    return IsAdmin(userId);
}
</code>```

This way, we've extended our function through creating an overload for it (functions should be open to extension).

Is it an Open/closed principle example?

答:
I would personally interpret the wiki statement thusly:

for a class: feel free to inherit the class and override or
extend its functionality, but don't hack the original class thereby changing what it does.

for a module (maybe a library for
instance): feel free to write a new module/library that wraps the
original, merges functions into easier to use versions or extends
the original with extra features, but don't change the original
module.

for a function (ie a static function, not a class method):
your example is reasonable to me; reuse the original IsAdmin(int)
function inside the new IsAdmin(string). the original does not
change, the new func extends its functionality.

the shot in the foot however is that if your code is using the 'cUserInfo' class wherein IsAdmin(int) resides, you are essentially breaking the rule and changing the class.  the rule would sadly only be kept if you made a new class cUserWithNameInfo : public cUserInfo class and put your IsAdmin(string) override there.  If I owned the code base I'd never obey the rule. I'd say bollocks and just make the change you suggest.


答:
Modules that conform to the open-closed principle have two primary
attributes.

They are “Open For Extension”. This means that the behavior of the module can be extended. That we can make  the module behave in new and
different ways as the requirements of the application change, or to
meet the needs of new applications.

They are “Closed for Modiﬁcation”. The source code of such a module is inviolate. No one is allowed to make source  code changes to it.

By overloading your method you are extending functionality of existing module, thus meeting new needs of your application

You are not making any changes to an existing method, so you are not violating second rule.

I would be interested to hear what others have to say regarding not allowing to change original method. Yes, you can put appropriate access modifiers and enforce encapsulation, but what else can be done?

Ref: http://www.objectmentor.com/resources/articles/ocp.pdf

Title: Is overloading an example of the Open/closed principle?

Body:
Wikipedia says

"software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification"

The word functions caught my eyes, and I now wonder if we can assume that creating an overload for a method can be regarded as an example of the Open/closed principle or not?

Let me explain an example. Consider that you have a method in your service layer, which is used in almost 1000 places. The method gets userId and determines whether user is admin or not:

```<code>bool IsAdmin(userId)
</code>```

Now consider that somewhere it's necessary to determine if the user is admin or not, based on username, not userId. If we change the signature of the above-mentioned method, then we've broken code in 1000 places (functions should be closed to modification). Thus we can create an overload to get the username, find the userId based on username, and the original method:

```<code>public bool IsAdmin(string username)
{
    int userId = UserManager.GetUser(username).Id;
    return IsAdmin(userId);
}
</code>```

This way, we've extended our function through creating an overload for it (functions should be open to extension).

Is it an Open/closed principle example?


问:
A Huge Database: Picking the right schema and data model
We want to store some genomic variant data but there are some problems, more important ones like problem of the data's immense size and variability.

Variant data can be huge.  For example, a single individuals variant data could feasibly some day require a million rows of data in a table, or require of a gigabyte of raw storage on disk.  Multiply this over several thousand individuals, and you could potentially end up with terabytes worth of information that you need to make sense of.

Each client and/or system we integrate with, will expose or want to see data slightly differently depending on their needs and use cases.  This can potentially lead to hundreds of fields that we might need to store, all of which might need to be in different configurations based on the clients needs. So this variant data model will need to keep this in mind in order to remain easy to use, expandable and most
importantly, scalable in the long term.

What do you think is better for such a problem? We were thining of having some coulmns in each table that point to an external database or even a file, where we save the huge BLOB data?

答:
For (1), look for common things, you may be surprised with its extent. Thats the only way to solve size problem. That is how all normalization and even compression works: find patterns (a.k.a. common stuff), store it at one place, replace values with references at every place its used.

Another solution for (1), use file system instead of database wherever you can to save blob data. In oracle you can even index to search them later.

For (2), use views (more maintainable) or stored-procedures (less maintainable).

Another solution for (2), may be its better to build separate small applications for each set of your users. I assume you are not expecting millions of users, just a few hundred or a few thousand. Making 10 separate projects is more maintainable than a large one. Alternatively you can divide on bases of modules, in .net a dll is a module, in database a schema is. Use this solution if you don't find much in common among your users, if you do then use normalization.

Don't forget fundamental technique of indexing your tables!


问:
Do you perfect your code as you go or FINISH the product first, improve structure later
I recently read a blog post (which I lost the link) that really make me think. The writer said that the one of the biggest problem in software projects is actaully completing it, and most people will end up abandoning the work.

I have been self-learning programming for over 15 years now, at this stage I actually feel pretty competent. However, I have never finish any big project that I set out to do.

What I usually do is this:

I "sketch" my idea in code, compile and run to see if it works, and imagine how other stuff can come toogether.

As the "sketch" becomes messy, I start to refactor it, consolidate functions, make classes, re-organisation data structures etc.

Repeat 1 and 2.... forever!

I tried to write on paper UML diagrams etc. but it always end up with things I overlook and then requires some drastic changes and then I becomes 1, 2, 1, 2, 1, 2 again.

How does commercial projects handle deadlines? Should I just keep on sketching until the final product is completed before thinking of making the readability/reusability/architecture/engine more sound?

答:
Should I just keep on sketching until the final product is completed
  before thinking of making the
  readability/reusability/architecture/engine more sound?

Here is the thing. The final product probably doesn't even exist even in your dreams. How can it be completed? Compagnies are selling software with support, which precisely mean that the work will keep coming. The only "finished" projects are the dead ones (with a few exception).

So yes, if you are working in a compagny you should care about readability/reusability/architecture before the end of a project because you will be more productive (and there is no point in caring after ...). That said, caring about something does not mean that it should be perfect (I don't think this word has any meaning in softwares anyway). It means having a pragmatic approach about developpement, and not solving only short term problems by creating long term ones when there is no need to.

For your pet projects, do what you want. If you are the only user, do what you enjoy i.e add functionnalities or refactor. If you have other users, discuss the matter with them.


答:
The main difference between you and a company is that a company has to produce something or it loses money, so it normally gets hammered out before the molten metal cools.  By that I mean, while nothing is carved in stone, ideas are shaped and bent and a project begins its long cycle with the initial decisions made.  As time passes, it becomes increasingly difficult to change as you probably know by now.

However, where a normal programmer might scrap it in favor of a new design, deadlines at work make it so that you don't have that luxury so you have to make it work, performing whatever adjustments needed to get it done by the deadline.  The end result is that if it wasn't a well-shaped idea to begin with, it has bumps and scratches and generally looks like it was forcibly made to look that way rather than a piece of art.

While it's true everyone wants to stare at a piece of artwork, there's a fine line between making something which takes a long time to make but is done remarkably and something which is done sooner and is cost-effective for the time put into it.

With that said, I find myself doing exactly what you do at home.  1, 2, 1, 2.  The only conclusion I can gather is that there is so much room for improvement, that it's hard to ignore the flaws we've made thus far.

Title: Do you perfect your code as you go or FINISH the product first, improve structure later

Body:
I recently read a blog post (which I lost the link) that really make me think. The writer said that the one of the biggest problem in software projects is actaully completing it, and most people will end up abandoning the work.

I have been self-learning programming for over 15 years now, at this stage I actually feel pretty competent. However, I have never finish any big project that I set out to do.

What I usually do is this:

I "sketch" my idea in code, compile and run to see if it works, and imagine how other stuff can come toogether.

As the "sketch" becomes messy, I start to refactor it, consolidate functions, make classes, re-organisation data structures etc.

Repeat 1 and 2.... forever!

I tried to write on paper UML diagrams etc. but it always end up with things I overlook and then requires some drastic changes and then I becomes 1, 2, 1, 2, 1, 2 again.

How does commercial projects handle deadlines? Should I just keep on sketching until the final product is completed before thinking of making the readability/reusability/architecture/engine more sound?


问:
How to handle file access transactions properly?
I'm looking for good practices or any advice regarding file access transaction mechanisms. We will have multiple instances of an application spread over a redundant network (cloud) watching a directory on a 100% available NAS. I'm also looking for any alternative architecture that may be more appropriate.

We will have thousands of mobile devices accessing the system every minute. The devices produce a binary file (picture for example) that is sent to a RESTful service without transformation. The device must do the job quickly to preserve battery.

Since RESTful service must take the input as fast as possible, the binary file is currently written directly as a file in a 100% availability NAS.

If an error occurs (file not being written correctly), the client is notified and can try again.

We must build a worker service that will watch the file folder for new files to process them. The worker will convert them to another format then move them to another folder on the NAS. We will use as many instances as possible to handle load.

My main concern is about file access. The RESTful service is writing to a temporary file with an extension that the worker service is ignoring (.tmp), then after the last byte is written, the file is renamed. The process is quick, but we can't afford the case where 2 or more worker services access the same file at the same time.

We need some transaction mechanism or any other entreprise architecture pattern.

Is there any kind of file system transaction mechanism that scales?

答:
A database for example would handle this situation in a transactional and  almost any db excepting MSAccess and SQLite will handle this quicker, more reliably and more efficiently than file access.

Another possibility is to use one of the many available Queue Managers (RabbitMQ,WebsphereMQ etc.) which would also ease any scheduling and load balancing problems you have.


答:
Welcome to the wonderful world of Project Management plc!

I've found that there are two extremes to programmers/developers:

The Ship-it-now

The Charles Winchester

The first type should be self-explanatory (they're the type of developer who wants to get the work done and shipped as fast as possible, fixing any bugs later), whereas the second type may need a quote to explain:

```<code>I do one thing at a time. I do it very well. And then I move on - Charles Emmerson Winchester III (MASH)
</code>```

It's the difference between writing an app that calculates a percentage for a given value using a command line interface with no checking (Ship-it-now), and a version with full input checking, rounding error notification and a custom GUI.

The process I use to write software is:

write the code (as per the spec/design document, or as close to it as is possible)

before it's committed ask myself "am I happy (within reason) with this code?"

ask a fellow developer if I can talk through the code with them

That way I can explain why I did things the way I did and they can give me input before I refactor/re-design or commit it back to the master branch.

You could spend years and years re-factoring or re-implementing code, fixing new bugs as they arise (and they will) or you could ignore feature creep and the need to redesign and ship something actually that works (with a few bugs... maybe).

As others have stated, it sounds like you might be working on your own (not part of a development company). At the end of the day, a development company HAS to have something to sell, otherwise they'll go out of business very fast. To that end, most project managers will not allow a developer to keep working on a piece of code that (to all intents and purposes) works, but looks a little nasty.

Don't get me wrong, I used to code they way you describe. But this was for pet projects or for unimportant code that would be given to relatives/friends.

Imagine that you're building a car or a house. You don't want to sell something that doesn't work (caught in the refactoring/re-design stage for too long and there are real projects that are like this - the big one of recent times was Duke Nukem Forever), but you also don't want to sell something that has major problems either. You need to figure out the best balance. Hopefully, the best balance would be a completed product with few to no problems (any huge piece of software that you can think of); but that's not always the case.

Giving yourself deadlines might help to teach yourself the necessary skills in project management. I know that when I was at uni, all of my assignments had a 25% time management mark - if you couldn't prove that you'd managed your time well (Gantt charts, recorded lecture and tutorial attendance, recorded use of the labs, etc.) you'd lose marks and potentially drop a grade.

Body:
Welcome to the wonderful world of Project Management plc!

I've found that there are two extremes to programmers/developers:

The Ship-it-now

The Charles Winchester

The first type should be self-explanatory (they're the type of developer who wants to get the work done and shipped as fast as possible, fixing any bugs later), whereas the second type may need a quote to explain:

I do one thing at a time. I do it very well. And then I move on - Charles Emmerson Winchester III (MASH)

It's the difference between writing an app that calculates a percentage for a given value using a command line interface with no checking (Ship-it-now), and a version with full input checking, rounding error notification and a custom GUI.

The process I use to write software is:

write the code (as per the spec/design document, or as close to it as is possible)

before it's committed ask myself "am I happy (within reason) with this code?"

ask a fellow developer if I can talk through the code with them

That way I can explain why I did things the way I did and they can give me input before I refactor/re-design or commit it back to the master branch.

You could spend years and years re-factoring or re-implementing code, fixing new bugs as they arise (and they will) or you could ignore feature creep and the need to redesign and ship something actually that works (with a few bugs... maybe).

As others have stated, it sounds like you might be working on your own (not part of a development company). At the end of the day, a development company HAS to have something to sell, otherwise they'll go out of business very fast. To that end, most project managers will not allow a developer to keep working on a piece of code that (to all intents and purposes) works, but looks a little nasty.

Don't get me wrong, I used to code they way you describe. But this was for pet projects or for unimportant code that would be given to relatives/friends.

Imagine that you're building a car or a house. You don't want to sell something that doesn't work (caught in the refactoring/re-design stage for too long and there are real projects that are like this - the big one of recent times was Duke Nukem Forever), but you also don't want to sell something that has major problems either. You need to figure out the best balance. Hopefully, the best balance would be a completed product with few to no problems (any huge piece of software that you can think of); but that's not always the case.

Giving yourself deadlines might help to teach yourself the necessary skills in project management. I know that when I was at uni, all of my assignments had a 25% time management mark - if you couldn't prove that you'd managed your time well (Gantt charts, recorded lecture and tutorial attendance, recorded use of the labs, etc.) you'd lose marks and potentially drop a grade.


问:
How do you deal with the anxiety of not knowing enough?
I just finished college a couple of months ago and I'm taking time out to improve my knowledge. I love programming but I feel like I don't know enough to be confident if I went for an interview. Last night I was browsing through questions and came across a question that asks interviewees how to work out a linked list. I learned these at college but if I was asked on the spot how to do it I wouldn't know. So that's another thing added to the list of what to learn.

This is when the anxiety hit me because I have so much to learn in so little time (at least it feels that way). Upon introspection, I think this anxiety is related to my perfectionism even though being perfect isn't rational e.g. Shakespeare and Einstein failed 80% of the time.

So the questions are, have you felt this anxiety of not knowing enough? If so, how did you deal with it? I suppose there's a point in time when you begin to feel comfortable in your abilities?

答:
Expect that you don't know enough. That's a sure thing. Either because you have gaps or because people just want to see how you handle situations you're not familiar with.

Break problems down into solvable or familiar pieces. If you don't know something important, try to direct the talk to something you know.


答:
My understanding from your description is, for RESTful service:

Input:

1- A file (and its name)

Output:
1- A temp file

2- A renamed temp file

Problem:

Prevent file access by 2 services.

Suggestion:

Based on this, if you name the temp file in output (1) with a unique name for every file, such as GUID+any file name then you can generate a safe and unique temp file name. Only the service instance that created the temp file knows that GUID. That same instance would use the same value to rename the temp file after it is moved away from the temp folder.

Title: How to handle file access transactions properly?

Body:
I'm looking for good practices or any advice regarding file access transaction mechanisms. We will have multiple instances of an application spread over a redundant network (cloud) watching a directory on a 100% available NAS. I'm also looking for any alternative architecture that may be more appropriate.

We will have thousands of mobile devices accessing the system every minute. The devices produce a binary file (picture for example) that is sent to a RESTful service without transformation. The device must do the job quickly to preserve battery.

Since RESTful service must take the input as fast as possible, the binary file is currently written directly as a file in a 100% availability NAS.

If an error occurs (file not being written correctly), the client is notified and can try again.

We must build a worker service that will watch the file folder for new files to process them. The worker will convert them to another format then move them to another folder on the NAS. We will use as many instances as possible to handle load.

My main concern is about file access. The RESTful service is writing to a temporary file with an extension that the worker service is ignoring (.tmp), then after the last byte is written, the file is renamed. The process is quick, but we can't afford the case where 2 or more worker services access the same file at the same time.

We need some transaction mechanism or any other entreprise architecture pattern.

Is there any kind of file system transaction mechanism that scales?


问:
OOP :What are some of the situations in which class based design is better than interface based one?
I was reading  JDOM's website.

Why is the JDOM API defined in terms of concrete classes rather than interfaces?

Jason Hunter summarizes the arguments against an interface-based API for JDOM:

With interfaces everything becomes a factory, elements have to be 'imported' into new documents instead of just added, features like long-term serialization cannot be guaranteed, and the list goes on.

We started with interfaces actually. During our pre-release review to some peers we received the feedback we should try concrete classes. We did, and the design was much better for it.

I am a beginner designer. All the advice I have heard about till now is advising against using designing with concrete classes.

May be using concrete classes are appropriate in certain places. Are there any common class problems for which using concrete classes in design is okay?

答:
You generally want an interface for anything that gets passed as a parameter or returned, essentially so you can decouple the class from its dependencies.

SO if we are looking for a class we never pass around normally exceptions spring to mind. I'm not a Java developer, but certainly in other similar languages I don't think I've seen interfaces defined for exceptions.


答:
First off, your example is unfortunately contrived. You'd never do that in the real world, because it causes an unnecessary double-get. Or, worse, because userid and username might become the same type at some point. Rather than

```<code>public bool IsAdmin(int userid)
{
    User user = UserManager.GetUser(userid);
    return user.IsAdmin();
}

public bool IsAdmin(string username)
{
    int userId = UserManager.GetUser(username).Id;
    return IsAdmin(userId);
}
</code>```

You should really extend that class.

```<code>public bool IsAdmin(int userid)
{
    User user = UserManager.GetUserById(userid);
    return user.IsAdmin();
}

public bool IsUsernameAdmin(string username)
{
    User userId = UserManager.GetUserByName(username);
    return user.IsAdmin();
}
</code>```

You might further refactor and change the first method name to IsUserIdAdmin, for consistency, but it's not necessary. The point is that, in adding the new method and guaranteeing no calling code is broken, you have found your class to be extensible. Or in other words, open to extension.

And here's the thing with the open-closed principle. You never really know how well your code conforms until you try to extend part of it and find yourself having to modify instead (with the increased risk that comes with that). But, with experience, you learn to predict.

As Uncle Bob says (emphasis mine):

Since closure cannot be complete, it must be strategic. That is, the designer must
  choose the kinds of changes against which to close his design. This takes a certain amount
  of prescience derived from experience. The experienced designer knows the users and the
  industry well enough to judge the probability of different kinds of changes. He then makes
  sure that the open-closed principle is invoked for the most probable changes.

Body:
First off, your example is unfortunately contrived. You'd never do that in the real world, because it causes an unnecessary double-get. Or, worse, because userid and username might become the same type at some point. Rather than

public bool IsAdmin(int userid)
{
    User user = UserManager.GetUser(userid);
    return user.IsAdmin();
}

public bool IsAdmin(string username)
{
    int userId = UserManager.GetUser(username).Id;
    return IsAdmin(userId);
}

You should really extend that class.

public bool IsAdmin(int userid)
{
    User user = UserManager.GetUserById(userid);
    return user.IsAdmin();
}

public bool IsUsernameAdmin(string username)
{
    User userId = UserManager.GetUserByName(username);
    return user.IsAdmin();
}

You might further refactor and change the first method name to IsUserIdAdmin, for consistency, but it's not necessary. The point is that, in adding the new method and guaranteeing no calling code is broken, you have found your class to be extensible. Or in other words, open to extension.

And here's the thing with the open-closed principle. You never really know how well your code conforms until you try to extend part of it and find yourself having to modify instead (with the increased risk that comes with that). But, with experience, you learn to predict.

As Uncle Bob says (emphasis mine):

Since closure cannot be complete, it must be strategic. That is, the designer must
  choose the kinds of changes against which to close his design. This takes a certain amount
  of prescience derived from experience. The experienced designer knows the users and the
  industry well enough to judge the probability of different kinds of changes. He then makes
  sure that the open-closed principle is invoked for the most probable changes.


问:
Replacing dao layer
I am developing a series of webservices (based on spring and spring mvc).

For the first time in my dev career I do plan on replacing the dao layer in the future(I have always seen it mentioned but never had to do it).

Currently I'm using spring annotations, so I could simply change the qualifier name of the injected dao in each place it is used; is there a better (global) mechanism I could use ?

Currently my code looks like this (declaring the dao) :

```<code>@Repository("regionDao")
public class RegionDao implements IRegionDao
</code>```

and Injecting it :

```<code>@Resource(name = "regionDao")
IRegionDao regionDao;
</code>```

But going into each service class and changing the qualifier name seems rather long winded, is their a better way. Basically in the future I want to flip a switch and each reference to a regionDao will then point to newRegionDao and so on for other dao's.

A solution using annotations is preferred- for no other reason than I subjectively prefer them. But I realize this may be a case for xml based config ?

答:
Personally I fail to see what could be easier than changing the name of the Resource that I am injecting into my Service classes and integration tests.  Even in a large system where you have hundreds of DAO's this will only take you what, 2 hours at most?  And besides, you can just make an intern or fresher do it :)

For a truly one step process, I suggest configuring Spring through XML documents however.  I know this isn't what you want to hear because I personally love Annotation based configuration as well, but considering that you anticipate a high likelihood of shifting data layers in the future then this could be a better idea for a number of reasons.

Also consider a system that you may need to deploy into very different configuration environments, possibly for different customers.  Where I work we are a software vendor and our two major clients for one of our products both have different needs to host our software.  One client has an enterprise license to Oracle, while the other has an enterprise license to SQL Server, neither of which want to spend additional money on database licenses and support for a single system, and rightfully so.

Creating a seperate Spring DAO configuration XML for each client at that point becomes a necessity for an automated build script that include the appropriate DAO configuration XML for the client build in question.  So basically as clean as annotations may look and as easy as it makes deciphering the purpose and configuration of a class, annotations are essentially useless to me in this scenario.

Title: Replacing dao layer


答:
Inheritance creates dependencies on implementation, which might be a big problem regarding maintainability. The corollary of this is that you can safely use inheritance and concrete classes when dealing with data transfer object, which by definition contain almost no implementation. You can also use inheritance of concrete classes when you want this dependency. You might want to use an abstract class containing the common methods (usually utility functions) at the the top of the hierarchy in this situation.

When using a concrete class hierarchy, do not forget to apply the Liskov Substitution Principle.

There is no problem with using concrete classes for clients (i.e. classes that uses, not classes that are used).

IMHO you can use concrete classes until there are things to change. The Open/Closed Principle  would tell you to use interfaces to avoid coupling, but regarding the You Ain't Gonna Need It Principle you might consider using concrete classes until the moment when you need to change something in the implementation. The problem is that you would have to change every client of your classes the first time something changes somewhere. While you only have one possible tool to do something, you can use concrete classes IMO.

[EDIT] JDOM's website takes java.io.File as an example, but this is definitely an interface based design as one can manipulate a java.io.File instance as if it were only a Serializable. In this situation only "creators" would know the concrete class

Title: OOP :What are some of the situations in which class based design is better than interface based one?

Body:
I was reading  JDOM's website.

Why is the JDOM API defined in terms of concrete classes rather than interfaces?

Jason Hunter summarizes the arguments against an interface-based API for JDOM:

With interfaces everything becomes a factory, elements have to be 'imported' into new documents instead of just added, features like long-term serialization cannot be guaranteed, and the list goes on.

We started with interfaces actually. During our pre-release review to some peers we received the feedback we should try concrete classes. We did, and the design was much better for it.

I am a beginner designer. All the advice I have heard about till now is advising against using designing with concrete classes.

May be using concrete classes are appropriate in certain places. Are there any common class problems for which using concrete classes in design is okay?