问:
Should I be wary of signing a non-disclosure agreement with someone I just met?
1/22/12 update in case you were puzzled as to why I haven't accepted an answer: Pretty much all of the answers make the obvious point that working for him would have been silly, but none of them seemed to answer the question.

tl;dr: Some guy I just met says he wants me to join his company. Before he shows me what they do, he wants me to sign a non-disclosure agreement. Is this weird?

I'm traveling right now. Someone who saw me coding seemed to think I was smart or something and started talking with me. He explained that he owns a software company, told me a bit about what it does and told me that he was looking for a programmer who would work for a stake in the company. He explained that the company's product is being developed rather secretly, so he couldn't tell me much. But he did tell enough about the product to convince me that he's not completely making this up, which is a decent baseline.

He suggested that he show me more of what he's been working on and, after seeing that, I decide whether I want to join. Because of the secrecy behind the product, he wants me to sign a non-disclosure agreement before we talk.

I'm obviously somewhat skeptical because of the random nature by which we met.

In the short term, I'm wondering if I should be wary of signing such an agreement. He said it would be easier to show me the product in person rather than over the internet, and I'm leaving town tomorrow, so I'd have to figure this out by tomorrow. If I decide to talk with him, I could decide later whether I trust that it's worth spending any time on this company.

The concept of being able to avoid telling a secret seems strange to me for the same reason that things like certain aspects of copyright seem strange. Should I be wary of signing a non-disclosure agreement? Is this common practice?

I don't know the details of the agreement of which he was thinking, (If I end up meeting with him, I'll of course read over the agreement before I decide whether to sign it.) so I could consider alternatives according to the aspects of the agreement. Or I could just consider the case of an especially harsh agreement.

This question seems vaguely related.
Do we need a non-disclosure agreement (NDA)?

Thanks

答:
I've had a dozen people ask me to develop their idea and get a stake in the company but you know what, none of them have come to anything. Here is the deal: they are employed and bringing in an income and would wouldn't risk their own money on the idea but you have to? If it was a great idea they would either get off their backside and get funding or risk all (give up their job) to see it through.

Any great ideas that come to something come with blood, sweat and tears, but we developers are an easy touch for all those great ideas out their. I would say almost every employed person have had a dream of one day starting out on their own with a great idea but how many are willing to give up their cosy life for the RISK?

I spoke to someone the other night who has a dream to turn his shell barn into a swimming pool with offices on the second floor. To turn that into reality he needs to first spend a bit of money and get his hands dirty or pay for someone to get their hands dirty.


问:
Is "code that generates code" really all that great?
I was looking through CodePen's "popular pens" and I noticed this cool little spiral animation somebody made with a seemingly ridiculously small amount of code.

This is quite impressive until you click the headings for HTML and CSS to show the "compiled" versions of the same code.  Suddenly the 3 lines of HAML and ~40 lines of SCSS turns into a gigantic monster of repetition.  Here's where my question comes in:

Is it acceptable to do something like this in practice?  Don't get me wrong - I love using preprocessors to help me write code faster, but in some cases it looks like it's an automatic copy-paste machine.

答:
A few things:

A compiler is a code generator, it takes a high level language and creates assembly or bytecode

Generated code is usually not as optimized as code written directly because despite of all the optimizations the compiler just doesn't understand the big picture all that well.

The code that is used to generate code is often shorter, more concise and easier to understand which leads to considerably less errors and easier maintenance.

In my opinion it comes down to one of the fundamental trade-offs for programming languages:  optimality of result vs programmer productivity.
And by optimality I also mean things relevant in this case like the size of the resulting site which has to be downloaded.

In general "code that generates code" is great.

ContentLicense: CC BY-SA 3.0


问:
"Whole-team" C++ features?
In C++, features like exceptions impact your whole program: you can either disable them in your whole program, or you need to deal with them throughout your code. As a famous article on C++ Report puts it:

Counter-intuitively, the hard part of coding exceptions is not the explicit throws and catches. The really hard part of using exceptions is to write all the intervening code in such a way that an arbitrary exception can propagate from its throw site to its handler, arriving safely and without damaging other parts of the program along the way.

Since even new throws exceptions, every function needs to provide basic exception safety — unless it only calls functions which guarantee throwing no exception — unless you disable exceptions altogether in your whole project.

Hence, exceptions are a "whole-program" or "whole-team" feature, since they must be understood by everybody in a team using them. But not all C++ features are like that, as far as I know.

A possible example is that if I don't get templates but I do not use them, I will still be able to write correct C++ — or will I not?. I can even call sort on an array of integers and enjoy its amazing speed advantage wrt. C's qsort (because no function pointer is called), without risking bugs — or not? It seems templates are not "whole-team".

Are there other C++ features which impact code not directly using them, and are hence "whole-team"? I am especially interested in features not present in C.

Update: I'm especially looking for features where there's no language-enforced sign you need to be aware of them. The first answer I got mentioned const-correctness, which is also whole-team, hence everybody needs to learn about it; however, AFAICS it will impact you only if you call a function which is marked const, and the compiler will prevent you from calling it on non-const objects, so you get something to google for. With exceptions, you don't even get that; moreover, they're always used as soon as you use new, hence exceptions are more "insidious". Since I can't phrase this as objectively, though, I will appreciate any whole-team feature.

Update 2: instead of C++ feature I should have written something like "C++-specific feature", to exclude things like multithreading which apply to a large amount of mainstream programming languages.

Appendix: Why this question is objective (if you wonder)

C++ is a complex language, so many projects or coding guides try to select "simple" C++ features, and many people try to include or exclude some ones according to mostly subjective criteria. Questions about that get rightfully closed regularly here on SO.

Above, instead, I defined (as precisely as possible) what a "whole-team" language feature is, provide an example (exceptions), together with extensive supporting evidence in the literature about C++, and ask for whole-team features in C++ beyond exceptions.

Whether you should use "whole-team" features, or whether that's a relevant concept, might be subjective — but that only means the importance of this question is subjective, like always.

答:
I would nominate concurrency as a 'whole team' feature.

Although it is possible to design the software such that only a few experts need to be aware of concurrency issues and the rest of the team can reap the benefits without being concerned with the complexities (like you can do with templates), in practice it does not work that way. In practice, if you have multiple threads, then you have to analyse carefully for each and every variable you use if there are potential concurrency issues with that use.

OwnerDisplayName: Blaisorblade

Title: "Whole-team" C++ features?


问:
Writing arguments in constructors
When creating constructors with multiple arguments, is ok to use the generic String[] args or is it better to list the arguments? Does it really make any significant difference as the coding becomes more complicated?

```<code>public static void Something (String[] args)
{
}
</code>```

or

```<code>public static void Something (String lots, ... int some, ... etc)
{
}
</code>```

答:
A String[] is suitable if your class has a single String[] that you need to construct it with.

It is not suitable if you need different types - how would you represent an int in a String[]? You would need some sort of convention and this would be prone to error and be overly complex to boot.

Use the right types for the class. It is normally OK to have several parameters for the class, but if there are 7 or more (rule of thumb - don't take this as gospel) it is probably doing too much (see Single Responsibility Principle).

Title: Writing arguments in constructors


问:
Whether to separate out methods or not
I am new to java and want to learn best coding practices and understand why one method is better than another, in terms of efficiency and as the coding becomes more complicated. This is just an example, but I can take the principles from here to apply elsewhere.

I have need an option to display stuff, and have put the method stuff separately from the method to ask if the user wants to display the stuff, as stuff has a lot of lines of code.

For readability I have done this:

```<code>public static void displayStuff ()
{

    String input = getInput ("Display stuff? Y/N \n");

        if (input..equalsIgnoreCase ("Y"))

            {
                stuff ();
            }
        else if (input.equalsIgnoreCase ("N"))
            {
                //quit program
            }
        else
            {
                //throw error
                System.out.print("Error! Enter Y or N: \n");

            }
    }

private static String stuff ()
    {
        //to lots of things here

        return stuff ();
    }
</code>```

Or

```<code>public static void displayStuff ()
{

    String input = getInput ("Display stuff? Y/N \n");

        if (input..equalsIgnoreCase ("Y"))

            {
                //to lots of things here
                                    stuff;
            }
        else if (input.equalsIgnoreCase ("N"))
            {
                //quit program
            }
        else
            {
                //throw error
                System.out.print("Error! Enter Y or N: \n");

            }
    }
</code>```

Is it better to keep them together and why?

Also, should the second method be private or public, if I am asking for data within the class?

I am not sure if this is on topic for here. please advise.

答:
It is a good practice when the code inside the function is long or complex or used by several parts of your logic. For example, when you want to validate person name composed of 4 parts, you may want to isolate the name validation and not repeat it 4 times.

Languages like COBOL thrives on the concept of separating logic and some programming methods revolve around structured programming and top down design.

In OO you should separate class methods into their own of course. However, your question, as I can see, is about code within a method.

It is not so good a practice to isolate code within a method into another function when:

You have to return more than one result

You have to pass several parameters

When the function has  not-so obvious side effects

Could raise serious errors that would need to be addressed by try-catch in the caller

I say 'not so good' because it could lead to confusion or difficulty in reading and possibly unnecessary longer code.

The above are just guidelines to consider before extracting out the code and placing it in a separate function.

Title: Whether to separate out methods or not


答:
It obviously depends on what "stuff" in this context is, if it is trivial then the second way is probably fine. On the other hand, if it is something you are going to need to call repeatedly and/or in different circumstances, or are going to want to call elsewhere, then it's best to abstract it into a method.

That being said, putting it into a method is likely to be better for futureproofing your code (e.g. what if "stuff" changes and becomes unwieldy, meaning you end up having to put it into a method anyway) and for readability. Is "stuff" self explanatory or would it be better encapsulated in a method that names it with clear purpose. Bear in mind, even if it's just you writing/maintaining the code, you might come back in two months and then you might as well be a different person for all you'll remember of what the code did.

Re public/private, if you're only calling it from within that class then it should be private. Again, it depends on the architecture of your program but if it's an internal working of the class then that should be private, if it needs to be called from elsewhere, then public.

But put more succinctly: Think carefully before making your privates public. ;-)

Title: Whether to separate out methods or not

Body:
I am new to java and want to learn best coding practices and understand why one method is better than another, in terms of efficiency and as the coding becomes more complicated. This is just an example, but I can take the principles from here to apply elsewhere.

I have need an option to display stuff, and have put the method stuff separately from the method to ask if the user wants to display the stuff, as stuff has a lot of lines of code.

For readability I have done this:

```<code>public static void displayStuff ()
{

    String input = getInput ("Display stuff? Y/N \n");

        if (input..equalsIgnoreCase ("Y"))

            {
                stuff ();
            }
        else if (input.equalsIgnoreCase ("N"))
            {
                //quit program
            }
        else
            {
                //throw error
                System.out.print("Error! Enter Y or N: \n");

            }
    }

private static String stuff ()
    {
        //to lots of things here

        return stuff ();
    }
</code>```

Or

```<code>public static void displayStuff ()
{

    String input = getInput ("Display stuff? Y/N \n");

        if (input..equalsIgnoreCase ("Y"))

            {
                //to lots of things here
                                    stuff;
            }
        else if (input.equalsIgnoreCase ("N"))
            {
                //quit program
            }
        else
            {
                //throw error
                System.out.print("Error! Enter Y or N: \n");

            }
    }
</code>```

Is it better to keep them together and why?

Also, should the second method be private or public, if I am asking for data within the class?

I am not sure if this is on topic for here. please advise.


问:
Just being hired as a senior developer, never even been a junior developer, what should I expect?
I've been a freelancer and a coder by night for a while, and recently, I've been hired after several levels of interviews in a nice NY company, even though I've some lacks in specific fields. Is this common for companies to hire seniors with less experience? Will they wait some weeks to respect a certain learning curve?

I don't know anything about working in a company, so that's why I worry. After one week, I'm still checking and exploring sources, but after one week of work, it seems that some coworkers are considering that I'm slow. I'm good in maths, physics, algorithms, but still I need to learn about all the templates used in this company.

Anyone here already received a less-experienced senior member in his team? Is this acceptable?

I'm planing on having a meeting with my boss to stop worrying about that. Sounds like a good idea?

[EDIT]

Thanks for these answers. I'm definitely a -new - senior developer. I returned to the office with more confidence on Monday. I guess that it's normal to feel a bit incompetent in front of unknown templates/sources during the first weeks when you receive a good pay.

答:
After one week, I'm still checking and exploring sources, but after one week of work, it seems that some coworkers are considering that I'm slow.

One week is a short period of time. Even after one month, you will still be checking sources. You are not engaged by this company to know their code by heart. Your development tools or IDE are here to help you with this. If some problem occurs with some coworkers after one week, simply ask them how they work and which tools do they use. If they considers that you are slow after one week, this is totally abusive. The minimal time necessary to understand an existing application is about one month. Especially with corporate stuff, that is sometimes or most of the time not documented at all. You are a human, not a computer.

You should ask to your coworkers to stop showing you that you are slow or they are better than you, this is non-sense! For sure they are quicker than you, because they wrote the stuff... Somebody gives you the job, you have been hired for what you are able to do and what you've done before, so these guys should only welcome you, help you with a kickstarter explaination, daily stand-ups and weekly debriefs. If they continue with this behavior, this is seriously worrying and you should consider to solve this problem with a manager or go away.

I'm good in maths, physics, algorithms, but still I need to learn about all the templates used in this company.

This is pretty normal, and can take months. Try to work on very small bits of the app first and then you will learn and become able to have a global view off the code, processes (this is maybe as important than code), methodology (even if it's not formal),  etc.


问:
Is there a pattern to restrict which classes can update another class?
Say I have a class ImportantInfo with a public writable property Data. Many classes will read this property but only a few will ever set it. Basically, if you want to update Data you should really know what you're doing.

Is there a pattern I could use to make this explicit other than by documenting it? For example, some way to enforce that only classes that implement IUpdateImportantData can do it (this is just an example)? I'm not talking about security here, but more of a "hey, are you sure you want to do that?" kind of thing.

UPDATE

I've been faced with similar situations before, that's why I tried to keep the question more generic but it seems that a more concrete example is definitely required. So here it goes:

I have a Context class with a a property CurrentYear. Many classes use this Context object and, whenever CurrentYear changes, they need to react (reload themselves, for example). Now, there are some classes that can legitimately change CurrentYear. Of course, you don't want just everybody to change CurrentYear as that has an effect in many other classes. How would you go about that?

答:
I was trying to create some way for the important data container to
  "know" what was setting the data, as mentioned in the question -
  Izkata

Then I think this is what you want:

```<code>public interface IUpdateImportantData {
    public Data newDataValue();
}

public class ImportantInfo {
    // constructor
    public ImportantInfo() { ... }

    // getter
    public Data getData() { ... }

    // safer setter
    public void setData(IUpdateImportantData iuid) {
        // instanceof always returns true when used on null
        if (iuid == null) {
            throw new IllegalArgumentException("Can't set data with null");
        }
        if ( (iuid instanceOf OkClass1) ||
             (iuid instanceOf OkClass2) ) {
            this.data = iuid.newDataValue();
        } else {
            throw new IllegalArgumentException("That class is not allowed to change data");
        }
    }
}
</code>```

Here's a usage example:

```<code>public OkClass2 implements IUpdateImportantData {
    @Override
    public Data newDataValue() { return Data(3); }
}

public OtherClass implements IUpdateImportantData {
    @Override
    public Data newDataValue() { return Data(3); }
}

ImporatntInfo ii = new ImportantInfo();
OkClass2 oc2 = new OkClass2();
ii.setData(oc2); // works.

OtherClass oc1 = new OtherClass();
ii.setData(oc1); // throws exception.
</code>```

I think I have now answered your question, but this is wrapping a problem with more complexity.  It is always superior to fix the underlying problem.

Sometimes you have to interface with some code or service that you cannot control.  If you can't fix the underlying problem, you can design an API that allows only valid uses of the underlying difficulty without caring about who is using that API.  Preventing invalid usES is far superior to preventing invalid usERS.  Can you:

Make ImportantInfo a private inner class of the one class that needs to access it?

Put ImportantInfo in the same package (folder) as the few classes that need to access it and give setData() default access (package-scope, no-modifier specified)?

Split ImportantInfo into 2 classes, one that holds the safe stuff, and one that just protects the unsafe stuff?

Redesign ImportantInfo to prevent the dangers that come with modifying the underlying data?

Make the underlying data unmodifiable.  Inject new versions of Data as needed without modifying the original.

Really, I could give better suggestions if I understood exactly what was dangerous about modifying Data.  If you understand that, then the best solution will probably present itself without my help.  If not, then you should probably do some experimenting to figure out the root cause of the problem and solve that instead of building layers of complexity around it.

Body:
I was trying to create some way for the important data container to
  "know" what was setting the data, as mentioned in the question -
  Izkata

Then I think this is what you want:

public interface IUpdateImportantData {
    public Data newDataValue();
}

public class ImportantInfo {
    // constructor
    public ImportantInfo() { ... }

    // getter
    public Data getData() { ... }

    // safer setter
    public void setData(IUpdateImportantData iuid) {
        // instanceof always returns true when used on null
        if (iuid == null) {
            throw new IllegalArgumentException("Can't set data with null");
        }
        if ( (iuid instanceOf OkClass1) ||
             (iuid instanceOf OkClass2) ) {
            this.data = iuid.newDataValue();
        } else {
            throw new IllegalArgumentException("That class is not allowed to change data");
        }
    }
}

Here's a usage example:

public OkClass2 implements IUpdateImportantData {
    @Override
    public Data newDataValue() { return Data(3); }
}

public OtherClass implements IUpdateImportantData {
    @Override
    public Data newDataValue() { return Data(3); }
}

ImporatntInfo ii = new ImportantInfo();
OkClass2 oc2 = new OkClass2();
ii.setData(oc2); // works.

OtherClass oc1 = new OtherClass();
ii.setData(oc1); // throws exception.

I think I have now answered your question, but this is wrapping a problem with more complexity.  It is always superior to fix the underlying problem.

Sometimes you have to interface with some code or service that you cannot control.  If you can't fix the underlying problem, you can design an API that allows only valid uses of the underlying difficulty without caring about who is using that API.  Preventing invalid usES is far superior to preventing invalid usERS.  Can you:

Make ImportantInfo a private inner class of the one class that needs to access it?

Put ImportantInfo in the same package (folder) as the few classes that need to access it and give setData() default access (package-scope, no-modifier specified)?

Split ImportantInfo into 2 classes, one that holds the safe stuff, and one that just protects the unsafe stuff?

Redesign ImportantInfo to prevent the dangers that come with modifying the underlying data?

Make the underlying data unmodifiable.  Inject new versions of Data as needed without modifying the original.

Really, I could give better suggestions if I understood exactly what was dangerous about modifying Data.  If you understand that, then the best solution will probably present itself without my help.  If not, then you should probably do some experimenting to figure out the root cause of the problem and solve that instead of building layers of complexity around it.


答:
Please, for the love of all that is holy, don't ever try to do this. You're completely missing the point of class design and encapsulation.

In OOP, classes have invariants. These are the conditions which must be in place in order for the class to function correctly. Almost every class will have at least some invariants unless it is a dumb "property bag" (AKA Data Transfer Object), and too many of these is considered an anti-pattern (Anemic Domain Model).

But back to the main point. A class's responsibilities are therefore to:

Ensure that its initial state is valid, via parameterized constructors and validation.

Not trust anything from the outside; validate the arguments to all public and probably all protected methods and property setters.

Refuse to execute any operation that would leave it in an invalid state (e.g. either by throwing an exception, adjusting other parts of the state to stay valid, or simply performing a no-op and returning an error status). Or, even better, use the type system to make it a compile-time error to supply an invalid value, e.g. by using an enumeration instead of a string/integer parameter.

This is encapsulation. An object does not permit outside access to anything that is not absolutely required, and where it does provide access, it does so very carefully.

With this in mind, it is therefore evident that any properly-designed class should not care who calls it because it is impossible to do anything dangerous - or at least, anything more dangerous than what the class is actually designed to do. If the class is intended to provide dangerous functionality, then you probably need another level of abstraction, i.e. to design your application so that only trusted callers can get a reference to the dangerous object in the first place.

A common example of the latter is data access. You typically do not provide the actual connection object to user-interface components where you might run the risk of data corruption or worse, SQL injection or other security vulnerabilities. Instead, you provide repository or command/query objects that encapsulate the connection.

Even if you came up with some eye-watering code that could reliably validate the caller - even when running in release mode or with binary-rewriters or interception proxies involved - it could only do so at runtime. Which means that programmers would have no clue that they're doing anything wrong until they actually try to run it, which is a terrible way to treat the poor bastards trying to maintain it later on. You'll also run into a mess of dependencies because you'll need to carry this placeholder interface or attribute all over the place.

Then you have "transitive trust" issues - in other words, the calling class may implement whatever interface you decided on, but do you trust the class that's calling that class? In all likelihood, maintenance programmers will get so frustrated with this limitation that they'll just create a wrapper class which technically meets your requirement, which they can then use without fear of nasty runtime errors.

So please, again, don't ever attempt to validate the caller. Validate the arguments if necessary and design your classes so that it is never necessary to validate the caller.

Interesting fact: The original version of the .NET Framework actually had a system for, essentially, validating the caller and the entire call stack. It was called Code Access Security. The policy system turned out to be so complex, awkward to work with, and generally despised by the .NET community, that Microsoft actually decided to remove it in .NET 4. There's still some traces of CAS itself left, but it's all mostly infrastructure-level stuff around assemblies and AppDomains (sandboxing). The fact that there used to be a bulletproof means of caller validation that was actually removed from the framework should tell you a lot about what the programming community at large thinks of this practice.

Title: Is there a pattern to restrict which classes can update another class?

Body:
Say I have a class ImportantInfo with a public writable property Data. Many classes will read this property but only a few will ever set it. Basically, if you want to update Data you should really know what you're doing.

Is there a pattern I could use to make this explicit other than by documenting it? For example, some way to enforce that only classes that implement IUpdateImportantData can do it (this is just an example)? I'm not talking about security here, but more of a "hey, are you sure you want to do that?" kind of thing.

UPDATE

I've been faced with similar situations before, that's why I tried to keep the question more generic but it seems that a more concrete example is definitely required. So here it goes:

I have a Context class with a a property CurrentYear. Many classes use this Context object and, whenever CurrentYear changes, they need to react (reload themselves, for example). Now, there are some classes that can legitimately change CurrentYear. Of course, you don't want just everybody to change CurrentYear as that has an effect in many other classes. How would you go about that?


问:
How do I encrypt the source code on the webserver?
I have a web application developed using Python, HTML, CSS & JavaScript.

The customer installs it in any of their own Machine and uses it through their LAN.
In short the customer sets up the webserver in any of their own machine.

Since its a web application, all the source code is open for the customer in the document root directory of webserver. I want to encrypt the whole source code in the document root directory in such a way that it should not effect the working of the web application.

Is there is any way to encrypt the Python, HTML, CSS & JavaScript for this purpose.

答:
As for Python, there are a number of ways to tackle this but you will need to do some of the heavy lifting.   Here are some thoughts:

zip file containing just the .pyc files.   This would mean you would need to either dictate the exact Python version and architecture or provide multiple .zip files, one for each architecture that you are supporting.

PEP 302 introduced the importlib that will allow you to integrate your own custom importer.   Examples that need custom importers are py2exe, freeze, etc.   You should be able to integrate your own importer to read encrypted zip files or whatever format though you'll probably want to put some of that code into compiled C as your own module.

As for Javascript, if you mean client side, then no.   But for node.js, you could do some work on the V8 engine where you load/save the compiled version of Javascript (similar to a .pyc) if available instead of using source.   You'll probably need a C developer to do that work and it may require patching to specific versions of node.js.


答:
It seems like a worrisome approach if you've got several other classes that know how to poke inside an instance of ImportantInfo to update the Data, not because it is safe or otherwise, but rather because you've then got more of a violation of the Law of Demeter.

It would instead be better to put the update code inside the class and have the other classes just pass in instructions on what update is to be performed. In the simple case, these instructions are just arguments to a method, but if you want to do something more complex then the instructions can be packaged up in a little class of their own (which probably should be as close to functionality-free as possible: it's just a description, a POJO in Java parlance). And the update code itself, because it is inside the class, can be much more easily managed in synch with the rest of the class.

I'd also consider seriously whether you really have to support modifying the state at all. Very often, you can make the object be entirely immutable and instead handle changes by returning a new object instead. This is a more functional-programming approach, and it works really rather well as it means that the non-updating users of the object can assume that they won't have changes sprung on them from behind their backs; I can't overstate just how much easier this makes programming!

If you have to support update from outside, consider giving out a true read-only delegate for the object instead so that consumers can't poke inside by mistake. In Java, I'd consider using the proxy mechanism to do this, and I'd have one of the reader methods return an ID (which the writers would need to present to some other manager class to get the updateable entity). Some frameworks can make this very easy to do…


问:
ASP.Net or WPF(C#)?
Our team is divided on this and I wanted to get some third-party opinions.

We are building an application and cannot decide if we want to use .Net WPF Desktop Application with a WCF server, or ASP.Net web app using jQuery. I thought I'd ask the question here, with some specs, and see what the pros/cons of using either side would be. I have my own favorite and feel I am biased.

Ideally we want to build the initial release of the software as fast as we can, then slow down and take time to build in the additional features/components we want later on. Above all we want the software to be fast. Users go through records all day long and delays in loading records or refreshing screens kills their productivity.

Application Details:

I'm estimating around 100 different screens for initial version, with plans for a lot of additional screens being added on later after the initial release.

We are looking to use two-way communication for reminder and event systems

Currently has to support around 100 users, although we've been told to allow for growth up to 500 users

We have multiple locations

Items to consider (maybe not initially in some cases but in future releases):

Room for additional components to be added after initial release (there are a lot of of these... perhaps work here than the initial application)

Keyboard navigation

Performance is a must

Production Speed to initial version

Low maintenance overhead

Future support

Softphone/Scanner integration

Our Developers:

We have 1 programmer who has been learning WPF the past few months and was the one who suggested we use WPF for this.

We have a 2nd programmer who is familiar with ASP.Net and who may help with the project in the future, although he will not be working on it much up until the initial release since his time is spent maintaining our current software.

There is me, who has worked with both and am comfortable in either

We have an outside company doing the project management, and they are an ASP.Net company.

We plan on hiring 1-2 others, however we need to know what direction we are going in first

Environment:

General users are on Windows 2003 server with Terminal Services. They connect using WYSE thin-clients over an RDP connection. Admin staff has their own PCs with XP or higher. Users are allowed to specify their own resolution although they are limited to using IE as the web browser.

Other locations connects to our network over a MPLS connection

Based on that, what would you choose and why?

答:
Technically, I believe the WPF/WCF combination is the better solution.

However, I am not convinced that your existing WPF programmer really has the experience for this project.  WPF is quite a shift in programming thought processes from Winform programming and so you will need to think long and hard about do you really have sufficient skills in the team to deliver this route.

Title: ASP.Net or WPF(C#)?

ContentLicense: CC BY-SA 2.5


问:
Why "Fork me on GitHub"?
I understand how GitHub works, but one thing I've been confused about is, why almost every OSS project lately has a "Fork me on GitHub" link on their homepage. For example,

http://jqtjs.com/, http://www.daviddurman.com/flexi-color-picker/, and others.

Why is this so common? Is it that they want/need code validation, checking for security/performance improvements that they may not know how to do?

Is it meant to show that this is a collaborative project - you're welcome to add improvements?

Do they work for GitHub, or want to promote their service? Oddly enough, I don't think I've seen a "Fork project on Bitbucket" logo recently.

My first reaction to that logo was that the project probably needs to be modified (forked) in order to integrate it with anything useful - or that they are encouraging fragmented codebase, encouraging everyone to make their own fork of the project. But I don't think that is the intent.

答:
forking on github makes it sound really easy to say like follow me on twitter. I
t brings a little socialization into the world of development from my own perspe
ctive also making it obvious that is open source and available for modifications
.I also think it's a nice concept with the "fork me on github" banner on one end
 of your project website</p>

Title: Why "Fork me on GitHub"?


问:
Are there any significant advantages to using a native language for mobile app development?
Forgive me if this question has already been answered but I couldn't quite find the answer I was looking for. What I wanted to know was, is there any significant advantage to using a native language when developing and deploying apps to a mobile environment?

The reason I ask is for a long while now I've been using Objective-C, Apple's native language for iOS, to build my apps. However I've been wondering whether or not there is any real benefit to doing this, over using a non-native language like JavaScript and then deploying it through a service like 'Phone Gap'?

I do stress 'significant' advantages as native languages are always more likely to have the upper hand when it comes to speed and access to the latest APIs. However in general I don't see using a non-native language or a service like 'Phone Gap' causing and major slow down to my apps or restricting my development. Additionally having the ability to deploy to multiple services is also very handy indeed.

This is why I put the question, are there any significant advantages to using a native language for mobile app development?

答:
There are some significant advantages to using native code over PhoneGap and other non-native languages. Obviously in your question you noted some of these already, but in the eyes of the consumer, these development advantages translate to customer advantages:

Native languages expose all of the device's core functionality through direct APIs, compared to PhoneGap (and others) which render web technologies (HTML5, JavaScript) on the device in a "compiled" state.

Native languages are much faster than JavaScript for data processing on the device.

You have the advantage of leveraging 3rd-party SDKs designed for the device's native language.

App performance, quality, and stability translate directly to customer success and, ultimately, success of the app. Here is an excellent article about how Facebook's experience with both HTML5 and native apps affected their business: http://www.theregister.co.uk/2012/09/14/facebook_html_5_vs_native_apps/

Design and UX can be more carefully tailored to device-specific UX. iOS doesn't behave the same way Android or Windows Phone do, and building a 'one-size-fits-all' app makes it difficult to respect those unique UX traits. (Caveat: you can handle this with non-native languages too, but it translates to complex code/logic).


问:
Is premature optimization really the root of all evil?
A colleague of mine today committed a class called ThreadLocalFormat, which basically moved instances of Java Format classes into a thread local, since they are not thread safe and "relatively expensive" to create. I wrote a quick test and calculated that I could create 200,000 instances a second, asked him was he creating that many, to which he answered "nowhere near that many". He's a great programmer and everyone on the team is highly skilled so we have no problem understanding the resulting code, but it was clearly a case of optimizing where there is no real need. He backed the code out at my request. What do you think? Is this a case of "premature optimization" and how bad is it really?

答:
In fact I learned that premature non-optimization is more often the root of all evil.

When people write software it will initially have problems, like instability, limited features, bad usability and bad performance. All of these usually get fixed, when the software matures.

All of these, except performance. Noone seems to care about performance. The reason is simple: if a software crashes, someone will fix the bug and that's it, if a feature is missing, someone will implement it and done, if the software has bad performance it is in many cases not due to missing microoptimization, but due to bad design and no one is going to touch the design of the software. EVER.

Look at Bochs. It's slow as hell. Will it ever get faster? Maybe, but only in the range of a few percent. It will never get performance comparable to virtualization software like VMWare or VBox or even QEMU. Because it's slow by design!

If the problem of a software is that it is slow, then because it is VERY slow and this can only be fixed by improving the performance by a multitude. +10% will simply not make a slow software fast. And you will usually not get more than 10% by later optimizations.

So if performance is ANY important for your software, you should take that into account from the beginning on, when designing it, instead of thinking "oh yes, it's slow, but we can improve that later". Because you can't!

I know that does not really fit to your specific case, but it answers the general question "Is premature optimization really the root of all evil?" - with a clear NO.

Every optimization, like any feature, etc. has to be designed carefully and implemented carefully. And that includes a proper evaluation of cost and benefit. Do not optimize an algorithm to save a few cycles here and there, when it doesn't create a measurable performance gain.

Just as an example: you can improve a function's performance by inlining it, possibly saving a handful of cycles, but at the same time you probably increase the size of your executable, increasing the chances of TLB and cache misses costing thousands of cycles or even paging operations, which will kill performance entirely. If you don't understand these things, your "optimization" can turn out bad.

Stupid optimization is more evil than "premature" optimization, yet both are still better than premature non-optimization.

OwnerDisplayName: Craig Day


答:
Based on @GlenPeterson's answer here's what I think I'm gonna do. I'll have two classes:

Context. This class is mutable and provides a SetData method.

ContextObserver. This class has a private reference to Context, it listens for modifications in Context and whenever Context changes it will execute whatever method you tell it to execute. It also has a method GetContext which returns an immutable version of Context.

So, those who really need to modify the data in Context get a reference to the Context object, while those who only consume the data get a referece to the ContextObserver class.

Plain and simple, if you want to make a class readonly for certain consumers, just give them a readonly wrapper over the original class.


问:
Organization standards for large programs
I'm the only software developer at the company where I work. I was hired straight out of college, and I've been working here for several years. When I started, eveeryone was managing their own data as they saw fit (lots of filing cabinets).

Until recently, I've only been tasked with small standalone projects to help with simple workflows. In the beginning of the year I was asked to make a replacement for their HR software. I used SQL Server, Entity Framework, WPF, along with MVVM and Repository/Unit of work patterns.

It was a huge hit. I was very happy with how it went, and it was a very solid program. As such, my employer asked me to expand this program into a corporate dashboard that tracks all of their various corporate data domains (People, Salary, Vehicles/Assets, Statistics, etc.) I use integrated authentication, and due to the initial HR build, I can map users to people in positions, so I know who is who when they open the program, and I can show each person a customized dashboard given their work functions.

My concern is that I've never worked on such a large project. I'm planning, meeting with end users, developing, documenting, testing and deploying it on my own. I'm part way through the second addition, and I'm seeing that my code is getting disorganized. It's still programmed well, I'm just struggling with the organization of namespaces, classes and the database model.

Are there any good guidelines to follow that will help me keep everything straight? As I have it now, I have folders for Data, Repositories/Unit of Work, Views, View Models, XAML Resources and Miscellaneous Utilities. Should I make parent folders for each data domain? Should I make separate EF models per domain instead of the one I have for the entire database? Are there any standards out there for organizing large programs that span multiple data domains?

I would appreciate any suggestions.

答:
What you are describing is what happens in many cases: in some ways you are a victim of your own success. You have one successful product and are trying to extend it, possibly in ways you initially did not envisage and design for. And maybe the whole thing is getting too big to fit it all in your head.

With the benefit of 20-20 hindsight, you might have redesigned the original (sub)system as part of the larger one. So what to do now?

You don't mention whether you are using a source control system. If not then get one now. The main choices are Git, Subversion, and Mercurial. Do it now, so that when you make changes you can see what you changed, and can undo it. I call it a time machine.

Is there an overall design? Do you have pictures of it on the wall? If the design is in your head, or you don't have pictures, produce those pictures now. And label them "version x", to make clear to yourself that they can change.

Add to every folder a README file that explains what it is for, is meant to be there, and what is not meant to be there. Later, these simple rules will help you decide where things belong.

Even though you are using powerful tools and frameworks, it is easy to scatter business logic in view logic and control logic, and vise versa, especially since the product started so small. You probably feel that you can't stop and untangle that now, but stop adding to the mess. At some stage soon, do a review to locate the stuff that is in the wrong place or at the wrong level, and add comments to the code describing what should happen to it when you get the chance.

Remember that abstraction is your friend: if you create abstract interfaces for your components, then you can substitute better or different implementations later. As you have now learned, successful systems evolve. The questions you ask are good ones. But the answer to most of them is "it depends". My guiding advice is to use abstraction to help keep things separate, and use that idea to guide the choices you make. Sorry that I cannot be more specific here.

Don't wait until you are totally snowed under before getting help. Discuss with the business leaders what they will do as your workload exceeds you capacity. It can be a scary conversation: approach it as a manager (since it seems you manage the IT Development Department), and show that you are thinking of how the business will manage growth.

Congratulations. It's a good problem to have!


答:
I'm surprised that this question is 5 years old, and yet nobody has posted more of what Knuth had to say than a couple of sentences.  The couple of paragraphs surrounding the famous quote explain it quite well.  The paper that is being quoted is called "Structured Programming with go to Statements", and while it's nearly 40 years old, is about a controversy and a software movement that both no longer exist, and has examples in programming languages that many people have never heard of, a surprisingly large amount of what it said still applies.

Here's a larger quote (from page 8 of the pdf, page 268 in the original):

The improvement in speed from Example 2 to Example 2a is only about 12%, and many people would pronounce that insignificant. The conventional wisdom shared by many of today's software engineers calls for ignoring efficiency in the small; but I believe this is simply an overreaction to the abuses they see being practiced by penny-wise-and-pound-foolish programmers, who can't debug or maintain their "optimized" programs. In established engineering disciplines a 12% improvement, easily obtained, is never considered marginal; and I believe the same viewpoint should prevail in software engineering. Of course I wouldn't bother making such optimizations on a one-shot job, but when it's a question of preparing quality programs, I don't want to restrict myself to tools that deny me such efficiencies.

There is no doubt that the grail of efficiency leads to abuse. Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil.

Yet we should not pass up our opportunities in that critical 3%. A good programmer will not be lulled into complacency by such reasoning, he will be wise to look carefully at the critical code; but only after that code has been identified. It is often a mistake to make a priori judgments about what parts of a program are really critical, since the universal experience of programmers who have been using measurement tools has been that their intuitive guesses fail.

Another good bit from the previous page:

My own programming style has of course changed during the last decade, according to the trends of the times (e.g., I'm not quite so tricky anymore, and I use fewer go to's), but the major change in my style has been due to this inner loop phenomenon. I now look with an extremely jaundiced eye at every operation in a critical inner loop, seeking to modify my program and data structure (as in the change from Example 1 to Example 2) so that some of the operations can be eliminated. The reasons for this approach are that: a) it doesn't take long, since the inner loop is short; b) the payoff is real; and c) I can then afford to be less efficient in the other parts of my programs, which therefore are more readable and more easily written and debugged.

Title: Is premature optimization really the root of all evil?

Body: A colleague of mine today committed a class called ThreadLocalFormat, which basically moved instances of Java Format classes into a thread local, since they are not thread safe and "relatively expensive" to create. I wrote a quick test and calculated that I could create 200,000 instances a second, asked him was he creating that many, to which he answered "nowhere near that many". He's a great programmer and everyone on the team is highly skilled so we have no problem understanding the resulting code, but it was clearly a case of optimizing where there is no real need. He backed the code out at my request. What do you think? Is this a case of "premature optimization" and how bad is it really?


问:
How come there is still so much programming work?
I wonder why programming jobs haven't yet "dried up" because of the software evolution. For example, I am a developer myself, which means that I do care about software (I mean I am not of the type of guys that needs a computer mainly to just browse the Internet), and still I wouldn't mind if I never receive any more updates on my Ubuntu machine.

I find that it provides everything I need, and while the updates provide various bug fixes/improvements, I wouldn't mind using it with its current state for the rest of my life. For two years of Ubuntu usage I have never bumped at a serious bug/problem.

Another example is Windows. Almost half of its users still use Windows XP, which is practically ancient, yet they find it satisfying for all their needs (and I agree with them).

I could go with many more examples, but by now you are understanding my point and my question. While new "trends" appears all of the time (like a new mobile OS) which runs on new platforms and requires some fresh development work, still the majority of the software effort goes in to what I consider as "completed projects", or at least a state of a project which is enough to be considered as completed.

Do you have an explanation?

答:
The thing with software is it will continue to evolve with and beyond the hardware that it operates on. Currently we are only writing software that is.. pre-programmed to a certain level and this will still be many more years before humans in the majority are writing "AI" software.

When you look at something like Google compared to something like the software that is used to operate a touchscreen interface in a vehicle, you can see so many gaps in the technology.

Until we have software that is able to expand and develop itself in a forever changing physical and intelligent world.. We'll have plenty of work to do..

Edited.. When a new technology or concept comes along, a lot of existing software is instantly out of date and the majority in that genre needs to be re-created/published. Say in two years we make the major break through with using a computer by mind/thought interfacing.

Even though you can make a simple plugin for most operating systems to translate a thought/command into keyboard/mouse operations.. This still is limited and a bad way to approach it. Technology will always advance and we have no idea what will be available in 12 months little alone 10 years.

Wont even start on quantum computers


答:
In your precise case, having HAML to HTML and SCSS to CSS is a good practice. This is because they translate the source to the compiled code directly. The rules applied are quite simple when compared to programming languages. Preprocessors just get a lot of work out of your way, don't do magic.

So, to answer the question, yes: it is a good practice to use this "code generated by code".

There are another cases where I hate it, such as purely graphical programming. Some tools are not that good and doesn't provide the programmer with a way to customize the final, compiled code. Purely graphical programming may have its limits and you don't want limits with a project with three or more months of code. (Actually, that ended in a completely rewrite of one of our projects).

Title: Is "code that generates code" really all that great?

Body:
I was looking through CodePen's "popular pens" and I noticed this cool little spiral animation somebody made with a seemingly ridiculously small amount of code.

This is quite impressive until you click the headings for HTML and CSS to show the "compiled" versions of the same code.  Suddenly the 3 lines of HAML and ~40 lines of SCSS turns into a gigantic monster of repetition.  Here's where my question comes in:

Is it acceptable to do something like this in practice?  Don't get me wrong - I love using preprocessors to help me write code faster, but in some cases it looks like it's an automatic copy-paste machine.


问:
Difference between bug, defect and flaw
I was reading "Software Security: Building Security In" and in the first chapter I faced with 3 terms: bug, defect and flaw. The author gave a definition for each of them but I couldn't completely understand these.

Can someone give me some examples for each term?

What is a defect and what is a flaw? I think I know what bug is, a bug is a malfunction of a part of system which produces undesirable result, be it crashing on a wrong input or miscalculating a series of computations.

Can someone elaborate more and correct me if I am wrong in this?

UPDATE

To be more precise in the book I mentioned above, they (the words) are presented in a way to make a distinction, that's why I am asking to know more.

In that book there are some examples denoting which sample belongs to what and which category.

For example:

Buffer overflow is said to be a bug and issues in method overriding (subclassing issues) is being related to flaw category.

Again race condition handling issues are considered bugs and Error-handling problems (fails open) are told to be flaws!

I want more elaboration on these regards.

答:
They are the same thing. Making a distinction between them serves no purpose. They all represent defects in the code. Either the code is correct or it is wrong. If it is wrong, it's a defect. Both "bug" and "flaw" simply water-down the meaning of the word "defect".

Use "defect", so you don't end up in long conversations about whether it is a defect, flaw or bug, instead of simply fixing it and moving on.

Title: Difference between bug, defect and flaw


问:
How to retain familiarity with previously worked on technology/language/feature
One problem that I have faced over the years is that when I stop using a technology (COM,QT)/language (VBScript)/feature (Templates) for development over the time I lose skill in that.

What in your opinion is the "easiest" way to retain familiarity so that when I come back to any of them, effort for relearning is minimal.

答: The best way to keep up to date with previous technologies is to have simple personal projects which use them.  I try to keep a list of personal projects based on different technologies, I can always revisit them if you want to brush up my skills.</p>


答:
The terms that are defined in Software Security: Building Security In are simply the author's definitions of the terms. There are different definitions of the terms, as pointed out in another question here on Programmers. Different sources will use different terms to mean different things - it's why the author in this particular case is choosing to define and give examples of the kinds of problems he means when he uses them.

In short, the book uses "defect" to mean any design or implementation flaw or problem, "bug" to mean implementation problems (including those that may exist in code paths not executed), and "flaw" refers to an issue that is manifested in implementation but may stem from design. Bugs and flaws appear to both be specific types of defects.

Personally, I find these confusing and very much prefer the definitions provided in dukeofgaming's answer on the other question, which is rooted in the IEEE definitions of the terms.

Title: Difference between bug, defect and flaw

Body:
I was reading "Software Security: Building Security In" and in the first chapter I faced with 3 terms: bug, defect and flaw. The author gave a definition for each of them but I couldn't completely understand these.

Can someone give me some examples for each term?

What is a defect and what is a flaw? I think I know what bug is, a bug is a malfunction of a part of system which produces undesirable result, be it crashing on a wrong input or miscalculating a series of computations.

Can someone elaborate more and correct me if I am wrong in this?

UPDATE

To be more precise in the book I mentioned above, they (the words) are presented in a way to make a distinction, that's why I am asking to know more.

In that book there are some examples denoting which sample belongs to what and which category.

For example:

Buffer overflow is said to be a bug and issues in method overriding (subclassing issues) is being related to flaw category.

Again race condition handling issues are considered bugs and Error-handling problems (fails open) are told to be flaws!

I want more elaboration on these regards.


问:
Why many designs ignore normalization in RDBMS?
I got to see many designs that normalization wasn't the first consideration in decision making phase.

In many cases those designs included more than 30 columns, and the main approach was "to put everything in the same place"

According to what I remember normalization is one of the first, most important things, so why is it dropped so easily sometimes?

Edit:

Is it true that good architects and experts choose a denormalized design while non-experienced developers choose the opposite?  What are the arguments against starting your design with normalization in mind?

答:
What's interesting about this Q&A thread is that there are actually 3 questions. Everybody has answered a different one, and almost nobody has answered the first one:

Why aren't some databases in the wild normalized?

Why/when should a normalized database be denormalized?

In what situations is it harmful or unnecessary to normalize in the first place?

Alert readers will note that these are very different questions, and I'll try to answer each of them separately while avoiding too much detail. By "too much", I mean that I don't think this is the appropriate context in which to be carrying out an extended debate over the merits of various arguments in favour of or against normalization; I'm simply going to explain what those arguments are, maybe list a few caveats, and save the philosophy for more specific questions, if they ever come up.

Also, in this answer I am assuming that "normalization" implies "BCNF, 3NF, or at least 2NF", since that's the level of normalization that designers generally aim to achieve. It's rarer to see 4NF or 5NF designs; although they certainly aren't impossible goals, they concern themselves with the semantics of relationships rather than just their representation, which requires considerably more knowledge about the domain.

So, onward and upward:

1. Why aren't some databases in the wild normalized?

The answer to this could be "because they shouldn't be", but making that assumption right off the bat is pretty piss-poor detective work. We wouldn't make very much progress as a society if we always operated on the assumption that whatever is, ought to be.

The real reasons that databases don't get normalized in the first place are more complicated. Here are the top 5 that I've come across:

The developers who designed it didn't know or didn't understand how to normalize. Strong evidence of this comes in the form of many other accompanying bad design choices, like using varchar columns for everything or having a spaghetti mess of meaningless table and column names. And I assure you, I've seen "real" databases that are every bit as bad as those in the TDWTF articles.

The developers who designed it didn't care or were actively against normalization on principle. Note, here I am not talking about instances where a deliberate decision was made not to normalize based on contextual analysis, but rather teams or companies where normalization is more-or-less understood but simply ignored or shunned out of habit. Again, surprisingly common.

The software is/was done as a Brownfield project. Many purists ignore this perfectly legitimate business rather than technical reason for not normalizing. Sometimes you don't actually get to design a new database from scratch, you have to bolt on to an existing legacy schema, and attempting to normalize at that point would involve far too much pain. 3NF wasn't invented until 1971, and some systems - especially financial/accounting systems - have their roots even farther back than that!

The database was originally normalized, but an accumulation of small changes over a long period of time and/or a widely distributed team introduced subtle forms of duplication and other violations of whatever normal form was originally in place. In other words, the loss of normalization was accidental, and too little time was spent on refactoring.

A deliberate business decision was made not to spend any time on business analysis or database design and just "get it done". This is often a false economy and ultimately becomes a mounting form of technical debt, but is sometimes a rational decision, at least based on information that was known at the time - for example, the database may have been intended as a prototype but ended up being promoted to production use due to time constraints or changes in the business environment.

2. Why/when should a normalized database be denormalized?

This discussion often comes up when a database is normalized to start with. Either the performance is poor or there is a lot of duplication in queries (joins), and the team feels, rightly or wrongly, that they've gone as far as they can with the current design. It is important to note that normalization improves performance most of the time, and there are several options to eliminate excess joins when normalization appears to be working against you, many of which are less invasive and risky than simply changing to a denormalized model:

Create indexed views that encapsulate the most common problem areas. Modern DBMSes are capable of making them insertable or updatable (e.g. SQL Server INSTEAD OF triggers). This comes at a slight cost to DML statements on the underlying tables/indexes but is generally the first option you should try because it is nearly impossible to screw up and costs almost nothing to maintain. Of course, not every query can be turned into an indexed view - aggregate queries are the most troublesome. Which leads us to the next item...

Create denormalized aggregate tables that are automatically updated by triggers. These tables exist in addition to the normalized tables and form a kind of CQRS model. Another CQRS model, more popular these days, is to use pub/sub to update the query models, which gives the benefit of asynchrony, although that may not be suitable in very rare instances where the data cannot be stale.

Sometimes, indexed views are not possible, the transaction rates and data volumes are too high to admit triggers with acceptable performance, and the queries must always return realtime data. These situations are rare - I'd hazard a guess that they might apply to things like High-Frequency Trading or law enforcement/intelligence databases - but they can exist. In these cases you really have no option but to denormalize the original tables.

3. In what situations is it harmful or unnecessary to normalize in the first place?

There are, in fact, several good examples here:

If the database is being used only for reporting/analysis. Typically this implies that there is an additional, normalized database being used for OLTP, which is periodically synchronized to the analysis database through ETL or messaging.

When enforcing a normalized model would require an unnecessarily complex analysis of the incoming data. An example of this is might be a system that needs to store phone numbers that are collected from several external systems or database. You could denormalize the call code and area code, but you'd have to account for all of the different possible formats, invalid phone numbers, vanity numbers (1-800-GET-STUFF), not to mention different locales. It's usually more trouble than it's worth, and phone numbers are usually just shoved into a single field unless you have a specific business need for the area code on its own.

When the relational database is primarily there to provide transactional support for an additional, non-relational database. For example, you might be using the relational database as a message queue, or to track the status of a transaction or saga, when the primary data is being stored in Redis or MongoDB or whatever. In other words, the data is "control data". There's usually no point in normalizing data that isn't actually business data.

Service-Oriented Architectures that share a physical database. This is a bit of an odd one, but in a true SOA, you will occasionally need to have data physically duplicated because services are not allowed to directly query each other's data. If they happen to be sharing the same physical database, the data will appear not to be normalized - but generally, the data owned by each individual service is still normalized unless one of the other mitigating factors is in place. For example, a Billing service might own the Bill entity, but the Accounting service needs to receive and store the Bill Date and Amount in order to include it in the revenue for that year.

I'm sure there are more reasons that I haven't listed; what I'm getting at, in essence, is that they are quite specific and will be fairly obvious when they come up in practice. OLAP databases are supposed to use star schemas, SOAs are supposed to have some duplication, etc. If you're working with a well-known architecture model that simply doesn't work with normalization, then you don't normalize; generally speaking, the architecture model takes precedence over the data model.

And to answer the very last question:

Is it true that good architects and experts choose a denormalized design while non-experienced developers choose the opposite? What are the arguments against starting your design with normalization in mind?

No, that is complete and utter B.S. It's also B.S. that experts always choose a normalized design. Experts don't just follow a mantra. They research, analyze, discuss, clarify, and iterate, and then they choose whatever approach makes the most sense for their particular situation.

The 3NF or BCNF database is usually a good starting point for analysis because it's been tried and proven successful in tens of thousands of projects all over the world, but then again, so has C. That doesn't mean we automatically use C in every new project. Real-world situations may require some modifications to the model or the use of a different model altogether. You don't know until you're in that situation.


问:
Is there a way to develop desktop software using PHP?
I have to develop a real estate marketing CRM software for my client - where the application is installed on desktop but can also be accessed from web.

2 reasons why they want the application to run from desktop :

So that it can work with/without internet connection

They don't want their complete data to be online

They want to access few of the data like property listing & inquiries (managed from desktop application) from their website through secure login & password.

The data that is entered in desktop application should be automatically synchronized with the website application. I was wondering if there is a way to develop this kind of software using PHP & MySQL.  If yes, it will be great if anyone can provide me the referral link.Else please suggest, which language should I use.

答:
Yes its possible php gtk project is no longer active, with the power of php 5.4 there is a better platform called wxphp something based on popular wxWidget, give a try I think you'll not disappointed

Here's why:

Its build over most popular wxWidget

Compatible with Windows, Mac, Linux/Ubuntu GUI platforms

wxWidget Always use native GUI

wxWidget still under active development

For more about wxWidget visit here wxWidget


问:
What code smell best describes this code?
Suppose you have this code in a class:

private DataContext _context;

public Customer[] GetCustomers()
{
    GetContext();

    return _context.Customers.ToArray();
}

public Order[] GetOrders()
{
    GetContext();

    return _context.Customers.ToArray();
}

// For the sake of this example, a new DataContext is *required*
// for every public method call
private void GetContext()
{
    if (_context != null)
    {
        _context.Dispose();
    }

    _context = new DataContext();
}
```

This code isn't thread-safe - if two calls to GetOrders/GetCustomers are made at the same time from different threads, they may end up using the same context, or the context could be disposed while being used. Even if this bug didn't exist, however, it still "smells" like bad code.

A much better design would be for GetContext to always return a new instance of DataContext and to get rid of the private field, and to dispose of the instance when done. Changing from an inappropriate private field to a local variable feels like a better solution.

I've looked over the code smell lists and can't find one that describes this. In the past I've thought of it as temporal coupling, but the Wikipedia description suggests that's not the term:

Temporal coupling

  When two actions are bundled together into one module just because they happen to occur at the same time.

This page discusses temporal coupling, but the example is the public API of a class, while my question is about the internal design.

Does this smell have a name? Or is it simply "buggy code"?

答:
I don't know of a catchy name for it, but I'd say that that code "relies on side-effects" - GetContext() isn't actually getting anything, it's changing something way off over there that affects how subsequent code will run.

That said, this code smell can evolve into an antipattern called sequential coupling.  The difference is that the antipattern usually applies to calls from outside the object, rather than inside.

Sequential coupling usually manifests more like this:

```<code>obj = Cls()
obj.Start()
obj.LoadParams()
obj.InitEviron()
obj.Run()
</code>```

where running these in a different order (or omitting one) would produce unexpected results.

Body:
I don't know of a catchy name for it, but I'd say that that code "relies on side-effects" - GetContext() isn't actually getting anything, it's changing something way off over there that affects how subsequent code will run.

That said, this code smell can evolve into an antipattern called sequential coupling.  The difference is that the antipattern usually applies to calls from outside the object, rather than inside.

Sequential coupling usually manifests more like this:

obj = Cls()
obj.Start()
obj.LoadParams()
obj.InitEviron()
obj.Run()

where running these in a different order (or omitting one) would produce unexpected results.


问:
Is the Joel Test really a good gauging tool?
I just learned about the Joel Test. I have been computer programmer for 22 years, but somehow I never heard about it before. I consider my best job so far to be this small investment managing company with 30 employees and only three people in the IT department.

I am no longer with them, but I had being working there for five years – my longest streak with any given company. To my surprise they scored extremely poor on the Joel Test. The only two questions I would answer “yes” are #4: Do you have a bug database? And #9: Do you use the best tools money can buy? Everything else is either “sometimes” or straight “no”.

Here is what I liked about the company however:

Good pay. They bragged about it to my face, and I bragged about it to their face, so it was almost like a family environment.

I always knew the big picture. When writing code to solve a particular problem there were no ambiguity about the business nature of that problem. Even though we did not always had written specifications we could ask business users a question anytime, often yelling it across the floor. I could even talk to executives any time I felt like doing it: no appointment necessary.

Immediate feedback. Once we implement a solution and make business users happy they immediately let us know that, we (programmers) become heroes of the moment.

No red tape. I could always buy any tools I deemed necessary, and design solutions the way my professional judgment dictates.

Flexibility. If I had mid-day dental appointment that is near my house rather than near the office, I would send email to the company: "FYI: I work from home today". As long as one of three IT guys was on the floor (to help traders in case their monitors go dark) they did not care where two others were.

So the question thus becomes: How valuable is the Joel Test? Why bother with it?

答:
I think it's important to keep in mind what the Joel test is for.

I don't think it in any way measures working conditions at a company. I don't think it was ever meant to do that. Your question seems to imply that this is what it gauges.

Joel claims this is a test is to

come up with my own, highly irresponsible, sloppy test to rate the
  quality of a software team.

Personally, while I believe everything on that list is important, I don't believe it is an accurate measure of how "good" a team is. Nothing is going to replace smart people with a solid work ethic.

If you have a team of smart people with a solid work ethic with a 0 on the Joel test, it will outperform a team of lazy idiots with a perfect score on the Joel Test any day of the week.

That being said, a team of smart people with a solid work ethic will likely implement at least some of the things on the Joel test.


答:
The Joel Test has nothing to do if you can have a comfortable position in a company. And #9: Yes, it is a sign that you can where you are.

It's about professional software development. In a very small IT with a small codebase that everybody knows very well, not all of the points are as important from my opinion, but 1-3 are:

1) Do you use source control?

This is essential. Set up a Git or Subversion repository immediately to have the possibility to check changes made since the last release to identify a buggy change or retest a report on a non-actual version.

2) Can you make a build in one step?

Build (and test everything) should be as easy as possible to force the developers to do it often!

3) Do you make daily builds?

A continious integration server is set up easily (like Jenkins, CruiseControl or a professional one like Bamboo or TeamCity) and ensures every change will be tested automatically and every developer gets informed about failures. 1. and 2. are prerequisites for this one!

The other point become more important the more developers are working on the code and the more complex the software becomes. For some of them there are work arounds (headphones for 8. for example.), but all of them will make a software company become more professional I think.

So think about it, and see if some of them make sense for you and which of them you can start by yourself. Point 1. to 3. should be possible and the preconditions can be done by one developer on a single day.

Title: Is the Joel Test really a good gauging tool?

Body:
I just learned about the Joel Test. I have been computer programmer for 22 years, but somehow I never heard about it before. I consider my best job so far to be this small investment managing company with 30 employees and only three people in the IT department.

I am no longer with them, but I had being working there for five years – my longest streak with any given company. To my surprise they scored extremely poor on the Joel Test. The only two questions I would answer “yes” are #4: Do you have a bug database? And #9: Do you use the best tools money can buy? Everything else is either “sometimes” or straight “no”.

Here is what I liked about the company however:

Good pay. They bragged about it to my face, and I bragged about it to their face, so it was almost like a family environment.

I always knew the big picture. When writing code to solve a particular problem there were no ambiguity about the business nature of that problem. Even though we did not always had written specifications we could ask business users a question anytime, often yelling it across the floor. I could even talk to executives any time I felt like doing it: no appointment necessary.

Immediate feedback. Once we implement a solution and make business users happy they immediately let us know that, we (programmers) become heroes of the moment.

No red tape. I could always buy any tools I deemed necessary, and design solutions the way my professional judgment dictates.

Flexibility. If I had mid-day dental appointment that is near my house rather than near the office, I would send email to the company: "FYI: I work from home today". As long as one of three IT guys was on the floor (to help traders in case their monitors go dark) they did not care where two others were.

So the question thus becomes: How valuable is the Joel Test? Why bother with it?


问:
Working on someone else's code
I have hardly a year's experience in coding. After I started working, most of the time I would be working on someone else's code, either adding new features over the existing ones or modifying the existing features. The guy who has written the actual code doesn't work in my company any more. I am having a hard time understanding his code and doing my tasks. Whenever I tried modifying the code, I have in some way messed with the working features. What all should I keep in mind, while working over someone else's code?</p>

答:
There are some really nice answers here. But I think it may also be worth mentioning how much familiarity with good design patterns can help, to read (well-written) existing code and to write readable code.

Of course it can be very confusing when you encounter a SomethingFactory in existing code, that does not actually follow the factory pattern. But as much as your team and framework allows, it may be beneficial to keep such cases to a minimum.

Following design patterns (where the business needs allow it) can also significantly reduce code duplication which in turn reduces bugs on future modifications.

Some good sources on design patterns are

http://sourcemaking.com/design_patterns

http://www.oodesign.com/

and of course the book

http://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612

Title: Working on someone else's code


问:
Trace code pascal
I haven't worked with Pascal so far, and my problem is understanding the recursive aspects that prm assignment operators and how the final (correct) value is derived. Would someone please explain that line for me. </p>

```<code>Program test(output);

FUNCTION prm(az:integer) : real;
begin
    if az = 1 then
        prm := sqrt(12)
    else
        prm := sqrt(12*prm(az-1));
end;

begin
    writeln(prm(30):0:2);
end.
</code>```

答:
This is a recursive function in pascal.  The 'return' value that C like language people are familiar with is instead done by assigning a value to the psuedo-value of the function name itself.

When passed a parameter of 1, it returns the square root of 12.

When passed a parameter of 2, it returns the square root of 12 times the square root of 12 (the value it was passed with 1).

When passed a parameter of 3, it returns the square root of 12 times the value when it was passed with 2.

And so on...

Title: Trace code pascal


问:
Entity Framework 5, separating business logic from model - Repository?
I am working on my first public-facing web application and I’m using MVC 4 for the presentation layer and EF 5 for the DAL.  The database structure is locked, and there are moderate differences between how the user inputs data and how the database itself gets populated.  I have done a ton of reading on the repository pattern (which I have never used) but most of my research is pushing me away from using it since it supposedly creates an unnecessary level of abstraction for the latest versions of EF since repositories and unit-of-work are already built-in.

My initial approach is to simply create a separate set of classes for my business objects in the BLL that can act as an intermediary between my Controllers and the DAL.  Here’s an example class:

```<code>public class MyBuilding
{
    public int Id { get; private set; }
    public string Name { get; set; }
    public string Notes { get; set; }

    private readonly Entities _context = new Entities(); // Is this thread safe?
    private static readonly int UserId = WebSecurity.GetCurrentUser().UserId;

    public IEnumerable<MyBuilding> GetList()
    {
        IEnumerable<MyBuilding> buildingList =
            from p in _context.BuildingInfo
            where p.Building.UserProfile.UserId == UserId
            select new MyBuilding {Id = p.BuildingId, Name = p.BuildingName, Notes = p.Building.Notes};
        return buildingList;
    }

    public void Create()
    {
        var b = new Building {UserId = UserId, Notes = this.Notes};
        _context.Building.Add(b);
        _context.SaveChanges();

        // Set the building ID
        this.Id = b.BuildingId;

        // Seed 1-to-1 tables with reference the new building
        _context.BuildingInfo.Add(new BuildingInfo {Building = b});
        _context.GeneralInfo.Add(new GeneralInfo {Building = b});
        _context.LocationInfo.Add(new LocationInfo {Building = b});
        _context.SaveChanges();
    }

    public static MyBuilding Find(int id)
    {
        using (var context = new Entities())  // Is this OK to do in a static method?
        {
            var b = context.Building.FirstOrDefault(p => p.BuildingId == id && p.UserId == UserId);
            if (b == null) throw new Exception("Error: Building not found or user does not have access.");
            return new MyBuilding {Id = b.BuildingId, Name = b.BuildingInfo.BuildingName, Notes = b.Notes};
        }
    }
}
</code>```

My primary concern: Is the way I am instantiating my DbContext as a private property thread-safe, and is it safe to have a static method that instantiates a separate DbContext?  Or am I approaching this all wrong?  I am not opposed to learning up on the repository pattern if I am taking the total wrong approach here.

答:
Because the database schema is both out of your scope and liable to change, it is extra important that you isolate it from your main code base. The mapping and table manipulation operations you are calling from your Create and GetList functions and should ideally live in your DAL. That way, your entities and business logic classes will be unaffected by unexpected changes to EF generated code. Even major changes to the database schema then become merely a matter of changing the mapping functions.

Other that that, I would avoid having business entity instances that have calls to load other instances of their own type - it smells of single responsibility principle violation, as your MyBuikding instances are both data finder objects and data entities. You could get your entities directly from calls to your DAL repositories, or via some intermediate service layer calls if you will require business logic.


答:
It has been remarked above that you need to understand the purpose of the system, not just the details of the code. A programmer with enough experience to write an order entry system is generally comfortable with the 'moving forward' part, which involves selecting products, formatting an invoice, and processing the payment.  Where they get stuck is when the user decides 'no never mind' and starts backing out transactions, or when they make an error in the payment processing and hit the 'back' button. At that point a lot of programmers get flummoxed, because they see code 'showing up out of nowhere' and can't figure out why it's there.

In short, you have to understand not just the 'normal flow', but all the backtracking that's necessary if someone makes a mistake or changes their mind.  This gets even worse with supervisor overrides, where some code can only be run with certain account privileges.

If someone writes 10,000 lines of code a year, and an application has a ten year 'life', then a programmer responsible for picking up someone else's work might have to understand 100,000 lines of code.  Divide this by 50 lines per page is 2000 pages.  If the program is written to a design pattern, the programmer will find that the understanding of one 'block' leads to at least a general understanding of most of the rest.  If not, then it's necessary to read every last damn line.

Some programmers 'just do what they're told' and write spaghetti.  They never do understand the 'big picture' - they simply put in fixes when users complain.  In such a circumstance it is a good idea to start migrating whatever you can to an appropriate pattern.  Eventually this may mean recoding stuff that isn't 'broken'.  Don't worry about it, just make sure that as long as it's your project it's progressively more maintainable.

Title: Working on someone else's code

Body: I have hardly a year's experience in coding. After I started working, most of the time I would be working on someone else's code, either adding new features over the existing ones or modifying the existing features. The guy who has written the actual code doesn't work in my company any more. I am having a hard time understanding his code and doing my tasks. Whenever I tried modifying the code, I have in some way messed with the working features. What all should I keep in mind, while working over someone else's code?</p>


答:
I can't stand Joel test because it requires you to give a simple yes or no answer. Below I'll give few examples on how this test completely fails in my eyes.

Do you use source control?

A1: Yes

A2: Yes, I do a check in once a week and I don't have any kind of version control strategy.

Do you have a spec?

A1: Yes

A2: Yes, it's written on a bit of A4 paper somewhere on my desk.

Do you have testers?

A1: Yes

A2: Yes, we have two testers and 20 developers.

Do new candidates write code during their interview?

A1: Yes

A2: Yes, we ask them to write FizzBuzz app

My point is, that if somebody simply gives you a 'Yes'/'No' answer, than it won't tell you anything about their company. I personally get put off the company as soon as Joel's test gets mentioned.


问:
Variable declaration versus assignment syntax
Working on a statically typed language with type inference and streamlined syntax, and need to make final decision about syntax for variable declaration versus assignment. Specifically I'm trying to choose between:

```<code>// Option 1. Create new local variable with :=, assign with =
foo := 1
foo = 2

// Option 2. Create new local variable with =, assign with :=
foo = 1
foo := 2
</code>```

Creating functions will use = regardless:

```<code>// Indentation delimits blocks
square x =
    x * x
</code>```

And assignment to compound objects will do likewise:

```<code>sky.color = blue
a[i] = 0
</code>```

Which of options 1 or 2 would people find most convenient/least surprising/otherwise best?

答: Both alternatives are bad.  The first because it is far from obvious that a := operator creates a local variable, and the second because it means you have two different meanings for the = operator.  Learn Dennis Ritchie's lesson, and don't have two operators that appear to be assignments, one of which is not.


问:
RequestContextHolder.currentRequestAttributes() and accessing HTTP Session
Need to access HTTP session for fetching as well storing some information.I am using Spring-MVC for my application and i have 2 options here.

User Request/ Session in my Controller method and do my work

Use RequestContextHolde to access Session information.

I am separating some calculation logic from Controller and want to access Session information in this new layer and for that i have 2 options

Pass session or Request object to other method in other layer and perform my work.

use RequestContextHolder.currentRequestAttributes() to access request/ session and perform my work.

I am not sure which is right way to go? with second approach, i can see that method calling will be more clean and i need not to pass request/ session each time.

答:
I would approach this problem a bit differently. Let's assume you need only an attribute "attr1" from the session. So what you actually should do is to get this attribute in @Controller pass it to your calculation logic class (@Service), return the result of the calculation back to @Controller and store it in session. Thanks to that your calculation logic will not be independent from a web layer (HttpSession), hence reusable.

E.g.:

```<code>@Controller
public class AController {

    @Autowired
    private SomeCalculationService someCalculationService;

    @RequestMapping(value = "/", method = RequestMethod.GET)
    @ResponseBody
    public Account accounts(HttpSession httpSession) {
        MyData myData = httpSession.getAttribute("attr1");
        SomeResult someResult = someCalculationService.calculate(myData);
        httpSession.setAttribute("attr2", someResult);
    }
}
</code>```

Body:
I would approach this problem a bit differently. Let's assume you need only an attribute "attr1" from the session. So what you actually should do is to get this attribute in @Controller pass it to your calculation logic class (@Service), return the result of the calculation back to @Controller and store it in session. Thanks to that your calculation logic will not be independent from a web layer (HttpSession), hence reusable.

E.g.:

@Controller
public class AController {

    @Autowired
    private SomeCalculationService someCalculationService;

    @RequestMapping(value = "/", method = RequestMethod.GET)
    @ResponseBody
    public Account accounts(HttpSession httpSession) {
        MyData myData = httpSession.getAttribute("attr1");
        SomeResult someResult = someCalculationService.calculate(myData);
        httpSession.setAttribute("attr2", someResult);
    }
}