问:
Clarification of "avoid if-else" advice
The experts in clean code advise not to use if/else since it's creating an unreadable code. They suggest rather using IF and not to wait till the end of a method without real need.

Now, this if/else advice confuses me. Do they say that I should not use if/else at all (!) or to avoid if/else nesting?

Also, if they refer to the nesting of if/else, should I not do even a single nesting or I should limit it to max 2 nestings (as some recommends)?

When I say single nesting, I mean this:

```<code>    if (...) {

        if (...) {

        } else {

        }

    } else {

    }
</code>```

EDIT

Also tools like Resharper will suggest reformatting if/else statements. It usually concerts them to if stand-alone statement, and sometimes even to ternary expression.

答:
I think this advice came from a software metric which called Cyclomatic complexity or Conditional complexity check this wiki page

Definition:

The cyclomatic complexity of a section of source code is the count of
  the number of linearly independent paths through the source code. For
  instance, if the source code contained no decision points such as IF
  statements or FOR loops, the complexity would be 1, since there is
  only a single path through the code. If the code had a single IF
  statement containing a single condition there would be two paths
  through the code, one path where the IF statement is evaluated as TRUE
  and one path where the IF statement is evaluated as FALSE.

So

Do they say that I should not use if/else at all (!) or to avoid
  if/else nesting?

No you shouldn't avoid if/else at all! but you should be careful about Cyclomatic complexity of your code. More code complexity tends to have more defects. According to this the right limit would be 11. A tool called Code Complete categorize the score like that Ref.:

0-5 - the routine is probably fine

6-10 - start to think about ways to simplify the routine

10+ - break part of the routine into a second routine and call it
from the first  routine

How to calculate Cyclomatic complexity "basically":

From example here:
consider the following pseudo code :

```<code>if (A=354) {

    if (B>C) {/*decision 1*/ A=B} else {/*decision 2*/ A=C}

   }/*decision 3 , in case A is NOT equal 354*/
print A
</code>```

please note that this metric is concerned about number of decision in your program/code so from the code above we could say that we have 3 decisions ( 3 values of A)

let's calculate it formally so consider the following control flow of the code:

The complexity M is then defined* as:Ref

```<code>M = E − N + 2P
</code>```

where

```<code>E = the number of edges of the graph
N = the number of nodes of the graph
P = the number of connected components (exit nodes).
</code>```

by applying the formula E(flow lines) = 8 , N (nodes)= 7 , P (exit nodes) =1
then M = 8-7 + (2*1) = 3

*there is also another definition stated but it is close :M = E − N + P check the reference for theory.

Please note that many of static code analysis tools could calculate the Cyclomatic complexity of your code.

Title: Clarification of "avoid if-else" advice

Body:
I think this advice came from a software metric which called Cyclomatic complexity or Conditional complexity check this wiki page

Definition:

The cyclomatic complexity of a section of source code is the count of
  the number of linearly independent paths through the source code. For
  instance, if the source code contained no decision points such as IF
  statements or FOR loops, the complexity would be 1, since there is
  only a single path through the code. If the code had a single IF
  statement containing a single condition there would be two paths
  through the code, one path where the IF statement is evaluated as TRUE
  and one path where the IF statement is evaluated as FALSE.

So

Do they say that I should not use if/else at all (!) or to avoid
  if/else nesting?

No you shouldn't avoid if/else at all! but you should be careful about Cyclomatic complexity of your code. More code complexity tends to have more defects. According to this the right limit would be 11. A tool called Code Complete categorize the score like that Ref.:

0-5 - the routine is probably fine

6-10 - start to think about ways to simplify the routine

10+ - break part of the routine into a second routine and call it
from the first  routine

How to calculate Cyclomatic complexity "basically":

From example here:
consider the following pseudo code :

if (A=354) {

    if (B>C) {/*decision 1*/ A=B} else {/*decision 2*/ A=C}

   }/*decision 3 , in case A is NOT equal 354*/
print A

please note that this metric is concerned about number of decision in your program/code so from the code above we could say that we have 3 decisions ( 3 values of A)

let's calculate it formally so consider the following control flow of the code:

The complexity M is then defined* as:Ref

M = E − N + 2P

where

E = the number of edges of the graph
N = the number of nodes of the graph
P = the number of connected components (exit nodes).

by applying the formula E(flow lines) = 8 , N (nodes)= 7 , P (exit nodes) =1
then M = 8-7 + (2*1) = 3

*there is also another definition stated but it is close :M = E − N + P check the reference for theory.

Please note that many of static code analysis tools could calculate the Cyclomatic complexity of your code.


问:
Java class to enforce an implementation of super classes' public methods
I have the following :

```
public Class A {

    public void methodA() {
        ....
    }

    public void methodB() {
        ....
    }

}
```

I don't have control over Class A. I would like to create subclasses of Class A with a restriction that it must override methodA() (super.methodA() call must run the implementation of Class A). is it possible? is so, how?

答:
I think you are talking about 'abstract class'. If you want that the subclass of Class A must override the methodA() of Class A, then you have to declare the methodA() as abstract method and Class A is an abstract class.

If any class method having some implementation then it will act as a default implementation of the subclasses. Subclasses can optionally override that with their own implementation. If you want to give implementation to the subclass only and force the subclasses to follow a contract (method signature) then this is a clear situation of abstract class.

```<code>class A
{
    void abstract methodA(); // No implementation.
}

class B extends A
{
    void methodA()
    {
        // Subclass implementation.
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I think you are talking about 'abstract class'. If you want that the subclass of Class A must override the methodA() of Class A, then you have to declare the methodA() as abstract method and Class A is an abstract class.

If any class method having some implementation then it will act as a default implementation of the subclasses. Subclasses can optionally override that with their own implementation. If you want to give implementation to the subclass only and force the subclasses to follow a contract (method signature) then this is a clear situation of abstract class.

class A
{
    void abstract methodA(); // No implementation.
}

class B extends A
{
    void methodA()
    {
        // Subclass implementation.
    }
}


答:
Once an method has been given an implementation, there is no way of making it abstract again. So, no, without changing A there is no way of writing a class B extends A so that all subclasses of B must provide another implementation, at least not via the type system.

The best you can do is write a method in B that throws an Exception at run time. This forces any subclass to override the method to be useful, but it will still compile without doing that.

Title: Java class to enforce an implementation of super classes' public methods

Body:
I have the following :

```
public Class A {

    public void methodA() {
        ....
    }

    public void methodB() {
        ....
    }

}
```

I don't have control over Class A. I would like to create subclasses of Class A with a restriction that it must override methodA() (super.methodA() call must run the implementation of Class A). is it possible? is so, how?


问:
Unit-Tests and databases: At which point do I actually connect to the database?
There are answers to the question on how test classes that connect to a database, e.g. "Should service test classes connect ..." and "Unit testing - Database coupled app".

So, in short let's assume you have a class A that needs to connect to a database. Instead of letting A actually connect, you provide A with an interface that A may use to connect. For testing you implement this interface with some stuff - without connecting of course. If class B instantiates A it has to pass a "real" database connection to A. But that means B opens a database connection. That means to test B you inject the connection into B. But B is instantiated in class C and so forth.

So at which point do I have to say "here I fetch data from a database and I will not write a unit test for this piece of code"?

In other words: Somewhere in the code in some class I must call sqlDB.connect() or something similar. How do I test this class?

And is it the same with code that has to deal with a GUI or a file system?

I want to do Unit-Test. Any other kind of test is not related to my question. I know that I will only test one class with it (I so agree with you Kilian). Now, some class has to connect to a DB. If I want to test this class and ask "How do I do this" many say: "Use Dependency Injection!" But that only shifts the problem to another class, doesn't it? So I ask, how do I test the class that really, really establishes the connection?

Bonus question: Some answers here boil down to "Use mock objects!" What does that mean? I mock classes that the class-under-test depend upon. Shall I mock the class-under-test now and actually test the mock (which comes close to the idea of using Template Methods, see below)?

答: Testing with external data is integration test. Unit test means you are testing the unit only. It is mostly done with your business logic. To make your code unit testable you have to follow some guidelines, like you have to make your unit independent from other part of your code. During unit test if you need data then you need to forcefully inject that data with dependency injection. There are some mocking and stubbing framework out there. </p>

ContentLicense: CC BY-SA 4.0


问:
Best books on Managing a Software Development Team?
The canonical books on software development is fairly well established. However, after reading through a dreadful book full of bad advice on managing programming teams this weekend I am looking for recommendations for really good books that focus on the management side of programming (recruiting, performance measurement/management, motivation, best practices, organizational structure,  etc.) and not as much on the construction of software itself.

Any suggestions?

答: Herding cats is especially written for programmers who have become managers.</p>

ContentLicense: CC BY-SA 2.5


答:
I really like what Abdurahman said in his answer.

Another way to look at the “avoiding if/else” statement is to think in terms of decisions.

The objective is to avoid confusion when following code.  When you have multiple if/else statements that are nested, it becomes hard to understand the functions main objective.  The programmer writing the code understands the logic now.  BUT, when that same programmer revisits that code a year or two down the road, the understanding is generally forgotten.  A new programmer looking at the code has to be able to identify what is going on.  So the objective is to break complexity up into simple, easy to understand functions.  The objective is not to avoid decisions, but to establish an easy to understand flow of logic.

Title: Clarification of "avoid if-else" advice

Body:
The experts in clean code advise not to use if/else since it's creating an unreadable code. They suggest rather using IF and not to wait till the end of a method without real need.

Now, this if/else advice confuses me. Do they say that I should not use if/else at all (!) or to avoid if/else nesting?

Also, if they refer to the nesting of if/else, should I not do even a single nesting or I should limit it to max 2 nestings (as some recommends)?

When I say single nesting, I mean this:

```<code>    if (...) {

        if (...) {

        } else {

        }

    } else {

    }
</code>```

EDIT

Also tools like Resharper will suggest reformatting if/else statements. It usually concerts them to if stand-alone statement, and sometimes even to ternary expression.


问:
Why do different java collections have different default capacity?
Looking at different collection constructors the question comes to mind. Why does ArrayList()
construct an empty list with an initial capacity of ten and ArrayDeque()
constructs an empty array deque with an initial capacity sufficient to hold 16 elements.</p>

答:
Do not exclude the possibility that there is no specific reason.

It could be that these two collections have been written by different teams. Both chose a small number as default capacity, but the first team thought decimally and choose 10, while the second team thought binary and choose 16.


问:
Design in one team, coding in another
I will be involved in a project where all the software design is made by a local team and these designs are sent to an offshore team for coding.

This is the first time I face a project with this characteristics and for me it feels kind of odd: The managers expects us to make very detailed design documents so there's no space for error for the offshore team; from my perspective they are making us coding in paper while we can do it in an IDE.

So, my question is is this approach good, or proven right? What are the main considerations our software process has to have to have success in our project?

答:
My opinion:

If all you'll give the offshore people is documents and diagrams, you will have a lot of miscommunication and disappointment.

My recommendation

Don't give them so many documents, but rather interfaces and abstract classes in order to straitjacket them into your design goals.

Require them to use a known naming standard.

Require them to use unit tests.

Send one of your designers/architects offshore to their premises to supervise the process, it will still be cheaper than coding in-house, but you will get better results.

Title: Design in one team, coding in another


答:
It's called Big Design Up Front, aka Waterfall.  It's not widely regarded as a highly successful methodology.  But I've seen it work, and when it does work, it works very well.  It's very expensive to do right.

It's also what your employers have asked you to do.

Offshore teams don't work the way onshore teams do. You have to be very, very specific about exactly what you want, otherwise you won't get what you want.

Title: Design in one team, coding in another

Body:
I will be involved in a project where all the software design is made by a local team and these designs are sent to an offshore team for coding.

This is the first time I face a project with this characteristics and for me it feels kind of odd: The managers expects us to make very detailed design documents so there's no space for error for the offshore team; from my perspective they are making us coding in paper while we can do it in an IDE.

So, my question is is this approach good, or proven right? What are the main considerations our software process has to have to have success in our project?


答:
In addition to the other answers, the advice may also mean that if/else should be substituted with if/else if where proper. The latter is more informative and readable (excluding trivial cases of course, like if (x > 0) else if (x <= 0)).

if/else if has one more advantage than just being more readable (though that is a considerable advantage too). It helps the programmer avoid mistakes in case when there are more than two branches depending on the condition. Such style will make the missed case more obvious.

Title: Clarification of "avoid if-else" advice


答:
The reason they are advising you to only use if statements, and not else is to avoid the classic bug of if this then for everything else do this. The scope of else is difficult to predict.

For example; let's say I am programming the controls for a self-driving car.

```<code>if (light is red) then {
    stop car
} else {
    drive forward
}
</code>```

While the logic is sound. When the car comes to a yellow light it will keep driving thru the intersection. Likely causing an accident when it should have slowed down and stopped.

Without the if/else the logic is less prone to mistakes.

```<code>if(light is red) then {
  stop car
}
if(light is yellow) then {
  slow down
}
if(light is green) then {
  drive forward
}
</code>```

While my code might not make the best self-driving car. It just demonstrates the difference between an ambiguous condition and explicit conditions. Which is what the author was likely referring too. Don't use else to short cut logic.

Title: Clarification of "avoid if-else" advice

Body:
The reason they are advising you to only use if statements, and not else is to avoid the classic bug of if this then for everything else do this. The scope of else is difficult to predict.

For example; let's say I am programming the controls for a self-driving car.

if (light is red) then {
    stop car
} else {
    drive forward
}

While the logic is sound. When the car comes to a yellow light it will keep driving thru the intersection. Likely causing an accident when it should have slowed down and stopped.

Without the if/else the logic is less prone to mistakes.

if(light is red) then {
  stop car
}
if(light is yellow) then {
  slow down
}
if(light is green) then {
  drive forward
}

While my code might not make the best self-driving car. It just demonstrates the difference between an ambiguous condition and explicit conditions. Which is what the author was likely referring too. Don't use else to short cut logic.


问:
Elegant ways to handle if(if else) else
This is a minor niggle, but every time I have to code something like this, the repetition bothers me, but I'm not sure that any of the solutions aren't worse.

if(FileExists(file))
{
    contents = OpenFile(file); // <-- prevents inclusion in if
    if(SomeTest(contents))
    {
        DoSomething(contents);
    }
    else
    {
        DefaultAction();
    }
}
else
{
    DefaultAction();
}
```

Is there a name for this kind of logic?

Am I a tad too OCD?

I'm open to evil code suggestions, if only for curiosity's sake...

答:
Your code is ugly because you are doing too much in a single function.  You want to either process the file or take the default action, so start by saying that:

if (!ProcessFile(file)) {
  DefaultAction();
}
```

<p>Perl and Ruby programmers write <code>processFile(file) || defaultAction()</code></p>

<p>Now go write ProcessFile:</p>

<pre class="lang-cs prettyprint-override"><code>if (FileExists(file)) {
  contents = OpenFile(file);
  if (SomeTest(contents)) {
    processContents(contents);
    return true;
  }
}
return false;
</code>```

Title: Elegant ways to handle if(if else) else

Body:
Your code is ugly because you are doing too much in a single function.  You want to either process the file or take the default action, so start by saying that:

if (!ProcessFile(file)) {
  DefaultAction();
}

Perl and Ruby programmers write processFile(file) || defaultAction()

Now go write ProcessFile:

if (FileExists(file)) {
  contents = OpenFile(file);
  if (SomeTest(contents)) {
    processContents(contents);
    return true;
  }
}
return false;


问:
How would you refactor nested IF Statements?
I was cruising around the programming blogosphere when I happened upon this post about GOTO's:

http://giuliozambon.blogspot.com/2010/12/programmers-tabu.html

Here the writer talks about how "one must come to the conclusion that there are situations where GOTOs make for more readable and more maintainable code" and then goes on to show an example similar to this:

```<code>if (Check#1)
{
    CodeBlock#1
    if (Check#2)
    {
        CodeBlock#2
        if (Check#3)
        {
            CodeBlock#3
            if (Check#4)
            {
                CodeBlock#4
                if (Check#5)
                {
                    CodeBlock#5
                    if (Check#6)
                    {
                        CodeBlock#6
                        if (Check#7)
                        {
                            CodeBlock#7
                        }
                        else
                        {
                            rest - of - the - program
                        }
                    }
                }
            }
        }
    }
}
</code>```

The writer then proposes that using GOTO's would make this code much easier to read and maintain.

I personally can think of at least 3 different ways to flatten it out and make this code more readable without resorting to flow-breaking GOTO's.  Here are my two favorites.

1 - Nested Small Functions.  Take each if and its code block and turn it into a function. If the boolean check fails, just return.  If it passes, then call the next function in the chain. (Boy, that sounds a lot like recursion, could you do it in a single loop with function pointers?)

2 - Sentinal Variable.  To me this is the easyest.  Just use a blnContinueProcessing variable and check to see if it is still true in your if check.  Then if the check fails, set the variable to false.

How many different ways can this type of coding problem be refactored to reduce nesting and increase maintainability?

答:
Personally, I like wrapping these if statements into separate functions which return a bool if the function succeeds.

The structure looks as follows:

```<code>
if (DoCheck1AndCodeBlock1() &&
    DoCheck2AndCodeBlock2() &&
    DoCheck3AndCodeBlock3())
{
   // ... you may perform the final operation here ....
}
</code>```

The only drawback is that these functions will have to output data using attributes passed by reference or member variables.

Body:
Personally, I like wrapping these if statements into separate functions which return a bool if the function succeeds.

The structure looks as follows:

if (DoCheck1AndCodeBlock1() &&
    DoCheck2AndCodeBlock2() &&
    DoCheck3AndCodeBlock3())
{
   // ... you may perform the final operation here ....
}

The only drawback is that these functions will have to output data using attributes passed by reference or member variables.


问:
What is the intention behind asking weight of plane?
I was asked this question "How would you find weight of Aeroplane" in an interview and I am not sure why this question was one of the two question asked in the interview.

I tried to answer it using all possible ways but could not give the correct answer.(found the correct answer after google search)

How much such questions decide your selection in the interview?

Here was my approach:
1. If measurement of plane is given then i will calculate volume and multiply by density, will consider fuel weight plus other dead weight.
2. Using water displacement method if i can put plane in water and somehow measure how much water is displaced.

But found using google search that right approach was to put place on a ship and mark the level of water on the hull, then remove plane and then ship will go up.
And start putting weight on the ship till marked hull reaches the water level.

答:
Job Interview 2.0: Now With Riddles! would be an article from TheDailyWTF that notes some of these including the weight of a 747, which is a type of plane:

Thankfully, Microsoft realized that the type of people who enjoy these
  riddles aren’t always good programmers, and good programmers aren’t
  always the type who enjoy these riddles. In fact, some of the folks
  who can solve these riddles are precisely the type of people you don’t
  want as programmers. Would you want to work with the guy who builds a
  water-displacement scale/barge, taxis a 747 to the docks, and then
  weights the jumbo jet using that, instead of simply calling Boeing in
  the first place?

Unfortunately, Microsoft’s realization came too late: a whole
  mini-industry has spawned around the concept of Job Interview 2.0. If
  Microsoft did it, it must work, right? There are books written on
  brainteasers in the interview, consultants who will help your company
  annoy the hell out candidates with your very own custom brainteasers,
  and now, everyone from small software firms to big ole’ banks are
  asking stupid riddle questions.

The key point in these questions is that it isn't so much that there is a correct answer as much as it is how well can you communicate how you'd solve this problem and upon revisions to the problem, what alternative approaches would you take.  For the weight of a plane, I'd probably look at specifications which should note this as part of the basics about the plane.  Failing that, then there are a few other approaches one can take.


答:
Code block nesting, aka the "arrowhead" anti-pattern, reduces readability of code because you must either continue shifting to the right, reducing the available width for lines of "real" code on the screen, or you must violate the indenting and other formatting rules that in the normal case make code easier to read.

Case in point:

```<code>if (X) {
    if (Y) {
       DoXandY();
    } else {
       DoXOnly();
    }
} else {
   DoDefault();
}
</code>```

This is a simple example and I wouldn't have issues with a few levels of this type of nesting, provided that the total LOC for this structure was only about a screen long, and that the formatting involved didn't add too much whitespace on the left hand side (consider using 3 or 4 spaces instead of a tabspace, especially if the code will be viewed in other editors where a tabspace may be 8 spaces or more). Beyond that, you may forget or not easily be able to see the initial condition under which the others are nested. This can cause you to get "lost" in your codebase, especially if you have a structure where X and Y are independent:

```<code>if (X) {
    if (Y) {
       DoXandY();
    } else {
       DoXOnly();
    }
} else {
   if (Y) {
       DoYOnly();
    } else {
       DoDefault();
    }
}
</code>```

In this alternate universe to the OP's specific question, now we have two "if(Y)" condition checks, and if, in a real piece of code, we couldn't see the nested parent condition, we could think we're in a different place in code than we really are, and that causes bugs.

One way to reduce nesting is to distribute the outer condition into the inner conditions. Back to your initial snippet (no "DoYOnly()"), consider the following:

```<code>if (X && Y) {
    DoXandY();
} else if (X) {
    DoXOnly();
} else {
    DoDefault();
}
</code>```

Look Ma, no nesting! At the cost of an additional evaluation of X (which, if it is computationally complex to evaluate X, you can perform up front and store in a boolean variable), you make the structure a single-level if/else decision tree, and when editing each branch, you know the condition that must be true to enter it. You must still remember what wasn't true in order to get to that "else if", but because everything's at the same level it should be easier to identify the previous branches of the decision tree. Alternately, you can remove all the else keywords by testing a more complete version of the condition at every step:

```<code>if (X && Y) {
    DoXandY();
}
if (X && !Y) {
    DoXOnly();
}
if(!X) {
    DoDefault();
}
</code>```

Now you know exactly what must be true for each statement to be executed. However, this starts toeing a line of other readability issues; it becomes harder to see that all of these statements are mutually exclusive (which is part of what an "else" block does for you).

Other ways to include nesting include reversing one or more conditions. If most or all of the code of a function is within an if statement testing a condition, then you can usually save yourself that level of nesting by instead testing that the condition is not true, and performing anything you'd do in an else block beyond the original if statement, before returning out of the function. For instance:

```<code>if(!X) {
    DoDefault();
    return;
}

if(Y) {
    DoXAndY();
} else {
    DoXOnly();
}
</code>```

This behaves the same way as both of the above statements, but only tests each condition once, and has no nested ifs. This pattern is sometimes known as a "guard clause"; the code below the initial if statement will never execute if X is false, so you can say the if statement "guards" the rest of the code (which is why we never need to test that X is true in the rest of the code; if we get to that line, X is true because we would have exited the function early otherwise). The downside is that this doesn't work as well for code that's a smaller part of a larger function. If there were a "DoMoreWork()" function after the entire snippet above, it would have to be included in both the guard clause code and below the remaining conditional statement. Or, the guard clause could be integrated with the remaining code using the "else if" pattern:

```<code>if(!X) {
    DoDefault();
} else if(Y) {
    DoXAndY();
} else {
    DoXOnly();
}

DoMoreWork();
</code>```

In this example, DoMoreWork() is always executed even if X is false. Adding the same call below the previous snippet with the return statement would cause DoMoreWork to be called only if X is true, but regardless of whether Y is true or false.

Title: Clarification of "avoid if-else" advice

Body:
Code block nesting, aka the "arrowhead" anti-pattern, reduces readability of code because you must either continue shifting to the right, reducing the available width for lines of "real" code on the screen, or you must violate the indenting and other formatting rules that in the normal case make code easier to read.

Case in point:

if (X) {
    if (Y) {
       DoXandY();
    } else {
       DoXOnly();
    }
} else {
   DoDefault();
}

This is a simple example and I wouldn't have issues with a few levels of this type of nesting, provided that the total LOC for this structure was only about a screen long, and that the formatting involved didn't add too much whitespace on the left hand side (consider using 3 or 4 spaces instead of a tabspace, especially if the code will be viewed in other editors where a tabspace may be 8 spaces or more). Beyond that, you may forget or not easily be able to see the initial condition under which the others are nested. This can cause you to get "lost" in your codebase, especially if you have a structure where X and Y are independent:

if (X) {
    if (Y) {
       DoXandY();
    } else {
       DoXOnly();
    }
} else {
   if (Y) {
       DoYOnly();
    } else {
       DoDefault();
    }
}

In this alternate universe to the OP's specific question, now we have two "if(Y)" condition checks, and if, in a real piece of code, we couldn't see the nested parent condition, we could think we're in a different place in code than we really are, and that causes bugs.

One way to reduce nesting is to distribute the outer condition into the inner conditions. Back to your initial snippet (no "DoYOnly()"), consider the following:

if (X && Y) {
    DoXandY();
} else if (X) {
    DoXOnly();
} else {
    DoDefault();
}

Look Ma, no nesting! At the cost of an additional evaluation of X (which, if it is computationally complex to evaluate X, you can perform up front and store in a boolean variable), you make the structure a single-level if/else decision tree, and when editing each branch, you know the condition that must be true to enter it. You must still remember what wasn't true in order to get to that "else if", but because everything's at the same level it should be easier to identify the previous branches of the decision tree. Alternately, you can remove all the else keywords by testing a more complete version of the condition at every step:

if (X && Y) {
    DoXandY();
}
if (X && !Y) {
    DoXOnly();
}
if(!X) {
    DoDefault();
}

Now you know exactly what must be true for each statement to be executed. However, this starts toeing a line of other readability issues; it becomes harder to see that all of these statements are mutually exclusive (which is part of what an "else" block does for you).

Other ways to include nesting include reversing one or more conditions. If most or all of the code of a function is within an if statement testing a condition, then you can usually save yourself that level of nesting by instead testing that the condition is not true, and performing anything you'd do in an else block beyond the original if statement, before returning out of the function. For instance:

if(!X) {
    DoDefault();
    return;
}

if(Y) {
    DoXAndY();
} else {
    DoXOnly();
}

This behaves the same way as both of the above statements, but only tests each condition once, and has no nested ifs. This pattern is sometimes known as a "guard clause"; the code below the initial if statement will never execute if X is false, so you can say the if statement "guards" the rest of the code (which is why we never need to test that X is true in the rest of the code; if we get to that line, X is true because we would have exited the function early otherwise). The downside is that this doesn't work as well for code that's a smaller part of a larger function. If there were a "DoMoreWork()" function after the entire snippet above, it would have to be included in both the guard clause code and below the remaining conditional statement. Or, the guard clause could be integrated with the remaining code using the "else if" pattern:

if(!X) {
    DoDefault();
} else if(Y) {
    DoXAndY();
} else {
    DoXOnly();
}

DoMoreWork();

In this example, DoMoreWork() is always executed even if X is false. Adding the same call below the previous snippet with the return statement would cause DoMoreWork to be called only if X is true, but regardless of whether Y is true or false.


答:
This may already have been mentioned, but my "go-to" (pun intended) answer to the "arrowhead antipattern" shown here is to reverse the ifs. Test the opposite of the current conditions (easy enough with a not operator) and return from the method if that is true. No gotos (though pedantically speaking, a void return is little more than a jump to the line of calling code, with the trivial extra step of popping a frame off the stack).

Case in point, here's the original:

```<code>if (Check#1)
{
    CodeBlock#1
    if (Check#2)
    {
        CodeBlock#2
        if (Check#3)
        {
            CodeBlock#3
            if (Check#4)
            {
                CodeBlock#4
                if (Check#5)
                {
                    CodeBlock#5
                    if (Check#6)
                    {
                        CodeBlock#6
                        if (Check#7)
                        {
                            CodeBlock#7
                        }
                        else
                        {
                            rest - of - the - program
                        }
                    }
                }
            }
        }
    }
}
</code>```

Refactored:

```<code>if (!Check#1) return;

CodeBlock#1

if (!Check#2) return;

CodeBlock#2

if (!Check#3) return;

CodeBlock#3

if (!Check#4) return;

CodeBlock#4

if (!Check#5) return;

CodeBlock#5

if (!Check#6) return;

CodeBlock#6

if (Check#7)
    CodeBlock#7
else
{
    //rest of the program
}
</code>```

At each if, we basically check to see if we should continue. It works exactly the same way as the original with only one level of nesting.

If there's something beyond the end of this snippet that should also be run, extract this code into its own method and call it from wherever this code currently lives, before proceeding to the code that would come after this snippet. The snippet itself is long enough, given sufficient actual LOC in each code block, to justify splitting out several more methods, but I digress.

Title: How would you refactor nested IF Statements?

Body:
I was cruising around the programming blogosphere when I happened upon this post about GOTO's:

http://giuliozambon.blogspot.com/2010/12/programmers-tabu.html

Here the writer talks about how "one must come to the conclusion that there are situations where GOTOs make for more readable and more maintainable code" and then goes on to show an example similar to this:

```<code>if (Check#1)
{
    CodeBlock#1
    if (Check#2)
    {
        CodeBlock#2
        if (Check#3)
        {
            CodeBlock#3
            if (Check#4)
            {
                CodeBlock#4
                if (Check#5)
                {
                    CodeBlock#5
                    if (Check#6)
                    {
                        CodeBlock#6
                        if (Check#7)
                        {
                            CodeBlock#7
                        }
                        else
                        {
                            rest - of - the - program
                        }
                    }
                }
            }
        }
    }
}
</code>```

The writer then proposes that using GOTO's would make this code much easier to read and maintain.

I personally can think of at least 3 different ways to flatten it out and make this code more readable without resorting to flow-breaking GOTO's.  Here are my two favorites.

1 - Nested Small Functions.  Take each if and its code block and turn it into a function. If the boolean check fails, just return.  If it passes, then call the next function in the chain. (Boy, that sounds a lot like recursion, could you do it in a single loop with function pointers?)

2 - Sentinal Variable.  To me this is the easyest.  Just use a blnContinueProcessing variable and check to see if it is still true in your if check.  Then if the check fails, set the variable to false.

How many different ways can this type of coding problem be refactored to reduce nesting and increase maintainability?

Body:
This may already have been mentioned, but my "go-to" (pun intended) answer to the "arrowhead antipattern" shown here is to reverse the ifs. Test the opposite of the current conditions (easy enough with a not operator) and return from the method if that is true. No gotos (though pedantically speaking, a void return is little more than a jump to the line of calling code, with the trivial extra step of popping a frame off the stack).

Case in point, here's the original:

if (Check#1)
{
    CodeBlock#1
    if (Check#2)
    {
        CodeBlock#2
        if (Check#3)
        {
            CodeBlock#3
            if (Check#4)
            {
                CodeBlock#4
                if (Check#5)
                {
                    CodeBlock#5
                    if (Check#6)
                    {
                        CodeBlock#6
                        if (Check#7)
                        {
                            CodeBlock#7
                        }
                        else
                        {
                            rest - of - the - program
                        }
                    }
                }
            }
        }
    }
}

Refactored:

if (!Check#1) return;

CodeBlock#1

if (!Check#2) return;

CodeBlock#2

if (!Check#3) return;

CodeBlock#3

if (!Check#4) return;

CodeBlock#4

if (!Check#5) return;

CodeBlock#5

if (!Check#6) return;

CodeBlock#6

if (Check#7)
    CodeBlock#7
else
{
    //rest of the program
}

At each if, we basically check to see if we should continue. It works exactly the same way as the original with only one level of nesting.

If there's something beyond the end of this snippet that should also be run, extract this code into its own method and call it from wherever this code currently lives, before proceeding to the code that would come after this snippet. The snippet itself is long enough, given sufficient actual LOC in each code block, to justify splitting out several more methods, but I digress.


答:
The last project I was the software designer.  All development was offshore.  We were successful.  So this process can work.

I did produce a lot of documentation but it was by no means comprehensive and by no means step by step instructions or detailed down to class names, function names etc.  For example, I produced sequence diagrams, use case, workflows, system, and integration diragrams, as well a more detailed design documentation as needed.

It really depends on how much you trust offshore development.  I trust my offshore team to be competent developers. That said, I provided overall direction but gave them leeway to implement which the offshore team found pleasantly satisfying.  In the past they were more micro-managed.  In certain situations I would guide them using the design patterns as needed.  I also regularly performed code reviews and analysis on the code they wrote and would advise refactoring or clean up efforts.  Also, since some of the team had accidents with recreational vehicles I ended up coding some of the stories during implementation since we ended up being short on some resources.

Additionally, I think this process really only succeeds on the strength of your technical lead(s) on the project and the communication between business, designer, leads, and developers.  We did spend a lot of time going over each feature and story and made sure that the offshore leads/resources were well versed on to what the requirements were.  If they are not asking questions during the review of the feature/story then expect some issues.  Also work wasn't considered complete until there was business signoff.  So that made everyone accountable since everything was tracked in a tool that managed agile development.

As one of the other answers has alluded to already, the development process included naming standards (resharper rules built in), test case coverage (it used TDD, Mocking, etc) so if there is good coding process and procedure in place it will increase your chances for a successful project.

Title: Design in one team, coding in another


答:
First thing to understand here is that this part of requirements: super.methodA() means this applies to the code of the classes extending A, in a way defined in JLS 15.12.4.4-2. Method Invocation Using super

An overridden instance method of a superclass may be accessed by using the keyword super to access the members of the immediate superclass, bypassing any overriding declaration in the class that contains the method invocation...

Let's say, we want a way to create some specific subclasses of A such that whenever super.methodA() is invoked in these, we are guaranteed that instead of code that was in class A (out of our control) it will run some other code, defined in some subclass of A (under our control).

Let's see what "tools" are at our disposal to achieve above.

Need to create some, specific subclasses of A brings to mind traditional way to specialize - subclassing, that is we'll consider subclass of A (let's call it B) that would redefine (override) methodA in the way we want.

Need to force a subclass to provide a code that would run where we want it in superclass can be satisfied by defining an abstract method, let's call it forcedImplementationInSubclass()

Now we've got all what we need.

We will define a class B extending A, so that all subclasses of B will also be subclasses of A.

In B, we will override methodA, so that its implementation in class A won't be available to subclasses of B anymore.

In overridden method in B we will invoke abstract method forcedImplementationInSubclass() which will guarantee that subclasses of B will have to define the code that will eventually run in methodA.

As a result, any subclass of B won't be able to invoke methodA implementation provided in class A and instead, will be guaranteed to run code defined in some subclass of B.

Extending B is the way to create specific subclasses of A that behave as we want. The code could look about as follows:

```<code>public abstract class B extends A {
    // override, so that subclasses of B won't be able to get to super.methodA
    @Override public void methodA() {
        // invoke abstract method here (subclass would have to implement it)
        forcedImplementationInSubclass();
    }

    // define abstract method so that subclass would have to implement it
    protected abstract void forcedImplementationInSubclass();
}

// extending B is the way to get what we need
public class C extends B {
    // enforced implementation of the abstract method
    @Override protected void forcedImplementationInSubclass() {
        // that will be invoked when B.methodA() is called, and since B is-a A...
        System.out.print("Hello from implemented methodA");
    }

    public void testSuperMethodA() {
        // that will invoke B.methodA() which won't go to class A
        super.methodA();
    }

    public static void main(String[] args) {
        A a = new C();
        a.methodA(); // goes to B.methodA(), which in turn invokes C.forcedImplementationInSubclass()
        C c = new C();
        c.testSuperMethodA(); // won't go to class A
    }
}
</code>```

Body:
First thing to understand here is that this part of requirements: super.methodA() means this applies to the code of the classes extending A, in a way defined in JLS 15.12.4.4-2. Method Invocation Using super

An overridden instance method of a superclass may be accessed by using the keyword super to access the members of the immediate superclass, bypassing any overriding declaration in the class that contains the method invocation...

Let's say, we want a way to create some specific subclasses of A such that whenever super.methodA() is invoked in these, we are guaranteed that instead of code that was in class A (out of our control) it will run some other code, defined in some subclass of A (under our control).

Let's see what "tools" are at our disposal to achieve above.

Need to create some, specific subclasses of A brings to mind traditional way to specialize - subclassing, that is we'll consider subclass of A (let's call it B) that would redefine (override) methodA in the way we want.

Need to force a subclass to provide a code that would run where we want it in superclass can be satisfied by defining an abstract method, let's call it forcedImplementationInSubclass()

Now we've got all what we need.

We will define a class B extending A, so that all subclasses of B will also be subclasses of A.

In B, we will override methodA, so that its implementation in class A won't be available to subclasses of B anymore.

In overridden method in B we will invoke abstract method forcedImplementationInSubclass() which will guarantee that subclasses of B will have to define the code that will eventually run in methodA.

As a result, any subclass of B won't be able to invoke methodA implementation provided in class A and instead, will be guaranteed to run code defined in some subclass of B.

Extending B is the way to create specific subclasses of A that behave as we want. The code could look about as follows:

public abstract class B extends A {
    // override, so that subclasses of B won't be able to get to super.methodA
    @Override public void methodA() {
        // invoke abstract method here (subclass would have to implement it)
        forcedImplementationInSubclass();
    }

    // define abstract method so that subclass would have to implement it
    protected abstract void forcedImplementationInSubclass();
}

// extending B is the way to get what we need
public class C extends B {
    // enforced implementation of the abstract method
    @Override protected void forcedImplementationInSubclass() {
        // that will be invoked when B.methodA() is called, and since B is-a A...
        System.out.print("Hello from implemented methodA");
    }

    public void testSuperMethodA() {
        // that will invoke B.methodA() which won't go to class A
        super.methodA();
    }

    public static void main(String[] args) {
        A a = new C();
        a.methodA(); // goes to B.methodA(), which in turn invokes C.forcedImplementationInSubclass()
        C c = new C();
        c.testSuperMethodA(); // won't go to class A
    }
}


问:
Are there any SQL servers that support compiled queries?
Can SQL queries be compiled into byte code or equivalent to enhance performance?

I know that most database servers support prepared statements, but is that the same thing as compiling? Most applications have to prepare statements on run-time so there is no benefit of pre-compiled byte code. Since it's prepared each time the application runs.

I'm also not referring to stored procedures, but strictly SQL statements you execute to get a result set.

答:
The statements are compiled to templates, not byte code.  But I suspect that's a semantic issue for your question.  The short answer is yes, a prepared statement is equivalent to compiling.

The Wikipedia article on prepared statements explains a number of items that should help clarify things.

```
1. Prepare: The statement template is created by the application and sent to the database
management system (DBMS). Certain values are left unspecified, called parameters,
placeholders or bind variables.

2. The DBMS parses, compiles, and performs query optimization on the statement template,
and stores the result without executing it.

3. Execute: At a later time, the application supplies (or binds) values for the
parameters, and the DBMS executes the statement (possibly returning a result).
```

And the following statement makes it clear that the (majority of) optimization occurs at compilation.

The overhead of compiling and optimizing the statement is incurred only once, although the statement is executed multiple times.

But there are cases where the DBMS has to do additional optimization at query time.

Not all optimization can be performed at the time the prepared statement is compiled, for two reasons: the best plan may depend on the specific values of the parameters, and the best plan may change as tables and indexes change over time

The article indicates that DB2, Microsoft SQL Server, MySQL, Oracle, and PostgreSQL support prepared statements.  I have used prepared statements with DB2 and can verify they work as explained in the article.

Body:
The statements are compiled to templates, not byte code.  But I suspect that's a semantic issue for your question.  The short answer is yes, a prepared statement is equivalent to compiling.

The Wikipedia article on prepared statements explains a number of items that should help clarify things.

1. Prepare: The statement template is created by the application and sent to the database
management system (DBMS). Certain values are left unspecified, called parameters,
placeholders or bind variables.

2. The DBMS parses, compiles, and performs query optimization on the statement template,
and stores the result without executing it.

3. Execute: At a later time, the application supplies (or binds) values for the
parameters, and the DBMS executes the statement (possibly returning a result).

And the following statement makes it clear that the (majority of) optimization occurs at compilation.

The overhead of compiling and optimizing the statement is incurred only once, although the statement is executed multiple times.

But there are cases where the DBMS has to do additional optimization at query time.

Not all optimization can be performed at the time the prepared statement is compiled, for two reasons: the best plan may depend on the specific values of the parameters, and the best plan may change as tables and indexes change over time

The article indicates that DB2, Microsoft SQL Server, MySQL, Oracle, and PostgreSQL support prepared statements.  I have used prepared statements with DB2 and can verify they work as explained in the article.


问:
How do you put a price on your source code?
I was asked to sell the source code (along with existing users) of small utility app I created years ago. I've investigated how to put a price on the source code but so far haven't come up with a good solution.

I've searched the net, but haven't found anything useful. Then I came across a few others who also sold their source code with users, but their prices seem unrealistically high. For example, one person calculated price per user at about $200. He had 80 users and ended up selling the source with users for $30k. How did he come up with this price?

Can I find a good price with this formula:

(number of users x app price) + (app price x num of new users in one year)

?

If this is a good formula, how do you price source that doesn't yet have users?

答:
The hardest part of doing this sort of thing for the first time is really psychological - there is a very strong tendency to think of what it cost you in man hours, which is usually wildly inaccurate when done retrospectively and ignores the "I wasn't sitting at a desk but I was thinking about that algorithm all day..." and other overhead details, etc.

So I'd like to invite you to change your frame of perspective using an analogy: you no longer have an app, you have a steel widget. You put things into it, and things come out the other side, and what it does to the things that go in have caused various people to become accustomed to having your widget around. To date, you've just been giving your widget away for free because someone gave you the steel for free so it doesn't cost you anything.

The Background Concepts

Now someone wants to buy the whole concept and user base of your widget from you.

First of all, why do they want to buy it? If it's a business, the answer is "to make money." Either they are improving an existing product they have and wish to increase loyalty and offer a benefit they think could sell more copies, or they want to avoid solving a problem they have and thus reduce costs or focus their own effort on other things. They might also want your users as potential "hot leads" who they know could be interested in their product and could be unusually likely to buy stuff from them.

The relevant equation:

```<code>Price Paid = (Buyer's Perceived Value - Seller's Cost) * Negotiation
</code>```

So if it costs you nothing (you already did the work without expectation of pay), and it's worth $100k to them, do they pay you $1? Or $99k? $50k? It's all about negotiation - trying to determine where the final price is between the maximum they'll pay and the minimum you'll accept.

Sometimes negotiation is so weird people pay too much, and sometimes people sell for less than cost. These are edge cases, and so we ignore them - but yes, they do exist. I want to hire Instagram's negotiators for everything I do ;)

So first, what's it worth to them? This is by far the hardest thing to know, and one tactic is to flat out ask them. I know, crazy right?

Super Secret Negotiation Tactic

"I'm a reasonable man - what's this worth to you?" or "What's your budget for this sort of acquisition?" You'd be amazed at how often people just flat out tell you. They might not want to haggle, and if they just want to do their job and buy something from you and go on with their day, they could just tell you, "We've got about $50k in the budget for acquisitions like yours, and yours is relatively small compared to some of the other things we are buying, so we figured 5-10k would be reasonable given the straight-purchase we are requesting." Or "We figured it would cost us about $4000 in expenses to make this ourselves, so that's the most we'd pay under any circumstances," or simply "We're looking to seal this deal at around $3000."

And then you get to decide if that's ok with you and if you want to push it or take it. How hard was that? In negotiation it's almost always very important that you must not be the first one to name a price - so if they volunteer a price then you have a baseline you can accept outright or argue up from. But they might not name a price, and we have to see if that price is reasonable anyway.

There are a few accounting systems to determine the value of something, and this is what a rational business will use to determine a budget for buying your little 'entity':

Cost

The value is what it cost, perhaps with yearly depreciation. This is the most common form of accounting in the world, and it literally says "the value is whatever it cost to buy it, decreasing over time." Seriously - it costs what it costs. Not very helpful to us here, but its true.

This is what people try to do by determining man hours, but I'll give you the bottom-line: this is meaningless in software. You can work 40 years on a million lines of code with a going rate of $50 an hour and the result is worth $0. You aren't freelancing or accepting a contract to build something at an hourly rate, nor did you make it "on spec" with the hope of selling it to recoup your expenses. This is psychologically pleasing, but utterly meaningless in the context of buying and selling.

Replacement Cost

The value of something is what it would cost to replace it. This can be easy with commodities, like asking "what is the value of a new Ford Focus?" But this is not so easy in software, because it can be like math - a single one line formula could take a century to discover if you don't already know it. Or what took you 10 hours could take someone else 100 - or maybe it would take them only an hour.

So this would look at trying to estimate what it would cost to have a replacement for your widget built that simultaneously doesn't violate any of your rights as an inventor. Looking at the lines of code/complexity/difficulty of your app would produce a range of anywhere from "maybe a month for a prototype that is low on bugs if one person who knows what they are doing works on it" to... who knows. It must not be trivial or they wouldn't offer you money at all.

If they have their own development team maybe their estimate of doing it themselves is very reasonable. But they don't want to - they have more important things to do with their time. They'd have to wait for months to get started, or they would have to hire someone - and who knows if they can deliver or if it'll just be a waste of time and money? There's so much risk!

You've got the goods Right NOW, and this has a special value. Take advantage of this.

Comps (short for "comparisons")

This is what other things are going for. For example, if this business is used to buying apps/users/source code, they can say, "Well, this widget is easier to make than the SuperWidget we bought last month for $10k, but the output isn't as marketable as our DeluxeWidget we bought last year which we paid only $5k for." So perhaps they figure a comparative value is somewhere between $5k and $10k, and it doesn't matter if you have a million lines of code or 10, they don't have to know or care.

This is how most non-commodities are sold (like real estate). It's a great system, and it's what you were trying to research, but in this market (software) there is very little public data, so you are at a disadvantage of being in the dark on this. Understand, though, they probably have more data on this than you do, and it is probably part of how they figure what they want to pay you.

Income Multiple (Projected Sales) System

As Mathew Foscarini pointed out, this is a system used to value business and commercial real estate properties.

The idea is that you have an asset that generates an income. For instance, an apartment building takes in $50k per year in rent. Then there is a Multiple applied, which is based on the comp system (mentioned above), say 10. So the market value of this apartment building is how much rent can be collected, based on current occupancy and rent rates, over 10 years = $500k. Of course if you raise rents and improve occupancy next year to get an extra 10k a year in rent, suddenly your property is worth an extra $100k - and thus why so many rich people (and bankrupt people, too, of course) are involved in real estate.

This system can be applied to software, but if your app isn't individually commercially viable it's hard to do this. With your example of 80 users paying $200 each, that means that if a company can convince those same people to buy a new version (which is way easier than selling to strangers), or convince a small portion of their larger client base to buy 80 copies, that's a quick $16k for maybe sending out an email blast and sending a memo to your sales staff.

Good established companies have estimated lifetime values of users, and if this number is high (like, say, Adobe's buyers of Creative Suite), then paying $30k to pick up even 1 new user or retain an existing customer was a great idea.

What You Should Do

The first step is "talk to them." Learn about their needs, why they are interested, what need does this fill for them, just learn as much about them and what they want as possible. This is Being A Good Salesman (not a sleazebag salesman) - get to know your customer.

Maybe they are actually buying to resell. I've had people offer to buy code of mine because they had a contract where they were supposed to make something that did what my code already was doing. If their total contract was $500, obviously the most they were going to pay me was "less than that." I asked and they pretty much flat out told me just like that. Sometimes I wasn't interested (it wasn't worth the hassle to me for that price, or I was too busy), sometimes I just gave them the code for free, and sometimes I took them up on their offer to make a little extra money on code I already wrote and could still keep using.

Maybe they want to reskin/repurpose the app and sell it as their own product. Maybe they want to add it to a menu of their existing software. Maybe they don't care about the app much but want the users and the app to be a free bonus given to buyers of their next version. Maybe it will be compiled into their own source code and the existing app will be 'discontinued' but the feature will be available in their app now... etc, etc, etc. I could make stuff up all day long, but the only way to have even a vague idea is Just Ask. Even if they lie, who cares, you learned something!

Sometimes these are job interviews of a sort and they'll want to buy your services in the future, maybe they just want a widget to save them the trouble.

Final Caution

The devil is in the details, and they matter. Do you retain ANY rights to the code? Do they even want you to stop using/delete all copies of the code and the app of your own? Do they just want a license to use your stuff and 'transfer' the name and users to them and they could care less what you do after that? Do they want ongoing support, consultation, and if so what is appropriate to contact you about and when?

If they are to make future demands of your time and effort, that is a good time to offer something like "x hours of support in the transition/interpretation, then I'm available at $Y per hour after that." Be interested, be professional, be supportive - don't give yourself, your time, and your work away because you forgot to clarify and put things in writing.

Body:
The hardest part of doing this sort of thing for the first time is really psychological - there is a very strong tendency to think of what it cost you in man hours, which is usually wildly inaccurate when done retrospectively and ignores the "I wasn't sitting at a desk but I was thinking about that algorithm all day..." and other overhead details, etc.

So I'd like to invite you to change your frame of perspective using an analogy: you no longer have an app, you have a steel widget. You put things into it, and things come out the other side, and what it does to the things that go in have caused various people to become accustomed to having your widget around. To date, you've just been giving your widget away for free because someone gave you the steel for free so it doesn't cost you anything.

The Background Concepts

Now someone wants to buy the whole concept and user base of your widget from you.

First of all, why do they want to buy it? If it's a business, the answer is "to make money." Either they are improving an existing product they have and wish to increase loyalty and offer a benefit they think could sell more copies, or they want to avoid solving a problem they have and thus reduce costs or focus their own effort on other things. They might also want your users as potential "hot leads" who they know could be interested in their product and could be unusually likely to buy stuff from them.

The relevant equation:

Price Paid = (Buyer's Perceived Value - Seller's Cost) * Negotiation

So if it costs you nothing (you already did the work without expectation of pay), and it's worth $100k to them, do they pay you $1? Or $99k? $50k? It's all about negotiation - trying to determine where the final price is between the maximum they'll pay and the minimum you'll accept.

Sometimes negotiation is so weird people pay too much, and sometimes people sell for less than cost. These are edge cases, and so we ignore them - but yes, they do exist. I want to hire Instagram's negotiators for everything I do ;)

So first, what's it worth to them? This is by far the hardest thing to know, and one tactic is to flat out ask them. I know, crazy right?

Super Secret Negotiation Tactic

"I'm a reasonable man - what's this worth to you?" or "What's your budget for this sort of acquisition?" You'd be amazed at how often people just flat out tell you. They might not want to haggle, and if they just want to do their job and buy something from you and go on with their day, they could just tell you, "We've got about $50k in the budget for acquisitions like yours, and yours is relatively small compared to some of the other things we are buying, so we figured 5-10k would be reasonable given the straight-purchase we are requesting." Or "We figured it would cost us about $4000 in expenses to make this ourselves, so that's the most we'd pay under any circumstances," or simply "We're looking to seal this deal at around $3000."

And then you get to decide if that's ok with you and if you want to push it or take it. How hard was that? In negotiation it's almost always very important that you must not be the first one to name a price - so if they volunteer a price then you have a baseline you can accept outright or argue up from. But they might not name a price, and we have to see if that price is reasonable anyway.

There are a few accounting systems to determine the value of something, and this is what a rational business will use to determine a budget for buying your little 'entity':

Cost

The value is what it cost, perhaps with yearly depreciation. This is the most common form of accounting in the world, and it literally says "the value is whatever it cost to buy it, decreasing over time." Seriously - it costs what it costs. Not very helpful to us here, but its true.

This is what people try to do by determining man hours, but I'll give you the bottom-line: this is meaningless in software. You can work 40 years on a million lines of code with a going rate of $50 an hour and the result is worth $0. You aren't freelancing or accepting a contract to build something at an hourly rate, nor did you make it "on spec" with the hope of selling it to recoup your expenses. This is psychologically pleasing, but utterly meaningless in the context of buying and selling.

Replacement Cost

The value of something is what it would cost to replace it. This can be easy with commodities, like asking "what is the value of a new Ford Focus?" But this is not so easy in software, because it can be like math - a single one line formula could take a century to discover if you don't already know it. Or what took you 10 hours could take someone else 100 - or maybe it would take them only an hour.

So this would look at trying to estimate what it would cost to have a replacement for your widget built that simultaneously doesn't violate any of your rights as an inventor. Looking at the lines of code/complexity/difficulty of your app would produce a range of anywhere from "maybe a month for a prototype that is low on bugs if one person who knows what they are doing works on it" to... who knows. It must not be trivial or they wouldn't offer you money at all.

If they have their own development team maybe their estimate of doing it themselves is very reasonable. But they don't want to - they have more important things to do with their time. They'd have to wait for months to get started, or they would have to hire someone - and who knows if they can deliver or if it'll just be a waste of time and money? There's so much risk!

You've got the goods Right NOW, and this has a special value. Take advantage of this.

Comps (short for "comparisons")

This is what other things are going for. For example, if this business is used to buying apps/users/source code, they can say, "Well, this widget is easier to make than the SuperWidget we bought last month for $10k, but the output isn't as marketable as our DeluxeWidget we bought last year which we paid only $5k for." So perhaps they figure a comparative value is somewhere between $5k and $10k, and it doesn't matter if you have a million lines of code or 10, they don't have to know or care.

This is how most non-commodities are sold (like real estate). It's a great system, and it's what you were trying to research, but in this market (software) there is very little public data, so you are at a disadvantage of being in the dark on this. Understand, though, they probably have more data on this than you do, and it is probably part of how they figure what they want to pay you.

Income Multiple (Projected Sales) System

As Mathew Foscarini pointed out, this is a system used to value business and commercial real estate properties.

The idea is that you have an asset that generates an income. For instance, an apartment building takes in $50k per year in rent. Then there is a Multiple applied, which is based on the comp system (mentioned above), say 10. So the market value of this apartment building is how much rent can be collected, based on current occupancy and rent rates, over 10 years = $500k. Of course if you raise rents and improve occupancy next year to get an extra 10k a year in rent, suddenly your property is worth an extra $100k - and thus why so many rich people (and bankrupt people, too, of course) are involved in real estate.

This system can be applied to software, but if your app isn't individually commercially viable it's hard to do this. With your example of 80 users paying $200 each, that means that if a company can convince those same people to buy a new version (which is way easier than selling to strangers), or convince a small portion of their larger client base to buy 80 copies, that's a quick $16k for maybe sending out an email blast and sending a memo to your sales staff.

Good established companies have estimated lifetime values of users, and if this number is high (like, say, Adobe's buyers of Creative Suite), then paying $30k to pick up even 1 new user or retain an existing customer was a great idea.

What You Should Do

The first step is "talk to them." Learn about their needs, why they are interested, what need does this fill for them, just learn as much about them and what they want as possible. This is Being A Good Salesman (not a sleazebag salesman) - get to know your customer.

Maybe they are actually buying to resell. I've had people offer to buy code of mine because they had a contract where they were supposed to make something that did what my code already was doing. If their total contract was $500, obviously the most they were going to pay me was "less than that." I asked and they pretty much flat out told me just like that. Sometimes I wasn't interested (it wasn't worth the hassle to me for that price, or I was too busy), sometimes I just gave them the code for free, and sometimes I took them up on their offer to make a little extra money on code I already wrote and could still keep using.

Maybe they want to reskin/repurpose the app and sell it as their own product. Maybe they want to add it to a menu of their existing software. Maybe they don't care about the app much but want the users and the app to be a free bonus given to buyers of their next version. Maybe it will be compiled into their own source code and the existing app will be 'discontinued' but the feature will be available in their app now... etc, etc, etc. I could make stuff up all day long, but the only way to have even a vague idea is Just Ask. Even if they lie, who cares, you learned something!

Sometimes these are job interviews of a sort and they'll want to buy your services in the future, maybe they just want a widget to save them the trouble.

Final Caution

The devil is in the details, and they matter. Do you retain ANY rights to the code? Do they even want you to stop using/delete all copies of the code and the app of your own? Do they just want a license to use your stuff and 'transfer' the name and users to them and they could care less what you do after that? Do they want ongoing support, consultation, and if so what is appropriate to contact you about and when?

If they are to make future demands of your time and effort, that is a good time to offer something like "x hours of support in the transition/interpretation, then I'm available at $Y per hour after that." Be interested, be professional, be supportive - don't give yourself, your time, and your work away because you forgot to clarify and put things in writing.


答:
I think to some degree we all work like that. Someone somewhere design something and we code something that's part of or work with the system. Examples are building apps based on a framework, like non-game apps on mobile devices. A lot of UI decision has been made by the design team of the people who built the framework. They controlled everything from learning to write an app to selling your app. If you want to look why this model was successful, just look at the amount of documentation and tools provided by some vendors.

Another example is web applications with lots of them trying to implement REST style. This one doesn't really tell how to implement something, although when there are specifications on how to use HTTP. Anyway, there are specifications and guiding principles to follow. If you see the amount of discussions about REST implementation on stackexchange or in workplace, it's like there's an architect telling people to implement something in certain ways. It's still a succesfull model, I think, with so many people following the style.

From those two examples you can see how designs are propagated, some as paper specifications, others come with books, tools and examples. You can see how people asking (in volume), trying to get the understanding right with different degrees depending what standards/designs they're trying to follow. Just go to stackoverflow and watch ;)

If you give me your specification I will ask. If you give me unit test, I will code and test.

Title: Design in one team, coding in another


答:
Short answer

Because ArrayDeque capacity must be a power of two, and 16 is the smallest power of two that is at least 10.

ArrayDeque needs to use a lot of % operations everywhere to wrap around a linear array that pretends to be circular.

a % b can be expressed as a & (b - 1) if b is a power of two. The bitwise AND is massively faster so the capacity of ArrayDeque is restricted to be power of two. All % operations are performed with bitmasking instead of actual % in the implementation.

This is also why the newer HashMap doesn't use prime number table sizes but power of two, again because the % operation needs to be performed so often and the bitwise and is that much faster.

So if the baseline is 10, then structures that have power of two limitations should use 16 becase it's the smallest power of two that is at least 10.

Title: Why do different java collections have different default capacity?

Body:
Looking at different collection constructors the question comes to mind. Why does ArrayList()
construct an empty list with an initial capacity of ten and ArrayDeque()
constructs an empty array deque with an initial capacity sufficient to hold 16 elements.</p>


问:
Why are methods considered the class attributes in Python?
I read in a book that both methods and fields are considered the attributes of a class in Python. However, recently I was told by a friend of mine that methods may not be considered the attributes of a class.

Then I decided to check this out again, and found this question mentioned on Wikipedia saying that this is a Python "tradition" to refer to methods as attributes, in contrast to other object-oriented programming languages.

So my question is: why are methods considered the class atributes along with the fields in Python in contrast to other languages?

Thank you!

答:
Your friend was wrong. Methods are attributes.

Everything in Python is objects, really, with methods and functions and anything with a __call__() method being callable objects. They are all objects that respond to the () call expression syntax.

Attributes then, are objects found by attribute lookup on other objects. It doesn't matter to the attribute lookup mechanism that what is being looked up is a callable object or not.

You can observe this behaviour by looking up just the method, and not calling it:

```<code>>>> class Foo(object):
...     def bar(self):
...         pass
...
>>> f = Foo()
>>> f.bar
<bound method Foo.bar of <__main__.Foo object at 0x1023f5590>>
</code>```

Here f.bar is an attribute lookup expression, the result is a method object.

Of course, your friend me be a little bit right too; what is really happening is that methods are special objects that wrap functions, keeping references to the underlying instance and original function, and are created on the fly by accessing the function as an attribute. But that may be complicating matters a little when you first start out trying to understand Python objects. If you are interested in how all that works, read the Python Descriptor HOWTO to see how attributes with special methods are treated differently on certain types of attribute access.

This all works because Python is a dynamic language; no type declarations are required. As far as the language is concerned, it doesn't matter if Foo.bar is a string, a dictionary, a generator, or a method. This is in contrast to compiled languages, where data is very separate from methods, and each field on an instance needs to be pinned down to a specific type beforehand. Methods generally are not objects, thus a separate concept from data.

Body:
Your friend was wrong. Methods are attributes.

Everything in Python is objects, really, with methods and functions and anything with a __call__() method being callable objects. They are all objects that respond to the () call expression syntax.

Attributes then, are objects found by attribute lookup on other objects. It doesn't matter to the attribute lookup mechanism that what is being looked up is a callable object or not.

You can observe this behaviour by looking up just the method, and not calling it:

>>> class Foo(object):
...     def bar(self):
...         pass
...
>>> f = Foo()
>>> f.bar
<bound method Foo.bar of <__main__.Foo object at 0x1023f5590>>

Here f.bar is an attribute lookup expression, the result is a method object.

Of course, your friend me be a little bit right too; what is really happening is that methods are special objects that wrap functions, keeping references to the underlying instance and original function, and are created on the fly by accessing the function as an attribute. But that may be complicating matters a little when you first start out trying to understand Python objects. If you are interested in how all that works, read the Python Descriptor HOWTO to see how attributes with special methods are treated differently on certain types of attribute access.

This all works because Python is a dynamic language; no type declarations are required. As far as the language is concerned, it doesn't matter if Foo.bar is a string, a dictionary, a generator, or a method. This is in contrast to compiled languages, where data is very separate from methods, and each field on an instance needs to be pinned down to a specific type beforehand. Methods generally are not objects, thus a separate concept from data.


问:
Am I required to memorize coding in a work space or can I fall onto references to provide me edge to finishing my development?
I would like to know if I am expected to memorize coding in a workspace or am I allow to fall into references whenever I am unsure.

In a week of non-stop self learning, I feel I can understand the basics html and CSS, but am I required to memorize every single code once I get a position in this field or is it fair to use references to provide you the edge to finish your development. I was always under the impression you had to hand-code everything but I am wondering if I'll be looked as less of a developer if I fall to references. Understanding that if I do memorize most things, it will save me the time it will take me to code something but I don't want to feel penalized if I need to refer back to a code because I need refresh myself.

This Programmers question held a lot of good answers, but they don't quite fit for me.  My role is as a graphic designer/illustrator not a developer, and I am still relative new with how the process works. I'll definitely like a strong input to make sure I go along the right path in my learnings Because HTML and CSS are just a starting point, I want to excel in other areas as well.

Thanks for taking the time to read my post.
P.S (if you have any other additional references or advice, I'll gladly appreciate it)

答:
Programmers are not human encyclopedias. We remember what we use often, and we keep actual encyclopedias nearby for what we don't. I consider myself a "veteran" C# coder, and there are things I Google every day to do my job. That's probably one of the hallmarks of a veteran; that he knows what he doesn't know, and where to find it.

The only reason you'd memorize as much technical detail you could is for the same reason any grade-schooler would; to pass an upcoming test. MS certification tests are full of this kind of crap, requiring you to memorize the order of parameters of obscure built-in method calls you typically code once, in a general-purpose library, before moving on to more interesting things. This is one of the reasons I don't like certification tests and don't think the resulting titles are worth much; all they prove is that you have managed to ingrain into your brain the same knowledge the IDE itself could tell you in two seconds.

What you usually need to know, given a basic intuitive grasp of how to program, are the basic rules around whatever language you're studying; structure, syntax, formatting and naming conventions, and a few best practices. That allows you to read code in that language, and to maintain it. From there, the reference books or online resources will tell you what the code doesn't, and that's what else you could do.


答: Programmers’ virtues include lazyness. HTML and CSS are not programming, but the same principle applies. Learn to use specifications and reliable references. Stay out of w3chools; see http://w3fools.com</p>

Title: Am I required to memorize coding in a work space or can I fall onto references to provide me edge to finishing my development?

Body:
I would like to know if I am expected to memorize coding in a workspace or am I allow to fall into references whenever I am unsure.

In a week of non-stop self learning, I feel I can understand the basics html and CSS, but am I required to memorize every single code once I get a position in this field or is it fair to use references to provide you the edge to finish your development. I was always under the impression you had to hand-code everything but I am wondering if I'll be looked as less of a developer if I fall to references. Understanding that if I do memorize most things, it will save me the time it will take me to code something but I don't want to feel penalized if I need to refer back to a code because I need refresh myself.

This Programmers question held a lot of good answers, but they don't quite fit for me.  My role is as a graphic designer/illustrator not a developer, and I am still relative new with how the process works. I'll definitely like a strong input to make sure I go along the right path in my learnings Because HTML and CSS are just a starting point, I want to excel in other areas as well.

Thanks for taking the time to read my post.
P.S (if you have any other additional references or advice, I'll gladly appreciate it)


答:
I'm not entirely sure there's a question here, but I'll take a stab at it.

This is a profession.  Some of us have been at this for 30+ years and are still learning.  What's a week compared to that?

The code (syntax, language, rules, etc) is easier to remember with practice.  Someone experienced with Photoshop can probably fly through that app 1000 times faster than I can.  Why should this be different?

Build something small using only a few tools (perhaps just html & css for starters).  Learn from it, then build something bigger.

Repeat #3 a lot.

Ask a lot of good questions.  See SSCCE.org and What have you tried? for some good info on how to ask a good question (hint: it's really hard, but important)

Repeat #5 a lot


答:
IMO, the previous answers focus on edge cases and code which should be rewritten anyway. Here are some cases I see nearly everywhere in which if/else should have been replaced by if or another language construct.

Note: I make the answer community wiki. Feel free to modify it and add other examples of cases where if/else usually leads to bad code.

Beginners, ye be warned! if/else has a potential of creating an unreadable code when not used carefully. The next examples show the most common cases where if/else is easily misused.

1. Guard clause

I stopped counting how many times I've seen something like this:

void Demo(...)
{
    if (ok_to_continue)
    {
        ... // 20 lines here.
    }
    else
    {
        throw new SomeException();
    }
}
```

<p>Nobody needs extra indentation. The same code could have been written like this:</p>

<pre class="lang-cs prettyprint-override"><code>void Demo(...)
{
    if (!ok_to_continue)
    {
        throw new SomeException();
    }

    ... // No indentation for the next 20 lines.
}
</code>```

Rule: if you can remove an else statement by inverting the if check, handling an error, and exiting immediately, (else otherwise continue on), then do so.

2. Code duplication

This one is also quite frequent.

if (!this.useAlternatePanel)
{
    currentInput = this.defaultTextBox.Text;
    bool missingInput = currentInput.Length == 0;
    this.defaultProcessButton.Enabled = !missingInput;
    this.defaultMissingInputHelpLabel.Visible = missingInput;
}
else
{
    currentInput = this.alternateTextBox.Text;
    bool missingInput = currentInput.Length == 0;
    this.alternateProcessButton.Enabled = !missingInput;
    this.alternateMissingInputHelpLabel.Visible = missingInput;
}
```

<p>This is an excellent example of beginners' code, because a beginner wouldn't always see how such code can be refactored. One of the ways is to create a map of controls:</p>

<pre class="lang-cs prettyprint-override"><code>var defaultControls = new CountriesProcessingControls(
    this.defaultTextBox,
    this.defaultProcessButton,
    this.defaultMissingInputHelpLabel);

var alternateControls = new CountriesProcessingControls(
    this.alternateTextBox,
    this.alternateProcessButton,
    this.alternateMissingInputHelpLabel);

void RefreshCountriesControls(CountriesProcessingControls controls)
{
    currentInput = controls.textBox.Text;
    bool missingInput = currentInput.Length == 0;
    controls.processButton.Enabled = !missingInput;
    controls.missingInputHelpLabel.Visible = missingInput;
}

RefreshCountriesControls(this.useAlternatePanel ? alternateControls : defaultControls);
</code>```

Rule: if the block in else is nearly identical to the block in if, you're doing it wrong and causing code duplication.

3. Trying to do two things

The opposite is also common:

if (...)
{
    foreach (var dateInput = this.selectedDates)
    {
        var isConvertible = convertToDate(dateInput);
        if (!isConvertible)
        {
            this.invalidDates.add(dateInput);
        }
    }
}
else
{
    var languageService = this.initializeLanguageService();
    this.Translated = languageService.translate(this.LastInput);
    if (this.Translated != null)
    {
        this.NotificationScheduler.append(LAST_INPUT_TRANSLATED);
    }
}
```

<p>The block within <code>if</code> has nothing to do with the block within <code>else</code>. Combining two blocks in the same method makes the logic difficult to understand and error-prone. Finding a name for the method, as well as commenting it properly is extremely difficult too.</p>

<p><strong>Rule: Avoid combining blocks which have nothing in common together in an <code>if/else</code> block.</strong></p>

<h2>4. Object-oriented programming</h2>

<p>This sort of coding is also frequent among beginners:</p>

<pre class="lang-cs prettyprint-override"><code>// `animal` is either a dog or a cat.
if (animal.IsDog)
{
    animal.EatPedigree();
    animal.Bark();
}
else // The animal is a cat.
{
    animal.EatWhiskas();
    animal.Meow();
}
</code>```

In object-oriented programming, this code shouldn't exist. It should be written like this instead:

IAnimal animal = ...;
animal.Eat();
animal.MakeSound();
```

<p>given that each class (<code>Cat : IAnimal</code> and <code>Dog : IAnimal</code>) will have their own implementation of those methods.</p>

<p><strong>Rule: when doing object-oriented programming, generalize functions (methods) and use inheritance and polymorphism.</strong></p>

<h2>5. Assigning a value</h2>

<p>I see this one everywhere in codebases written by beginners:</p>

<pre class="lang-cs prettyprint-override"><code>int price;
if (this.isDiscount)
{
    price = -discount;
}
else
{
    price = unitCost * quantity;
}
</code>```

This is a terrible piece of code, since it's not written for humans.

It is misleading. It makes you think that the main operation here is the choosing between discount and non-discount mode, while the actual main operation is the assignment of price.

It is error prone. What if later, one condition is changed? What if one of two assignments is removed?

It invites even worse code. I've seen a lot of pieces like that where int price was instead int price = 0;, just to get rid of compiler warning if one of the assignments is missing. Hiding warnings instead of solving them is one of the worst things one can do.

There is a tiny code duplication, which means more characters to type originally, and more changes to do later.

It's uselessly long.

The same could be written like this:

int price = this.isDiscount ? -discount : unitCost * quantity;
```

Rule: use the ternary operator instead of if/else blocks for simple value-assignments.

Title: Clarification of "avoid if-else" advice

Body:
IMO, the previous answers focus on edge cases and code which should be rewritten anyway. Here are some cases I see nearly everywhere in which if/else should have been replaced by if or another language construct.

Note: I make the answer community wiki. Feel free to modify it and add other examples of cases where if/else usually leads to bad code.

Beginners, ye be warned! if/else has a potential of creating an unreadable code when not used carefully. The next examples show the most common cases where if/else is easily misused.

1. Guard clause

I stopped counting how many times I've seen something like this:

void Demo(...)
{
    if (ok_to_continue)
    {
        ... // 20 lines here.
    }
    else
    {
        throw new SomeException();
    }
}

Nobody needs extra indentation. The same code could have been written like this:

void Demo(...)
{
    if (!ok_to_continue)
    {
        throw new SomeException();
    }

    ... // No indentation for the next 20 lines.
}

Rule: if you can remove an else statement by inverting the if check, handling an error, and exiting immediately, (else otherwise continue on), then do so.

2. Code duplication

This one is also quite frequent.

if (!this.useAlternatePanel)
{
    currentInput = this.defaultTextBox.Text;
    bool missingInput = currentInput.Length == 0;
    this.defaultProcessButton.Enabled = !missingInput;
    this.defaultMissingInputHelpLabel.Visible = missingInput;
}
else
{
    currentInput = this.alternateTextBox.Text;
    bool missingInput = currentInput.Length == 0;
    this.alternateProcessButton.Enabled = !missingInput;
    this.alternateMissingInputHelpLabel.Visible = missingInput;
}

This is an excellent example of beginners' code, because a beginner wouldn't always see how such code can be refactored. One of the ways is to create a map of controls:

var defaultControls = new CountriesProcessingControls(
    this.defaultTextBox,
    this.defaultProcessButton,
    this.defaultMissingInputHelpLabel);

var alternateControls = new CountriesProcessingControls(
    this.alternateTextBox,
    this.alternateProcessButton,
    this.alternateMissingInputHelpLabel);

void RefreshCountriesControls(CountriesProcessingControls controls)
{
    currentInput = controls.textBox.Text;
    bool missingInput = currentInput.Length == 0;
    controls.processButton.Enabled = !missingInput;
    controls.missingInputHelpLabel.Visible = missingInput;
}

RefreshCountriesControls(this.useAlternatePanel ? alternateControls : defaultControls);

Rule: if the block in else is nearly identical to the block in if, you're doing it wrong and causing code duplication.

3. Trying to do two things

The opposite is also common:

if (...)
{
    foreach (var dateInput = this.selectedDates)
    {
        var isConvertible = convertToDate(dateInput);
        if (!isConvertible)
        {
            this.invalidDates.add(dateInput);
        }
    }
}
else
{
    var languageService = this.initializeLanguageService();
    this.Translated = languageService.translate(this.LastInput);
    if (this.Translated != null)
    {
        this.NotificationScheduler.append(LAST_INPUT_TRANSLATED);
    }
}

The block within if has nothing to do with the block within else. Combining two blocks in the same method makes the logic difficult to understand and error-prone. Finding a name for the method, as well as commenting it properly is extremely difficult too.

Rule: Avoid combining blocks which have nothing in common together in an if/else block.

4. Object-oriented programming

This sort of coding is also frequent among beginners:

// `animal` is either a dog or a cat.
if (animal.IsDog)
{
    animal.EatPedigree();
    animal.Bark();
}
else // The animal is a cat.
{
    animal.EatWhiskas();
    animal.Meow();
}

In object-oriented programming, this code shouldn't exist. It should be written like this instead:

IAnimal animal = ...;
animal.Eat();
animal.MakeSound();

given that each class (Cat : IAnimal and Dog : IAnimal) will have their own implementation of those methods.

Rule: when doing object-oriented programming, generalize functions (methods) and use inheritance and polymorphism.

5. Assigning a value

I see this one everywhere in codebases written by beginners:

int price;
if (this.isDiscount)
{
    price = -discount;
}
else
{
    price = unitCost * quantity;
}

This is a terrible piece of code, since it's not written for humans.

It is misleading. It makes you think that the main operation here is the choosing between discount and non-discount mode, while the actual main operation is the assignment of price.

It is error prone. What if later, one condition is changed? What if one of two assignments is removed?

It invites even worse code. I've seen a lot of pieces like that where int price was instead int price = 0;, just to get rid of compiler warning if one of the assignments is missing. Hiding warnings instead of solving them is one of the worst things one can do.

There is a tiny code duplication, which means more characters to type originally, and more changes to do later.

It's uselessly long.

The same could be written like this:

int price = this.isDiscount ? -discount : unitCost * quantity;

Rule: use the ternary operator instead of if/else blocks for simple value-assignments.