问:
Why do programming languages allow shadowing/hiding of variables and functions?
Many of the most popular programming languges (such as C++, Java, Python etc.) have the concept of hiding / shadowing of variables or functions. When I've encountered hiding or shadowing they have been the cause of hard to find bugs and I've never seen a case where I found it necessary to use these features of the languages.

To me it would seem better to disallow hiding and shadowing.

Does anybody know of a good use of these concepts?

Update:

I'm not refering to encapsulation of class members (private/protected members).

答:
Here are my two cents.

Programs can be structured into blocks (functions, procedures) that are self-contained units of program logic.
Each block can refer to "things" (variables, functions, procedures) using names / identifiers. This mapping from names to things is called binding.

The names used by a block fall into three categories:

Locally defined names, e.g. local variables, that are only known inside the block.

Arguments that are bound to values when the block is invoked and can be used by the caller to specify input / output parameter of the block.

External names / bindings that are defined in the environment in which the block is contained and are in scope within the block.

Consider for example the following C program

```<code>#include<stdio.h>

void print_double_int(int n)
{
  int d = n * 2;

  printf("%d\n", d);
}

int main(int argc, char *argv[])
{
  print_double_int(4);
}
</code>```

The function print_double_int has a local name (local variable) d, and argument n, and uses the external, global name printf, which is in scope but not defined locally.

Notice that printf could also be passed as an argument:

```<code>#include<stdio.h>

void print_double_int(int n, int printf(const char *, ...))
{
  int d = n * 2;

  printf("%d\n", d);
}

int main(int argc, char *argv[])
{
  print_double_int(4, printf);
}
</code>```

Normally, an argument is used to specify input / output parameters of a function (procedure, block), whereas global names are used to refer to things like library functions that "exist in the environment", and therefore it is more convenient to mention them only when they are needed.
Using arguments instead of global names is the main idea of dependency injection, which is used when dependencies must be made explicit instead of being resolved by looking at the context.

Another similar use of externally defined names can be found in closures. In this case a name defined in the lexical context of a block can be used within the block, and the value bound to that name will (typically) continue to exist as long the block refers to it.

Take for example this Scala code:

```<code>object ClosureExample
{
  def createMultiplier(n: Int) = (m: Int) => m * n

  def main(args: Array[String])
  {
    val multiplier3 = createMultiplier(3)
    val multiplier5 = createMultiplier(5)

    // Prints 6.
    println(multiplier3(2))

    // Prints 10.
    println(multiplier5(2))
  }
}
</code>```

The return value of the function createMultiplier is the closure (m: Int) => m * n, which contains the argument m and the external name n. The name n is resolved by looking at the context in which the closure is defined: the name is bound to the argument n of function createMultiplier. Notice that this binding is created when the closure is created, i.e. when createMultiplier is invoked. So the name n is bound to the actual value of an argument for a particular invocation of the function. Contrast this with the case of a library function like printf, which is resolved by the linker when the program's executable is built.

Summarizing, it can be useful to refer to external names inside a local block of code so that you

don't need / want to pass externally defined names explicitly as arguments, and

you can freeze bindings at runtime when a block is created, and then access it later when the block is invoked.

Shadowing comes in when you consider that in a block you are only interested in relevant names that are defined in the environment, e.g. in the printf function that you want to use. If by chance you want to use a local name (getc, putc, scanf, ...) that has already been used in the environment, you simple want to ignore (shadow) the global name.
So, when thinking locally, you do not want to consider the whole (possibly very big) context.

In the other direction, when thinking globally, you want to ignore the internal details of the local contexts (encapsulation). Therefore you need shadowing, otherwise adding a global name could break every local block that was using that name already.

Bottom line, if you want a block of code to refer to externally defined bindings, you need shadowing to protect local names from global ones.

Body:
Here are my two cents.

Programs can be structured into blocks (functions, procedures) that are self-contained units of program logic.
Each block can refer to "things" (variables, functions, procedures) using names / identifiers. This mapping from names to things is called binding.

The names used by a block fall into three categories:

Locally defined names, e.g. local variables, that are only known inside the block.

Arguments that are bound to values when the block is invoked and can be used by the caller to specify input / output parameter of the block.

External names / bindings that are defined in the environment in which the block is contained and are in scope within the block.

Consider for example the following C program

#include<stdio.h>

void print_double_int(int n)
{
  int d = n * 2;

  printf("%d\n", d);
}

int main(int argc, char *argv[])
{
  print_double_int(4);
}

The function print_double_int has a local name (local variable) d, and argument n, and uses the external, global name printf, which is in scope but not defined locally.

Notice that printf could also be passed as an argument:

#include<stdio.h>

void print_double_int(int n, int printf(const char *, ...))
{
  int d = n * 2;

  printf("%d\n", d);
}

int main(int argc, char *argv[])
{
  print_double_int(4, printf);
}

Normally, an argument is used to specify input / output parameters of a function (procedure, block), whereas global names are used to refer to things like library functions that "exist in the environment", and therefore it is more convenient to mention them only when they are needed.
Using arguments instead of global names is the main idea of dependency injection, which is used when dependencies must be made explicit instead of being resolved by looking at the context.

Another similar use of externally defined names can be found in closures. In this case a name defined in the lexical context of a block can be used within the block, and the value bound to that name will (typically) continue to exist as long the block refers to it.

Take for example this Scala code:

object ClosureExample
{
  def createMultiplier(n: Int) = (m: Int) => m * n

  def main(args: Array[String])
  {
    val multiplier3 = createMultiplier(3)
    val multiplier5 = createMultiplier(5)

    // Prints 6.
    println(multiplier3(2))

    // Prints 10.
    println(multiplier5(2))
  }
}

The return value of the function createMultiplier is the closure (m: Int) => m * n, which contains the argument m and the external name n. The name n is resolved by looking at the context in which the closure is defined: the name is bound to the argument n of function createMultiplier. Notice that this binding is created when the closure is created, i.e. when createMultiplier is invoked. So the name n is bound to the actual value of an argument for a particular invocation of the function. Contrast this with the case of a library function like printf, which is resolved by the linker when the program's executable is built.

Summarizing, it can be useful to refer to external names inside a local block of code so that you

don't need / want to pass externally defined names explicitly as arguments, and

you can freeze bindings at runtime when a block is created, and then access it later when the block is invoked.

Shadowing comes in when you consider that in a block you are only interested in relevant names that are defined in the environment, e.g. in the printf function that you want to use. If by chance you want to use a local name (getc, putc, scanf, ...) that has already been used in the environment, you simple want to ignore (shadow) the global name.
So, when thinking locally, you do not want to consider the whole (possibly very big) context.

In the other direction, when thinking globally, you want to ignore the internal details of the local contexts (encapsulation). Therefore you need shadowing, otherwise adding a global name could break every local block that was using that name already.

Bottom line, if you want a block of code to refer to externally defined bindings, you need shadowing to protect local names from global ones.


问:
How bad is it to have two methods with the same name but different signatures in two classes?
I have a design problem related to a public interface, the names of methods, and the understanding of my API and code.

I have two classes like this:

```<code>class A:
    ...
    function collision(self):
        ....

...

class B:
    ....
    function _collision(self, another_object, l, r, t, b):
        ....
</code>```

The first class has one public method named collision, and the second has one private method called _collision. The two methods differs in argument type and number.

As an example let's say that _collision checks if the object is colliding with another object with certain conditions l, r, t, b (collide on the left side, right side, etc) and returns true or false. The public collision method, on the other hand, resolves all the collisions of the object with other objects.

The two methods have the same name because I think it's better to avoid overloading the design with different names for methods that do almost the same thing, but in distinct contexts and classes.

Is this clear enough to the reader or I should change the method's name?

答:
These functions both have to do with collisions, but what they do is very different, so giving them names that more clearly describe what they actually do will make it easier for future developers to understand the difference without having to look at the logic inside.

The method that checks if the object is colliding with another object could be called checkForCollision.

The method that resolves collisions of the object with other objects could be called resolveCollisions or handleCollisions.

When two functions do almost the same thing is often the best time to give them more specific names to make their difference clear.

ContentLicense: CC BY-SA 3.0


问:
Subclassing to avoid line length
The standard line length of code is 80 characters per line. This is accepted and followed by the most of programmers.

I working on a state machine of a character and is necessary for me follow this too.

I have four classes who pass this limit.

I can subclass each class in two more and then avoid the line length limit.

```<code>class Stand

class Walk

class Punch

class Crouch
</code>```

The new classes would be StandLeft, StandRight and so on. Stand, Walk, Punch and Crouch would be then abstract classes.

The question if there is a limit for the long of the hierarchies tree or this is depends of the case.

答:
Subclasses and subtypes bring a lot of baggage with them in the form of inheritence and the desirabality of supporting the Liskov Substitution Principle.  It would be pretty foolish to start creating subclasses simply to support an arbitrary naming convention.

It's unclear why you would need separate classes for what you are describing.  How is StandLeft significantly different from StandRight?  can you separate them and use composition instead?  That is, the Stand class has an attribute called direction, which is in turn a Left or Right implementation of the IDirection interface:

```<code>class Stand {
    private IDirection direction;
    ...
}
</code>```

The IDirection object would either define useful state information or a different strategy for how the Stand object should behave.

Title: Subclassing to avoid line length

Body:
Subclasses and subtypes bring a lot of baggage with them in the form of inheritence and the desirabality of supporting the Liskov Substitution Principle.  It would be pretty foolish to start creating subclasses simply to support an arbitrary naming convention.

It's unclear why you would need separate classes for what you are describing.  How is StandLeft significantly different from StandRight?  can you separate them and use composition instead?  That is, the Stand class has an attribute called direction, which is in turn a Left or Right implementation of the IDirection interface:

class Stand {
    private IDirection direction;
    ...
}

The IDirection object would either define useful state information or a different strategy for how the Stand object should behave.


答:
As far as I'm aware, there's no hard limit in terms of class hierarchy as far as coding conventions or anything like that go, but you need to make sure making more subclasses and such is really the answer.

I would never recommend making more subclasses to help limit the number of characters per line.  Usually you solve a problem like that just by concatenating strings, using more variables, etc.

Title: Subclassing to avoid line length

Body:
The standard line length of code is 80 characters per line. This is accepted and followed by the most of programmers.

I working on a state machine of a character and is necessary for me follow this too.

I have four classes who pass this limit.

I can subclass each class in two more and then avoid the line length limit.

```<code>class Stand

class Walk

class Punch

class Crouch
</code>```

The new classes would be StandLeft, StandRight and so on. Stand, Walk, Punch and Crouch would be then abstract classes.

The question if there is a limit for the long of the hierarchies tree or this is depends of the case.


问:
UI design and confirmation paradigm
I just saw this lecture by Spolsky, where he questions the need for choices and confirmation dialogs. At some point he has a MacOS settings window and he mentions that "now some are getting rid of the OK button". The window indeed has no OK (or cancel) button. Changing a setting makes it change, when you're done configuring, you close that window, period.

Being a long time Windows user and a recent Mac owner, the difference is noticeable at first. I looked for the OK button for a while, only to find out, quite naturally and painlessly, that there was none. I expressed satisfaction and went on my merry way.

However, I'm curious to know if this UI design pattern would succeed in the Windows-based world. Granted that if Microsoft brought it out with say Windows-8 (fat chance, I know), people would get used to it eventually. But is there some experience out there of such an approach, of changing the "confirmation paradigm" on a platform where it's so prevalent? Did it leave users (especially the non-technical ones) confused, frustrated, scared, or happy?

TL;DR: Remove OK/cancel confirmation, what happens?

EDIT:

Mac GUI for appearance settings.

答: If there's no OK/Cancel, there better be Undo.</p>

ContentLicense: CC BY-SA 2.5

Title: UI design and confirmation paradigm


问:
How should I evaluate the Database Solution for Large Data Application
Background

I have been tasked to write an application that will be a combination of document and inventory management in VB.net which will be used to store document images in TIFF, PDF, XPS, TXT, DOC, PPT and so on as binary data that can be retrieved for viewing, printing, and possible OCR to be searchable as well along with meta data such as sender, recipient, type of document, date, source, etc. So the table would probably be something like:

DOC_NAME, DOC_DATE, NOTES, ... DOC_BINARY (where the actual document will be put inside)

Help Please

I need help with understanding how to evaluate my database options.

What my concern is finding a database solution that will not become unstable due to size restrictions, records limitations and performance. Some of the options are MS_SQL, SQL Express, SQLite, mySQL, and Access. Now I can pretty much eliminate Access right off the bat as it is just too limiting and not scalable. I can further eliminate SQL Express because of the 2 GB limit and again scalability.

So I believe that leaves me with MS_SQL, SQLite and mySQL (note, I am open to alternatives). And this is where I need help in understanding how to evaluate those databases.

The goal is that the data is all in one place (a single file) that will make backup and portability easier. For small volume usage, pretty much any solution will hold for a while, but my goal is to think ahead and make sure its able to withstand heavy large volume usage as well. Another consideration is also the interoperability with .NET and stability of such code to avoid errors and memory leaks.

How should I evaluate my database options for this scenario?

答:
2gb limit is very old -- IIRC that was MSDE, which you could call Sql Express 2000. 2005 had 4gb, 2008 had 8gb and I think 2012 has 10gb limits.

Anyhow, since all SQL Express is is a hamstrung version of SQL server the path I would take is to build / test against and distribute for SQL Express and let folks upsize to full-blown SQL Servers when they need it. As long as the database connection is configurable this is a zero code impact change.

The SQL Server family has some advantages for what you want to do -- there are free SKUs that should get you out of the gate, the VB.NET integration is sweet (though it won't help you avoid memory leaks) and FILESTREAM support will help you handle the BLOBs.


问:
Requiring a specific order of compilaiton
When designing a compiled programming language, is it a bad idea to require a specific order of compilation of separate units, according to their dependencies?

To illustrate what I mean, consider C. C is the opposite of what I'm suggesting. There are multiple .c files, that can all depend on each other, but all of these separate units can be compiled on their own, in no particular order - only to be linked together into a final executable later.

This is mostly due to header files. They enable separate units to share information with each other, and thus the units are able to be compiled independently.

If a language were to dispose of header files, and only keep source and object files, then the only option would be to actually include the unit's meta-information in the unit's object file.

However, this would mean that if the unit A depends on the unit B, then the unit B would need to be compiled before unit A, so unit A could "import" the unit B's object file, thus obtaining the information required for its compilation.

Am I missing something here? Is this really the only way to go about removing header files in compiled languages?

答:
One possible way is to generate metadata ("header files") for each compilation unit first. This normally does not require any dependency and can be performed independently.

Then when actual do type checking/code generation, each compilation unit can refer to other's metadata to get type information.

Otherwise you will have problem if unit A import unit B and unit B also import unit A, you cannot compile any of them without compile other one first.


答:
The approach you're describing is what languages like Java and C# do.  Instead of header files, the metadata is compiled into the object file.  Those languages also don't compile each source file in a module (a .jar or .dll) separately; they take all the source files that make up a project and compile them all together, and then link them into an executable or library.

A consequence is that the modules' dependencies will dictate the compilation sequence.  If module B depends on (references) module A, then module A must be compiled and linked first, so that module B can reference the metadata when it gets compiled.  If classes in those modules really have a circular reference to each other, then those classes must be in the same module.

It's hard to see another approach. The linker needs to know the metadata of a compiled module, so that information has to be available somewhere.  Either it's in source code, like a header file, or it's in the object code.

Title: Requiring a specific order of compilaiton

Body:
When designing a compiled programming language, is it a bad idea to require a specific order of compilation of separate units, according to their dependencies?

To illustrate what I mean, consider C. C is the opposite of what I'm suggesting. There are multiple .c files, that can all depend on each other, but all of these separate units can be compiled on their own, in no particular order - only to be linked together into a final executable later.

This is mostly due to header files. They enable separate units to share information with each other, and thus the units are able to be compiled independently.

If a language were to dispose of header files, and only keep source and object files, then the only option would be to actually include the unit's meta-information in the unit's object file.

However, this would mean that if the unit A depends on the unit B, then the unit B would need to be compiled before unit A, so unit A could "import" the unit B's object file, thus obtaining the information required for its compilation.

Am I missing something here? Is this really the only way to go about removing header files in compiled languages?


问:
Storing a pass-by-reference parameter as a pointer - Bad practice?
I recently came across the following pattern in an API I've been forced to use:

```<code>class SomeObject
{
public:
    // Constructor.
    SomeObject(bool copy = false);

    // Set a value.
    void SetValue(const ComplexType &value);

private:
    bool         m_copy;
    ComplexType *m_pComplexType;
    ComplexType  m_complexType;
};

// ------------------------------------------------------------

SomeObject::SomeObject(bool copy) :
  m_copy(copy)
{
}

// ------------------------------------------------------------

void SomeObject::SetValue(const ComplexType &value)
{
    if (m_copy)
        m_complexType.assign(value);
    else
        m_pComplexType = const_cast<ComplexType *>(&value);
}
</code>```

The background behind this pattern is that it is used to hold data prior to it being encoded and sent to a TCP socket. The copy weirdness is designed to make the class SomeObject efficient by only holding a pointer to the object until it needs to be encoded, but also provide the option to copy values if the lifetime of the SomeObject exceeds the lifetime of a ComplexType.

However, consider the following:

```<code>SomeObject SomeFunction()
{
    ComplexType complexTypeInstance(1);  // Create an instance of ComplexType.

    SomeObject encodeHelper;
    encodeHelper.SetValue(complexTypeInstance); // Okay.

    return encodeHelper;

    // Uh oh! complexTypeInstance has been destroyed, and
    // now encoding will venture into the realm of undefined
    // behaviour!
}
</code>```

I tripped over this because I used the default constructor, and this resulted in messages being encoded as blank (through a fluke of undefined behaviour). It took an absolute age to pinpoint the cause!

Anyway, is this a standard pattern for something like this? Are there any advantages to doing it this way vs overloading the SetValue method to accept a pointer that I'm missing?

Thanks!

答:
I'd say yes it is standard to have a reference that is taken as a pointer (as in I have seen it in multiple projects) and yes it is bad as it does hide the problem of object lifetime.

And the const cast is unnecessary and completely horrible. At the very least it should be a ref that is passed in, not a const ref.

As you suggest one way of improving it would be better to have 2 different functions one that takes a const ref and copies (setting the copy flag at the same time), and the other that takes a pointer, so the user is forced to explicitly call the non copy behaviour.

Better would be to have 2 different methods that have different names (maybe CopyValue and ReferenceValue), and better still would be to have a base class with 2 different sub classes classes that do the 2 different behaviours.


问:
At what point does caching become necessary for a web application?
I'm considering the architecture for a web application.  It's going to be a single page application that updates itself whenever the user selects different information on several forms that are available that are on the page.

I was thinking that it shouldn't be good to rely on the user's browser to correctly interpret the information and update the view, so I'll send the user's choices to the server, and then get the data, send it back to the browser, and update the view.

There's a table with 10,000 or so rows in a MySQL database that's going to be accessed pretty often, like once every 5-30 seconds for each user.  I'm expecting 200-300 concurrent users at one time.  I've read that a well designed relational database with simple queries are nothing for a RDBMS to handle, really, but I would still like to keep things quick for the client.

Should this even be a concern for me at the moment?  At what point would it be helpful to start using a separate caching service like Memcached or Redis, or would it even be necessary?

I know that MySQL caches popular queries and the results, would this suffice?

答:
You need caching when you have a problem that can be solved by caching. That problem may be too much processor usage on the DB; if it is then MySQL caching is going to help you a lot -- but maybe not enough, it depends what else is going on. Or it could be that your network connection from the application instances to the DB are getting overloaded.

In that case, MySQL caching isn't going to do much for you; it'll cache the response but you still need to go to the database to get it. It could be that the bottleneck is server processor, or even bandwidth between the server and the outside world, or memory usage, or number of threads, or number of handles, or any number of other things -- some of which cannot be solved by caching at all. Memory usage COULD be made worse.

Donald Knuth is quoted a lot in programming circles. Often badly or invalidly. But in the case of "Premature optimisation is the root of all evil," he at least had a point, if slightly dramatically stated.

When you're thinking about the general architecture of your new app, think about two things: reporting and extensibility. There are plenty of AOP-style caching frameworks out there that can cache the results of any method; so as long as you keep database access well-isolated, it'll be extensible enough to ask the question of caching later.

The question you should be asking now is this: How do I know, on the day that I first get techcrunched, and my application or the database or the network cannot cope with the load, which layer of the application is the bottleneck, so I can fix it?

You really should be looking for metrics and reporting frameworks long before you ask questions about caching.


问:
Differences between Software Quality certification levels?
First off,  thanks for reading the question.  I understand that this would theoretically be best asked in the SQA stack area - but - seeing as how that doesn't officially exist yet, maybe this was the most appropriate place for it for now.

I'm looking into tracking down a certification in Software Quality, however, there are so many different awarding bodies and certifications that telling the difference between them is difficult.

So far I've found:

Six Sigma - a QA process, originally founded by Motorola & not limited to software. (in fact I'm not sure if it even covers software development).  Based on a series of 'belts' (black being the best, I assume it starts at green? or white?)

ASQ - American Society of Quality - offers numerous certifications in quality

CQA - Quality Auditor

CQE - Quality Engineer

CQIA - Quality Improvement Associate

CQI - Quality Inspector

CQPA - Quality Process Analyst

CQT - Quality Technician

CRE - Reliability Engineer

QAI Global

Software Testing

Software Quality Assurance

Process Engineering

Process Management

With all the different designations and levels, I'm having trouble understanding the differences and the 'start point' and progression between the levels.  (Are they a hierarchy or are they in parallell?)

答:
QAI, ASQ, and ISTQB (another big one you didn't mention) are all parallel (six sigma is a bit of a different beast, but not a gradiation of any of the others).

There's a bit of a controversy in the testing / qa world these days on the value of certifications - one front calls them a money making machine with little value and the other cites the need for a common baseline of testing terms and knowledge.

I won't hijack your question to go any deeper :}


问:
How to Avoid a Busy Loop Inside a Function That Returns the Object That's Being Waited For
I have a function which has the same interface as Python's input builtin, but it works in a client-server environment. When it's called, the function, which runs in the server, sends a message to the client, asking it to get some input from the user. The user enters some stuff, or dismisses the prompt, and the result is passed back to the server, which passes it to the function. The function then returns the result.

The function must work like Python's input [that's the spec], so it must block until it has the result.

This is all working, but it uses a busy loop, which, in practice, could easily be spinning for many minutes. Currently, the function tells the client to get the input, passing an id. The client returns the result with the id. The server puts the result in a dictionary, with the id as the key. The function basically waits for that key to exist.

```<code>def input():

    '''simplified example'''

    key = unique_key()
    tell_client_to_get_input(key)
    while key not in dictionary: pass
    return dictionary.pop(pin)
</code>```

Using a callback would be the normal way to go, but the input function must block until the result is available, so I can't see how that could work. The spec can't change, as Python will be using the new input function for stuff like help and pdb, which provide their own little REPLs.

I have a lot of flexibility in terms of how everything works overall, but just can't budge on the function acting exactly like Python's.

Is there any way to return the result as soon as it's available, without the busy loop?

答:
You want a semaphore.

```<code>def input():
    make_network_call()
    sem.acquire()
    return shared_return_value

def callback():
    shared_return_value = whatever
    sem.release()
</code>```

This makes input() block on the acquire() line until release() is called in the callback.  The caller to input() isn't aware a callback was involved.  Make sure to initialize the semaphore with a value of zero.

Body:
You want a semaphore.

def input():
    make_network_call()
    sem.acquire()
    return shared_return_value

def callback():
    shared_return_value = whatever
    sem.release()

This makes input() block on the acquire() line until release() is called in the callback.  The caller to input() isn't aware a callback was involved.  Make sure to initialize the semaphore with a value of zero.


问:
Class design issue
I'm new to OOP and a lot of times I become stumped in situations similar to this example:

Task: Generate an XML document that contains information about a person.  Assume the information is readily available in a database. Here is an example of the structure:

```<code><Person>
    <Name>John Doe</Name>
    <Age>21</Age>
    <Address>
        <Street>100 Main St.</Street>
        <City>Sylvania</City>
        <State>OH</State>
    </Address>
    <Relatives>
        <Parents>
            <Mother>
                <Name>Jane Doe</Name>
            </Mother>
            <Father>
                <Name>John Doe Sr.</Name>
            </Father>
        </Parents>
        <Siblings>
            <Brother>
                <Name>Jeff Doe</Name>
            </Brother>
            <Brother>
                <Name>Steven Doe</Name>
            </Brother>
        </Siblings>
    </Relatives>
</Person>
</code>```

Ok lets create a class for each tag (ie: Person, Name, Age, Address)
Lets assume each class is only responsible for itself and the
elements directly contained

Each class will know (have defined by
default) the classes that are directly contained within them

Each
class will have a process() function that will add itself and its
children to the XML document we are creating

When a child is drawn, as in the previous line, we will have them call process() as well

Now we are in a recursive loop where each object draws their children
until all are drawn

But what if only some of the tags need to be drawn, and the rest are
optional? Some are optional based on if the data exists (if we have
it, we must draw it), and some are optional based on the preferences
of the user generating the document

How do we make sure each object
has the data it needs to draw itself and its children?  We can pass
down a massive array through every object, but that seems shitty
doesn't it?  We could have each object query the database for it, but
that's a lot of queries, and how does it know what its query is?

What
if we want to get rid of a tag later? There is no way to reference
them.

I've been thinking about this for 20 hours now.  I feel like I am misunderstanding a design principle or am just approaching this all wrong.  How would you go about programming something like this?

I suppose this problem could apply to any scenario where there are classes that create other classes, but the classes created need information to run. How do I get the information to them in a way that doesn't seem messy?

答:
A partial answer, addressing the core points of your question:

Each class will know (have defined by default) the classes that are directly contained within them

A class should know the other classes only to the extent needed for it to do its job. If all you need is generating a XML document that might be as little as a constructor, a loadFromDatabase() method to fill in the fields and a toXML() method to create the XML fragments you will need. Everything else is best kept private, including whatever is needed to make the constructor and the public methods work.

Each class will have a process() function that will add itself and its childeren to the XML document we are creating

A better approach would be a Person class (which would correspond to the top level of the desired XML) having a toXML() method which returns the full XML document, doing so by calling the toXML() methods of the children and composing the fragments as appropriate.

Title: Class design issue

OwnerDisplayName: duplode


问:
Why is there a 20 and not 21 in some versions of Planning Poker?
In Planning Poker, cards usually contain numbers of the Fibonacci sequence, which is 0,1,1,2,3,5,8,13,21,34,55 etc.

However, you can see on the Wikipedia page (and this has been confirmed to me by people that work at several positions where Planning Poker is applied) in some editions the cards stray away from Fibonacci sequence after 13. They lower 21 to 20 and then continue with 40 and 100.

Is there some rationale on why these values have been changed, specifically 21 to 20?

(Also note that some other cards are added, such as ? and 1/2, but these are easier for me to understand, compared to the 21 -> 20 shift.)

答:
Estimation in agile can be performed using various tools, as long as it is based on relative sizing of stories (effort required to complete one story as compared to the other). Fibonacci series is just one of those tools. Some teams use the 't-shirt sizes' to estimate, Small, Medium, Large, XLarge. In short, planning poker (agile estimation) does not require the use of Fibonacci series for estimations.

However, Fibonacci series does help in providing arbitrary numbers which are not exact multiples and increase exponentially. So numbers like 4, 6, 10, etc. are out of the picture. Exponential increase is required to express bigness as well as uncertainty. A story which is, lets say, bigger than a 5-points story will remain big, so the team should not spend time in figuring out if it is a 10 or 11. Fibonacci series makes your life easier by not having a 10 or 11 and the team has to use either a 8 or 13 for the bigger story.

As the story size increases, it becomes difficult to precisely estimate (which requires that the story needs to be broken down first). Using precise numbers such as 34, 55 for uncertain estimates does not provide much value. So some teams follow a practice of using numbers having larger differences between each successive number. So they stop using Fibonacci series after 13 and use 20, 40, 100 or 20, 50, 100.

Actually there is no hard and fast rule about it other than ease of use, as agile recommends to use whatever works best for you.

This is what is mentioned on Mike Cohn's Mountain Goat Software site:

Why do the cards deviate slightly from the Fibonacci sequence?

We’re anal software people, too. We know that the Fibonacci sequence
  should go from 8 to 13 to 21. We use 20, though, instead of 21. Of
  course we used 21 in the early days, but dropped it after meeting with
  a product owner who looked at the 21 and said, “Oh, a 21. You must be
  very confident to give such a precise estimate. Most people would have
  called it 20 or 25, but you called it 21.” We replied that we used the
  Fibonacci sequence. The product owner said, “The Fibo-what?” After
  which, we decided that deviating from the Fibonacci sequence would be
  better because the numbers started to imply a very high level of
  precision that just wasn’t there. The 1/2 is included because after
  awhile some teams decide they want some room in between “free” (a
  zero) and one. Using 1/2 isn’t something a team should do a lot, but
  it’s a nice option to have in some cases.

OwnerDisplayName: SuffixTreeMonkey

OwnerDisplayName: Aziz Shaikh


问:
Why I'm not selected in an interview?
I'm working in development for 4 years, and 3.5 in PHP - why I don't seem to be able to be selected in an interview.

I want to know what special things the interviewer wants to see in candidates - for senior PHP developer roles.

Interviewer asks me 10 questions and I'm able to answer only 5. Does selection depend on these things? It doesn't mean that I can't solve the problem, I can google the question, I can ask on forums. Why don't they understand that a man can't remember all the answers for each and every question? Especially programming ones.

Please advise.

答:
By the sounds of it, you would fail my interview technique as well. At interview I expect candidates to write code on the whiteboard.  It might seem tough, but it allows candidates to show that they do know the language, and are not relying on intelsense and google to program.  Lets face it, if you are claiming on your CV to have 3.5 years of PHP experience, then at interview I want to see some evidence of your experience.

I also use the process to identify people that think logically about their designs, write code that actually implements their design, and when faced with a new constraint understand how it affects their design, and what they need to adjust to accommodate this new information.

Whilst lots of companies do use the 20 question interview method, this method is a poor differentiator in identifying who the best programmers are, and good at identifying who has been reading a lot of books recently.  If you are constantly facing this interview technique, start reading.  You should want a 95-100% good answer rate on these questions to get offered the job, however it will not make you a better programmer on its own.

The major problem with "programming by google" is that whilst you may deliver code that works, but its quite possible that you have no understanding of it increasing the risk of subtle bugs and undesirable consequences. It will certainly take longer to write the code and your source code will have the same consistency as the internet making it much harder for your replacement to support your code in the future.

Whilst I'm sure that my answer is not the warm fuzzy reassurance that you may have wanted, hopefully it will help you to understand what you need to do differently to gain the knowledge and experience, or perhaps, may help you to understand why a career in a different sector may be a better choice for you.  good luck for the future.

Title: Why I'm not selected in an interview?


问:
Get Info From Database, or Build Inferred Info?
Does it make more sense to store and retrieve properties or information directly related to an item in a database, or, say in such a case that a product's ID could describe information about it, should the information be gathered from that?

Example: Item SKU -- 4HBU12

4 - is the number of motors

H - the voltage

B - the color, blue

U - the model

12 - the length

Should I store those individual attributes as well as the SKU, or should I store only the SKU and build the attributes from it?

答:
I would suggest considering to store just the SKU.

I have found that any setup that stores both is ripe for them getting out of sync in the long term and the problems it causes can be devious.


问:
How can I apply Readme Driven Development to an ongoing project?
I'm assigned to a project where the goal is to update an existing software. This software was developed in a totally ad hoc manner, which means that any documentation generated is outdated, confused and just plain useless. I do not want to retroactivelly produce all the missing artifacts, since this would just be a waste of time. The code base is ugly, and really need some serious refactoring, but this is another story.

What I want is to apply Readme Driven Development to guide this project. So, basically, I want to write a Readme, which will document every change meaningful at the user level. The problem is, I have no idea about how to structure this document. For me, it's pretty clear that it should have a different layout than the traditional Readme. I really want to document changes, and not the current state of affairs.

Any ideas?

答:
My advice is to avoid the readme's approach.

You are recreating and worsening the problem for the future.

Te readme's will, over time, be maintained by different developers with different styles.  Eventually there will be differences between the readme's and the implementation and that will be really annoying.

I can only give this advice - which I know will probably seem (and may well be) very impractical for all the change it seems to imply, but the thing is I think it is the RIGHT thing to do and in the end that's better.

So what I would do is:

1) focus on getting those tests written or upgraded first.  Your regression test suites are key to further changes.  They are the core of the documentation
you seek.

2) Refactor the code making sure the tests pass and coverage the needed case.


问:
Role based access to resources for a RESTful service
I'm still wrapping my head around REST, but I wonder if someone can help with any suggestions or approaches to role based access control for a RESTful service, particularly from the point of view of securing the data and how the URLs might look. It's probably best to consider an example:

Say I have a REST service for Customers, and want to split the users of this REST service into Admin, Editor and Reader roles:

Admins can change all attributes of a Customer resource

Editors can change only some

Readers can only view them.

Access control rights are assigned to the Customers entities individually. So for example a user of the service might have admin rights to Customers 1,2 and 3 but Editor access to 4,5 and Reader access to 7,8,9.

Now consider the user calling the service. What is a good way to seperate the list of Customers for the current User?

GET /Customer - this might get a list of all customers that the current user has Admin\Editor\Reader access to.  But then on each Customer the consumer would need an indication of what role they have.

Or would it be "better" having something like

GET /Customer/Admin - return all customers the current user has Admin access to.

Just looking for some high level pointers or reading on a decent way to secure\filter the resources based on roles of the current user.

答:
A method I have used to great success to expose the access level or roles the authenticated user has with respect to a particular resource is to expose it as HTTP verbs on the entity itself.

For instance requesting a list of all customers:

```<code>GET /customers
{
   customers: [
     {
        id: "/customers/1"
        allowed: ["GET", "UPDATE", "PUT", "DELETE"]
     },
     {
        id: "/customers/2"
        allowed: ["GET"]
     }
   ]
}
</code>```

GET indicated read access UPDATE, PUT, DELETE would indicated Editor and or Admin access based upon the semantics of your API. If this sort of abstraction doesn't work in your case you could call the rolls out directly.

Additionally, you could provide a filter to the customers request

```<code>GET /customers?role=admin
</code>```

Would return only the customers for which the authenticated user has the "admin" role.

Body:
A method I have used to great success to expose the access level or roles the authenticated user has with respect to a particular resource is to expose it as HTTP verbs on the entity itself.

For instance requesting a list of all customers:

GET /customers
{
   customers: [
     {
        id: "/customers/1"
        allowed: ["GET", "UPDATE", "PUT", "DELETE"]
     },
     {
        id: "/customers/2"
        allowed: ["GET"]
     }
   ]
}

GET indicated read access UPDATE, PUT, DELETE would indicated Editor and or Admin access based upon the semantics of your API. If this sort of abstraction doesn't work in your case you could call the rolls out directly.

Additionally, you could provide a filter to the customers request

GET /customers?role=admin

Would return only the customers for which the authenticated user has the "admin" role.


问:
How Microsoft Market DotNet?
I just read an Joel's article about Microsoft's breaking change (non-backwards compatibility) with dot net's introduction. It is interesting and explicitly reflected the condition during that time. But now almost 10 years has passed.

The breaking change

It is mainly on how bad is Microsoft introducing non-backwards compatibility development tools, such as dot net, instead of improving the already-widely used asp classic or VB6. As much have known, dot net is not natively embedded in windows XP (yes in vista or 7), so in order to use the .net apps, you need to install the .net framework of over 300mb (it's big that day).

However, as we see that nowadays many business use .net as their main development tools, with asp.net or mvc as their web-based applications. C# nowadays be one of tops programming languages (the most questions in stackoverflow). The more interesing part is, win32api still alive even there is newer technology out there (and still widely used).

Imagine if microsoft does not introduce the breaking change, there will many corporates still uses asp classic or vb-based applications (there still is, but not that much). There are many corporates use additional services such as azure or sharepoint (beside how expensive is it).

Please note that I also know there are many flagships applications (maybe adobe's and blizzard's) still use C-based or older language and not porting to newer high-level language.

The question

How can Microsoft persuade the users to migrate their old applications into dot net? As we have known it is very hard and give no immediate value when rewrite the applications (netscape story), and it is very risky. I am more interested in Microsoft's way and not opinion such as "because dot net is OOP, or dot net is dll-embedable, etc".

This question may be constructive, as the technology is vastly changes over times lately. As we can see, Microsoft changes Asp.Net webform to MVC, winform is legacy now, it is starting to change to use windows store rather than basic-installment, touchscreen and later on we will have see-through applications such as google class. And that will be breaking changes.

We will need to account portability as an issue nowadays. We will need other than just mere technology choice, but also migration plans. Even maybe as critical as we might need multiplatform language compiler, as approached by Joel's Wasabi. (hey, I read his articles too much!)

答:
Aside from the technological breakthroughs, Microsoft Marketed the Dot Net framework by making it so easy for the developers to use that it became their first choice when being asked to develop new applications. Just look at Microsoft loves to spoil developers with Visual Studio. Microsoft sold the idea to developers first then they sold it to the business. Once the businesses saw that it made developers more productive, they started to make more use of it. Though it wasn't a field of roses as there are people who shun Microsoft after experiencing breaking changes every now and then.

Ok, so back to the way of the "Breaking Changes"

Why did Microsoft invest in the .NET Framework, because after seeing the success of java with the JVM, they perceived that was where the market was going, and they want a piece of that market. And thus, .NET was born. Microsoft is making these breaking changes to somehow force the market to move forward and to keep its market from stagnating. Their competitors are steadily improving as well, and to keep themselves relevant, they have to make decisions. These breaking changes are a result of those decisions. If MS ignored the java threat back then and didn't make .NET, M$ might've spiraled into oblivion long ago. And these changes continue to happen, just look at the metro interface. If M$ didn't do that, their tablet market share would never be able to recover from the onslaught of ipads and android tablets.

Lastly, migration plans and a language to run across all platforms. Microsoft's solution to that is the .NET Framework. Though it is limited to Windows devices only. But as you can see, they borrowed the idea from java, compile once then run everywhere. Their big difference is how they handle backwards compatibility. .NET allows you to keep multiple version of it to keep older applications from being broken. And Microsoft will keep on supporting older .NET framework versions to a certain extent in newer platforms to keep this backward compatibility.

Title: How Microsoft Market DotNet?


问:
How should I start with Lisp?
I've been programming for years now, working my way through various iterations of Blub (BASIC, Assembler, C, C++, Visual Basic, Java, Ruby in no particular order of "Blub-ness") and I'd like to learn Lisp. However, I have a lot of intertia what with limited time (family, full time job etc) and a comfortable happiness with my current Blub (Java).

So my question is this, given that I'm someone who would really like to learn Lisp, what would be the initial steps to get a good result that demonstrates the superiority of Lisp in web development? Maybe I'm missing the point, but that's how I would initially see the application of my Lisp knowledge.

I'm thinking "use dialect A, use IDE B, follow instructions on page C, question your sanity after monads using counsellor D". I'd just like to know what people here consider to be an optimal set of values for A, B, C and perhaps D. Also some discussion on the relative merit of learning such a powerful language as opposed to, say, becoming a Rails expert.

Just to add some more detail, I'll be developing on MacOS (or a Linux VM) - no Windows based approaches will be necessary, thanks.

Notes for those just browsing by

I'm going to keep this question open for a while so that I can offer feedback on the suggestions after I've been able to explore them. If you happen to be browsing by and feel you have something to add, please do. I would really welcome your feedback.

Interesting links

Assuming you're coming at Lisp from a Java background, this set of links will get you started quickly.

Using Intellij's La Clojure plugin to integrate Lisp (videocast)

Lisp for the Web

Online version of Practical Common Lisp (c/o Frank Shearar)

Land of Lisp a (+ (+ very quirky) game based) way in but makes it all so straightforward

Install Clojure and Sublime 2 on MacOS an excellent getting started guide

Look at the Clojure in Action book. Worked for me.

答:
A very nice place to start using Lisp is inside the Emacs editor, where it can be used to redefine just about anything.  You want the 'e' key to insert the time of date, just write a small Lisp snippet to generate the string and bind it to the e key.  Done.

This will also allow you to actually USE what you learn in a daily setting, if you happen to use a plain editor during the day.

Title: How should I start with Lisp?


问:
Area of testing
I'm trying to understand which part of my code I should to test. I have some code. Below is example of this code, just to understand the idea.
Depends of some parametrs I put one or another currency to "Event" and return his serialization in the controller. Which part of code I should to test? Just the final serialization, or only "Event" or every method: getJson, getRows, fillCurrency, setCurrency?</p>

```<code>class Controller {
    public function getJson()
    {
        $rows = $eventManager->getRows();

         return new JsonResponse($rows);
    }
}

class EventManager {
    public function getRows()
    {
        //some code here
        if ($parameter == true) {
            $this->fillCurrency($event, $currency);
        }
    }

    public function fillCurrency($event,  $currency)
    {
        //some code here
        if ($parameters == true) {
            $event->setCurrency($currency);
        }
    }
}

class Event {
    public function setCurrency($currency) {
        $this->updatedAt = new Datetime();
        $this->currency = $currency;
    }
}
</code>```

答:
I think you should test:
 - Event.setCurrency: Are the date and currency in the instance correctly set? (This can probably left out since it is just a setter with no data handling, but in case this changes the test should be in place)
 - EventManager.getRows: Does it return proper JSON?
 - Controller.getJson: Does it behave correctly if getRows returns NULL or 0?

I would not write an explicit test for EventManager.fillCurrency since in the end it is just passing on values.

Title: Area of testing


答:
Depends on what kind of testing you want to do. There are unit tests and integration tests.

Unit Tests are tests where you test individual units of your application. Normally, this refers to classes. Integration tests are tests where you test how each class/method/api/interface interacts with each other.

With Unit Tests, As stated in "The Art of Unit Testing" by Roy Osherove

You should test every method that deals with any form of logic. That means you shouldn't bother testing getters and setters unless there is a chance that calling Object.setValue(x) does something more than just set the value of Object to x. For example, checking if the value is correct etc. So here is some code example

```<code>boolean setValue(Object x) { value = x; }
boolean setValue(Object x) { if(typeof x == Integer) value = x else value = null}
</code>```

The first one isn't worth testing since you're sure that value will always be x. The second on the other hand, is worth testing because there is a chance that the value might be set to null instead of x.

You can watch some of Roy's classes/talks here: http://artofunittesting.com/

Title: Area of testing

Body:
I'm trying to understand which part of my code I should to test. I have some code. Below is example of this code, just to understand the idea.
Depends of some parametrs I put one or another currency to "Event" and return his serialization in the controller. Which part of code I should to test? Just the final serialization, or only "Event" or every method: getJson, getRows, fillCurrency, setCurrency?</p>

```<code>class Controller {
    public function getJson()
    {
        $rows = $eventManager->getRows();

         return new JsonResponse($rows);
    }
}

class EventManager {
    public function getRows()
    {
        //some code here
        if ($parameter == true) {
            $this->fillCurrency($event, $currency);
        }
    }

    public function fillCurrency($event,  $currency)
    {
        //some code here
        if ($parameters == true) {
            $event->setCurrency($currency);
        }
    }
}

class Event {
    public function setCurrency($currency) {
        $this->updatedAt = new Datetime();
        $this->currency = $currency;
    }
}
</code>```

Body:
Depends on what kind of testing you want to do. There are unit tests and integration tests.

Unit Tests are tests where you test individual units of your application. Normally, this refers to classes. Integration tests are tests where you test how each class/method/api/interface interacts with each other.

With Unit Tests, As stated in "The Art of Unit Testing" by Roy Osherove

You should test every method that deals with any form of logic. That means you shouldn't bother testing getters and setters unless there is a chance that calling Object.setValue(x) does something more than just set the value of Object to x. For example, checking if the value is correct etc. So here is some code example

boolean setValue(Object x) { value = x; }
boolean setValue(Object x) { if(typeof x == Integer) value = x else value = null}

The first one isn't worth testing since you're sure that value will always be x. The second on the other hand, is worth testing because there is a chance that the value might be set to null instead of x.

You can watch some of Roy's classes/talks here: http://artofunittesting.com/


答:
It's about reality not marketing. Microsoft could have made it easier to port existing VB6 applications to .Net.

It is horribly difficult and expensive to port large applications. Many companies couldn't justify spending that kind of money for no new features.

It is possible to make automatic tools which make the port easier - almost entirely automatic. Third-party companies make a living selling such tools (Artinsoft, Code Architects). The built-in Microsoft upgrade wizard was pathetic - according to the guy who wrote it - of course he is from Artinsoft so he wants to sell you something better. Microsoft UK also admitted the Artinsoft and Code Architects tools are better than the built-in upgrade wizard.

Microsoft should have written better porting tools, or bought these ones from the third-party companies and made them free.

Title: How Microsoft Market DotNet?

Body:
I just read an Joel's article about Microsoft's breaking change (non-backwards compatibility) with dot net's introduction. It is interesting and explicitly reflected the condition during that time. But now almost 10 years has passed.

The breaking change

It is mainly on how bad is Microsoft introducing non-backwards compatibility development tools, such as dot net, instead of improving the already-widely used asp classic or VB6. As much have known, dot net is not natively embedded in windows XP (yes in vista or 7), so in order to use the .net apps, you need to install the .net framework of over 300mb (it's big that day).

However, as we see that nowadays many business use .net as their main development tools, with asp.net or mvc as their web-based applications. C# nowadays be one of tops programming languages (the most questions in stackoverflow). The more interesing part is, win32api still alive even there is newer technology out there (and still widely used).

Imagine if microsoft does not introduce the breaking change, there will many corporates still uses asp classic or vb-based applications (there still is, but not that much). There are many corporates use additional services such as azure or sharepoint (beside how expensive is it).

Please note that I also know there are many flagships applications (maybe adobe's and blizzard's) still use C-based or older language and not porting to newer high-level language.

The question

How can Microsoft persuade the users to migrate their old applications into dot net? As we have known it is very hard and give no immediate value when rewrite the applications (netscape story), and it is very risky. I am more interested in Microsoft's way and not opinion such as "because dot net is OOP, or dot net is dll-embedable, etc".

This question may be constructive, as the technology is vastly changes over times lately. As we can see, Microsoft changes Asp.Net webform to MVC, winform is legacy now, it is starting to change to use windows store rather than basic-installment, touchscreen and later on we will have see-through applications such as google class. And that will be breaking changes.

We will need to account portability as an issue nowadays. We will need other than just mere technology choice, but also migration plans. Even maybe as critical as we might need multiplatform language compiler, as approached by Joel's Wasabi. (hey, I read his articles too much!)


问:
Which one is better offline method for large scale application
We've a big data management website used by several property. Some of our customers have downtime (they can't access net for an hour or two). We want our site to support offline data viewing and inventory management (typical data search and add/remove) and when the user goes online we can sync the changes back to our central database. Customers use several platforms like Windows, iOS, etc.

We've been looking into several different options, here are the major choices -

Develop offline web app supported in HTML5. Develop a 'fallback' mechanism and interact with data from the app cache as explained in here (http://www.htmlgoodies.com/html5/tutorials/introduction-to-offline-web- applications-using-)

Develop a desktop based cross platform solution. I remember the old MONO which has been popular. Here's a post (What do you suggest for cross platform apps, including web cross-platform-apps-including-web) and another one (Technology choice for cross platform development (desktop and phone)? platform-development-desktop-and-phone?rq=1)

I realize the the desktop solution might be hard to maintain and result in some compatibility issues and demand test environments.

Can HTML5 handle moderate to high level complexity and data flow? Or would it be better to rely on a desktop based app for better scalability & performance?

答:
If you are going HTML5 I have developed a project for doing just this thing!

It uses principles of version control to detect conflicts and is generally quite well thought out with good documentation on workings and principles which will be helpful even if you don't use it and a very technical demo.

I've just added a MongoDB server component in a branch that I will be integrated into master soon.

You can see the project on GitHub

Matt


答:
I'm confused by the article which seems to say Microsoft is wonderful for allowing bad programming behavior. However, I was caught up in their breaking backwards compatibility with their own software back in that same time period as I was making my first step into the web development market. I spent lots of money and lots of time developing an application that, when Microsoft updated, sent that whole application down in flames.

Out of frustration, I moved on to FreeBSD and Linux and have not touched a Windows machine since. My company is 28 employees strong now and never, ever trusts Microsoft for anything.

Title: How Microsoft Market DotNet?


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

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

How do you handle this? Some possible approaches:

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

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

Something in between. Is there a sweet spot?

答:
This would depend on your release shedules.

But my advice would be to install a set of libraries on all of the developers machines. Consider it a gold standard if you wish to call it something, then start you development for that release.

Only once the release has been deployed and you are in the post release phase, reassess your libraries, their versions and features. If they offer some significant improvements or new functionality then install then prior to the start of the next development cycle.

Only install new versions if there is a major issue or bug that must be fixed before deploying the software.

It will mean you will miss some versions but it should save some headaches and versioning issues allowing you to concentrate on developing your application.


问:
What are the types of dynamically typed languages arrays?
For example, in JavaScript, I can do such things:

```<code>var arr = [1, "two", /three/, [4]];
</code>```

There is no way to do such a thing in C! Except by using a void*, which is not an efficient/safe way.

Is this how implementations do it? Using void* everywhere?

答:
Basically, yes. Each element of the array has to take the same amount of space, so some representation that can represent any value must be used for all elements. A simple option is making everything heap allocated and always (variables, array elements, object attributes, etc.) use pointers to boxed objects. Another option is to store values of a few types directly and others as pointers. There are a variety of clever schemes for this, but of course they're all limited in that they only support a few types without indirection.

Finally, some implementations automatically recognize when the values stored in an array are homogenous, despite the lanugage not guaranteeing that, and use an optimized representation for those cases. PyPy calls this list strategies.


答:
Everything is like a void*, and yes it's more inefficient than values that are stored directly in the array.

But for example in V8 an array can have three type modes: int, double, anything and only in anything-mode everything is stored in the generic format. In int or double modes, the array directly stores those values.

In V8 your array is in generic mode and is represented like:

(SMi means a pointer that actually embeds a direct integer rather than pointing at valid memory)

```<code>[MapPointer, Properties[]Pointer, Elements[]Pointer, LengthSMi]
</code>```

Then at the Elements[] (the actual storage array) array you have:

```<code>[MapPointer, LengthSMi, SMiForOne, PointerAtString, PointerAtRegexpObject, PointerAtArrayObject, PointerAtHole, PointerAtHole...]
</code>```

The holes special objects that mark a reserved slot.

And you don't have to use any struct at all for them (V8 doesn't) - you can and should manage everything yourself with raw memory.

Title: What are the types of dynamically typed languages arrays?

Body:
For example, in JavaScript, I can do such things:

```<code>var arr = [1, "two", /three/, [4]];
</code>```

There is no way to do such a thing in C! Except by using a void*, which is not an efficient/safe way.

Is this how implementations do it? Using void* everywhere?

Body:
Everything is like a void*, and yes it's more inefficient than values that are stored directly in the array.

But for example in V8 an array can have three type modes: int, double, anything and only in anything-mode everything is stored in the generic format. In int or double modes, the array directly stores those values.

In V8 your array is in generic mode and is represented like:

(SMi means a pointer that actually embeds a direct integer rather than pointing at valid memory)

[MapPointer, Properties[]Pointer, Elements[]Pointer, LengthSMi]

Then at the Elements[] (the actual storage array) array you have:

[MapPointer, LengthSMi, SMiForOne, PointerAtString, PointerAtRegexpObject, PointerAtArrayObject, PointerAtHole, PointerAtHole...]

The holes special objects that mark a reserved slot.

And you don't have to use any struct at all for them (V8 doesn't) - you can and should manage everything yourself with raw memory.


问:
Software attribution / design credits
We just completed developing a web app for a client. And like I usually do, I added
developed by "My Company" at the footer at a very small insignificant size.

I sent the client an End user license stating some of the following in summary

```<code>you can't resell, redistribute, etc without our notice
...
you can't remove the attribution or design credits
</code>```

the client got back to me and complained, telling me now that he was also developing for someone, and that 'I can't add my attribution' without his/her consent, but?

Although I sign a NDA within summary states that I cannot disclose the software to anyone else.

There was no agreement before the project that am not to add design credits or attribution.

I know every software I install have that, and so is every products from companies, mostly technological products.

How does this work (adding design credits)?

答:
Generally, this is something you'd want to discuss before signing the actual contract and starting work. I won't pretend to understand all the details in your situation, but the way I would do something like this is during the negotiation phase (figuring out how much to charge for the project, the scope of the project, NDAs and contracts being drawn up), bring up that you would like attribution, and would also like to copyright the work. The actual copyright of the work depends on the contract. Some are willing to give you full attribution and copyright control, and a lot will tell you they are paying for the actual work, making it their own.

If this bothers you, I highly recommend bringing it up before signing anything for your next contract, and try to get your terms in during negotiations. After you sign, they'll have all the rights outlined in the contract. Generally with contracts though, they'll want to have all rights to the final software, and leave you without access to any of it.

Title: Software attribution / design credits


答:
void* is not enough if you want dynamic typing. You need a type information for each value as well. Something like:

```<code>struct {
  void * data;
  int type_id;
};
</code>```

Body:
void* is not enough if you want dynamic typing. You need a type information for each value as well. Something like:

struct {
  void * data;
  int type_id;
};


问:
Can Setter Validation affect performance?
In a scenario where you use an ORM to map your entities to the DB and you have setter validations (nullable, date lower than today validation, etc), every time the ORM gets a result, it will pass into the setter to instance the object.

If I have a grid that usually returns 500 records, I assume that for each record it passes on all validations. If my entity has 5 setter validations, than I have passed in 2.500 validations.

Are these 2.500 validations going to affect the performance?

If it was 15.000 validation, will it be different?

In my opinion, and according to this answer, setter validation is useful than constructors validation.

Is there a way to avoid unnecessary validation, since I am safe to say that
the values I send to the DB when saving the entity won't change until I
edit it on my system?

答:
Does it effect performance? Sure.

Does it matter? Ask your profiler.

Is it worse than bad data in your database? Not a chance.


问:
Should every member of a team use the same IDE?
Do you think it makes sense to enforce that every member of a team must use the same IDE?

For instance all engineers that are already on the team use IDE X. Two new engineers come and want to use IDE Y instead because that's what they have been using for several years now.

Do you have any experience with "mixed IDE" teams? If so what is it?

答: At our place we build our projects using Visual Studio.  When it comes to editing text I switch to Emacs.  Your company shouldn't care as long as the work is done.</p>


答:
Some suggestions for building the object graph:

As you said, to populate the objects you'd have to pass a datastructure through the object hierarchy. But this is only true if you build the graph from top to bottom.

A better approach would be to build it from bottom to top using e.g. a factory (the example is written in Java):

```<code>public class Person {
    private String name;
    private int age;
    private Address address;
    private List<Relatives> relatives;

    public Person(String name, int age, Address address, List<Relatives> relatives) {
        this.name = name;
        this.age = age;
        this.address = address;
        this.relatives = relatives;
    }
}

public class Address {
    String street;
    String city;
    String state;

    public Address(String street, String city, String state) {
        this.street;
        this.city;
        this.state;
    }
}

public interface Relative {
}

public interface Parent extends Relative {
}

public class Mother implements Parent {
    private String name;

    public Parent(String name) {
        this.name = name;
    }
}

// and some more classes; this is left as an exercise to the reader ;)

public class PersonFactory {
    public static Person newPerson() {
        // create the address
        Address addr = new Address("100 Main St.", "Sylvania", "OH");
        // create the list of parents
        List<Parent> parents = new List<Parent>();
        parents.add(new Mother("Jane Doe"));
        parents.add(new Father("Jane Doe"));
        List<Sibling> siblings = new List<Siblings>();
        // analogue to parents

        List<Relatives> relatives = new List<Relatives>();
        relatives.add(parents);
        relatives.add(siblings);
        // now create the person and return him

        return new Person("John Doe", 21, addr, relatives);
    }
}
</code>```

Passing the direct dependencies via the constructor is called dependecy injection. This can be achieved manually (e.g. using factories) or using libaries like Spring or Juice (in Java).

(The PersonFactory's only responsibility is building the object graph).

Title: Class design issue

Body:
I'm new to OOP and a lot of times I become stumped in situations similar to this example:

Task: Generate an XML document that contains information about a person.  Assume the information is readily available in a database. Here is an example of the structure:

```<code><Person>
    <Name>John Doe</Name>
    <Age>21</Age>
    <Address>
        <Street>100 Main St.</Street>
        <City>Sylvania</City>
        <State>OH</State>
    </Address>
    <Relatives>
        <Parents>
            <Mother>
                <Name>Jane Doe</Name>
            </Mother>
            <Father>
                <Name>John Doe Sr.</Name>
            </Father>
        </Parents>
        <Siblings>
            <Brother>
                <Name>Jeff Doe</Name>
            </Brother>
            <Brother>
                <Name>Steven Doe</Name>
            </Brother>
        </Siblings>
    </Relatives>
</Person>
</code>```

Ok lets create a class for each tag (ie: Person, Name, Age, Address)
Lets assume each class is only responsible for itself and the
elements directly contained

Each class will know (have defined by
default) the classes that are directly contained within them

Each
class will have a process() function that will add itself and its
children to the XML document we are creating

When a child is drawn, as in the previous line, we will have them call process() as well

Now we are in a recursive loop where each object draws their children
until all are drawn

But what if only some of the tags need to be drawn, and the rest are
optional? Some are optional based on if the data exists (if we have
it, we must draw it), and some are optional based on the preferences
of the user generating the document

How do we make sure each object
has the data it needs to draw itself and its children?  We can pass
down a massive array through every object, but that seems shitty
doesn't it?  We could have each object query the database for it, but
that's a lot of queries, and how does it know what its query is?

What
if we want to get rid of a tag later? There is no way to reference
them.

I've been thinking about this for 20 hours now.  I feel like I am misunderstanding a design principle or am just approaching this all wrong.  How would you go about programming something like this?

I suppose this problem could apply to any scenario where there are classes that create other classes, but the classes created need information to run. How do I get the information to them in a way that doesn't seem messy?

Body:
Some suggestions for building the object graph:

As you said, to populate the objects you'd have to pass a datastructure through the object hierarchy. But this is only true if you build the graph from top to bottom.

A better approach would be to build it from bottom to top using e.g. a factory (the example is written in Java):

public class Person {
    private String name;
    private int age;
    private Address address;
    private List<Relatives> relatives;

    public Person(String name, int age, Address address, List<Relatives> relatives) {
        this.name = name;
        this.age = age;
        this.address = address;
        this.relatives = relatives;
    }
}

public class Address {
    String street;
    String city;
    String state;

    public Address(String street, String city, String state) {
        this.street;
        this.city;
        this.state;
    }
}

public interface Relative {
}

public interface Parent extends Relative {
}

public class Mother implements Parent {
    private String name;

    public Parent(String name) {
        this.name = name;
    }
}

// and some more classes; this is left as an exercise to the reader ;)

public class PersonFactory {
    public static Person newPerson() {
        // create the address
        Address addr = new Address("100 Main St.", "Sylvania", "OH");
        // create the list of parents
        List<Parent> parents = new List<Parent>();
        parents.add(new Mother("Jane Doe"));
        parents.add(new Father("Jane Doe"));
        List<Sibling> siblings = new List<Siblings>();
        // analogue to parents

        List<Relatives> relatives = new List<Relatives>();
        relatives.add(parents);
        relatives.add(siblings);
        // now create the person and return him

        return new Person("John Doe", 21, addr, relatives);
    }
}

Passing the direct dependencies via the constructor is called dependecy injection. This can be achieved manually (e.g. using factories) or using libaries like Spring or Juice (in Java).

(The PersonFactory's only responsibility is building the object graph).


答:
Today's developer wants to choose their own tools

This has changed over time though.  10 or 15 years ago there wasn't as many choices at places where I've worked. (yes there were lots of editors but they weren't a 'choice').  The shop that I worked at 15 years ago was very 'old school' (even then!) and vi was the editor. No choice. This was actually pretty useful, because after the first month of cussing and swearing I actually got to like it.

Today, there are many choices and each has many advantages.

In my personal experience I used an IDE - rubyMine - for a couple of years before switching 'back' to vi(m).  I did this because Ruby is a very hard language to write an IDE for (duck typing and other dynamic features) and as a result IDE's tend to be slow and/or require the latest, fastest machine.

Title: Should every member of a team use the same IDE?

Body:
Do you think it makes sense to enforce that every member of a team must use the same IDE?

For instance all engineers that are already on the team use IDE X. Two new engineers come and want to use IDE Y instead because that's what they have been using for several years now.

Do you have any experience with "mixed IDE" teams? If so what is it?

ContentLicense: CC BY-SA 4.0


问:
Switch vs Polymorphism when dealing with model and view
I can't figure out a better solution to my problem. I have a view controller that presents a list of elements. Those elements are models that can be an instance of B, C, D, etc and inherit from A. So in that view controller, each item should go to a different screen of the application and pass some data when the user select one of them. The two alternatives that comes to my mind are (please ignore the syntax, it is not a specific language)

1)
switch (I know that sucks)

```<code>//inside the view controller
void onClickItem(int index) {
    A a = items.get(index);

    switch(a.type) {
         case b:
             B b = (B)a;
             go to screen X;
             x.v1 = b.v1; // fill X with b data
             x.v2 = b.v2;
         case c:
             go to screen Y;
         etc...
    }
}
</code>```

2) polymorphism

```<code>//inside the view controller
void onClickItem(int index) {
    A a = items.get(index);
    Screen s = new (a.getDestinationScreen()); //ignore the syntax
    s.v1 = a.v1;   // fill s with information about A
    s.v2 = a.v2;
    show(s);
}

//inside B
Class getDestinationScreen(void) {
    return Class(X);
}

//inside C
Class getDestinationScreen(void) {
    return Class(Y);
}
</code>```

My problem with solution 2 is that since B, C, D, etc are models, they shouldn't know about view related stuff. Or should they in that case?

答:
I think going with the switch is a better option than going with polymorphism for this case.

Its a fairly simple thing to do, so I don't think it has to be overcomplicated by use of polymorphism.

I'd like to coin in this blog post. Switch statements aren't necessarily ugly as long as you use them properly. And in your case, Abstracting models like that for use in a controller may be overkill and might bring forth unwanted results. Like violating the SRP.


答:
My problem with solution 2 is that since B, C, D, etc are models, they shouldn't know about view related stuff.

I agree with this concern.  I also am a little concerned that objects that sit in a combobox would have behavior.  I'm not sure that's a "bad thing" having never done it, it just seems like an unnatural choice to me.

Also, it does not seems like A and it's subclasses are the type that you have interesting polymorphism with.  The interesting type is actually Screen.  In this example, A is just a class that holds information to inform Screen creation.

If you make the combobox contain a list of whatever a.type returns then a switch statement seems more natural.  However, instead of putting it right in the click event handler, I would put it in a ScreenFactory.  Then you have:

```<code>//inside the view controller
void onClickItem(int index) {
    A a = items.get(index);

    s = _screenFactory.GetScreen(a);
    show(s);
    }
}

//inside a ScreenFactory implementation
internal Screen GetScreen(A typeIndicator)
{
switch(a.type) {
     case b:
         return new ScreenX();
     case c:
         return new ScreenY();
     etc...
}
</code>```

This lets you test the screen building behavior, and nicely pulls some functionality out of your UI.  It keeps your View layering intact.  Perhaps it simplifies your design, if it means A and subclasses can be collapsed into the type flag that they contain.

Title: Switch vs Polymorphism when dealing with model and view

Body:
I can't figure out a better solution to my problem. I have a view controller that presents a list of elements. Those elements are models that can be an instance of B, C, D, etc and inherit from A. So in that view controller, each item should go to a different screen of the application and pass some data when the user select one of them. The two alternatives that comes to my mind are (please ignore the syntax, it is not a specific language)

1)
switch (I know that sucks)

```<code>//inside the view controller
void onClickItem(int index) {
    A a = items.get(index);

    switch(a.type) {
         case b:
             B b = (B)a;
             go to screen X;
             x.v1 = b.v1; // fill X with b data
             x.v2 = b.v2;
         case c:
             go to screen Y;
         etc...
    }
}
</code>```

2) polymorphism

```<code>//inside the view controller
void onClickItem(int index) {
    A a = items.get(index);
    Screen s = new (a.getDestinationScreen()); //ignore the syntax
    s.v1 = a.v1;   // fill s with information about A
    s.v2 = a.v2;
    show(s);
}

//inside B
Class getDestinationScreen(void) {
    return Class(X);
}

//inside C
Class getDestinationScreen(void) {
    return Class(Y);
}
</code>```

My problem with solution 2 is that since B, C, D, etc are models, they shouldn't know about view related stuff. Or should they in that case?

Body:
My problem with solution 2 is that since B, C, D, etc are models, they shouldn't know about view related stuff.

I agree with this concern.  I also am a little concerned that objects that sit in a combobox would have behavior.  I'm not sure that's a "bad thing" having never done it, it just seems like an unnatural choice to me.

Also, it does not seems like A and it's subclasses are the type that you have interesting polymorphism with.  The interesting type is actually Screen.  In this example, A is just a class that holds information to inform Screen creation.

If you make the combobox contain a list of whatever a.type returns then a switch statement seems more natural.  However, instead of putting it right in the click event handler, I would put it in a ScreenFactory.  Then you have:

//inside the view controller
void onClickItem(int index) {
    A a = items.get(index);

    s = _screenFactory.GetScreen(a);
    show(s);
    }
}

//inside a ScreenFactory implementation
internal Screen GetScreen(A typeIndicator)
{
switch(a.type) {
     case b:
         return new ScreenX();
     case c:
         return new ScreenY();
     etc...
}

This lets you test the screen building behavior, and nicely pulls some functionality out of your UI.  It keeps your View layering intact.  Perhaps it simplifies your design, if it means A and subclasses can be collapsed into the type flag that they contain.


答:
There is no way to do such a thing in C! Except by using a void*, which is not an efficient/safe way.

Why do you believe that using a (void*) is not an efficient/safe way?

If you want to hide implementation details in C, it is a common technique to expose it as typedef to (void*) in a header and provide functions to manipulate it.

Here is an exaple header for a dynamic type holding integers and strings:

```<code>/* Dynamic types in C */

#define DYNAMIC_INT 0
#define DYNAMIC_STRING  1

struct dynamic_phantom;

typedef struct dynamic_phantom* dynamic;

dynamic dynamic_of_int(int c);
dynamic dynamic_of_string(char *s);
int dynamic_classify(dynamic v);
int dynamic_get_int(dynamic v, int *c);
int dynanic_get_string(dynamic v, char **s);
void dynamic_free(dynamic v);
</code>```

I hope that the names of the functions and their protoypes are enough to get what they are for. There is a lot of options to implement this.  Let me outline two popular choices:

UNIONS

In your implementation file, you implement the dynamic as a unionlike this:

```<code>union dynamic_value {
  int value_int;
  char* value_string;
};

struct dynamic_cell {
  int cell_type;
  union dynamic_value cell_value;
};

typedef struct dynamic_cell *dynamic;
</code>```

and implement the functions I enumerated above is straightforward. (Of course, you can refine this in several ways, defining error control procedures, add control bits if you wish to avoid duplicating string contents, and so on.)

SPECIALISED MEMORY POOLS

For each available dynamic type, you allocate a memory pool, i.e. a large array of such values. A dynamic value is then implemented as a pointer to some value in these memory pools casted to void*.  The type of the value is then recovered from the pointer range.

An advantage of this strategy over the previous one is that it natively deals with values of different sizes while the union approach takes the biggest size of the possible value types. It is however slightly more complicated to implement, especially because of memory management—it needs to reimplement efficiently the logic of malloc if you want to deal with a significant number of values.

Body:
There is no way to do such a thing in C! Except by using a void*, which is not an efficient/safe way.

Why do you believe that using a (void*) is not an efficient/safe way?

If you want to hide implementation details in C, it is a common technique to expose it as typedef to (void*) in a header and provide functions to manipulate it.

Here is an exaple header for a dynamic type holding integers and strings:

/* Dynamic types in C */

#define DYNAMIC_INT 0
#define DYNAMIC_STRING  1

struct dynamic_phantom;

typedef struct dynamic_phantom* dynamic;

dynamic dynamic_of_int(int c);
dynamic dynamic_of_string(char *s);
int dynamic_classify(dynamic v);
int dynamic_get_int(dynamic v, int *c);
int dynanic_get_string(dynamic v, char **s);
void dynamic_free(dynamic v);

I hope that the names of the functions and their protoypes are enough to get what they are for. There is a lot of options to implement this.  Let me outline two popular choices:

UNIONS

In your implementation file, you implement the dynamic as a unionlike this:

union dynamic_value {
  int value_int;
  char* value_string;
};

struct dynamic_cell {
  int cell_type;
  union dynamic_value cell_value;
};

typedef struct dynamic_cell *dynamic;

and implement the functions I enumerated above is straightforward. (Of course, you can refine this in several ways, defining error control procedures, add control bits if you wish to avoid duplicating string contents, and so on.)

SPECIALISED MEMORY POOLS

For each available dynamic type, you allocate a memory pool, i.e. a large array of such values. A dynamic value is then implemented as a pointer to some value in these memory pools casted to void*.  The type of the value is then recovered from the pointer range.

An advantage of this strategy over the previous one is that it natively deals with values of different sizes while the union approach takes the biggest size of the possible value types. It is however slightly more complicated to implement, especially because of memory management—it needs to reimplement efficiently the logic of malloc if you want to deal with a significant number of values.


问:
Does anyone use Ceiling and *not* immediately cast it to an integer?
I think every single time I've used Math.Ceiling or its language variant, I've always had to cast it to an integer. I mean... that's the whole point, isn't it? To get a whole number. So why doesn't it just return an int?

答: For one, REALs/FLOATs usually have a much greater range. The result might not fit into an INTEGER.</p>


答:
More of a comment than an answer, but I think it's a toss up.  Either the View has to know all about the Model so it can choose the screen (switch) or the Model has to know all about the View so it can choose the screen (polymorphism).  I think you have to choose what you think will be the simplest over time; there's no right answer to the question.  (I hope someone can prove me wrong.)  I do lean towards polymorphism, myself.

I bump into this problem a bit.  The most annoying case was a Wanderer class, instances of which wandered about a map.  To draw it, either the display needed to know about Wanderer or Wanderer needed to know about the display.  The problem was there were two displays (with more coming along).  As the number of different Wanderer subclasses was large and growing, I put the drawing code in the Wanderer subclasses.  That meant each large class had exactly one method that needed to know about Graphics2D and exactly one method that needed to know about Java3D.  Ugly.

I did end up splitting the class, giving me two parallel class structures.  The Wanderer class was freed from knowing about the graphics, but the DrawWanderer class still needed to know more about Wanderer than was decent and it needed to know about two (and maybe more) completely different graphics environments (Views).  (I suppose this splitting-the-class idea might be an answer of sorts, but all it really does is contain the problem a bit.)

I do think this is a very general and fundamental problem of Object Oriented design.