问:
What are the advantages of GLSL's compilation model?
GLSL is fundamentally different from other shader solutions because the server (GPU driver) is responsible for shader compilation. Cg and HLSL are (afaik) generally compiled a priori and sent to the GPU in that way.

This causes some real-world practical issues:

many drivers provide buggy compilers

compilers differ in terms of strictness (one GPU can accept a program while another won't)

also we can't know how the assembler code will be optimised

What are the upsides of GLSL's current approach? Is it worth it?

答:
This model pushes on code portability, decoupling the GLSL code from any specific platform (hardware and/or software). Because it is a royalty-free standard, every vendor could decide to support GLSL platform. Normally this support will result in a OS-specific OpenGL driver implementation.

many drivers provide buggy compilers

Probably there are many bugs in the drivers out there, but my experience says that the most of the times the bug is not a bug, but it is a misunderstanding of the GLSL specification. For example, this code run fine on NVIDIA platforms, while not on Intel platforms:

```<code>// We are in fragment shader

in vec2 ds_TexCoord[3];

uniform int ds_FrontMaterialAmbientTexCoord = -1;

uniform sampler2D ds_FrontMaterialAmbientTexture;

...

if (ds_FrontMaterialAmbientTexCoord >= 0) {
    fragmentMaterial.AmbientColor = texture(ds_FrontMaterialAmbientTexture, ds_TexCoord[ds_FrontMaterialAmbientTexCoord]);
}
</code>```

The trick here is that the array cannot be accessed using directly an uniform variable. Indeed the code running on NVIDIA and Intel platforms is:

```<code>if (ds_FrontMaterialAmbientTexCoord >= 0) {
     int index = ds_FrontMaterialAmbientTexCoord;
    fragmentMaterial.AmbientColor = texture(ds_FrontMaterialAmbientTexture, ds_TexCoord[index]);
}
</code>```

Once you got few tricks, writing portable GLSL code is just like writing C.

compilers differ in terms of strictness (one GPU can accept a program
  while another won't)

Use the strictest one. AMD and Intel have a strict interpretation of the GLSL specification, while NVIDIA don't: this is because the GLSL compiler is based on CG implementation, indeed being more permessive than what should be allowed.

The solution is simple: follow strctly the GLSL specification.

also we can't know how the assembler code will be optimised

If you can about optimization, write in ARB assembly (here some specification and hints). The driver will probably do the best it can for the current platform, will you do better?

Remember that the main goal is portability!

Body:
This model pushes on code portability, decoupling the GLSL code from any specific platform (hardware and/or software). Because it is a royalty-free standard, every vendor could decide to support GLSL platform. Normally this support will result in a OS-specific OpenGL driver implementation.

many drivers provide buggy compilers

Probably there are many bugs in the drivers out there, but my experience says that the most of the times the bug is not a bug, but it is a misunderstanding of the GLSL specification. For example, this code run fine on NVIDIA platforms, while not on Intel platforms:

// We are in fragment shader

in vec2 ds_TexCoord[3];

uniform int ds_FrontMaterialAmbientTexCoord = -1;

uniform sampler2D ds_FrontMaterialAmbientTexture;

...

if (ds_FrontMaterialAmbientTexCoord >= 0) {
    fragmentMaterial.AmbientColor = texture(ds_FrontMaterialAmbientTexture, ds_TexCoord[ds_FrontMaterialAmbientTexCoord]);
}

The trick here is that the array cannot be accessed using directly an uniform variable. Indeed the code running on NVIDIA and Intel platforms is:

if (ds_FrontMaterialAmbientTexCoord >= 0) {
     int index = ds_FrontMaterialAmbientTexCoord;
    fragmentMaterial.AmbientColor = texture(ds_FrontMaterialAmbientTexture, ds_TexCoord[index]);
}

Once you got few tricks, writing portable GLSL code is just like writing C.

compilers differ in terms of strictness (one GPU can accept a program
  while another won't)

Use the strictest one. AMD and Intel have a strict interpretation of the GLSL specification, while NVIDIA don't: this is because the GLSL compiler is based on CG implementation, indeed being more permessive than what should be allowed.

The solution is simple: follow strctly the GLSL specification.

also we can't know how the assembler code will be optimised

If you can about optimization, write in ARB assembly (here some specification and hints). The driver will probably do the best it can for the current platform, will you do better?

Remember that the main goal is portability!


问:
How do inheritance and composition differ?
I'm wondering about the differences between inheritance and composition examined with concrete code relevant arguments.

In particular my example was:

Inheritance:

class Do:
    def do(self):
        self.doA()
        self.doB()

    def doA(self):
        pass

    def doB(self):
        pass

class MyDo(Do):
    def doA(self):
        print("A")

    def doB(self):
        print("B")

x=MyDo()
```

<p>vs <strong>Composition</strong>:</p>

<pre class="lang-python prettyprint-override"><code>class Do:
    def __init__(self, a, b):
        self.a=a
        self.b=b

    def do(self):
        self.a.do()
        self.b.do()

x=Do(DoA(), DoB())
</code>```

(Note for composition I'm missing code so it's not actually shorter)

Can you name particular advantages of one or the other?

I'm think of:

composition is useful if you plan to reuse DoA() in another context

inheritance seems easier; no additional references/variables/initialization

method doA can access internal variable (be it a good or bad thing :) )

inheritance groups logic A and B together; even though you could equally introduce a grouped delegate object

inheritance provides a preset class for the users; with composition you'd have to encapsule the initialization in a factory so that the user does have to assemble the logic and the skeleton

...

Basically I'd like to examine the implications of inheritance vs composition. I heard often composition is preferred, but I'd like to understand that by example.

Of course I can always start with one and refactor later to the other.

答:
Conceptually speaking, composition models "consists of" relationships, whereas inheritance models "is a".

Using the car analogy, "a car has wheels" is a textbook example for composition, and it makes sense to have a class Wheel, and a class Car with a property wheels of type Wheel[].

In theory, an example of inheritance would be "a truck is a vehicle": properties common to all vehicles can be implemented in class Vehicle, while those specific to trucks can be implemented in class Truck.

The truck example, however, also illustrates the problem of the inheritance approach: what if you have to make your vehicle class polymorphic not only for the vehicles purpose (passengers vs. freight), but also for fuel type? You'd have to create four classes to cover passenger cars and freight vehicles, as well as diesel vs. gasoline powered. Add another orthogonal property, and the number of classes doubles again. Worse yet, you have to decide which of these orthogonal properties comes first in the class hierarchy: is it Vehicle -> DieselVehicle -> DieselFreightVehicle -> Truck, or is it Vehicle -> FreightVehicle -> DieselFreightVehicle -> Truck? Either way, you have to duplicate some functionality, either the freight-specific things, or the diesel-specific things. The solution is to use composition anyway: A vehicle has an engine (which can be diesel- or gasonline-powered), and a cargo type (which can be passengers or freight); you don't need a truck class anymore, because your vehicle class can already model all sorts of vehicles by combining suitable engines and cargo types. Note that the components are still polymorphic, but the container object is not. The trick is to keep polymorphism one-dimensional, that is, each polymorphic hierarchy models one of many orthogonal properties, such as engine type, freight type, etc.

This is why people say "favor composition over inheritance"; of course you are still inheriting, but you have separated your inheritance into independent strains.

ContentLicense: CC BY-SA 3.0


答:
It's depends on the architecture and what you need to resolve.

In your example a client of your code if want to change the implementation of doA, and doB with the inheritance example would need to write a class that extends from MyDo but with composition, just initialize with a class which have the same interface.

Now you need to thing what are the code of.

Suppose the class D before call doA or doB call another methods to perform validation or configurations and then execute doA, the inheritance approach is good.(in this case the client never call doA if not another method that do things and then call doA)

Simple example: Class Component. Class window extends Component. The class component have methods that would be used in class Window, and suppose that you what to add a button of close always, then imagine that you need overwrite the method addChildrens() to add that button. But you never call addChildern() it is doing by the initialize method of Component Class, that have already a life cycle implemented. (Be aware this could be done with different approach)

For composite situation.
MyDo use directly the doA or doB as services, so expect some interface, but need to be flexible, suppose doA and doB read data form some source. Then you can have different implementations of Do whit the different sources.

Simple example: MyDo is a log tool class and doA, doB method log the information. You can have different implementation do Do that log in diferents sources.

I'm be leave that are more examples, but in general it depends of what you need to do with your classes after.

Title: How do inheritance and composition differ?

Body:
I'm wondering about the differences between inheritance and composition examined with concrete code relevant arguments.

In particular my example was:

Inheritance:

class Do:
    def do(self):
        self.doA()
        self.doB()

    def doA(self):
        pass

    def doB(self):
        pass

class MyDo(Do):
    def doA(self):
        print("A")

    def doB(self):
        print("B")

x=MyDo()
```

<p>vs <strong>Composition</strong>:</p>

<pre class="lang-python prettyprint-override"><code>class Do:
    def __init__(self, a, b):
        self.a=a
        self.b=b

    def do(self):
        self.a.do()
        self.b.do()

x=Do(DoA(), DoB())
</code>```

(Note for composition I'm missing code so it's not actually shorter)

Can you name particular advantages of one or the other?

I'm think of:

composition is useful if you plan to reuse DoA() in another context

inheritance seems easier; no additional references/variables/initialization

method doA can access internal variable (be it a good or bad thing :) )

inheritance groups logic A and B together; even though you could equally introduce a grouped delegate object

inheritance provides a preset class for the users; with composition you'd have to encapsule the initialization in a factory so that the user does have to assemble the logic and the skeleton

...

Basically I'd like to examine the implications of inheritance vs composition. I heard often composition is preferred, but I'd like to understand that by example.

Of course I can always start with one and refactor later to the other.


答:
When you use inheritance, a subclass depends on implementation details of its superclass.  If the superclass implementation details change, the subclass could break even though its code doesn't change.  When you use composition you're not dependent on the implementation of a class, only its interface.

If the classes Do and MyDo are in the same package and under the control of the same programmers, it's generally safe to use inheritance.  If you're aware of the dependencies, you can test the classes together when the superclass implementation changes.  If you're extending a class that's not under your control (like a class from a standard library) you want to use composition so that a change in implementation details of the library class won't break your client code.


问:
Why are pointers not recommended when coding with C++?
I read from somewhere that when using C++ it is recommended not to use pointers. Why is pointers such a bad idea when you are using C++. For C programmers that are used to using pointers, what is the better alternative and approach in C++?</p>

答:
Since I’m the one who published the polemic “don’t use f*cking pointers” I feel that I should comment here.

First of all, as a polemic it obviously represents an extreme viewpoint. There are definitely legitimate uses of (raw, and other) pointers. But I (and many professional C++ programmers) maintain that pointers in C++ are vastly overused. But what we really mean is the following:

First:

Raw pointers must under no circumstances own memory.

Here, “own memory” essentially means that at some point delete is called on that pointer (but it’s more general than that). This statement can safely be taken as an absolute. The only exception is when implementing your own smart pointer (or other memory management strategy). And even there you should normally still use a smart pointer at low level.

The rationale for this is quite simple: raw pointers which own memory introduce a source of error. And these errors are prolific in existing software: memory leaks and double deletion – both a direct consequence of unclear resource ownership (but going in opposite direction).

This problem can be entirely eliminated, at virtually no cost, by simply using smart pointers instead of raw pointers (caveat: this still requires thinking, of course; shared pointers can lead to cycles and thus once again to memory leaks – but this is easily avoidable).

Second:

Most uses of pointers in C++ are unnecessary.

Unlike other languages, C++ has very strong support for value semantics and simply doesn’t need the indirection of pointers. This wasn’t immediately realised – historically, C++ was invented to facilitate easy object orientation in C, and relied heavily on constructing object graphs which were connected by pointers. But in modern C++, this paradigm is rarely the best choice, and modern C++ idioms often don’t need pointers at all. They operate on values rather than pointers.

Unfortunately, this message has still not caught on in large parts of the C++ user community. As a result, most of the C++ code that is written is still littered with superfluous pointers which make the code complex, slow and faulty / unreliable.

For somebody who knows modern C++, it’s clear that you very rarely need any pointers (either smart or raw; except when using them as iterators). The resulting code is shorter, less complex, more readable, often more efficient and more reliable.

ContentLicense: CC BY-SA 4.0


问:
How to learn to make better estimates?
I suck at estimates. When someone asks me how long something will take, I don't even dare to make a guess since I will be completely off the mark. Usually I'm way too optimistic, and should probably multiply my guess with some large X factor...

How can I learn to make better estimates? It's not taught at my uni, and even though we have deadlines for all laborations I never think about how long something will actually take. Which I should. For everyone's sake (especially mine).

答:
I'm still not great at it, but I have found that tracking how long you estimate for tasks and how long you actually take can be a big help.  That way you can get a solid idea of how far off you usually are.  Issue management software with time tracking (Jira in my case) or a spread sheet can be a big help with this.

I think more than anything it's an experience thing.

ContentLicense: CC BY-SA 2.5

Title: How to learn to make better estimates?


问:
I don't understand why algorithms are so special
I'm a student of computer science trying to soak up as much information on the topic as I can during my free time. I keep returning to algorithms time and again in various formats (online course, book, web tutorial), but the concept fails to sustain my attention. I just don't understand: why are algorithms so special?

I can tell you why fractals are awesome, why the golden ratio is awesome, why origami is awesome and scientific applications of all the above. Heck I even love Newton's laws and conical sections. But when it comes to algorithms, I'm just not astounded. They are not insightful in new ways about human cognition at all. I was expecting algorithms to be shattering preconceptions and mind-altering, but time and time again they fail miserably. Perhaps I am doing something wrong in my approach.

Can someone tell me why algorithms are so important to programming?

答:
can tell you why fractals are awesome, why the golden ratio is
  awesome, why origami is awesome and scientific applications of all the
  above

Algorithms are "awesome" because they enable all those things. How do you tell someone how to create a given fractal structure? You give them an unambiguous set of instructions. That's an algorithm. How do you compute phi? You follow an algorithm. If the general notion doesn't inspire you, it's probably because it's already so deeply engrained in your daily life that you simply take it for granted. If you can't think of scientific applications of algorithms, though, you either don't understand the concept or you don't know the first thing about science.

I was expecting algorithms to be shattering preconceptions and
  mind-altering but time and time again they fail miserably.

Turning just to algorithms for computing, perhaps your expectations are inflated. It's hard to be floored by anything when you're expexcting to be floored. nevertheless, there are plenty of algorithms that are beautiful in some sense or that required impressive insight. These may not be the ones you're learning in class right now, but if you don't think that an algorithm like quicksort is at least pretty nifty you might be in the wrong field. If you're not impressed that there are algorithms that allow databases containing billions of records to be searched instantly, you're really not trying. If you don't find it "awesome" that relatively straightforward algorithms enable millions of computers to send each other zillions of packets of data very reliably, there's nothing I can say that'll impress you.


问:
Is there any benefit to obsession with making code "look pretty"?
Sometimes I spend ridiculous amounts of time (hours) agonizing over making code "look pretty". I mean making things look symmetrical. I will actually rapidly scroll through an entire class to see if anything jumps out as not looking "pretty" or "clean".

Am I wasting my time? Is there any value in this kind of behavior? Sometimes the functionality or design of the code won't even change, I'll just re-structure it so it looks nicer.

Am I just being totally OCD or is there some benefit hidden in this?

答:
Holy Bovine!

You folks have never heard of indent?

its a code formatting utility that been around for over 20 years. Its got a mega-bucket of options so your code can be formatted anyway you want it, automatically.

ermm - but it only works on C and some but not all C++.... (wtf? why doesn't GNU upgrade it?)


答:
They are not insightful in new ways about human cognition at all.

I’m not sure how you reached this conclusion but it’s completely wrong. The opposite is true: algorithms offer the deepest insight into human cognition ever. This is formalised in the Church–Turing thesis. The conjecture is about the computability of functions but it has a very important corollary about our intuition of computability.

It effectively states that the human mind is in principle limitless (sometimes termed a “universal constructor”; not to be confused with the similar but distinct concepts of “universal assembler” and “von Neumann universal constructor”).

If the hypothesis is true, then (according to David Deutsch, The Beginning of Infinity) the (human) mind is unique in all of the known Universe: it alone is capable of causing a sustained effect over the rest of the physical Universe.

The argument becomes a bit convoluted but it essentially reduces to the point that everything else on our world, our solar system and even our galaxy is limited in scope: go away far enough and its effect vanishes. A creative mind (like the human mind) alone is able of extending its own physically imposed limits, because our minds are able of generating knowledge.

If you’re interested in human cognition, I recommend you read Deutsch’s book which explains this in great detail. And all of this follows directly from … the insightfulness of algorithms, in particular the Church–Turing thesis.

Apart from that, algorithms are interesting once they cause you a shift in cognition. For instance, once you first understand recursion, or dynamic programming, or transitivity, it’s as if a small light goes on in your head – you have an insight. So algorithms are, in the primary sense of the world, insightful.

Title: I don't understand why algorithms are so special

Body:
I'm a student of computer science trying to soak up as much information on the topic as I can during my free time. I keep returning to algorithms time and again in various formats (online course, book, web tutorial), but the concept fails to sustain my attention. I just don't understand: why are algorithms so special?

I can tell you why fractals are awesome, why the golden ratio is awesome, why origami is awesome and scientific applications of all the above. Heck I even love Newton's laws and conical sections. But when it comes to algorithms, I'm just not astounded. They are not insightful in new ways about human cognition at all. I was expecting algorithms to be shattering preconceptions and mind-altering, but time and time again they fail miserably. Perhaps I am doing something wrong in my approach.

Can someone tell me why algorithms are so important to programming?


答:
Relatively simply, the C mentality is "Got a problem? Use a pointer". You can see this in C strings, function pointers, pointers-as-iterators, pointer-to-pointer, void pointer- even in the early days of C++ with member pointers.

But in C++ you can use values for many or all of these tasks. Need a function abstraction? std::function. It's a value that's a function. std::string? It's a value, that's a string. You can see similar approaches all over C++. This makes analyzing the code vastly easier for both humans and compilers.

Title: Why are pointers not recommended when coding with C++?

Body: I read from somewhere that when using C++ it is recommended not to use pointers. Why is pointers such a bad idea when you are using C++. For C programmers that are used to using pointers, what is the better alternative and approach in C++?</p>


问:
Why is design by contract considered an alternative to the pseudo programming process?
Right now I'm reading Code Complete by Steve McConnell and in chapter 9 he talks about the Pseudo Programming Process (PPP).

From what I've understood, the PPP is a way of programming in which the programmer first writes the pseudo code for the routine he's working on, then refines it up to the point where pretty much each pseudo code line can be implemented in 1-3 lines of code, then writes the code in the designated programming language and finally the pseudo code is saved as comments for the purpose of documenting the routine.

In chapter 9.4 the author mentions alternatives to the PPP, one of which is 'design by contract'. In design by contract you basically assert preconditions and postconditions of each routine.

Now why would that be considered an alternative? To me it seems obvious that I should use both techniques at the same time and not chose one over the other.

答:
I think its the intent of the concepts. In both cases, you're describing what the code will do before writing it. In PPP you're describing the logic that will be utilised to make the functions work, in the other you're describing the functions themselves. I'd say one is just a "higher level" description.

I think that you could use both, but if you did you'd probably realise one or the other was pretty much redundant given the descriptions provided by the other.


答:
Design by contract approaches the problem from a different angle. Design by contract starts with describing the allowable program state at certain points, such as the beginning and ends of methods, and enforcing it. Languages like Eiffel have been built from the ground up with this in mind.

Theoretically, if the state has been specified completely by the contracts, the program logic may be derivable. In practise, it becomes executable unit tests included with the application.

PPP, by comparison, is a top-down way of arriving at the code by only dealing with a level of abstraction the developer is comfortable with and slowly decomposing it. PPP deals with the "how" at increasingly lower levels of detail whereas design by contract focuses on the "what" first.

Title: Why is design by contract considered an alternative to the pseudo programming process?

Body:
Right now I'm reading Code Complete by Steve McConnell and in chapter 9 he talks about the Pseudo Programming Process (PPP).

From what I've understood, the PPP is a way of programming in which the programmer first writes the pseudo code for the routine he's working on, then refines it up to the point where pretty much each pseudo code line can be implemented in 1-3 lines of code, then writes the code in the designated programming language and finally the pseudo code is saved as comments for the purpose of documenting the routine.

In chapter 9.4 the author mentions alternatives to the PPP, one of which is 'design by contract'. In design by contract you basically assert preconditions and postconditions of each routine.

Now why would that be considered an alternative? To me it seems obvious that I should use both techniques at the same time and not chose one over the other.


问:
Difference between spring setter and interface injection?
I know how constructor and setter injection works in spring.

Normally I use interfaces instead of classes to inject beans using setter and I consider it as interface injection, but in case of constructor we also use interfaces (I am confused). In following example I use JobProcessor interface instead of JobProcessorImpl class.

```<code>public class JobScheduler {
    // JobProcessor interface
    private JobProcessor jobProcessor;
    // Dependecy injection
    public void setJobProcessor(JobProcessor jobProcessor){
        this.jobProcessor = jobProcessor;
    }
}
</code>```

I tried to find a solution by googling but there are different opinions by writers. Even some people says that spring doesn't support interface injection in their blogs/statements.

Can someone help me by example?

答:
In interface injection, the setter method is provided by an interface that is implemented by the bean in which we are going to inject the dependency.

Example:

package some.package;
public class Car implements EngineMountable {
    private Engine engine;
    @Override //dependency injection
    public void mount(Engine engine){
        this.engine = engine;
    }
}

public interface EngineMountable {
    void mount(Engine engine);
}
```

<p>The same is working for me in spring by applying the following configuration:</p>

<pre class="lang-xml prettyprint-override"><code><bean name="car" class="some.package.Car">
    <property name="mount" ref="engineObject" />
</bean>
</code>```

In some sites people says that spring does not supports interface injection, but for me the above example works in spring. As per me : spring supports interface injection.

Reference : Martin Fowler : Interface Injection

Body:
In interface injection, the setter method is provided by an interface that is implemented by the bean in which we are going to inject the dependency.

Example:

package some.package;
public class Car implements EngineMountable {
    private Engine engine;
    @Override //dependency injection
    public void mount(Engine engine){
        this.engine = engine;
    }
}

public interface EngineMountable {
    void mount(Engine engine);
}

The same is working for me in spring by applying the following configuration:

<bean name="car" class="some.package.Car">
    <property name="mount" ref="engineObject" />
</bean>

In some sites people says that spring does not supports interface injection, but for me the above example works in spring. As per me : spring supports interface injection.

Reference : Martin Fowler : Interface Injection


问:
When should code favour optimization over readability and ease-of-use?
I am in the process of designing a small library, where one of my design goals is that the API should be as close to the domain language as possible. While working on the design, I've noticed that there are some cases in the code where a more intuitive, readable attribute/method call requires some functionally unnecessary encapsulation. Since the final product will not necessarily require high performance, I am unconcerned about making the decision to favour ease-of-use in my current project over the most efficient implementation of the code in question.

I know not to assume readability and ease-of-use are paramount in all expected use-cases, such as when performance is required. I would like to know if there are more general reasons that argue for a design preferring more efficient implementations—even if only marginally so?

答:
When you're building a library, or any tool that will be used by many people for different purposes, this is a problem, because they all have different needs.

What I try to do is get some representative use cases, and make sure my product makes a reasonable choice for those cases,
and is not atrociously bad in any case.

If I can just give one example of what can happen:

The LAPACK routine DGEMM is a general routine for multiplying matrices.
Its calling sequence contains initial character arguments for specifying certain options, like  whether either argument is to be transposed.

The customizing arguments are in there for two purposes: to make programming easier for the user, and to make it easier for the library writer.
Without them, either the user would have to transpose the arguments him/her-self, or the library writer would have to provide multiple routines.

To handle those arguments, DGEMM calls a function LSAME that compares characters. That also makes life easier for the library writer, because character representation can be very different for some machines.

The downside of this is, if the matrices are not very large, that DGEMM spends most of its time calling LSAME, compared to the time it spends multiplying matrices!
If the user's program spends a large fraction of time calling DGEMM, that means a large fraction of time is spent calling LSAME, comparing characters (even though those characters are practically always the same).
Repeated effort is wasted effort.
If a user can figure that out, such as by random pausing, they can make ad-hoc routines for multiplying their matrices.

But the more general point is -
that is the problem in writing libraries or any tools.
You have to try to be useful for a spectrum of needs.


答:
Have you ever Googled something?

How long did it take for you to get results? I bet it was pretty quick. That's down to an algorithm.

How many results did it return to you? Again, that's down to an algorithm.

How relevent/correct were the results to what you Googled? Algorithm.


问:
Constructor vs setter validations
I have the following class :

```<code>public class Project {

    private int id;
    private String name;

    public Project(int id, String name, Date creationDate, int fps, List<String> frames) {
        if(name == null ){
            throw new NullPointerException("Name can't be null");
        }

        if(id == 0 ){
            throw new IllegalArgumentException("id can't be zero");
        }

            this.name = name;
            this.id = id;

    }

    private Project(){}

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}
</code>```

I have three questions:

Do I use the class setters instead of setting the fields directly. One of the reason that I set it directly, is that in the code the setters are not final and they could be overridden.

If the right way is to set it directly and I want to make sure that the name filed is not null always. Should I provide two checks, one in the constructor and one in the setter.

I read in effective java that I should use NullPointerException for null parameters. Should I use IllegalArgumentException for other checks, like id in the example.

答:
Your class allows someone to say myProject.setName(null), avoiding the null check in the constructor. If you want to set stuff through the constructor but need checks (question 2), I suggest doing the checks in set-methods and call those from the constructor. Example:

```<code>public class Project {

    private int id;
    private String name;

    public Project(int id, String name, Date creationDate, int fps, List<String> frames) {
        setName(name);
        setId(id);
    }

    public void setId(int id) {
        if(id == 0 ){
            throw new IllegalArgumentException("id can't be zero");
        }
        this.id = id;
    }

    public void setName(String name) {
        if(name == null ){
            throw new NullPointerException("Name can't be null");
        }
        this.name = name;
    }

}
</code>```

This avoids code duplication.

Title: Constructor vs setter validations

Body:
Your class allows someone to say myProject.setName(null), avoiding the null check in the constructor. If you want to set stuff through the constructor but need checks (question 2), I suggest doing the checks in set-methods and call those from the constructor. Example:

public class Project {

    private int id;
    private String name;

    public Project(int id, String name, Date creationDate, int fps, List<String> frames) {
        setName(name);
        setId(id);
    }

    public void setId(int id) {
        if(id == 0 ){
            throw new IllegalArgumentException("id can't be zero");
        }
        this.id = id;
    }

    public void setName(String name) {
        if(name == null ){
            throw new NullPointerException("Name can't be null");
        }
        this.name = name;
    }

}

This avoids code duplication.


问:
Bug severity classification issues
In a book I have, there is a following classification of defect:

Critical : A defect receives a “critical” severity level if one or more critical
system functionalities are impaired by a defect with is impaired and there
is no workaround.

High: A defect receives a “high” severity level if some fundamental system
functionalities are impaired but a workaround exists.

Medium: A defect receives a “medium” severity level if no critical functionality
is impaired and a workaround exists for the defect.

Low: A defect receives a “low” severity level if the problem involves a
cosmetic feature of the system.

To be honest, I do not get it.. For example point 2. What if fundamental but not critical feature is impaired and there is NOT a workaround. The same for point 3: what if no critical functionality is affected but there is no workaround?
E.g. optional field in the registration form does not work. No workaround but barely an issue.

答:
It is impossible to draw clear lines between these categories.  In practice, it doesn't matter.  We assign categories to communicate with the people who will respond to the defects.  When a defect is discovered, choose the category that will elicit the response most useful to the enterprise.  If it has to be fixed as soon as possible, and preferably sooner, it is definitely critical.  If it's important, but can be managed during normal work hours, maybe it's high.

Organizations should not create processes where the precise categorization of defects drives financial rewards.  That creates incentives to work outside the defect tracking system.

Title: Bug severity classification issues


问:
Should I continue my self-taught coding practice or learn how to do coding professionally?
Lately I've been getting professional work, hanging out with other programmers, and making friends in the industry. The only thing is I'm 100% self-taught. It's caused my style to extremely deviate from the style of those that are properly trained. It's the techniques and organization of my code that's different.

It's a mixture of several things I do. I tend to blend several programming paradigms together. Like Functional and OO. I lean to the Functional side more than OO, but I see the use of OO when something would make more sense as an abstract entity. Like a game object. Next I also go the simple route when doing something. When in contrast, it seems like sometimes the code I see from professional programmers is complicated for the sake of it! I use lots of closures. And lastly, I'm not the best commenter. I find it easier just to read through my code than reading the comment. And most cases I just end up reading the code even if there are comments. Plus I've been told that, because of how simply I write my code, it's very easy to read it.

I hear professionally trained programmers go on and on about things like unit tests. Something I've never used before so I haven't even the faintest idea of what they are or how they work. Lots and lots of underscores "_", which aren't really my taste. Most of the techniques I use are straight from me, or a few books I've read. Don't know anything about MVC, I've heard a lot about it though with things like backbone.js. I think it's a way to organize an application. It just confuses me though because by now I've made my own organizational structures.

It's a bit of a pain. I can't use template applications at all when learning something new like with Ubuntu's Quickly. I have trouble understanding code that I can tell is from someone trained. Complete OO programming really leaves a bad taste in my mouth, yet that seems to be what EVERYONE else is strictly using.

It's left me not that confident in the look of my code, or wondering whether I'll cause sparks when joining a company or maybe contributing to open source projects. In fact I'm rather scared of the fact that people will eventually be checking out my code. Is this just something normal any programmer goes through or should I really look to change up my techniques?

答:
In short, the best way to learn is generally to hang out with someone you can learn from. If you feel that your skills aren't up to scratch, hanging out with people who are better than you is the best you can do. Certainly much better than withdrawing and isolating yourself further.

However, I think you're painting a very simplified and misleading picture.
Far from all "professionally taught" programmers are really any good. Just because they do something doesn't necessarily mean it's the right thing to do.

And much (but not all) of what you're saying really sounds like you're the one who could teach them a trick or two.

I lean to the Functional side more than OO, but I see the use of OO when something would make more sense as an abstract entity.

That sounds great to me. The best coders are the ones who use the right tool for the job. I'd always pick someone who knows both paradigms, and uses each of them where it makes sense over someone who religiously uses only one paradigm.

Next I also go the simple route when doing something. When in contrast, it seems like sometimes the code I see from professional programmers is complicated for the sake of it!

Again, simplicity is good. Don't make your code complex until it needs to be complex. Some people do tend to make things complex out of some misguided idea of elegance, or because "we'll need this additional functionality later". Generally, it's better to do the simplest thing that solves your problem.

I use lots of closures.
  Good. That's why they're there. They do scare some people who got stuck in the 1990's  and Java's outmoded quasi-OOP model, but really, that's their problem.

And lastly, I'm not the best commenter.

What should be commented, and how, is highly subjective. There's no real "right" or "wrong" there, but when working on a team, it's important to write code that the entire team, and not just the author of the code, can understand. And sometimes, compromises have to be made to conform to the team's coding style. That doesn't necessarily mean that you should write more comments, it simply means that it's something you and your team will have to agree on.

I hear professionally trained programmers go on and on about things like unit tests. Something I've never used before so I haven't even the faintest idea of what they are or how they work.

Well, ask them. :)  Testing your code is essential, and unit tests are a popular and useful tool for this.

Lots and lots of underscores "_", which aren't really my taste.

As with commenting, that is subjective, and depends on the language. In C and C++, lowercase_with_underscores is a fairly common naming convention. In many other languages, you'd virtually never see an underscore. But at the end of the day, it's really not important. Whether a function is called write_to_log or WriteToLog isn't actually going to make a difference. Someone is going to have to just suck it up and conform to what the team has agreed upon there.

Don't know anything about MVC, I've heard a lot about it though with things like backbone.js. I think it's a way to organize an application. It just confuses me though because by now I've made my own organizational structures.

As with unit tests, never stop learning. You work together with people who know things you don't, and who come from a different background than you do. Learn from each others. There are clearly things you can teach them, but there are also things you don't know, or have never heard of, which they can teach you. That doesn't mean you (or they) are a bad programmer. It means that a good programmer is one who strives to improve, and to learn from others.

Complete OO programming really leaves a bad taste in my mouth

Same here, and I am what you'd call "professionally trained" (a CS degree). People who have been taught programming differ just as much as people who are self-taught. It sounds like you're working with some who really need to learn a few new tricks.

In fact I'm rather scared of the fact that people will eventually be checking out my code. Is this just something normal any programmer goes through or should I really look to change up my techniques?

Both. Of course it's scary to have others look at (and judge) what you've made. But it's also very educational. They can tell you what they'd have done otherwise, or why they'd have done it otherwise. They can help you improve, and they might also learn something themselves. Show them code that solves a problem better than their "preferred" solution would have done, and hopefully they'll go "oh, that's neat. How did you know to do that? What do you call this? I should use this technique myself"


问:
What's your favourite quote about programming?
What's your favourite quote about programming?

One quote per answer, and please check for duplicates before posting!

答:
Being able to get a machine to do what you want is the closest thing we've got in technology to adolescent wish-fulfillment.

  — Guy Steele in Coders at Work

LastEditorDisplayName: Roger Pate


答:
You can learn by doing them collectively.

I use Planning Poker. It a consensus-based technique for estimating.

Your estimation must be tracked and compared to what you have effectively done. You will get the Velocity.

Each time you estimate something, multiplicate by your recent velocity to get accurate estimation.

Title: How to learn to make better estimates?

Body:
I suck at estimates. When someone asks me how long something will take, I don't even dare to make a guess since I will be completely off the mark. Usually I'm way too optimistic, and should probably multiply my guess with some large X factor...

How can I learn to make better estimates? It's not taught at my uni, and even though we have deadlines for all laborations I never think about how long something will actually take. Which I should. For everyone's sake (especially mine).


问:
Is it possible to implement a completely-stateless multiplayer game?
I'm facing a challenge understanding how to program a web version of a card game that is completely stateless.

I create my object graph when the game begins and distribute cards to PlayerA and PlayerB so I lay them out on the screen. At this point I could assume that HTML and the querystring is what holds at least some of my state and just keep a snapshot copy of the game state on the server-side for the sole purpose of validating the inputs I receive from the web clients.

Still it appears to me that the state of the game is by its nature mutable: cards are being dealt from the deck, etc.

Am I just not getting it? Or should I just strive to minimize the side-effects of my functions to the objects that I take as my input? How would you design a stateless card game?

答:
A single player game can be completely stateless if the entire description of the game is transmitted on each request.  A chess game against a computer program implemented by your server could just send the complete position after each move.

It's hard to see how a multiplayer game can be completely stateless - someone has to keep track of who the players are and who needs to be informed of state changes, and at least
remember the state "in transit" long enough for all the players to receive it.

In any case, the primary role of the server can be just to relay bags of bits among the clients, and only need to keep track of where the bits are supposed to go.  Depending on
the nature of the game, the bits may need to be authenticated in some way to prevent cheating, for example by adding a checksum to the parts the clients aren't supposed to be able to change.


答:
There's a good metaphor, issue severity scale is relative.

It's only goal is to provide means for prioritizing bug-fixing effort. The ultimate question is, "what issues to focus on, in the first place?", and the answer is a sorted list of issues. If the list does not work that way, it becomes useless.

There are many considerations specific to the product you're working on:

Workarounds may or may not be relevant at all.

Say, you are developing a firmware for a washing machine, and a certain button does not work as expected - would you even consider if there is a workaround by simultaneous pressing two other buttons?

The definition of "Critical feature" also changes.

Say, you are working on version #15 of your product, and it has planned feature of A.

According to your plans, there will be another feature B scheduled for version #16.

You find a failure in feature B, and you need assigning severity. Regardless of the fact B will become critical for release #16, it is not that important for current release. So you assign it medium severity so that the developers were not wasting their time now. As soon as release #15 occurs, the severity should be updated.

Title: Bug severity classification issues

Body:
In a book I have, there is a following classification of defect:

Critical : A defect receives a “critical” severity level if one or more critical
system functionalities are impaired by a defect with is impaired and there
is no workaround.

High: A defect receives a “high” severity level if some fundamental system
functionalities are impaired but a workaround exists.

Medium: A defect receives a “medium” severity level if no critical functionality
is impaired and a workaround exists for the defect.

Low: A defect receives a “low” severity level if the problem involves a
cosmetic feature of the system.

To be honest, I do not get it.. For example point 2. What if fundamental but not critical feature is impaired and there is NOT a workaround. The same for point 3: what if no critical functionality is affected but there is no workaround?
E.g. optional field in the registration form does not work. No workaround but barely an issue.


答:
The most important thing is to develop flexibility. The more familiar you are with fundamental concepts, the more responsive you can be in any language, programming approach, style, or environment.

Mastery is less about learning every /thing/ there is to learn, and more about learning /how/ to go about solving a problem, in a variety of situations.

And the best prescription for that is practice. You should always have a project; if you're between paid gigs, take up a personal toy. Spare time one weekend? Work through the 'hello world' for a language or platform you've never used before. Look for ways to learn a lot at once. For example, build something in Google App Engine, and you'll learn all at once about Python, BigTable, and column-oriented databases. You'll get a good dose of "professional" Google style as well.

A good general knows how to apply his learned tactics and collected experience in a variety of terrain. It sounds like you have some tactics and experience, but you need to encounter some unfamiliar terrain. That's probably the single best way to ascertain what you know and what next you need to learn.

And if "professional" style is what you're after, take on some "professional" projects. Find an open-source project you like, assign yourself a change to make, and set about it. Be prepared for jackass reviewers, but remember that the majority of folks in this field didn't get where they are for having smooth social skills. The point is to expose yourself to as much of what you want to be as possible. And you have to build yourself up well enough to do it yourself. No class can really teach you. In fact, there's too damn much class-learning going on today, and not enough solid real-world competence.

Title: Should I continue my self-taught coding practice or learn how to do coding professionally?

Body:
Lately I've been getting professional work, hanging out with other programmers, and making friends in the industry. The only thing is I'm 100% self-taught. It's caused my style to extremely deviate from the style of those that are properly trained. It's the techniques and organization of my code that's different.

It's a mixture of several things I do. I tend to blend several programming paradigms together. Like Functional and OO. I lean to the Functional side more than OO, but I see the use of OO when something would make more sense as an abstract entity. Like a game object. Next I also go the simple route when doing something. When in contrast, it seems like sometimes the code I see from professional programmers is complicated for the sake of it! I use lots of closures. And lastly, I'm not the best commenter. I find it easier just to read through my code than reading the comment. And most cases I just end up reading the code even if there are comments. Plus I've been told that, because of how simply I write my code, it's very easy to read it.

I hear professionally trained programmers go on and on about things like unit tests. Something I've never used before so I haven't even the faintest idea of what they are or how they work. Lots and lots of underscores "_", which aren't really my taste. Most of the techniques I use are straight from me, or a few books I've read. Don't know anything about MVC, I've heard a lot about it though with things like backbone.js. I think it's a way to organize an application. It just confuses me though because by now I've made my own organizational structures.

It's a bit of a pain. I can't use template applications at all when learning something new like with Ubuntu's Quickly. I have trouble understanding code that I can tell is from someone trained. Complete OO programming really leaves a bad taste in my mouth, yet that seems to be what EVERYONE else is strictly using.

It's left me not that confident in the look of my code, or wondering whether I'll cause sparks when joining a company or maybe contributing to open source projects. In fact I'm rather scared of the fact that people will eventually be checking out my code. Is this just something normal any programmer goes through or should I really look to change up my techniques?


答:
This isn't a full answer, you've already got several good ones. However, there are a couple of points that to me look a bit confused and haven't been addressed.

It's a mixture of several things I do. I tend to blend several programming paradigms together. Like Functional and OO. I lean to the Functional side more than OO, but I see the use of OO when something would make more sense as an abstract entity. Like a game object.

To me it looks like you are confusing declarative vs imperative programming, rather than Functional Vs Object Oriented programming. If you mean that you lean towards declarative programming and away from imperative then that is a good thing. Declarative seeks to remove side effects, which should make your code easier to understand.

Modern programming languages often support declarative programming model. For example, in C#, using Linq results in a declarative style, because you aren't saying how to obtain what you want; you are only saying what you want.

Complete OO programming really leaves a bad taste in my mouth, yet
  that seems to be what EVERYONE else is strictly using.

Modern languages are often multi-paradigm languages. It's rare that anyone uses a "pure" language. Many Functional languages support objects and side effects. Languages considered Object-oriented often don't impose the constraint that everything is an object.

What do you mean by complete OO? I've never worked on "pure" OO code. Perhaps you can give us some more specifics of what you dislike. An illustration from an open source project might help.

OO programmings gives us many features to support things like: data abstraction, encapsulation, messaging, modularity, polymorphism, and inheritance. If I looked at a code base that didn't take advantage of that, it would leave a bad taste in my mouth.


问:
Why is OOP difficult?
When I started using an object-oriented language (Java), I pretty much just went "Cool" and started coding. I've never really thought about it until only recently after having read lots of questions about OOP. The general impression I get is that people struggle with it. Since I haven't thought of it as hard, and I wouldn't say I'm any genius, I'm thinking that I must have missed something or misunderstood it.

Why is OOP difficult to understand? Is it difficult to understand?

答:
The main jump for me was just understanding the abstract concept of OOP. Now I'm very new to programming in general I've been programming for a year to a year and a half now so my introduction into OOP was with Actionscript and Processing. When I first learned Actionscript coding, it wasn't in OOP. I learned to code directly into the Actions panel and that is how I learned the basic fundamentals of programming (variables, functions, loops etc). So I learned it as doing something directly to the stage in Flash or Processing.

When OOP came into things, realizing that I could create methods and properties within an object to be able to use and reuse was a little difficult for me to grasp at first. Everything was very abstract and difficult to process but the programming languages themselves a lot better but it kind of took a leap of faith to make those connections at first.

Title: Why is OOP difficult?

OwnerDisplayName: Kobby


问:
Should a project start with the client or the server?
Pretty simple question with a complex answer.

Should a project start with the client or the server, and why?

Where should a single programmer start a client/server project?

What are the best practices and what are the reasons behind them? If you can't think of any, what reasons do you use to justify why you would choose to start one before the other?

Personally, I'm asking this question because I'm finishing up specs for a project I will be doing for myself on the side for fun. But now that I'm finishing this phase, I'm wondering "ok, now where do I begin?" Since I've never done a project like this by myself, I'm not sure where I should start.

In this project, my server will be doing all the heavy lifting and the client will just be sending updates, getting information from the server, and displaying it. But, I don't want that to sway the answer as I'm looking for more of an in depth and less specific answer that would apply to any project I begin in the future.

答:
With any client-server system, you need to start with defining how the two should communicate:

What infrastructure to use? Connected? Disconnected? Stateless? Stateful?

What kind of communication method? Push? Pull? A bit of both?

What calls should be available to each side?

What are the latency requirements?

What are the scalability requirements?

(there are probably many other questions you need to answer before you can start implementing)

Once you drive out the non-functional and functional requirements, you can start defining the technology to use. At this point you can start by coding some simple exchanges of information between client and server - you evolve both at the same time.


答:
It's left me not that confident in the look of my code, or wondering
  whether I'll cause sparks when joining a company or maybe contributing
  to open source projects. In fact I'm rather scared of the fact that
  people will eventually be checking out my code. Is this just something
  normal any programmer goes through or should I really look to change
  up my techniques?

In my opinion, there's no need to worry about what others think of your code if you focus on objective measures of the quality of it. Is it

Correct?

Understandable?

Maintainable?

Efficient?

As a first principle, It should always be your goal to focus on objective qualities, rather than others' opinions. Focusing on others' opinions is the path to mediocrity, and, as you're experiencing, anxiety.

The only reason to be concerned with others' opinions is to be able to integrate well socially (or in a work environment) with them. If you have in the forefront of your mind the goal of improving objective qualities of your work, then there's no need for feeling scared about others' reactions -- they're just opportunities to learn or, at the worst, practical details to deal with.

Be true to yourself!! Continue learning and enjoying what you do.


问:
Dependency injection with n-tier Entity Framework solution
I am currently designing an n-tier solution which is using Entity Framework 5 (.net 4) as its data access strategy, but am concerned about how to incorporate dependency injection to make it testable / flexible.

My current solution layout is as follows (my solution is called Alcatraz):

Alcatraz.WebUI: An asp.net webform project, the front end user interface, references projects Alcatraz.Business and Alcatraz.Data.Models.

Alcatraz.Business: A class library project, contains the business logic, references projects Alcatraz.Data.Access, Alcatraz.Data.Models

Alcatraz.Data.Access: A class library project, houses AlcatrazModel.edmx and AlcatrazEntities DbContext, references projects Alcatraz.Data.Models.

Alcatraz.Data.Models: A class library project, contains POCOs for the Alcatraz model, no references.

My vision for how this solution would work is the web-ui would instantiate a repository within the business library, this repository would have a dependency (through the constructor) of a connection string (not an AlcatrazEntities instance).  The web-ui would know the database connection strings, but not that it was an entity framework connection string.

In the Business project:

```<code>public class InmateRepository : IInmateRepository
{
    private string _connectionString;

    public InmateRepository(string connectionString)
    {
        if (connectionString == null)
        {
            throw new ArgumentNullException("connectionString");
        }

        EntityConnectionStringBuilder connectionBuilder = new EntityConnectionStringBuilder();

        connectionBuilder.Metadata = "res://*/AlcatrazModel.csdl|res://*/AlcatrazModel.ssdl|res://*/AlcatrazModel.msl";
        connectionBuilder.Provider = "System.Data.SqlClient";
        connectionBuilder.ProviderConnectionString = connectionString;

        _connectionString = connectionBuilder.ToString();
    }

    public IQueryable<Inmate> GetAllInmates()
    {
        AlcatrazEntities ents = new AlcatrazEntities(_connectionString);

        return ents.Inmates;
    }
}
</code>```

In the Web UI:

```<code>IInmateRepository inmateRepo = new InmateRepository(@"data source=MATTHEW-PC\SQLEXPRESS;initial catalog=Alcatraz;integrated security=True;");

List<Inmate> deathRowInmates = inmateRepo.GetAllInmates().Where(i => i.OnDeathRow).ToList();
</code>```

I have a few related questions about this design.

Does this design even make sense in terms of Entity Frameworks capabilities?  I heard that Entity framework uses the Unit-of-work pattern already, am I just adding another layer of abstract unnecessarily?

I don't want my web-ui to directly communicate with Entity Framework (or even reference it for that matter), I want all database access to go through the business layer as in the future I will have multiple projects using the same business layer (web service, windows application, etc.) and I want to have it easy to maintain / update by having the business logic in one central area.  Is this an appropriate way to achieve this?

Should the Business layer even contain repositories, or should that be contained within the Access layer?  If where they are is alright, is passing a connection string a good dependency to assume?

Thanks for taking the time to read!

答:
The way you are doing DI is wrong.

First, the connection string belongs in the data layer. Or in the web.config file.

The next abstraction you will be dealing with is the DbContext, not a connection string. Your repositories should not know about connection strings. Your business logic will not know about DbContext etc.

Your UI will have no idea and will not instantiate anything related to EF.

Concrete answers to your points:

Do not add abstractions, until you are very familiar with EF. It already adds good abstractions like UoW, queries, using POCOs etc.

For DI to work, you have a Composition Root which references all components needed. This might or might not be in the WebUI project. If it isn't, you should expect that it does not reference EF or any other data related tech.

Stop right here. Stop adding abstractions over abstractions. Start with direct and 'naive' architecture and develop it over time.

Abstractions are a tool to deal with complexity. Absence of complexity means no abstractions needed (yet).


答:
There is no best practice. Whether you build a client or server first depends on the context of what you're building. However, if you are starting from scratch then you need to build both.

If you're building a client-server project for fun, why do you care what to build first? You're going to need both, build just enough of each to demonstrate that they can connect and prove that features work. Building a client that connects to a basic server should take no more than an hour. There are plenty of basic examples on the web.

@Oded correctly answered with several questions. However, the chances are unless you're building something with high realtime (latency) requirements then a web project will be sufficient. You will then already have a browser to act as your client. Web technologies offer solutions to the common problems that distributed system developers solve.

Are there any legacy clients or servers to the thing you're building. If so, then consider building client and using the existing server or vice versa.

Title: Should a project start with the client or the server?

Body:
Pretty simple question with a complex answer.

Should a project start with the client or the server, and why?

Where should a single programmer start a client/server project?

What are the best practices and what are the reasons behind them? If you can't think of any, what reasons do you use to justify why you would choose to start one before the other?

Personally, I'm asking this question because I'm finishing up specs for a project I will be doing for myself on the side for fun. But now that I'm finishing this phase, I'm wondering "ok, now where do I begin?" Since I've never done a project like this by myself, I'm not sure where I should start.

In this project, my server will be doing all the heavy lifting and the client will just be sending updates, getting information from the server, and displaying it. But, I don't want that to sway the answer as I'm looking for more of an in depth and less specific answer that would apply to any project I begin in the future.


问:
Hiring at start-ups vs established companies
I have always wondered about this and perhaps experienced folks here can comment on this. I always read that big established software companies such as Google, Microsoft, etc are always wary of hiring software engineers/(or other related professionals) who don't exactly meet the job requirements, and would rather turn down a close "Yes/Maybe" decision.

There's also the general perception that start-ups are generally more willing to hire such "less-than-perfect" employees. But to me this sounds counter-intuitive: start-ups are generally much smaller and resource constrained so they would actually need a "10/10" hire while established companies with bigger teams and more resources would be willing to take a (small) risk on a hire.

Anyone have any comments on this from first-hand experience?

Thanks,

答:
Well, I do have some experience with this situation.  A point you may be overlooking is how those established companies have a reputation that may well allow them to be picky.  For any position, if there are hundreds of applications they can weed out whomever they want in a sense.  Start-ups do not get the same deluge of resumes which can mean that if filling the position becomes crucial to the success of the company, they will take the best they can get which will often be less than perfect.  Your counter-intuitive point does make business sense but there are plenty of times where when theory meets practice, practice brutally teaches the world a lesson, in my experience.  If you want to see this in action, just go to the University of Waterloo and each semester look at the jobs posted by big established companies like Microsoft and notice how many applications go into those boxes compared to others that may be with a much smaller company.

An example of that would be the idea of releasing software with bugs.  In theory, if there are bugs in the software, this should be fixed before one ships the software.  However, if one really holds that view, the software will likely never ship.

I have had a couple of interviews for positions at Microsoft.  The first one I bombed rather horribly and couldn't believe I had the issues that I did.  The second time I got up to the hiring manager being on the fence and I declined to try to fight for why I should get hired as there were 2 areas where I seemed to be so-so and thus wasn't a solid, "Yes, we should get him," situation.


问:
I don't understand the definition of side effects

Possible Duplicate:

  What is a “side effect?”

I don't understand the wikipedia article on Side Effects:

In computer science, a function or expression is said to have a side effect if, in addition to returning a value, it also 1.) Modifies some state or 2.) Has an observable interaction with calling functions or the outside world.

I know an example of the first thing that causes a function or expression to have side effects - modifying a state

Function and Expression modifying a state
:

1.)

```<code>foo(int X)
{
return x = x % x;
}

a = a + 1;
</code>```

What does 2.) - Has an observable interaction with calling functions or the outside world," mean?  - Please give an example.

The article continues on to say, "For example, a function might modify a global or static variable,
modify one of its arguments, raise an exception, write data to a display or file, read data, or call other side-effecting functions...." Are all these examples, examples of 1.) -  Modifiying some state , or are they also part of 2.) - Has an observable interaction with calling functions or the outside world?

答:
First, your example is wrong (unless x refers to a field, and X is not used). foo(int x) { return x = x % x; } is actually a pure method, i.e. it doesn't have side effects. What would have side effects is a method like:

```<code>private int x;

public void ComputeValue()
{
    this.x = this.x * 2 + 1; // Modifies a state of this.x
}
</code>```

As for the second point, the outside world can be any element with which your app interacts: file system, a database, user display, printer, USB port, web service, user settings (like the desktop background), etc.

Some examples of methods which interact with the outside world:

```<code>public void SayHello()
{
    Console.WriteLine("Hello World!");
}
</code>```

interacts with the console. In other words, SayHello has a side effect to change the console state by adding characters to it (and optionally moving the previous text to the top, removing the oldest line from the user).

```<code>public void SaveHello()
{
    File.Save(this.fileName, "Hello World");
}
</code>```

interacts with the file system. In other words, SaveHello has a side effect to alter the contents of a file (or create a file).

Think about side effects as something which changes something somewhere outside the method itself. If a method adds a row to a database, the database state changes: this is a side effect. If a method logs an event, the state of the log changes.

Understanding those side effects is crucial when doing parallel computing. A pure method, i.e. a method without side effects, can be run by multiple cores of the CPU at the same time without any problem. A method which changes the state of something must be used with caution. Often, locks and transactions are required to ensure that the program will run as expected.

Body:
First, your example is wrong (unless x refers to a field, and X is not used). foo(int x) { return x = x % x; } is actually a pure method, i.e. it doesn't have side effects. What would have side effects is a method like:

private int x;

public void ComputeValue()
{
    this.x = this.x * 2 + 1; // Modifies a state of this.x
}

As for the second point, the outside world can be any element with which your app interacts: file system, a database, user display, printer, USB port, web service, user settings (like the desktop background), etc.

Some examples of methods which interact with the outside world:

public void SayHello()
{
    Console.WriteLine("Hello World!");
}

interacts with the console. In other words, SayHello has a side effect to change the console state by adding characters to it (and optionally moving the previous text to the top, removing the oldest line from the user).

public void SaveHello()
{
    File.Save(this.fileName, "Hello World");
}

interacts with the file system. In other words, SaveHello has a side effect to alter the contents of a file (or create a file).

Think about side effects as something which changes something somewhere outside the method itself. If a method adds a row to a database, the database state changes: this is a side effect. If a method logs an event, the state of the log changes.

Understanding those side effects is crucial when doing parallel computing. A pure method, i.e. a method without side effects, can be run by multiple cores of the CPU at the same time without any problem. A method which changes the state of something must be used with caution. Often, locks and transactions are required to ensure that the program will run as expected.


问:
What are the best education options for software engineers after an undergraduate degree?
Having recently completed a BSC (computer science), I am working as software engineer.  With one year of experience, what educational options are available to me?  I want to move further in management.  </p>

<p>Please provide suggestions.  I am considering a MSC but I got negative reply from lots of people. </p>

答:
Business vs. Engineering

As an undergraduate, I started a business degree in accounting.  In the fourth semester, I registered for classes late and the Computer Information Systems class I wanted to take was full.  Somehow, I had myself as an academic advisor, and figured the introduction to computer science from the engineering department would fit my program somehow.

That was my last semester as a business major, so you can probably guess how my answer will end.

I have undergrad and masters degrees in computer science, but not an MBA, so my answer is based on a little research and experience in the work place.

A Little Research: What is an MBA (Masters of Business Administration)

I have heard about the MBA for years, and figured it was like a business degree with content from all areas (accounting, finance, marketing, etc.) studied by business majors instead of just one area.  Here is a list of classes I found for Rochester Institute of Technology.

```<code>MBA degree (traditional), typical course sequence (semesters)
Course  Sem. Cr. Hrs.
MGMT-601    Foundations of Business Ethics  1
MGMT-740    Organizational Behavior and Leadership  3
ACCT-703    Accounting for Decision Makers  3
MKTG-761    Marketing Concepts and Commercialization    3
ESCB-705    Economics and Decision Modeling 3
FINC-721    Financial Analysis for Managers 3
DECS-743    Operations and Supply Chain Management  3
MGMT-735    Management of Innovation in Products and Services   3
MGMT-759    Competitive Strategy*   3
    MBA Elective 1, 2, 3, 4, 5, 6, 7, 8 24
Total Semester Credit Hours 49
</code>```

Nothing too shocking here.  Having had econ 101 and 102, accounting 101 and 102, quantitative business analysis 101 and 102, intro to business law, I have an idea what the grad level version might be like.

Like most master's degrees, electives depend on are of specialization.  Assuming you are staying in technology, perhaps the following is appropriate:

```<code>TECHNOLOGY MANAGEMENT (SEMESTERS)
Course  Sem. Cr. Hrs.
MGMT-742    Technology Management    3
Choose two or three of the following:    6-9
   MGMT-761    Managing Research and Innovation
   MGMT-762    Managing New Process and Product Development
   MGMT-741    Managing Organizational Change
   MGMT-776    Product and Brand Management
   DECS-744    Project Management
   BLEG-745    Legal and Ethical Issues in Technology Intensive Environments
</code>```

MCS programs may include content similar to MGMT-761, 762, 741 and DECS-744 but under course titles like "Software Project, Process, and Quality Management" or "Principles of Software Engineering."  Some MBA topics may be mixed into software life cycle oriented classes like Requirements Analysis, Object Oriented Analysis and Design, Software Testing that are highly focused on both software engineering practice and on fitting into models like SEI CMMi.  On the MCS side, there is almost always team programming or documentation project, and homework or a project where software tools are identified and used.

Academic Crossovers - Non-Computer Science to Masters in Computer Science

One of the other answers to this question described the MS in IT as a degree that had suffered as being like a rebadged BS for undergraduates crossing over from something else as a way to enter the software profession.  Where I got my MCS, if your undergrad was not CS, you needed to fulfill 18 credit hours of undergrad level course work to make up the deficiency.

```<code>CSE 230 Computer Organization and Assembly Language Programming
CSE 310 Data Structures and Algorithms
CSE 340 Principles of Programming Languages
CSE 355 Introduction to Theoretical Computer Science
CSE 360 Introduction to Software Engineering
CSE 430 Operating Systems
</code>```

Compared with a BS in CS, that approach is missing around 15 credits of CS electives.  Depending on where they are coming from, they might be missing a lot of math and physics too.  If I interviewed a candidate who took this route, I might want to ask questions about the undergrad material like:

What does a D flip-flop do?

How does a processor, memory, and bus work together?

What initialization and handling is needed to make a timer interrupt work?

What is in a class for a linked list?  A binary tree?

What is a recursive descent parser?

Tell me about order notation?

Name two sort algorithms and identify and contrast their orders of complexity.

Name two search algorithms and identify and contrast their orders of complexity.

Maybe crossovers get a break, but I expect things balance out in the end.  I would like to see people who changed their mind about their future goals have a chance to earn their reward on a level playing field.

Academic Crossovers - Computer Science to MBA

Without any undergrad work in these areas, the vocabulary, concepts, and practices might become an issue, so I don't know how well an engineer crossing over to business would fare.   I didn't see information about deficiencies from business, but if your classmates have 18-36 credits of business classes that you don't have, even if it doesn't appear in classes, you are missing something valued by business colleges and perhaps employers.

Could you answer questions like:

What are the inputs to create a statement of changes (from accounting)?

What is price inelasticity (from economics)?

What is the difference between monetary and fiscal policy and who controls them (economics)?

What is the UCC (business law)?

Name five methods of accounting for pension expense (intermediate accounting)?

What is GAAP (accounting)?

Compare and contrast the approaches of Adam Smith and John Maynard Keynes (economics)?

On a balance sheet, is goodwill an asset or a liability and what does it represent?

One Executive MBA program I saw online expected six years work experience.  Perhaps in your organization there is a chicken and egg problem where to be a manager they expect an MBA, but before committing that level of resource to management, I would want to be sure I liked it better than technical work.

Experience with MBAs in the Software Development Organization

Having worked in an organization with MBAs and several MCS graduates my perspective is that it depends what kind of management you want.  Characterize whether you want to stay close to the technical leadership or step away from the technical work toward the work of communications between technical people and executive management.

One MBA who I knew, took on the role of project manager and created many Microsoft Project schedules which he monitored and tried to control.  He also took over the software part of process definitions for ISO 9000.  Although his degree was IT, he had never written code.  His approach was pretty much straight waterfall, and he was hostile to Agile.

He became a protege of VP of operations, and for a while had high visibility and influence in many areas of the company, including supervision of project managers.  The company restructured, engineering took back process definition for software and hardware development.  He was moved to the IT department, and was no longer involved with product or process definition.  Not sure if he still works on quality, but he is the support go to guy for the company wiki and a few related tools.  I think he presently supervises no one.

Experience with MCSs in the Software Development Organization

In contrast, the MCS graduates I know are more tailored to the needs of software development and take the lead in introducing agile methods.  They still do a lot of development, and are involved in requirements management, defining the design, assigning coding tasks, participating in daily scrum meetings and grooming the burn down list.  It can be helpful to have a scrum master who clears obstacles for the team, but what I see are team leads becoming the lead of teams of team leads.  Contrast this with System of Systems design approaches for large DoD and industrial projects.

My preference within the product development organization would be someone with both the BS and MS in computer science which should impart a lot of insight to the software development life cycle and how it plays out in projects.

Some Ideas about Management and Quality

I would also caution against process definition as a way to build a career in management.  I have seen a lot of people involved in ISO 9000, and to a lesser extent SEI CMM, and other quality roles get their company over a big hump for certification.  Afterward, they become isolated and exited because they were the process police and once the conversion from adhoc process is complete, they are seen as obstructive to taking products from idea to result.  I believe that process and most decision making should be done at the lowest level possible in the organization.  This permits the person who lives the job to control it and tailor it, and to have an intimate connection and dedication to using it as a productivity tool rather than a role in the org chart.

With that in mind, unless you are executive management, if you manage it, I think you should live it (or have previously lived it).  My personal sweet spot would be 10-15% mentoring, administration, and process definition/improvement, with the remaining part being hands on development and product definition or product verification in the form of unit and integration testing.

MBA Prospects

I think companies will always have need of generalists, and if CEO is your target, there probably is no substitute for an MBA.  It can help you rise in the organization because you will have the vocabulary, tools, and mindset of executive management.  Traditional organizations may reward MBAs in technology leadership roles.  My concern would be that in software development, Agile is pushing more of the management functions into the development team (or the development team is taking back more control, depending on your perspective). and when times are tight, if the choice is between a generalist and a guy who writes code and helps lead the team, the generalist might get cut.

Body:
Business vs. Engineering

As an undergraduate, I started a business degree in accounting.  In the fourth semester, I registered for classes late and the Computer Information Systems class I wanted to take was full.  Somehow, I had myself as an academic advisor, and figured the introduction to computer science from the engineering department would fit my program somehow.

That was my last semester as a business major, so you can probably guess how my answer will end.

I have undergrad and masters degrees in computer science, but not an MBA, so my answer is based on a little research and experience in the work place.

A Little Research: What is an MBA (Masters of Business Administration)

I have heard about the MBA for years, and figured it was like a business degree with content from all areas (accounting, finance, marketing, etc.) studied by business majors instead of just one area.  Here is a list of classes I found for Rochester Institute of Technology.

MBA degree (traditional), typical course sequence (semesters)
Course  Sem. Cr. Hrs.
MGMT-601    Foundations of Business Ethics  1
MGMT-740    Organizational Behavior and Leadership  3
ACCT-703    Accounting for Decision Makers  3
MKTG-761    Marketing Concepts and Commercialization    3
ESCB-705    Economics and Decision Modeling 3
FINC-721    Financial Analysis for Managers 3
DECS-743    Operations and Supply Chain Management  3
MGMT-735    Management of Innovation in Products and Services   3
MGMT-759    Competitive Strategy*   3
    MBA Elective 1, 2, 3, 4, 5, 6, 7, 8 24
Total Semester Credit Hours 49

Nothing too shocking here.  Having had econ 101 and 102, accounting 101 and 102, quantitative business analysis 101 and 102, intro to business law, I have an idea what the grad level version might be like.

Like most master's degrees, electives depend on are of specialization.  Assuming you are staying in technology, perhaps the following is appropriate:

TECHNOLOGY MANAGEMENT (SEMESTERS)
Course  Sem. Cr. Hrs.
MGMT-742    Technology Management    3
Choose two or three of the following:    6-9
   MGMT-761    Managing Research and Innovation
   MGMT-762    Managing New Process and Product Development
   MGMT-741    Managing Organizational Change
   MGMT-776    Product and Brand Management
   DECS-744    Project Management
   BLEG-745    Legal and Ethical Issues in Technology Intensive Environments

MCS programs may include content similar to MGMT-761, 762, 741 and DECS-744 but under course titles like "Software Project, Process, and Quality Management" or "Principles of Software Engineering."  Some MBA topics may be mixed into software life cycle oriented classes like Requirements Analysis, Object Oriented Analysis and Design, Software Testing that are highly focused on both software engineering practice and on fitting into models like SEI CMMi.  On the MCS side, there is almost always team programming or documentation project, and homework or a project where software tools are identified and used.

Academic Crossovers - Non-Computer Science to Masters in Computer Science

One of the other answers to this question described the MS in IT as a degree that had suffered as being like a rebadged BS for undergraduates crossing over from something else as a way to enter the software profession.  Where I got my MCS, if your undergrad was not CS, you needed to fulfill 18 credit hours of undergrad level course work to make up the deficiency.

CSE 230 Computer Organization and Assembly Language Programming
CSE 310 Data Structures and Algorithms
CSE 340 Principles of Programming Languages
CSE 355 Introduction to Theoretical Computer Science
CSE 360 Introduction to Software Engineering
CSE 430 Operating Systems

Compared with a BS in CS, that approach is missing around 15 credits of CS electives.  Depending on where they are coming from, they might be missing a lot of math and physics too.  If I interviewed a candidate who took this route, I might want to ask questions about the undergrad material like:

What does a D flip-flop do?

How does a processor, memory, and bus work together?

What initialization and handling is needed to make a timer interrupt work?

What is in a class for a linked list?  A binary tree?

What is a recursive descent parser?

Tell me about order notation?

Name two sort algorithms and identify and contrast their orders of complexity.

Name two search algorithms and identify and contrast their orders of complexity.

Maybe crossovers get a break, but I expect things balance out in the end.  I would like to see people who changed their mind about their future goals have a chance to earn their reward on a level playing field.

Academic Crossovers - Computer Science to MBA

Without any undergrad work in these areas, the vocabulary, concepts, and practices might become an issue, so I don't know how well an engineer crossing over to business would fare.   I didn't see information about deficiencies from business, but if your classmates have 18-36 credits of business classes that you don't have, even if it doesn't appear in classes, you are missing something valued by business colleges and perhaps employers.

Could you answer questions like:

What are the inputs to create a statement of changes (from accounting)?

What is price inelasticity (from economics)?

What is the difference between monetary and fiscal policy and who controls them (economics)?

What is the UCC (business law)?

Name five methods of accounting for pension expense (intermediate accounting)?

What is GAAP (accounting)?

Compare and contrast the approaches of Adam Smith and John Maynard Keynes (economics)?

On a balance sheet, is goodwill an asset or a liability and what does it represent?

One Executive MBA program I saw online expected six years work experience.  Perhaps in your organization there is a chicken and egg problem where to be a manager they expect an MBA, but before committing that level of resource to management, I would want to be sure I liked it better than technical work.

Experience with MBAs in the Software Development Organization

Having worked in an organization with MBAs and several MCS graduates my perspective is that it depends what kind of management you want.  Characterize whether you want to stay close to the technical leadership or step away from the technical work toward the work of communications between technical people and executive management.

One MBA who I knew, took on the role of project manager and created many Microsoft Project schedules which he monitored and tried to control.  He also took over the software part of process definitions for ISO 9000.  Although his degree was IT, he had never written code.  His approach was pretty much straight waterfall, and he was hostile to Agile.

He became a protege of VP of operations, and for a while had high visibility and influence in many areas of the company, including supervision of project managers.  The company restructured, engineering took back process definition for software and hardware development.  He was moved to the IT department, and was no longer involved with product or process definition.  Not sure if he still works on quality, but he is the support go to guy for the company wiki and a few related tools.  I think he presently supervises no one.

Experience with MCSs in the Software Development Organization

In contrast, the MCS graduates I know are more tailored to the needs of software development and take the lead in introducing agile methods.  They still do a lot of development, and are involved in requirements management, defining the design, assigning coding tasks, participating in daily scrum meetings and grooming the burn down list.  It can be helpful to have a scrum master who clears obstacles for the team, but what I see are team leads becoming the lead of teams of team leads.  Contrast this with System of Systems design approaches for large DoD and industrial projects.

My preference within the product development organization would be someone with both the BS and MS in computer science which should impart a lot of insight to the software development life cycle and how it plays out in projects.

Some Ideas about Management and Quality

I would also caution against process definition as a way to build a career in management.  I have seen a lot of people involved in ISO 9000, and to a lesser extent SEI CMM, and other quality roles get their company over a big hump for certification.  Afterward, they become isolated and exited because they were the process police and once the conversion from adhoc process is complete, they are seen as obstructive to taking products from idea to result.  I believe that process and most decision making should be done at the lowest level possible in the organization.  This permits the person who lives the job to control it and tailor it, and to have an intimate connection and dedication to using it as a productivity tool rather than a role in the org chart.

With that in mind, unless you are executive management, if you manage it, I think you should live it (or have previously lived it).  My personal sweet spot would be 10-15% mentoring, administration, and process definition/improvement, with the remaining part being hands on development and product definition or product verification in the form of unit and integration testing.

MBA Prospects

I think companies will always have need of generalists, and if CEO is your target, there probably is no substitute for an MBA.  It can help you rise in the organization because you will have the vocabulary, tools, and mindset of executive management.  Traditional organizations may reward MBAs in technology leadership roles.  My concern would be that in software development, Agile is pushing more of the management functions into the development team (or the development team is taking back more control, depending on your perspective). and when times are tight, if the choice is between a generalist and a guy who writes code and helps lead the team, the generalist might get cut.


问:
The cost of longer delay between development and QA
At my current position, QA has become a bottleneck.  We have had the unfortunate occurence of features being held out of the current build so that QA could finish testing.  This means features that are done being developed may not get tested for 2-3 weeks after the developer has already moved on.  With dev moving faster thean QA, this time gap is only going to get bigger.

I keep flipping through my copy of Code Complete, looking for a "Hard Data" snippet that shows the cost of fixing defects grows exponentially the longer it exists.  Can someone point me to some studies that back up this concept?  I am trying to convince the powers that be that the QA bottleneck is a lot more costly than they think.

答:
I keep flipping through my copy of Code Complete, looking for a "Hard
  Data" snippet that shows the cost of fixing defects grows
  exponentially the longer it exists. Can someone point me to some
  studies that back up this concept?

Exponential cost of finding a bug seems to be based upon a NIST study. The study was a survey assumes distinct waterfall stages:

```<code>Software Development Stage         | Cost
-----------------------------------+------
Requirements and Design            | 1X
Code and Unit Testing              | 5X
Integration and System Testing     | 10X
Beta Testing                       | 15X
Post Release                       | 30X
</code>```

(table here from here)

One of the aims of Agile software development methodologies is to remove these distinct stages and reduce these costs. The figures do not apply when using other methodologies to waterfall.

Body:
I keep flipping through my copy of Code Complete, looking for a "Hard
  Data" snippet that shows the cost of fixing defects grows
  exponentially the longer it exists. Can someone point me to some
  studies that back up this concept?

Exponential cost of finding a bug seems to be based upon a NIST study. The study was a survey assumes distinct waterfall stages:

Software Development Stage         | Cost
-----------------------------------+------
Requirements and Design            | 1X
Code and Unit Testing              | 5X
Integration and System Testing     | 10X
Beta Testing                       | 15X
Post Release                       | 30X

(table here from here)

One of the aims of Agile software development methodologies is to remove these distinct stages and reduce these costs. The figures do not apply when using other methodologies to waterfall.


答:
A proper function makes no changes in the environment.  It receives arguments, computes a value, and returns it.  Anything else is a side effect.

Technically, a function takes some time which you could observe passing, and that could be called a side effect too, so in the real world there is no such thing as "no side effects".

Title: I don't understand the definition of side effects

Body:
Possible Duplicate:

  What is a “side effect?”

I don't understand the wikipedia article on Side Effects:

In computer science, a function or expression is said to have a side effect if, in addition to returning a value, it also 1.) Modifies some state or 2.) Has an observable interaction with calling functions or the outside world.

I know an example of the first thing that causes a function or expression to have side effects - modifying a state

Function and Expression modifying a state
:

1.)

```<code>foo(int X)
{
return x = x % x;
}

a = a + 1;
</code>```

What does 2.) - Has an observable interaction with calling functions or the outside world," mean?  - Please give an example.

The article continues on to say, "For example, a function might modify a global or static variable,
modify one of its arguments, raise an exception, write data to a display or file, read data, or call other side-effecting functions...." Are all these examples, examples of 1.) -  Modifiying some state , or are they also part of 2.) - Has an observable interaction with calling functions or the outside world?


问:
How to learn to make better estimates?
I suck at estimates. When someone asks me how long something will take, I don't even dare to make a guess since I will be completely off the mark. Usually I'm way too optimistic, and should probably multiply my guess with some large X factor...

How can I learn to make better estimates? It's not taught at my uni, and even though we have deadlines for all laborations I never think about how long something will actually take. Which I should. For everyone's sake (especially mine).

答:
Whenever you encounter an estimation problem, try to split them in to smaller pieces. Then see if you have already done stuff similar to the pieces. If you have, you should already have a fair idea of how long each piece takes. If you don't, you should start to actively keep track of time taken for various kinds of tasks. This will help you in future estimations.

Total time needed will be more than the sum of the individual pieces, since you need some time for integration and testing.

If you haven't done something similar, you can probably rely on other peoples experience and get an estimate from them. Don't take this at face value though. Nothing teaches you like experience.

Its kind of like shooting a target. Previous shots at estimation should tell you how off the mark you are, so that you can correct it.

Title: How to learn to make better estimates?