问:
Continuous integration and modifying existing UI automation tests
Our team is currently facing a situation where we are changing a feature that is in the product today. This feature has Selenium automation tests associated with it.

We are performing a fairly major overhaul of the system, including its UI. We expect this work to take quite a few sprints. During this time, other teams may do work that would affect the feature as it exists today. For this reason, we want the existing automation tests for the feature to remain intact so that they can detect issues.

Of course, we will need to write automation for the feature as it will be after our changes are done. The most efficient way for us to do this from a Dev/QA perspective would be to modify the existing test cases in a separate branch (testing locally) and then merge those changes in when the feature is ready. That way the existing automation continues to function and we don't have to do extra work duplicating each test.

However, this separate branch doesn't fit well with the principles of continuous integration (which our organization likes to adhere to). Is our only CI-compliant option to do the extra overhead of duplicating the tests for modification?

答:
I would try to see it from this point of view:

you are going to develop a parallel branch for a defined time interval (which is of course oppsoed to the "standard" CI model)

this will cause a parallel development of your tests as well - branch them accordingly (and merge them back into the trunk when you merge the main source code).

apply that branch to your CI environment as well - for example, if you have automated builds and tests on a server, let your server build and test both, the trunk as well as the branch, as long as the branch exists

you can still apply continuos integration techniques to your trunk and your branch separately

to minimize the effort of merging later, you should try to merge any changes in the trunk back into the development branch as often as possible, once per day would be best. This may not be simple in the area where the UI of the dev branch differs from the trunk, so try to restrict changes to the trunk UI in that area to a minimum during that time.

As you see, when you leave the "CI" path and make a long-term branch and merge, you may have to do it completely, for your whole source code including the tests and the CI environment, causing additional administrative effort. But sometimes pure CI is just not the development model you need and it may be worth it.

EDIT: as an alternative, you could try avoid branching within your VCS and solve your problem with a feature toggle. You could design that toggle in a way so can switch between the old and the new UI at runtime. This may be used within your Selenium tests - modfiy the tests in a way so the old tests run only against the old UI (feature disabled), and the tests adapted to the new UI only against the new UI (feature enabled).


问:
Does an in-code enumeration provide a stronger domain model than a static table?
Does an in-code enumeration provide a stronger domain model than a static database table?

As an example, say I have an Marble entity, with a Color attribute. The color attribute has a finite set of possible values—say red, green, blue. Say the database team recommends having a static S_ValidColors table, to the effect of:

```<code>-----------------------
| ColorId | ColorName |
-----------------------
|    0    |    Red    |
-----------------------
|    1    |   Green   |
-----------------------
|    2    |    Blue   |
-----------------------
</code>```

Whereas I'm thinking more along the lines of (this is just a sketch for the general concept):

public class Color {
    public static const Color Red = Color(0);
    public static const Color Green = Color(1);
    public static const Color Blue = Color(2);

    private Color(uint typeCode) {
        ...
    }
    ...
}
```

Aside from the question of which is better (which probably depends on any number of other factors not represented here), is this a question that touches how strong the domain model is? Is one way more anemic than the other?

答:
Creating a static database model can provide some difficulties without any benefits:

Reading from a database will be slower;

If the color values change update deployment will be more difficult since you won't only need to update the source, but also the database;

Like Euphoric mentioned, you will be more prone to errors in case some of the objects in the DB are missing or modified.

So if the user is not expected to add his own colors, I don't see any reason to store them in a database.

ContentLicense: CC BY-SA 3.0


问:
When to use embedded script language?
I already read some post about the why use embedded script language but I want to ask when to use it.

I have implemented an Objective-C / Javascript binding framework which allow me to write Javascript to use any Objective-C classes and methods. I found it very useful for debugging purpose because I can check / modify the internal state of my app at runtime. But I also found I still prefer to write ObjC code instead of JS code when building my app for some reasons:

Code completion. If I want to call some UIKit method froom JS, I often have to check the document for its name compare to just type first few letters and let Xcode complete it for me in ObjC.

All the benefit of static typed language. ObjC is static typed and dynamic typed language so compiler can do lots type checking for me when possible.

Performance?

C binding to JS not ready yet (this required to parse header and generate code to expose C function, enum, struct, etc)

More natural to write ObjC when dealing with ObjC methods. (e.g. in JS write code like view.setEdit_animated(true, true) compare to ObjC [view setEdit:YES animated:YES]

But I feel I should write more JS code so I can take the benefit scripting language (e.g. replace methods with bug fixes at runtime)

I am not sure which part of my app should be written in JS and which part should be written in ObjC. Any advice?

Also any design pattern can be used for embedded script language?

答:
There are two main benefits of scripting in my opinion:

it is usually faster

and it is usually faster

The first faster is for JIT compilation and underlying C interpreters that most languages have and the second one is for not needing to recompile your code.

Scripting should be used whenever you want to quickly change behavior without the need of recompilation. So you probably want to script the user interface and just tell it how to connect to the binary code. Writing GUIs in statically typed languages is most likely hard and complex. Most scripting languages are also useful when you want to do things like events or implement simple behavior in certain parts of your application.

The benefit of splitting it is, that you get a program core that is compiled once, and a number of script files that maybe make up your application behavior. So actually there is a third advantage to it: Scripting is usually faster. This time in terms of application development. You just adapt a script file and run your program again, or even change scripts at runtime and the immediately see the results.

One field where applications in native binaries are really faster than scripts is when it comes to hardware interaction and OS calls. Since scripting usually is intended to be cross-platform, you are likely to have to use the native libraries for applications. Scripting languages would have to wrap them, applying a performance penalty. And also Interpreters have their own threading model and garbage collection. If you need control over these facilities, choose native binaries.

Title: When to use embedded script language?


问:
Best practice for code coverage of empty interface methods
Given a class that implements an interface, but does not need all of the methods implemented, what is the best practice for unit testing this class with respect to code coverage? - or is it considered a sign for a code smell?

To make the problem more concrete, consider a Java class (the question is not limited to Java though) that implements ComponentListener but derives from some X (so as to rule out the choice to use ComponentAdapter). The class is however only interested in the componentResized() method and leaves the other callback method bodies empty.

When checking the code coverage, we get a report that indicates correctly that the remaining methods are untested. For obvious reasons, I hesitate to add a test that simply calls a no-op method for the sake of coverage.

While I am not bound to reach a certain coverage, I still think that in and of itself, this phenomenon may indicate a code smell with respect to the single-responsibility principle. On the other hand, it's not far-fetched either that a component representation is responsible for updating its state on a resize.

Is there some sort of consensus or best practice on how to handle such methods, or is the question illegitimate as in it is a result of a supposedly bad design?

答:
I'm not sure what the best practice would be but to me, your problem isn't a problem of empty interface methods - it's a problem that your interfaces are wrong.

If you implement an interface, implement the entire interface - if the interface is too broad or has functionality that you're not interested in then split the interface and have the main interface implement sub-interfaces and have your component only implement the bit that's appropriate.


答:
I would write a test for the interface, which calls all methods and ignores the results (just to check if no exceptions are thrown ant any method).
Than you can make your test-class extend this test-class of the interface.

This way you get full coverage.

Title: Best practice for code coverage of empty interface methods

Body:
Given a class that implements an interface, but does not need all of the methods implemented, what is the best practice for unit testing this class with respect to code coverage? - or is it considered a sign for a code smell?

To make the problem more concrete, consider a Java class (the question is not limited to Java though) that implements ComponentListener but derives from some X (so as to rule out the choice to use ComponentAdapter). The class is however only interested in the componentResized() method and leaves the other callback method bodies empty.

When checking the code coverage, we get a report that indicates correctly that the remaining methods are untested. For obvious reasons, I hesitate to add a test that simply calls a no-op method for the sake of coverage.

While I am not bound to reach a certain coverage, I still think that in and of itself, this phenomenon may indicate a code smell with respect to the single-responsibility principle. On the other hand, it's not far-fetched either that a component representation is responsible for updating its state on a resize.

Is there some sort of consensus or best practice on how to handle such methods, or is the question illegitimate as in it is a result of a supposedly bad design?


答:
An Interface represents a contract that your implementation class agrees to fulfill. The parts of that contract that you are not interested in, you are still implementing and therefore they still have behavior - the behavior being either do nothing (as I expect in your example) or throwing an UnsupportedOperationException if you are purposefully reducing the scope of the implementation (such as List#Clear).

I think it is still important to a) document the lack of implementation, b) add tests to validate the implementation so that when someone comes along and changes it, your tests break and they have to think a little before modifying your IOnlyCareAboutResizedComponentsListener class.


答:
Michael's answer shares my feeling that it is a design smell in the first place.

If it is an empty callback that gets called at runtime, you should write the test to make sure that nothing happens in that method.

If the method is not implemented and must never be called, you should consider throwing a java.lang.UnsupportedOperationException.


问:
Update strategy for a software framework once it has been deployed
I need to update a software framework once it has been deployed.

The framework we are creating is made up of .NET 4.0 libraries (in Visual Studio). This common set of code libraries will be available for 2 .NET Windows services, a standalone .NET application, and a .NET MVC 4 website. (The services will run on a single server, and the standalone application will be used by a select few individuals.)

We are in the early stages of the project, and the big questions that have come up are:

What happens when we have to make a change to 1 or more of the framework files?

How do we deploy patches and/or updates to each part that relies on the framework?

What considerations can we make early on to make the update/patching process easier later on?

This is the first time our small team has tackled a problem like this and we're not sure what the best practices are.

edit

We have 4 software pieces that rely on the framework: 2 services, 1 app, 1 website. Once this all hits production, there are already upgrades and updates planned. The updates will require changes to the framework files and the programs. My question was intended to refer to that later process of redeploying the upgrades. Once we're in production, and we've coded the updates/upgrades to the framework files, the applications, and the website, deploying those updates will need to happen as quickly as possible. What do we need to do to streamline that process?

答:
For production you want to use Windows installer - MSI - files.

Once its installed correctly, you can use patch installation file to update (msp files).

The Windows Installer site has a whole heap of information on patching and upgrading.

I'd use Wix to create the installer files in the first place.


问:
what are the practical steps of software development life cycle
I am building a software and trying to learn the typical steps for software life cycle, I am not sure if what I did is correct or enough so I would like to ask for the typical steps you follow during your life cycle in terms of actual steps taken for example requirement gathering is a not the step i mean, but gathering requirements using User Stories from the customer or from the requirements documents is the step I mean.

This is what I do now,

Write User Stories from the requirement document I had.

Write Use Cases for these stories.

Collected nouns from the requirement documents and used them as classes to build class diagram.

Draw state diagrams for main entities in the class diagram.

Draw database diagram to map the class diagram to database tables

Started coding to 3-tier architecture.

Please tell me if I am doing it right or missing something.

答:
Ah, one of life's great questions.  There are many ways to answer this question and the answer that works for you will depend entirely on:

The skill and professionalism of the development team

The nature of the development work

How the customers interact with the development team

How the development team is financed

The character of the manager / company owner responsible for the development team

The latest management buzz words on software development

Ohh, who am I kidding, the list is infinite.

Software development is always done somewhere on the spectrum between complete chaos, and a defined development methodology that has some flaws, but its how we have decided to do it here. Most developers believe its closer to the chaos end, and managers think its following the methodology

The steps you have described are part of several methodologies, but are not appropriate to be used in other situations.  Take for example, the start-up company boldly going to launch a new product in a new market sector with no existing customers. Its very difficult to write clear and definitive user stories when you don't yet know who your customers are going to be, or what they expect your service to do in the kind of detail needed to do this properly.

Other environments, are very formal, This IS the set of requirements, That IS what you will deliver, and last month IS when you will have delivered it. (Otherwise characterised as industry standard software - costs too much to develop, doesn't do what the end customer wanted, full of bugs and delivered years late)

In reality, the practical solution is this:

There are a range of process approaches that have strengths and weaknesses. You make a choice from these approaches of which aspects fit within the business and team constraints about how the world around the development team operate, and develop accordingly.

If your customer is big on requirements, specifications etc, then you are more likely going to be developing along a waterfall approach.

If your customer is problem focused, 'solve this problem for me' then you are much more likely going to be doing agile or rapid prototyping development.


问:
Object Oriented Programming Concepts and Interviews
I'm an Object Oriented Programming fanatic. I have always believed in modelling solutions in terms of objects. It is something that comes to me naturally. I work with a services start up that essentially works on application development using OOP languages. So I tend to test understanding of OOP in the candidate being interviewed.

To my shock, I found very very few developers who really understood OOP. Most candidates brainlessly spit out definitions they mugged up from some academic book on object oriented programming but they don't know squat about what they are saying. Needless to say I reject these candidates. However, over the course of time, I ended up rejecting almost 98% of the candidates. Now this gets me thinking if I'm being over critical about their OOP skills. I still believe OOP is fundamental and every programmer MUST GET it. Language knowledge and experience is secondary.

Do you think I'm being over critical or do I just get to interview bad programmers unfortunately?

EDIT:

I usually interview programmers with 2 to 5 years of experience. The position that I usually interview for is Ruby/Ruby on Rails application developer.

答:
Disclaimer: I'm not a big fan of this test. But I must agree that failing it is a pretty good indication we don't know OO enough to state on our resume that we know OO.

A small exercice that requires just few minutes to complete for someone that know OO.

The question is: "What is the output on the following code?"

```<code>using System;

namespace Polymorphism
{
    class Animal
    {
        public void MakeSound() { Console.WriteLine("bip"); }
        public virtual void MakeSound2() { Console.WriteLine("bip"); }
        public void MakeSound3() { Console.WriteLine("bip"); }
    }

    class Dog : Animal
    {
        public void MakeSound() { Console.WriteLine("woof"); }
        public override void MakeSound2() { Console.WriteLine("woof"); }
        public new void MakeSound3() { Console.WriteLine("woof"); }
    }

    class Test
    {
        static void Main(string[] args)
        {
            Animal animal;
            Dog dog;

            animal = new Animal();
            dog = new Dog();
            animal.MakeSound();
            dog.MakeSound();

            animal = new Dog();
            animal.MakeSound();

            animal = new Animal();
            dog = new Dog();
            animal.MakeSound2();
            dog.MakeSound2();

            animal = new Dog();
            animal.MakeSound2();

            animal = new Animal();
            dog = new Dog();
            animal.MakeSound3();
            dog.MakeSound3();

            animal = new Dog();
            animal.MakeSound3();

            Console.ReadKey();
        }
    }
}
</code>```

Oh and if you are a real a***ole, you can add this just before the Console.ReadKey(); statement:

```<code>    dog = new Animal();
    dog.MakeSound3();
</code>```

And if being an a***ole is not enough, add this:

```<code>    dog = (Dog)new Animal();
    dog.MakeSound3();
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Disclaimer: I'm not a big fan of this test. But I must agree that failing it is a pretty good indication we don't know OO enough to state on our resume that we know OO.

A small exercice that requires just few minutes to complete for someone that know OO.

The question is: "What is the output on the following code?"

using System;

namespace Polymorphism
{
    class Animal
    {
        public void MakeSound() { Console.WriteLine("bip"); }
        public virtual void MakeSound2() { Console.WriteLine("bip"); }
        public void MakeSound3() { Console.WriteLine("bip"); }
    }

    class Dog : Animal
    {
        public void MakeSound() { Console.WriteLine("woof"); }
        public override void MakeSound2() { Console.WriteLine("woof"); }
        public new void MakeSound3() { Console.WriteLine("woof"); }
    }

    class Test
    {
        static void Main(string[] args)
        {
            Animal animal;
            Dog dog;

            animal = new Animal();
            dog = new Dog();
            animal.MakeSound();
            dog.MakeSound();

            animal = new Dog();
            animal.MakeSound();

            animal = new Animal();
            dog = new Dog();
            animal.MakeSound2();
            dog.MakeSound2();

            animal = new Dog();
            animal.MakeSound2();

            animal = new Animal();
            dog = new Dog();
            animal.MakeSound3();
            dog.MakeSound3();

            animal = new Dog();
            animal.MakeSound3();

            Console.ReadKey();
        }
    }
}

Oh and if you are a real a***ole, you can add this just before the Console.ReadKey(); statement:

    dog = new Animal();
    dog.MakeSound3();

And if being an a***ole is not enough, add this:

    dog = (Dog)new Animal();
    dog.MakeSound3();


问:
State pattern long state class names
I am using state pattern on 28 states in my application. The states are for membership cards that has 7 major states, there are 4 boolean attributes for the membership card that actually affects the its behavior so I have decided to embed them with states, that's how it multiplied to 28 states.

The problem now is with states class naming, it is getting crazing, I am ending up with class state named like this Membership-UnderCreation-Printed-Linked-Premium-Frozen ----- I have hyphened different attributes to make it clear.

Is it ok for state class names to be like this?

答:
It is not the strategy I personally would have chosen.  I would have defined the 7 states, and defined the 4 attributes as properties of the application object.  You then have to define business rules that apply to the application based on these attributes that may apply changes of state to the application.

The benefit of this approach is that additional business rules are implemented in code as additional business rules which is very maintainable.

In your design, you are encoding business rules into the state machine, which means that over time, as business rules are introduced the state machine grows and becomes completely unmaintainable.

As an example:

```<code>public decide_next_state(IApplication application,  Dictionary<state, List<IBusinessRules>> rules)
{
    //  by default we remain in the current state.
    next_state = application.current_state

    foreach(state in rules.keys())
    {
        bool matched = true;
        foreach(rule in rules[state])
        {
          //  if this business rule blocks the transition, then it
          //  returns false.
          if rule.apply(application) == false
          {
            matched = false;
            break;
          }
        }
        if(matched == true)
        {
           next_state = state;
           break;
        }
    }
    return next_state;
}
</code>```

Now with this code, you would pass in the rules dictionary for the applications current state.  The rules then define which state the current application is will transition to.  However it can only make that transition if all the business rules for that transition allow it.

This is a very simple model, but it can be made much more complex if you need to.

Title: State pattern long state class names

Body:
It is not the strategy I personally would have chosen.  I would have defined the 7 states, and defined the 4 attributes as properties of the application object.  You then have to define business rules that apply to the application based on these attributes that may apply changes of state to the application.

The benefit of this approach is that additional business rules are implemented in code as additional business rules which is very maintainable.

In your design, you are encoding business rules into the state machine, which means that over time, as business rules are introduced the state machine grows and becomes completely unmaintainable.

As an example:

public decide_next_state(IApplication application,  Dictionary<state, List<IBusinessRules>> rules)
{
    //  by default we remain in the current state.
    next_state = application.current_state

    foreach(state in rules.keys())
    {
        bool matched = true;
        foreach(rule in rules[state])
        {
          //  if this business rule blocks the transition, then it
          //  returns false.
          if rule.apply(application) == false
          {
            matched = false;
            break;
          }
        }
        if(matched == true)
        {
           next_state = state;
           break;
        }
    }
    return next_state;
}

Now with this code, you would pass in the rules dictionary for the applications current state.  The rules then define which state the current application is will transition to.  However it can only make that transition if all the business rules for that transition allow it.

This is a very simple model, but it can be made much more complex if you need to.


问:
How does MVC work with the principle "Tell, Don't ask"?

Procedural code gets information then makes decisions. Object-oriented
  code tells objects to do things.

— Alec Sharp

So, when a view wants to display some information that is suppose to be derived from properties of a model it is displaying, should the calculation be part of the model or the view?

Ideally the view should tell the object about the information it needs, and model should do the calculation and return the result.

But now, should the model start having new methods every time a new type of view wants to display extra information which is derived out of the model's property?

Should such methods be in the view or in the model? Or in such cases should we subclass the model, add the required methods, and then assign it to the view?

I am an Objective-C developer, I can also add a category to the model for the view but in languages where we don't have features where we can add methods to objects and classes at runtime, what is the ideal design?

Or are models in MVC meant to be just information in key-value pairs instead of real objects to be passed around, where a view reads each value based on a getter?

答:
Ideally view should tell the object about the information it needs, model to should do the calculation and return the result.

That maybe an object oriented way, but not MVC. In MVC, the view typically sends a message to the controller "I want to display information", and the controller does the calculation using the model (or using model attributes or functions). Afterwards, the controller sends the result message back to the view (typically using an interface to decouple from the concrete kind of view).

but now, should model start having new methods every-time a new type of view wants to display extra information which is derived out of model's property?

Information derived out of model's property can be calculated either

in the model

in a controller using the model

I would place such calculation functions in the model only if they are not view-specific and have a certain chance of beeing reused. Functions totally specific to one view are better suited for the corresponding controller.


问:
What does "Released under MIT and GPL license" mean?
There are lots of projects released under more than one license. One example is Mozilla's tri-license, which states that the Software is released under the MPL, but the user can also choose GPL or LGPL instead of MPL (I think this is because the MPL license is incompatible with the GPL license).

However, I came across projects released under both the GPL license and the MIT license. What conditions must be met in this case? For the MPL/GPL/LGPL case, things are clear because you can choose MPL or GPL or LGPL. But from GPL & MIT I understand that the conditions from both licenses must be met at the same time in order to use it, and this doesn't make much sense because they have different purposes.

In this case, should the MIT license be interpreted as an exception, similar to, for example, the QT's LGPL exception or as an additional set of conditions on top of the GPL license?

答: It means that you can pick either GPL or the MIT license (not both at the same time). If you pick GPL you need to go with the GPL terms (eg. all derivative works must also be released under GPL). If you pick MIT that's not required (just an example among the many terms). </p>


问:
What techniques are there for debugging remote client side errors?
What techniques are there for debugging remote client side errors in a web application, especially when they only affect a small subset of users?

In my case we have an app that is working well for hundreds of users, internally and externally, but a handful (12) have a specific problem with a JavaScript that prevents them from using the site.  We have screenshots of the error, have confirmed they have no server side errors, confirmed that everything is getting rendered to the browser correctly, have seen the specific error in the IE console, but still have no idea why it isn't working for these specific users.  The issue is exhibiting on different versions of IE.  We have never been able to replicate the problem here.

I'm not looking for a solution to my problem here, but rather what are the steps you would take to solve this kind of problem, and what tools there may be that might help?

答:
I'll start by asking what version of IE is used. There are chances that in this version, there is a JavaScript error, but any other version runs the code fine. Remember that those JavaScript errors are tricky to test, since IE compatibility mode won't help: on IE10 in IE7 compatibility mode, it's still the IE10 JavaScript engine which runs.

Another problem may come from the specific configuration. An accessibility option. A blocked resource. It could be anything, which makes it particularly difficult to find. In order to get an idea, I would ask one of the users to be able to connect to his machine remotely in order to inspect the configuration by hand. Of course, this works well for internal products done for a small set of customers, but is out of the question for a public website.

Finally, changing the JavaScript code to trace as much information as possible (and submit it to the server) can also help. With enough hard data, A/B testing can be used in order to narrow the problem by making small variants to the code and check whether they solve the issue.


问:
Why can static methods only use static data?
I don't understand why a static method can't use non-static data. Can anybody explain what the problems are and why we can't do it?</p>

答: Non-static data is associated to an instance of the class. Static methods (and data) are not associated to a particular instance of the class. There does not need to be an instance of a class to use static methods on it. Even if there were instance(s), there would be no way for Java to guarantee that you are operating on the instance you are expecting when you call a static method. Therefore, static methods cannot have access to non-static data.</p>


答:
It can use field data; consider the following java code:</p>

```<code>class MyBean {
    private String myString;

    static void myStaticMethod() {
        myString = "tada";/*not allowed; if this was possible how would
                           be different from a field without static?*/

        MyBean myBean = new MyBean();//allowed if associated with an instance
        myBean.myString = "tada";
    }
}
</code>```

Title: Why can static methods only use static data?

Body: I don't understand why a static method can't use non-static data. Can anybody explain what the problems are and why we can't do it?</p>

Body:
It can use field data; consider the following java code:

class MyBean {
    private String myString;

    static void myStaticMethod() {
        myString = "tada";/*not allowed; if this was possible how would
                           be different from a field without static?*/

        MyBean myBean = new MyBean();//allowed if associated with an instance
        myBean.myString = "tada";
    }
}


答:
In most OO languages, when you define a method inside a class, it becomes an Instance Method. When you create a new instance of that class, via the new keyword, you initialize a new set of data unique to just that instance. The methods belonging to that instance can then work with the data you defined on it.

Static Methods, by contrast, are ignorant of individual class instances. The static method is similar to a free function in C or C++. It isn't tied to a specific instantiation of the class. This is why they cannot access instance values. There's no instance to take a value from!

Static Data is similar to a static method. A value that is declared static has no associated instance. It exists for every instance, and is only declared in a single place in memory. If it ever gets changed, it will change for every instance of that class.

A Static Method can access Static Data because they both exist independently of specific instances of a class.

It might help to look at how you invoke a static method, compared to a instance method. Let's say we had the following class (using Java-like pseudocode):

```<code>class Foo {
    // This static value belongs to the class Foo
    public static final string name = "Foo";

    // This non-static value will be unique for every instance
    private int value;

    public Foo(int value) {
         this.value = value;
    }

    public void sayValue() {
        println("Instance Value: " + value);
    }

    public static void sayName() {
        println("Static Value: " + name);
    }
}

Foo foo1 = new Foo(10);
Foo foo2 = new Foo(20);

foo1.sayValue(); // Prints "Instance Value: 10" - called on foo1
foo2.sayValue(); // Prints "Instance Value: 20" - called on foo2

Foo.sayName(); // Prints "Static Value: Foo" - called on Foo (not foo1 or foo2)
</code>```

Update

As COME FROM points out in the comments, a static method is capable of working with non-static data, but it must be passed explicitly. Let's assume the Foo class had another method:

```<code>public static Foo Add(Foo foo1, Foo foo2) {
    return new Foo(foo1.value + foo2.value);
}
</code>```

Add is still static, and has no value instances of its own, but being a member of the class Foo it can access the private value fields of the passed-in foo1 and foo2 instances. In this case, we're using it to return a new Foo with the added values of both passed-in values.

```<code>Foo foo3 = Foo.Add(foo1, foo2); // creates a new Foo with a value of 30
</code>```

Body:
In most OO languages, when you define a method inside a class, it becomes an Instance Method. When you create a new instance of that class, via the new keyword, you initialize a new set of data unique to just that instance. The methods belonging to that instance can then work with the data you defined on it.

Static Methods, by contrast, are ignorant of individual class instances. The static method is similar to a free function in C or C++. It isn't tied to a specific instantiation of the class. This is why they cannot access instance values. There's no instance to take a value from!

Static Data is similar to a static method. A value that is declared static has no associated instance. It exists for every instance, and is only declared in a single place in memory. If it ever gets changed, it will change for every instance of that class.

A Static Method can access Static Data because they both exist independently of specific instances of a class.

It might help to look at how you invoke a static method, compared to a instance method. Let's say we had the following class (using Java-like pseudocode):

class Foo {
    // This static value belongs to the class Foo
    public static final string name = "Foo";

    // This non-static value will be unique for every instance
    private int value;

    public Foo(int value) {
         this.value = value;
    }

    public void sayValue() {
        println("Instance Value: " + value);
    }

    public static void sayName() {
        println("Static Value: " + name);
    }
}

Foo foo1 = new Foo(10);
Foo foo2 = new Foo(20);

foo1.sayValue(); // Prints "Instance Value: 10" - called on foo1
foo2.sayValue(); // Prints "Instance Value: 20" - called on foo2

Foo.sayName(); // Prints "Static Value: Foo" - called on Foo (not foo1 or foo2)

Update

As COME FROM points out in the comments, a static method is capable of working with non-static data, but it must be passed explicitly. Let's assume the Foo class had another method:

public static Foo Add(Foo foo1, Foo foo2) {
    return new Foo(foo1.value + foo2.value);
}

Add is still static, and has no value instances of its own, but being a member of the class Foo it can access the private value fields of the passed-in foo1 and foo2 instances. In this case, we're using it to return a new Foo with the added values of both passed-in values.

Foo foo3 = Foo.Add(foo1, foo2); // creates a new Foo with a value of 30


答:
Lets explain it with a hypothetical sample.

Imagine a simple class:

```<code>class User
{
User(string n) { name = n; };
string name;
}
</code>```

Now we create 2 instances of this class:

```<code>User Bones = new User("Bones");
User Jim = new User("Jim");
</code>```

now, think - what if we add a new static method to User, eg:

```<code>static string GetName();
</code>```

and you call it:

```<code>string x = User::GetName()
</code>```

what would x contain? "Jim", "Bones", or something else?

The problem is that a static method is a single method, defined on the class, not the objects. As a result, you don't know which object it might apply to. This is why its a special thing. Its best to think of static methods as individual things, like functions in C for example. That languages like Java have them contained inside classes is mainly a problem with Java not allowing anything to exist outside a class, so functions like this have to be forced inside a class in some manner (a bit like how main() is forced to be inside a class too when all sense says it should be a singular, standalone function).

Body:
Lets explain it with a hypothetical sample.

Imagine a simple class:

class User
{
User(string n) { name = n; };
string name;
}

Now we create 2 instances of this class:

User Bones = new User("Bones");
User Jim = new User("Jim");

now, think - what if we add a new static method to User, eg:

static string GetName();

and you call it:

string x = User::GetName()

what would x contain? "Jim", "Bones", or something else?

The problem is that a static method is a single method, defined on the class, not the objects. As a result, you don't know which object it might apply to. This is why its a special thing. Its best to think of static methods as individual things, like functions in C for example. That languages like Java have them contained inside classes is mainly a problem with Java not allowing anything to exist outside a class, so functions like this have to be forced inside a class in some manner (a bit like how main() is forced to be inside a class too when all sense says it should be a singular, standalone function).


问:
Level of detail of a user story
I am about to start User story sessions in my team. It's quite new for them and I am also wrestling with certain things. For the current project we have some well worked out wireframes.

I read a lot about the way of writing user stories. What the template should be like and about different aids like Invest

The plan is to turn them around in user stories. Lets say I have a screen where a user could edit an order. There is a lot of detail on that screen. Now when creating a user story of this story. Will it suffice to say:

As an Admin I can edit a purchase order so that mistakes typed by the
user can be enhanced.

Or should i specify each detail like:

As an Admin I can resend an invoice to the customer, so he can get a copy of his lost one.

As an Admin I can review the customer order so he has detailed information about each purchase

As an admin I can remove items forma on order so that in case the customer made a mistake I can remove Items.

And how about the acceptance criteria. How should the be defined for a user story as such. Where do I define which fields need to be shown on an order detail page? Can this be part of the acceptance criteria?

答:
Since this is tagged scrum, you likely want to defer to a more detailed user story. If you were using something like XP or FDD, you can be a bit more agile because the milestone is not time-based.

With Scrum, you really only want to define the user story enough to be able to adequately give an accurate time estimate - however much definition that requires.

It really depends on the whims of the team and the stakeholders, but if you delineate 10 aspects or subfeatures of editing purchase orders, you aren't likely going to be able to add another once the sprint has been planned, and if one of those subfeatures is involved enough (like removing items from an order, possibly), it may need to be turned into a feature with a story of its own.

It's impossible to do Scrum perfectly, however the end goal of Scrum is not to remove all ambiguity, but rather to clearly define basic functionality to remove enough ambiguity to give a mostly accurate time estimate.

Title: Level of detail of a user story


问:
Why isn't protection against SQL injection a high priority?
On Stack Overflow, I see a lot of PHP code in questions and answers that have MySQL queries that are highly vulnerable to SQL injection attacks, despite basic workarounds being widely available for more than a decade.

Is there a reason why these types of code snippets are still in use today?

答:
As a human, and a programmer, I find it remarkably easy to make mistakes, and overlook certain things, especially when pressed for time.

It's easy, and perhaps all too tempting, to blame a certain language, for being too accessible for its own good. But that would be glossing over the larger problem of human fallibility, regardless of the language chosen to program in.

Granted, we've come a long way since assembly language, and I think I would be far more productive programming in a more modern language, such as PHP, Python, Ruby, or Java.

PHP (and other scripting languages) have in fact lowered the barrier to entry. That may mean that more newcomers to programming try PHP first. But that certainly does not also mean that all PHP programmers are somehow less qualified, or less able to learn from their mistakes than programmers of other languages.

Rasmus Lerdorf created PHP in its original form back in 1994, it has evolved considerably since then. In its most modern incarnation, it supports object oriented programming, as well as superb frameworks, such as Symfony. PHP as a language has broken free from its original constraints, and has grown to offer great flexibility in how programmers can choose to use it. You can use it to create a 9,000 line script of spaghetti code, or you can use it within the context of a modern, MVC framework, such as Symfony: it's your choice!

I strongly suspect that security vulnerabilities are not restricted to a single language.
It's tempting to write off all PHP programmers as somehow less capable, or more prone to writing insecure code. But I wonder how much of that is language bias, and how much of it is fact?

OwnerDisplayName: Tomalak Geret'kal


答:
I think a better pattern if you need code coverage is using an abstract factory.  The difference between interfaces and abstract classes already has had some discussion on this site.  I find this explanation the most relevant for your question.

Are abstract classes / methods obsolete?


答:
Think of it as static methods living in a non-object-oriented dimension.

In the "object oriented dimension" a class can spawn multiples egos (instances), each ego has conscience of itself via its state.

In the flat, non-OO-dimension a class is oblivious of their egos living in the OO-dimension. Their world is flat and procedural, almost as if OOP had not been invented yet, and as if the class was a small procedural program, and the static data were just global variables.


问:
things to think of when moving into C-land
Hello

Over the years have I made a programming journey from C in 1990 to Pascal, C++ with I programmed commercially, java VHDL, C# and now I'm taking a look on F#.

In the spring I will go back to study embedded programming in C in a university course so before I do that I will refresh my knowledge in C.

I don't remember much of the C that I learnt and I think I am thankful for that for probably learned some bad habits back then.

I have some questions to get me on the way.

--edit--

To clarify: I am thankful for tips that have been given regarding embedded programming but now I am more interested in relearning C in general. Sorry if my question was unclear,

Compiler, Debugger, IDE? As a microslave I was thinking about 2010 C++ Express, any alternatives?

Where do you find good libraries with code for C. I'm thinking something similar to Boost, POCO in C++

Source for procedural programming patterns and best practices. Where can you find good code learn from?

Thanks in advance

Gorgen

答:
I can't say enough good things about Valgrind for memory error detection, spotting leaks, profiling (massif), not mentioning helgrind / cachegrind. Used in combination with a debugger such as GDB, many problems become shallow and trivial to correct.

Unfortunately, Valgrind isn't yet 'officially' ported to all popular embedded architectures, but it isn't far away.

The other thing I recommend doing is taking advantage of the fact that GCC is self hosting, it can compile itself for an array of architectures. Being able to manage cross compilation is very important - the system that actually compiles your code is quite often not the system that will actually run it.

Finally, get as intimate as you can with how malloc() is implemented. You might want to implement a garbage collector, use a static pool in lieu of asking the kernel for each block or do your own profiling / debugging. This coincides with the reference you made to alternative C library implementations.


问:
What is the benefit of 64 bit A7 in iPhone
I'm trying to figure out why going to 64 bit processors is such a big deal in an iPhone. I understand that there will be twice as many registers so the processor can work with twice as much data which should increase performance.

However I don't see many phones going to more than 4GB of memory any time soon. It seems like overkill and it would negatively impact battery life.

Another problem that I see is that most variables now need twice as much memory. This will create problems in a mobile environment with small amounts of memory.

I believe that the folks at Apple are intelligent and they probably have great reasons for doing this, I'm just trying to understand them.

EDIT

Don't know much about GPU's but I was told that with 64 bit registers 2 pixels can be loaded into each register and operations can be performed on them individually. Is there a graphical advantage regarding 64 bit?

答: I don't think there are a lot of technical benefits.  First I think it makes more sense when you consider the iPad (it has a bigger battery so it can support more ram, higher energy consumption by the processor, etc.). Second look at the other announcements going on right now. AMD just announced it is going to be shipping 64bit ARM processors in 2014.  This is basically Apple keeping market leadership in the face of what is coming to high end Android and Win8 tablets.</p>


问:
Seeking xinetd alternative for forking concurrent servers in Linux
I recently posted here asking about the drawbacks of having a server process bind to a dynamically assigned port.  That approach came about because xinetd, which launched the server process, allocates STDIN and STDOUT as the server's communication channel to the client, and we wanted the server to use a bidirectional socket.  The responses (and our operations team) convinced me to abandon that approach.

I need a daemon process to monitor a designated port and fork concurrent servers.  The server process is written using an I/O infrastructure that is socket-based.  We have developed a server process that can be launched by xinetd.  The first thing it does is to bind to a dynamically-assigned port number, send the port number to the client over STDOUT, and then listen on the socket for the client's connect() - at which point it is good to go with the socket-based I/O infrastructure.

Our operations team has nixed the use of dynamic ports on security grounds (see link).  I'm looking for an alternate way for a client to connect to a dynamically-spawned server and communicate using sockets.  The simplest solution would be something identical in most respects to xinetd, but which, instead of allocating STDIN/STDOUT as the server's connection to the client, would pass the socket that was allocated when the daemon accept()ed the connection, to the server.  Presumably, since the socket number wouldn't be predictable, the daemon would also need to pass the number as a command line arg.

I have written such a daemon in Perl, but I hesitate to roll my own because I'm certain that (x)inetd is far better "hardened" than what I could easily come up with.

So that's the problem, and what I conceive to be the simplest solution.  I'd appreciate hearing alternate solutions, or even whether in fact xinetd can be configured to pass a socket as I described.

答:
The first question is simply 'why can you not use the stream IO from xinetd? Other than you saying you want to use socket IO, there is no clear explanation of why you need to make life more complicated for your self.

If you really do need to handle sockets yourself, the solution is to implement your own socket server.  From a process perspective, its really straightforward. You create your server socket, listen for connection, and then when you accept each connection you have a client specific socket for you to provide your service.

However, here is where things get a lot more interesting. you will need to support multiple client connections without one request blocking other requests. The simplest strategy is based on how xinetd solves this, by forking a new process and the new process handles that client connection and exits when the socket closes.  If you are planing a service that is not going to be heavily loaded, this is good enough for you.

To handle 1k+ connections at a time, using fork() and creating a new process becomes very inefficient. Lots of memory, lots of context switching, and performance starts to fade.  This is where you need to switch to an asynchronous IO approach.


问:
How would my custom language be categorized?
I'm developing my own scripting language to solve some unique challenges for a project.

The language takes source code and converts the contents into tokens, and then a command factory is used to convert those tokens into something that can be executed.

An example of a script might look like this.

```<code>accept: always;
reject: title has "something" or body has "something else";
reject: title length < 10;
</code>```

Each line in the script ends with a ; terminator, and each line starts with a named rule that ends with :. Each rule uses a command followed by arguments. The commands can be joined together using logical operators. The number of arguments a command can have is fixed. So when I find a command I can expect X number of additional tokens for the syntax to be correct. The goal is human readable code because non-programmers will be using it.

An alternative way of writing the same above code using a C style structure would be.

```<code>accept(true);
reject(has(title,"something") || has(body,"something else"));
reject(length(title) < 10);
</code>```

What is the term used for a parser that handles a language where () for structuring arguments is omitted, and there are no clear boundaries defined for arguments.

I would like to read up on how these kinds of parsers are implemented. To ensure I'm not overly reinventing the wheel or running into common problems.

答:
See off-side rule.

Generally, tokens are tokens though, and parentheses are tokens (operators really) just like keywords. Not having parentheses means that you are trying to stay away from the function call paradigm, but the semantics are still there in your examples far as I can tell. So I am not sure if you should be looking for differentiation at the parser rather than at the scanner level.

Another avenue to explore is the implementation of declarative/non-procedural languages like SQL.


问:
Should my team use some common well-regarded coding standard as a basis for its own?
The R&D team I'm in has decided to adopt a coding standard. We have only recently formed, and have too little code and common coding time of our own to base our standards/conventions document on what has developed organically in our team, and on good examples from our own code etc.

Now, every one of us has some experience from past workplaces - although none of us is at a state of saying "let's adopt this here comprehensive document I have found to be fitting for the kind of work we do here" (*). Plus, some of us (including myself) only have experience from places with no official coding standard, or writing in different languages in a different setting (high-pressure weekly-release production environment as opposed to more research-oriented development work)

So, one of the options I've been thinking about is taking a relatively well-known and well-regarded document, snipping off what we don't care about/care for, and making some modifications based on our preferences.

Is this a common practice? Do you believe this is a good idea? If so, what would be a reasonable 'baseline' coding standard (don't tell me which is best, I don't want to start a religious conflict here; just point out what would be comprehensive or 'neutral' enough to build upon.)

Notes:

We are expecting to work with C, C++, OpenCL, CUDA, Python.

We are a team of 4 people + manager, expected to grow to about 5-6 within a year or so.

In our company, teams are almost entirely autonomous and usually don't interact at all (not even by using each other's code - the work is on entirely different projects); so - no company-wide considerations to make.

Regarding tools, at the moment what we know is that we're going to be using Eclipse, so its code formatter is going to be one tool at least. Ctrl+Shift+F has long been my friend

When I write Java, I've adopted the practice of adhering as strictly as possible to Bloch's Effective Java. Now, that's not quite a coding standard, but you could call some bricks, cement and mortar for a coding standard. I was thinking of possibly including something like that as part of the 'mix' (minding that we don't do Java).

I mean coding standards in the wider sense of the word, e.g. adopting suggestions made in the answers to this P.SE question.

I've found a big list of C++ coding standards documents; maybe I should mine that our baseline.

(*) That's not quite true, but I don't want to complicate this question with too many specifics.

答:
A standard usually helps communication and maintenance. In my opinion, it should be subject to some give and take, especially in small teams, and should evolve. Calling them guidelines may help :-)

Take a look at the Google guidelines for inspiration.


答:
I'd start with python. Python has coding guidelines that almost every single python programmer out there follows. They are part of official documentation called PEP8.

C/C++ is a huge mess for historical reasons, but since python is not, I'd recommend you follow the python naming convention in C/C++ too for sake of consistency.

Now for C++ it is actually more important to agree on common idioms and make sure that everybody understands reasonable modern C++ style than any wars on naming conventions. You should start with C++ Coding Standards and from online resources make sure to read C++ FAQ.

Title: Should my team use some common well-regarded coding standard as a basis for its own?

Body:
The R&D team I'm in has decided to adopt a coding standard. We have only recently formed, and have too little code and common coding time of our own to base our standards/conventions document on what has developed organically in our team, and on good examples from our own code etc.

Now, every one of us has some experience from past workplaces - although none of us is at a state of saying "let's adopt this here comprehensive document I have found to be fitting for the kind of work we do here" (*). Plus, some of us (including myself) only have experience from places with no official coding standard, or writing in different languages in a different setting (high-pressure weekly-release production environment as opposed to more research-oriented development work)

So, one of the options I've been thinking about is taking a relatively well-known and well-regarded document, snipping off what we don't care about/care for, and making some modifications based on our preferences.

Is this a common practice? Do you believe this is a good idea? If so, what would be a reasonable 'baseline' coding standard (don't tell me which is best, I don't want to start a religious conflict here; just point out what would be comprehensive or 'neutral' enough to build upon.)

Notes:

We are expecting to work with C, C++, OpenCL, CUDA, Python.

We are a team of 4 people + manager, expected to grow to about 5-6 within a year or so.

In our company, teams are almost entirely autonomous and usually don't interact at all (not even by using each other's code - the work is on entirely different projects); so - no company-wide considerations to make.

Regarding tools, at the moment what we know is that we're going to be using Eclipse, so its code formatter is going to be one tool at least. Ctrl+Shift+F has long been my friend

When I write Java, I've adopted the practice of adhering as strictly as possible to Bloch's Effective Java. Now, that's not quite a coding standard, but you could call some bricks, cement and mortar for a coding standard. I was thinking of possibly including something like that as part of the 'mix' (minding that we don't do Java).

I mean coding standards in the wider sense of the word, e.g. adopting suggestions made in the answers to this P.SE question.

I've found a big list of C++ coding standards documents; maybe I should mine that our baseline.

(*) That's not quite true, but I don't want to complicate this question with too many specifics.


问:
How do you approach database design?
I am primarily a web developer and I have a couple of personal projects which I want to kick off.

One thing that is bugging me is database design. I have gone through in school db normalization and stuff like that but it has been a couple of years ago and I have never had experience with relational database design except for school.

So how you do you approach database from a web app perspective? How do you begin and what do you look out for? What are flags for caution?

答:
database design cannot be done completely without considering how the data will be used, so here's a short list of steps:

write short sentences capturing the relationship among entities

draw an entity-relationship diagram representing the sentences

create a normalized logical data model from the E-R diagram

make a CRUD matrix for applications and entities

use the matrix to verify coverage of the lifecycle of each entity

extract subschemas for each application

examine the navigation paths over the subschemas for each major/CRUD operation

consider the reports that will be required

design the physical data model based on all of the above; denormalize, partition, and use star schemas where appropriate

Title: How do you approach database design?


答:
Put another way, you're asking if you should jump-start your team's coding standards by borrowing external standards that you've found.  It doesn't sound like anyone on the team has super-strong opinions (yet) on what those standards should be.

Unequivocally, the answer is yes.

An externally sourced standard is superior to nothing.  Look at the answers in "https://softwareengineering.stackexchange.com/q/84203/53019" in order to see some of the advantages for having a standard.  Consistency and having a basis to change from are critical from your point of view.

Also have a look at "Handling Coding Standards at Work (I'm not the boss)" as it goes into some of the team dynamics that your team needs to consider when selecting what the standard(s) should be.  The team needs to own their coding standard(s) so everyone willingly complies with the restrictions it places upon how each person codes.

You linked to this question, but it's worth pointing out the top answer and its focus on understanding why the requirements are in place.  If you use an external standard, it will be hard for your team to understand the basis behind all of those requirements.  But if you accept that they are there simply because your team needed something to start with, then it's easy to move on to changing that external standard to something that works better for your team.

Having any standard in place allows your to populate the formatting rules you'll use with your IDE (Eclipse in your case).  "Advantages and Disadvantages of Forced Code Reformat" goes into the benefits for everyone on the team for having that consistency with the code they are working on, and gives you the ability to reformat snippets you may borrow from other projects. An added bonus of using an external standard is that it may already be pre-populated in the code formatting portion of your IDE.

Someone on the team will likely complain about a particular portion of the standard and will blame it on the fact that you used an external standard as the base.  Have them read over:

- I hate one of our coding standards and it drives me insane, how to process it?

- How do you overcome your own coding biases when handed legacy code?

and then realize they likely would have complained about something within the standard no matter where it came from.  Across the number of teams I have worked on, I have yet to see a standard that everyone a) universally liked and b) agreed with every portion of the standard.  Reference back to some of the early links to see how to deal with those concerns.

Addendum, you asked about "which one" you should use.  I'm specifically not going to answer that as any answer is potentially frought with opinion fueled flame wars.  However, you could look at your IDE (Eclipse) and see what options it provides as standard configuration.  I'd also search a bit and see if there are any projects that plugin to your IDE and provide additional standards options to pick from.  Right or wrong, those standards are already populated for you and can save your team a chunk of work in configuring it for everyone.


问:
When should complexity be removed?
Prematurely introducing complexity by implementing design patterns before they are needed is not good practice.

But if you follow all (or even most of) the SOLID principles and use common design patterns you will introduce some complexity as features and requirements are added or changed to keep your design as maintainable and flexible as needed.

However once that complexity is introduced and working like a champ when do you removed it?

Example. I have an application written for a client. When originally created there where several ways to give raises to employees. I used the strategy pattern and factory to keep the whole process nice and clean. Over time certain raise methods where added or removed by the application owner.

Time passes and new owner takes over. This new owner is hard nosed, keeps everything simple and only has one single way to give a raise.

The complexity needed by the strategy pattern is no longer needed. If I where to code this from the requirements as they are now I would not introduce this extra complexity (but make sure I could introduce it with little or no work should the need arise).

So do I remove the strategy implementation now? I don't think this new owner will ever change how raises are given. But the application itself has demonstrated that this could happen.

Of course this is just one example in an application where a new owner takes over and has simplified many processes. I could remove dozens of classes, interfaces and factories and make the whole application much more simple. Note that the current implementation does works just fine and the owner is happy with it (and surprised and even happier that I was able to implement her changes so quickly because of the discussed complexity).

I admit that a small part of this doubt is because it is highly likely the new owner isn't going to use me any longer. I don't really care that somebody else will take this over since it has not been a big income generator.

But I do care about 2 (related) things

I care a bit that the new maintainer will have to think a bit harder when trying to understand the code. Complexity is complexity and I don't want to anger the psycho maniac coming after me.

But even more I worry about a competitor seeing this complexity and thinking I just implement design patterns to pad my hours on jobs. Then spreading this rumor to hurt my other business. (I have heard this mentioned.)

So...

In general should previously needed complexity be removed even though it works and there has been a historically demonstrated need for the complexity but you have no indication that it will be needed in the future?

Even if the question above is generally answered "no" is it wise to remove this "un-needed" complexity if handing off the project to a competitor (or stranger)?

答:
In general should previously needed complexity be removed even though it works and there has been a historically demonstrated need for the complexity but you have no indication that it will be needed in the future?

There's an effort and risk to remove the complexity. If that is higher than the added effort and risk of maintaining the overly complex code, then you keep it. Otherwise, you remove it. It's hard to estimate those risks, however.

I would add that you can mitigate the risk of more difficult maintenance by documenting why you used the design pattern Strategy in the first place, in the code. I personally believe any design pattern should be traceable to an explicit requirement (functional or non-functional).

Even if the question above is generally answered "no" is it wise to remove this "un-needed" complexity if handing off the project to a competitor (or stranger)?

Your scenario of being dissed by competition for padding hours is precisely the reason why you should document the complexity. If you document and justify (with a specific customer requirement) the use of any pattern, then you're covered. If you can't justify a pattern with a customer's requirement, then it looks like overdesign or patternitis.

If the requirements change, then you can justify leaving it because of the risk that you could break the code (or the amount of work to surgically remove the pattern).

I think it's good to distinguish between accidental complexity and essential complexity, since patterns often involve both.

That is, your requirement to support varying algorithms for deciding raises is an essential complexity (part of the problem to be solved). The maintenance of your code is made easier by the Strategy pattern, but the hard-coded if/then alternative to Strategy will still work. I have done exercises in my master's courses where students find opportunities to apply Strategy in open-source projects. The complexity is not necessarily better/worse when applying Strategy (because it is essential complexity). Sometimes it might be even harder to understand Strategy, because code is split into multiple classes with polymorphism, rather than one big if/then/else block.

Ideally, a pattern works when the benefits it provides outweigh the cost of its drawbacks. Again, quantifying these things is difficult. Often a pattern makes the developer happy (not just because it makes adding a new raise strategy easier, but gives it the developer warm fuzzies to know that a pattern was applied). It's hard to show customers how it's benefiting them.

The customer doesn't care or even understand the details. In the case of the new owner applying KISS in her processes, it's her reducing the essential complexity, which should have an impact on the software solution, too.

Title: When should complexity be removed?


答:
It's mostly just throwing a big number out there because it impresses the masses.  Bigger numbers are obviously superior so anything with a 64-bit processor is clearly better than something with a 32-bit processor.  The new CPU is significantly better than its predecessor but, in Apple fashion, they're not going to try marketing based on tech specs - they're just going to tell you that the 64-bit A7 is newer & better than the 32-bit A-6.  Looking at the tech specs, however, you see:

28nm vs 32nm chipworks

Improved integrated graphics processor

ARM v8 architecture v. ARM v7 (adds SIMD functions; jumps from 13 to 31 general purpose registers)

On-die (ie - faster) main memory

Beyond that, there's the fact that they can start rolling out (backwards compatible) 64-bit hardware today, before we run up against the '4GB wall'.  In a few years, when 64-bit becomes a necessity, all the hardware will support it & there won't be any need to handle legacy 32-bit architectures.

Title: What is the benefit of 64 bit A7 in iPhone

Body:
I'm trying to figure out why going to 64 bit processors is such a big deal in an iPhone. I understand that there will be twice as many registers so the processor can work with twice as much data which should increase performance.

However I don't see many phones going to more than 4GB of memory any time soon. It seems like overkill and it would negatively impact battery life.

Another problem that I see is that most variables now need twice as much memory. This will create problems in a mobile environment with small amounts of memory.

I believe that the folks at Apple are intelligent and they probably have great reasons for doing this, I'm just trying to understand them.

EDIT

Don't know much about GPU's but I was told that with 64 bit registers 2 pixels can be loaded into each register and operations can be performed on them individually. Is there a graphical advantage regarding 64 bit?


问:
Can you be Agile without doing TDD (test driven development)?
Is is possible to correctly call yourself (or your team) "Agile" if you don't do TDD (Test-Driven Development)?</p>

答:
Comparing to engineering a castle.

Agile Castle

If you were to engineer a castle using Agile. You'd write portions that have specific functions and encourage the user to use the functional parts, adjusting future design to the reactions of the user. So, you build the dungeon, and communicate with the dungeon keeper, you'd test the foundation provided by the land and the dungeon. You'd build the parapets and ask the nightwatchmen if it's good. You'd build the walls and have the soldiers test the defensive value. You'd build the kitchen and have the cooks look it over. And during this process, every part to date would function in addition to the current structure. So when you finished the dungeon, you could move the prisoners in. And so on. But when you've finally finished the castle, you find out the prisoners escaped. Now you need to go back into the dungeon and find out that you need thicker bars, but the doors aren't deep enough to hold the bars, and the hinges don't support bigger doors.

TDD Castle

With TDD, you show up with the prisoners, and see if they escape. Then you write the jail cells until they can't escape. Then you'd refactor the code cleanly removing unneeded cells, and removing bars that are in the wrong location, and test again. Prisoners didn't escape. You don't have to communicate with the jailor. And you could deliver the entire castle once you've finished it all. At that point the jailor says that the dungeon needs more cells, and now you've got to dig up more of the foundation.

Agile TDD Castle

If you combine Agile and TDD. You'd see if the prisoners escaped, then ask the jailor what's needed. He says you need more cells. You'd go grab some random people to pretend to be prisoners and see if they escape. If they don't, then you show it to the jailor, and he's happy with it. Then you start building the parapets.

Conclusion

So both solve different problems. Agile helps with changing requirements based on discovering users needs as they see the product develop at the point in the process where it's easiest to adapt. It involves releasing stable additions broken up from the overall design.

TDD solves the problem of anticipating failure. Discovering and correcting failure as it occurs at a point in the process where it's easiest to fix. It involves testing stable de-coupled units of code broken up from the overall design.

It's easy to see TDD as an extension to Agile, because they both follow the same pattern, unit driven progress and review. The difference is that the units in Agile function externally to-date as a whole, whereas the units in TDD function as a part, and may not produce a functioning product for external review. And both processes govern different needs (usability vs. correctness). Since both function over a process of developing in units, both review processes can occur at similar points, with TDD being more finely divided.

Notes

Having unit tests alone does not mean you use TDD. TDD means having the test before the produced unit, and using the test as you develop to confirm the unit. Unit testing without TDD can be used to make sure you don't invalidate previously built functionality.

Having sprints and other meetings doesn't make you agile. The goals of the manifest makes you agile. You can break up waterfall goals into sprints with units-of-work, without meeting the commitment to favor people over processes.

By definition of TDD and Agile. Your unit-tests will govern non-deliverable units, and so TDD will cycle faster than Agile. And if you employ both, your Agile cycles will contain one or more TDD cycles (if every unit is tested).

From what I understand: You fail Agile by failing to develop a deliverable / meaningful unit to the user. The unit can be meaningful even if it speeds up the product. But how does Agile explain refactoring for easier maintenance? I haven't covered it enough to answer that.

You fail TDD by failing the unit test. Producing code that doesn't produce the feature correctly.


答:
NO, I wouldn't bother - I think the only benefit would be if your team moved to a place where those standards were used as well, which is not what you want to happen :)

Standards are only there to encourage easier collaboration, so if you know that a #define macro is always in uppercase, then when you see an uppercase identifier in code, you'll have a fair idea its a macro. Similarly, other naming conventions or style conventions will remind you what you're dealing with.

I find standards like file location and name are more useful1 that the code ones (after all, code comes in all shapes and sizes, and you still have to read it) whereas not knowing the readme.txt is in /bin/doc/debug/release/documents is a real pain (as is such a crappy path, but that's another story).

I would recommend you make your own standards up as you go along. That way, you not only get the ones you all like, but you get ones that are definitely suitable for you, your team and the work you do. If you decide that you don;t really care what a while loop looks like, or that case statements must be indented in a certain way, then you're good. If you decide that ++ operators are banned, good too. All your own choice.

You'd have to make it easy to find and update it, a wiki maybe or auto-generated web page from a text description, but otherwise - go for it. Standards have a mythical attitude from some people who are more interested in fanatically following the standard than writing good code, don't be like them - make your own standard that helps you where you need it.


问:
Issue with scrum adaptation by team
I have been playing with Scrum methodology since year and half. I am using VersionOne as scrum tool. I have tried to follow most of the scrum principles. Sometimes, I feel like there is an issue with transparency of the stories. As of now, the whole team can get an access to all stories defined for the project. This creates issues with different levels of developers like junior and senior level developer.

People's complains are about the work distribution or type of work they are assigned to. There is an issue of comparison among the developers. I don't know if I am following scrum properly or not.

In scrum, should we give access of the all stories to everyone? or only assigned person can view his/her story?

答:
Give all the stories to everyone, let anyone pick the story they want to work on - however, restrict the number of stories within a sprint to a number you think can be done, and make sense from a point of view of delivery.

The whole aspect of agile, including scrum, is that the team should make the decisions of what to work on and how to achieve it, not individuals. So you should consider the team as  a whole and let them decide who gets to work on what. As long as the delivery completes all the stories (not just the fun ones) then all's good.

All team members should be seeing progress of all stories that are being worked on during the standups - so they can all work as a team. If you have a situation where some people get 'good' stories to work on, and others get the testing and documentation, then there's something wrong with the team itself. Break hierarchies down, flatten the structure so everyone is equal and make sure they all know they are all responsible for delivery.

Title: Issue with scrum adaptation by team


答:
I think part of the problem is people who simply copy code without bothering to learn what they are doing, but really to my mind the way we teach porgamnming is broken and it is one of the reasons why there is so much bad code. We teach syntax out of context and so the beginners don't know when to use something and when not to or what problems the syntax is intended to solve and what problems it is not intended to solve. SO they use a hammer when a wrench would have been the better tool.

So for instance instead of teaching just syntax, you organize the course like (Clearly there would be more steps, this is just a basic example of building from basic to more complex problems rather than just teaching syntax):

This is how you set up a basic web page

This is how you make the web page pull data from a database

This is how you send data from a web page to a database

This is how you make sure the right data is sent.

This is how you protect your database from malicious data entry

Title: Why isn't protection against SQL injection a high priority?

Body:
On Stack Overflow, I see a lot of PHP code in questions and answers that have MySQL queries that are highly vulnerable to SQL injection attacks, despite basic workarounds being widely available for more than a decade.

Is there a reason why these types of code snippets are still in use today?


答:
You're trying to make things too complicated.  If you want to use xinetd, write your application to run each new instance talking over stdin/stdout.  If you want to directly use sockets, have your service listen on a fixed socket and handle the connections itself.

You don't have any compelling arguments for why you need to complicate things like this, you just seem to think it's the only solution.  Either you're leaving out major details, you're confused about how networking works or we're dealing with an X Y Problem.

You say you want to use a "bidirectional socket" - when you have stdin/stdout that'a bidirectional channel.  Unless you plan on using complex ioctls, there's not really any difference - "passing a socket" isn't buying you anything.

You say that xinetd is "hardened" - if you're on a private, firewalled network, it's safe to write your own daemon to listen directly on a fixed port.  If you're concerned about security or DOSes, xinetd doesn't buy you much.

What is wrong with either of the simple approaches?

Title: Seeking xinetd alternative for forking concurrent servers in Linux

Body:
I recently posted here asking about the drawbacks of having a server process bind to a dynamically assigned port.  That approach came about because xinetd, which launched the server process, allocates STDIN and STDOUT as the server's communication channel to the client, and we wanted the server to use a bidirectional socket.  The responses (and our operations team) convinced me to abandon that approach.

I need a daemon process to monitor a designated port and fork concurrent servers.  The server process is written using an I/O infrastructure that is socket-based.  We have developed a server process that can be launched by xinetd.  The first thing it does is to bind to a dynamically-assigned port number, send the port number to the client over STDOUT, and then listen on the socket for the client's connect() - at which point it is good to go with the socket-based I/O infrastructure.

Our operations team has nixed the use of dynamic ports on security grounds (see link).  I'm looking for an alternate way for a client to connect to a dynamically-spawned server and communicate using sockets.  The simplest solution would be something identical in most respects to xinetd, but which, instead of allocating STDIN/STDOUT as the server's connection to the client, would pass the socket that was allocated when the daemon accept()ed the connection, to the server.  Presumably, since the socket number wouldn't be predictable, the daemon would also need to pass the number as a command line arg.

I have written such a daemon in Perl, but I hesitate to roll my own because I'm certain that (x)inetd is far better "hardened" than what I could easily come up with.

So that's the problem, and what I conceive to be the simplest solution.  I'd appreciate hearing alternate solutions, or even whether in fact xinetd can be configured to pass a socket as I described.


问:
Does an in-code enumeration provide a stronger domain model than a static table?
Does an in-code enumeration provide a stronger domain model than a static database table?

As an example, say I have an Marble entity, with a Color attribute. The color attribute has a finite set of possible values—say red, green, blue. Say the database team recommends having a static S_ValidColors table, to the effect of:

```<code>-----------------------
| ColorId | ColorName |
-----------------------
|    0    |    Red    |
-----------------------
|    1    |   Green   |
-----------------------
|    2    |    Blue   |
-----------------------
</code>```

Whereas I'm thinking more along the lines of (this is just a sketch for the general concept):

public class Color {
    public static const Color Red = Color(0);
    public static const Color Green = Color(1);
    public static const Color Blue = Color(2);

    private Color(uint typeCode) {
        ...
    }
    ...
}
```

Aside from the question of which is better (which probably depends on any number of other factors not represented here), is this a question that touches how strong the domain model is? Is one way more anemic than the other?

答:
It entirely depends on the use of the enum.  If they are going to change often then in the DB is better, you don't want to recompile and redeploy once a week because Joe changed his favorite color again.  If the enum is more fixed then hard coding it will be better, it is easier to reason about and less likely to get broken. Do you need to access it from stored procedures?  Might be a good idea to have it in the database where both stored procs and regular code can access it. You really don't want the headache of maintaining two different versions of the same thing.  What does the logic that uses this enum look like? There are situations where either option is more practical.

As far as the anemic domain model thing goes I don't think it applies.  As long as the domain model enforces the domain model's rules and processes, then the domain model is not anemic.  Storing values in the DB just makes them more dynamic and easier to change(which could be a bad thing given the right assumptions.)


问:
Should I put utility methods inside a class?
I have been working on a library which contains a large set of functions. For the sake of simplicity, I am going to use just one set as an example.

I am not sure which is the better way, in terms of ease of use and performance, whether I should put those methods provided as individual methods, prepended with the function category, or whether it is better to create a Class containing all the method as static methods.

For Example:

Individual methods: (p.s. this could also be writen without request_ in the function name and using Namespaces instead)

```<code>function request_method() { ... }
function request_url() { ... }
function request_useragent() { ... }
....
</code>```

Classed method:

```<code>class Request {
    public static function method() { ... }
    public static function url() { ... }
    public static function useragent() { ... }
    ...
}
</code>```

答:
The key is to put logically related functions in the same namespace. Prefixing as a "namespace by convention" is a bad idea. Depending on the language this has different meanings.

In a language like Java you have no choice you're going to have a utility class.

If you're in a language like Haskell, OCaml, or Python, these should be in a module.

In C++ you have namespaces for the same purpose.

By doing this you leave the burden of making sure you avoid naming clashes to your compiler. With prefixes you're liable to run into something like compiler_typecheck_ast. Does this refer to the class in the "namespace" compiler_typecheck or is it a function in the compiler namespace that typechecks an ast?


问:
In need of a more technical answer for an interview question about how the internet works from beginning to end
I've had interviews with 5 separate people over the past two weeks and three of those five have all asked me this question:  Explain what happens between hitting "Google.com" and the page coming up on the screen.  Basically, how the Internet works.  I figure after three times that I better be prepared if I ever get this question again.

I know some things, but I'm not fully convinced that my answer is good enough.  Basically, I mention that the DNS server translates "google.com" into an IP address.  I kinda gloss over TCP/IP, then talk about the web server literally serving up requested pages that get sent back to the browser which the browser then interprets and displays.

As I said before, I'm not convinced my answer is technical enough.  What are the steps that I'm leaving out?

For what it's worth, two of those three times have been with the same company and I'm being called back for a third interview with them, so I can't have bombed it too hard.

答:
Leaving out mentions of cookies and firewalls would be a couple of things missing here.  There is something to be said for cookies being sent so that "Google.com" may recognize a user and serve up a page that may be different for someone not logged into Google.  There is also the question of where is the person looking this up: Smartphone, tablet or regular computer(laptop or desktop)?

I wonder if there may be some side questions that you were meant to ask but didn't that could be a factor here.  This is more of a question of how the Web works as the Internet would be a bit broader and include e-mail and other stuff I'd think.

My guess is that was more a test of your communication capabilities.  Can you take a rather technical question and break it down so that technical and non-technical would understand it?  What kind of questions would you return in being asked to explain someone bringing up the "Google.com" home page on their browser?  Do you make a bunch of assumptions or ask the questions?  In some ways I see this as a parallel to a white board question where things are left vague enough that either you'll ask questions so that you can give a precise correct answer or you make assumptions in giving an answer.


答: 64-bit allows a great deal more code sharing with the desktop builds of OSX (which are all 64-bit)</p>


问:
How does MVC work with the principle "Tell, Don't ask"?

Procedural code gets information then makes decisions. Object-oriented
  code tells objects to do things.

— Alec Sharp

So, when a view wants to display some information that is suppose to be derived from properties of a model it is displaying, should the calculation be part of the model or the view?

Ideally the view should tell the object about the information it needs, and model should do the calculation and return the result.

But now, should the model start having new methods every time a new type of view wants to display extra information which is derived out of the model's property?

Should such methods be in the view or in the model? Or in such cases should we subclass the model, add the required methods, and then assign it to the view?

I am an Objective-C developer, I can also add a category to the model for the view but in languages where we don't have features where we can add methods to objects and classes at runtime, what is the ideal design?

Or are models in MVC meant to be just information in key-value pairs instead of real objects to be passed around, where a view reads each value based on a getter?

答:
Actually, the "tell don't ask" principle does not mean that you cannot query an object about its state.

It means that you should not query an object's state and then change that object's state based on your own logic. That would mean the object (or its class) is not in control of its own innards, and you are doing open heart surgery where you should really only be a MRI scanner (or some such).

What you can do is query state, decide what that means to you, then tell the object to do something based on your logic and let the object take care of changing its state to reflect what was done.

In MVC a view does not have to tell a model what information it needs. Ideally a view is mostly passive. Telling the controller what the user has done and responding to update notifications from the model by changing the content of its controls.

The controller should control (!) the model based on what it was told the user has done (clicked a button). Usually the controller just conveys what happened to the model. It may query other controllers and models to decide how to handle what the user has done.

The model should respond to being told what happened (by the controller) by changing its state accordingly and sending out notifications to whomever subscribed to receive such notifications (usually the view will have been subscribed by the controller).

Please note that in MVC a controller can orchestrate multiple views on the same model, but you can also have multiple controller/view pairs working with the same model. This is for example how you would allow multiple views (sic) on the same document (for example an HTML view and a simultaneous raw text view).


问:
What is the general tech news website every programmer should read?
A link and a quick explanation why would be very helpful.

General tech news, I mean not like InfoQ which is too technical. Probably much more like P.SE than SO.

EDIT: site should help developers gain general knowledge about the industry, technologies, inventions, etc. Much like when we listen to the news every morning in our car to know what is happening in our world. But target audience must be either programmmers, geeks or any other persons interested in technology.

答:
Hacker News

It comes from a broadly tech entrepreneur position so combines interesting tech stories with relevant business and general stories.

Because the stories that make the front page are submitted and voted on by the community they tend to be more relevant and interesting than those which are run by many news sites who aren't necessarily as well placed to judge these things.

The comments/discussions can be entertaining too.


答:
Everyone should be involved in the scrum process equally, if there are issues around allocating work to the right developer they should be addressed in the sprint review but it sounds more like your team isn't acting like a team and jealousy and personalities are getting in the way of professionalism.

Although s flat structure is great when it works it sometimes takes a respected individual in the team to make decisions and delegate where the team can't come to a mutual consensus.

I'd make sure the initial testing and documentation are done by the developer responsible for the story so everyone has some of the dull stuff to do, provided there's done peer review in place as well.

Try pairing up for some of the most interesting or hardest work and make sure the pair's are mixed up regularly, this spreads skills through the team and gives more people access to better stories.

Title: Issue with scrum adaptation by team

Body:
I have been playing with Scrum methodology since year and half. I am using VersionOne as scrum tool. I have tried to follow most of the scrum principles. Sometimes, I feel like there is an issue with transparency of the stories. As of now, the whole team can get an access to all stories defined for the project. This creates issues with different levels of developers like junior and senior level developer.

People's complains are about the work distribution or type of work they are assigned to. There is an issue of comparison among the developers. I don't know if I am following scrum properly or not.

In scrum, should we give access of the all stories to everyone? or only assigned person can view his/her story?


问:
API design: concrete vs. abstract approach - best practices?
When discussing APIs between systems (on the business level) there are often two different point of views in our team: some people prefer a more - lets say - generic abstract approach, other a straight forward "concrete" approach.

Example: the design of a simple "person search" API. the concrete version would be

```<code> searchPerson(String name, boolean soundEx,
              String firstName, boolean soundEx,
              String dateOfBirth)
</code>```

People in favour of the concrete version say:

the API is self-documenting

it is easy to understand

it is easy to validate (compiler or as a webservice: schema validation)

KISS

The other group of people in our team would say "That is just a list of search criteria"

```<code>searchPerson(List<SearchCriteria> criteria)
</code>```

with

```<code>SearchCritera {
  String parameter,
  String value,
  Map<String, String> options
}
</code>```

with possibly making "parameter" of some enumeration type.

Proponents say:

without changing the (declaration of) the API the implementation can change, e.g. adding more criteria or more options. Even without synchronizing such a change at deployment time.

documentation is necessary even with the concrete variant

schema validation is overrated, often you have to validate further, schema cannot handle all cases

we already have a similiar API with another system - reuse

The counter-argument is

lots of documentation about valid parameters and valid parameter combinations

more communication effort because it's more difficult to understand for other teams

Are there any best practices? Literature?

答:
My personal preference is to be abstract, yet my company's policies lock me into being concrete. That's the end of the debate for me :)

You've done a good job listing pros and cons for both approaches, and if you keep digging you'll find plenty arguments in favor of both sides. As long as your API's architecture is developed properly - meaning you've given thought as to how it will be used today and how it may evolve and grow in the future - then you should be fine either way.

Here's two bookmarks I had with opposing viewpoints:

Favoring Abstract Classes

Favoring Interfaces

Ask yourself: "Does the API fulfill my business requirements? Do I have well defined criteria for success? Can it scale?". Those seem like really simple best practices to follow, but honestly they're far more important than concrete vs. generic.