答:
There are too many cases where using a literal is the right approach.

From a performance standpoint, there are times that you want literals in your queries.  Imagine I have a bug tracker where once it gets big enough to worry about performance I expect that 70% of the bugs in the system will be "closed", 20% will be "open", 5% will be "active" and 5% will be in some other status.  I may reasonably want to have the query that returns all active bugs to be

```<code>SELECT *
  FROM bug
 WHERE status = 'active'
</code>```

rather than passing the status as a bind variable.  I want a different query plan depending on the value passed in for status-- I'd want to do a table scan to return the closed bugs and an index scan on the status column to return the active loans.  Now, different databases and different versions have different approaches to (more or less successfully) allow the same query to use a different query plan depending on the value of the bind variable.  But that tends to introduce a decent amount of complexity that needs to be managed to balance out the decision of whether to bother re-parsing a query or whether to reuse an existing plan for a new bind variable value. For a developer, it may make sense to deal with this complexity.  Or it may make sense to force a different path when I have more information about what my data is going to look like than the optimizer does.

From a code complexity standpoint, there are also plenty of times that it makes perfect sense to have literals in SQL statements.  For example, if you have a zip_code column that has a 5 character zip code and sometimes has an additional 4 digits, it makes perfect sense to do something like

```<code>SELECT substr( zip_code, 1, 5 ) zip,
       substr( zip_code, 7, 4 ) plus_four
</code>```

rather than passing in 4 separate parameters for the numeric values.  These aren't things that will ever change so making them bind variables only serves to make the code potentially more difficult to read and to create the potential that someone will bind parameters in the wrong order and end up with a bug.

Title: Why not just make non-parameterized queries return an error?

Body:
SQL injection is a very serious security issue, in large part because it's so easy to get it wrong: the obvious, intuitive way to build a query incorporating user input leaves you vulnerable, and the Right Way to mitigate it requires you to know about parameterized queries and SQL injection first.

Seems to me that the obvious way to fix this would be to shut down the obvious (but wrong) option: fix the database engine so that any query received that uses hard-coded values in its WHERE clause instead of parameters returns a nice, descriptive error message instructing you to use parameters instead.  This would obviously need to have an opt-out option so that stuff like ad-hoc queries from administrative tools will still run easily, but it should be enabled by default.

Having this would shut down SQL injection cold, almost overnight, but as far as I know, no RDBMS actually does this.  Is there any good reason why not?

Body:
There are too many cases where using a literal is the right approach.

From a performance standpoint, there are times that you want literals in your queries.  Imagine I have a bug tracker where once it gets big enough to worry about performance I expect that 70% of the bugs in the system will be "closed", 20% will be "open", 5% will be "active" and 5% will be in some other status.  I may reasonably want to have the query that returns all active bugs to be

SELECT *
  FROM bug
 WHERE status = 'active'

rather than passing the status as a bind variable.  I want a different query plan depending on the value passed in for status-- I'd want to do a table scan to return the closed bugs and an index scan on the status column to return the active loans.  Now, different databases and different versions have different approaches to (more or less successfully) allow the same query to use a different query plan depending on the value of the bind variable.  But that tends to introduce a decent amount of complexity that needs to be managed to balance out the decision of whether to bother re-parsing a query or whether to reuse an existing plan for a new bind variable value. For a developer, it may make sense to deal with this complexity.  Or it may make sense to force a different path when I have more information about what my data is going to look like than the optimizer does.

From a code complexity standpoint, there are also plenty of times that it makes perfect sense to have literals in SQL statements.  For example, if you have a zip_code column that has a 5 character zip code and sometimes has an additional 4 digits, it makes perfect sense to do something like

SELECT substr( zip_code, 1, 5 ) zip,
       substr( zip_code, 7, 4 ) plus_four

rather than passing in 4 separate parameters for the numeric values.  These aren't things that will ever change so making them bind variables only serves to make the code potentially more difficult to read and to create the potential that someone will bind parameters in the wrong order and end up with a bug.


问:
Are data type declarators like "int" and "char" stored in RAM when a C program executes?
When a C program is running, the data is stored on the heap or the stack. The values are stored in RAM addresses. But what about the type indicators (e.g., int or char)? Are they also stored?

Consider the following code:

```<code>char a = 'A';
int x = 4;
</code>```

I read that A and 4 are stored in RAM addresses here. But what about a and x? Most confusingly, how does the execution know that a is a char and x is an int? I mean, is the int and char mentioned somewhere in RAM?

Let's say a value is stored somewhere in RAM as 10011001; if I am the program which executes the code, how will I know whether this 10011001 is a char or an int?

What I don't understand is how the computer knows, when it reads a variable's value from an address such as 10001, whether it is an int or char. Imagine I click on a program called anyprog.exe. Immediately the code starts executing. Does this executable file include information on whether the variables stored are of the type int or char?

答:
Most processors provide different instructions for working with data of different types, so type information is usually "baked in" to the generated machine code.  There's no need to store additional type metadata.

Some concrete examples might help.  The machine code below was generated using gcc 4.1.2 on an x86_64 system running SuSE Linux Enterprise Server (SLES) 10.

Assume the following source code:

```<code>int main( void )
{
  int x, y, z;

  x = 1;
  y = 2;

  z = x + y;

  return 0;
}
</code>```

Here's the meat of the generated assembly code corresponding to the above source (using gcc -S), with comments added by me:

main:
.LFB2:
        pushq   %rbp               ;; save the current frame pointer value
.LCFI0:
        movq    %rsp, %rbp         ;; make the current stack pointer value the new frame pointer value
.LCFI1:
        movl    $1, -12(%rbp)      ;; x = 1
        movl    $2, -8(%rbp)       ;; y = 2
        movl    -8(%rbp), %eax     ;; copy the value of y to the eax register
        addl    -12(%rbp), %eax    ;; add the value of x to the eax register
        movl    %eax, -4(%rbp)     ;; copy the value in eax to z
        movl    $0, %eax           ;; eax gets the return value of the function
        leave                      ;; exit and restore the stack
        ret
```

<p>There's some extra stuff that follows <code>ret</code>, but it isn't relevant to the discussion.</p>

<p><code>%eax</code> is a 32-bit general purpose data register.  <code>%rsp</code> is a 64-bit register reserved for saving the <em>stack pointer</em>, which contains the address of the last thing pushed onto the stack.  <code>%rbp</code> is a 64-bit register reserved for saving the <em>frame pointer</em>, which contains the address of the current <em>stack frame</em>.  A stack frame is created on the stack when you enter a function, and it reserves space for the function's arguments and local variables.  Arguments and variables are accessed by using offsets from the frame pointer.  In this case, the memory for the variable <code>x</code> is 12 bytes "below" the address stored in <code>%rbp</code>.  </p>

<p>In the above code, we copy the integer value of <code>x</code> (1, stored at <code>-12(%rbp)</code>) to the register <code>%eax</code> using the <code>movl</code> instruction, which is used to copy 32-bit words from one location to another.  We then call <code>addl</code>, which adds the integer value of <code>y</code> (stored at <code>-8(%rbp)</code>) to the value already in <code>%eax</code>.  We then save the result to <code>-4(%rbp)</code>, which is <code>z</code>.  </p>

<p>Now let's change that up so we're dealing with <code>double</code> values instead of <code>int</code> values:</p>

```int main( void )
{
  double x, y, z;

  x = 1;
  y = 2;

  z = x + y;

  return 0;
}
```

<p>Running <code>gcc -S</code> again gives us:</p>

<pre class="lang-none prettyprint-override"><code>main:
.LFB2:
        pushq   %rbp
.LCFI0:
        movq    %rsp, %rbp
.LCFI1:
        movabsq $4607182418800017408, %rax ;; copy literal 64-bit floating-point representation of 1.00 to rax
        movq    %rax, -24(%rbp)            ;; save rax to x
        movabsq $4611686018427387904, %rax ;; copy literal 64-bit floating-point representation of 2.00 to rax
        movq    %rax, -16(%rbp)            ;; save rax to y
        movsd   -24(%rbp), %xmm0           ;; copy value of x to xmm0 register
        addsd   -16(%rbp), %xmm0           ;; add value of y to xmm0 register
        movsd   %xmm0, -8(%rbp)            ;; save result to z
        movl    $0, %eax                   ;; eax gets return value of function
        leave                              ;; exit and restore the stack
        ret
</code>```

Several differences.  Instead of movl and addl, we use movsd and addsd (assign and add double-precision floats).  Instead of storing interim values in %eax, we use %xmm0.

This is what I mean when I say that the type is "baked in" to the machine code.  The compiler simply generates the right machine code to handle that particular type.

ContentLicense: CC BY-SA 3.0

Body:
Most processors provide different instructions for working with data of different types, so type information is usually "baked in" to the generated machine code.  There's no need to store additional type metadata.

Some concrete examples might help.  The machine code below was generated using gcc 4.1.2 on an x86_64 system running SuSE Linux Enterprise Server (SLES) 10.

Assume the following source code:

int main( void )
{
  int x, y, z;

  x = 1;
  y = 2;

  z = x + y;

  return 0;
}

Here's the meat of the generated assembly code corresponding to the above source (using gcc -S), with comments added by me:

main:
.LFB2:
        pushq   %rbp               ;; save the current frame pointer value
.LCFI0:
        movq    %rsp, %rbp         ;; make the current stack pointer value the new frame pointer value
.LCFI1:
        movl    $1, -12(%rbp)      ;; x = 1
        movl    $2, -8(%rbp)       ;; y = 2
        movl    -8(%rbp), %eax     ;; copy the value of y to the eax register
        addl    -12(%rbp), %eax    ;; add the value of x to the eax register
        movl    %eax, -4(%rbp)     ;; copy the value in eax to z
        movl    $0, %eax           ;; eax gets the return value of the function
        leave                      ;; exit and restore the stack
        ret

There's some extra stuff that follows ret, but it isn't relevant to the discussion.

%eax is a 32-bit general purpose data register.  %rsp is a 64-bit register reserved for saving the stack pointer, which contains the address of the last thing pushed onto the stack.  %rbp is a 64-bit register reserved for saving the frame pointer, which contains the address of the current stack frame.  A stack frame is created on the stack when you enter a function, and it reserves space for the function's arguments and local variables.  Arguments and variables are accessed by using offsets from the frame pointer.  In this case, the memory for the variable x is 12 bytes "below" the address stored in %rbp.

In the above code, we copy the integer value of x (1, stored at -12(%rbp)) to the register %eax using the movl instruction, which is used to copy 32-bit words from one location to another.  We then call addl, which adds the integer value of y (stored at -8(%rbp)) to the value already in %eax.  We then save the result to -4(%rbp), which is z.

Now let's change that up so we're dealing with double values instead of int values:

int main( void )
{
  double x, y, z;

  x = 1;
  y = 2;

  z = x + y;

  return 0;
}

Running gcc -S again gives us:

main:
.LFB2:
        pushq   %rbp
.LCFI0:
        movq    %rsp, %rbp
.LCFI1:
        movabsq $4607182418800017408, %rax ;; copy literal 64-bit floating-point representation of 1.00 to rax
        movq    %rax, -24(%rbp)            ;; save rax to x
        movabsq $4611686018427387904, %rax ;; copy literal 64-bit floating-point representation of 2.00 to rax
        movq    %rax, -16(%rbp)            ;; save rax to y
        movsd   -24(%rbp), %xmm0           ;; copy value of x to xmm0 register
        addsd   -16(%rbp), %xmm0           ;; add value of y to xmm0 register
        movsd   %xmm0, -8(%rbp)            ;; save result to z
        movl    $0, %eax                   ;; eax gets return value of function
        leave                              ;; exit and restore the stack
        ret

Several differences.  Instead of movl and addl, we use movsd and addsd (assign and add double-precision floats).  Instead of storing interim values in %eax, we use %xmm0.

This is what I mean when I say that the type is "baked in" to the machine code.  The compiler simply generates the right machine code to handle that particular type.


问:
OCaml criticism: is it still valid?
I am a complete newbie with OCaml. I have recently stumbled into this page listing a good amount of criticism towards OCaml.

Seeing that the page it quite old (2007): which of the bullets points listed there are still true today? For instance: is it still true that it is impossible to print a generic object?

I want to make it clear that I am not looking for a discussion of the opinions expressed therein. I am asking whether the information listed, such as the fact that integers overflow without warnings, is still correct for more recent versions of OCaml

答:
Seeing that the page it quite old (2007): which of the bullets points listed there are still true today?

False Sense of Security. This is nonsense.

Few Basic Types. OCaml now has bytes and byte arrays but no built-in unicode strings, 16-bit integers, unsigned integers, 32-bit floats, vectors or matrices. Third-party libraries provide some of these.

Silent Integer Overflow. Unchanged but it was never a problem.

Module Immutability. His recommendation that functions and modules should be mutable is a grim throwback to Lisp and a really bad idea. You can supercede modules using include if you want to but you cannot mutate them, of course.

Polymorphism Causes Run-time Type Errors. This is a big problem with OCaml and it has not been fixed. As your types evolve polymorphic equality, comparison and hashing will start to fail when they encounter types like functions and debugging the problem is very hard. F# has a great solution to this problem.

No Macros. Ironically, when he wrote this OCaml actually had full support for macros but they have now decided to pull the feature out.

Wrappers. This was a real problem and it has not been fixed. There is still no try ... finally construct in the OCaml language and no wrapper implementing it in the stdlib.

Places. Unchanged but a non-problem.

Record field naming hell. Structure your code properly using modules.

Syntax. Unchanged but a non-problem.

No Polymorphism. This was mostly nonsense when he wrote it and nothing has changed.

Inconsistent function sets. OCaml still doesn't have a cons function. That's fine. I don't want Lisp stuff in my language, thank you.

No dynamic variables. Was a good thing about OCaml. Is still a good thing about OCaml.

Optional ~ arguments suck. Optional arguments rock. I badgered Microsoft to get them to add optional arguments to F#.

Partial argument application inconsistency. Eh?

Arithmetic's readability. This has changed since I stopped using OCaml ~8 years ago. Apparently now you can do Int64.((q * n - s * s) / (n - 1L)).

Silent name conflict resolution. He was trying to do full-blown software development in the REPL as you would in Lisp. Don't do that in OCaml. Use files and batch compilation resorting to the REPL only for testing, running disposable code and interactive technical computing.

Order of evaluation. This was wrong when he wrote it. Order of evaluation is undefined in OCaml.

No object input/output. He cited a third-party library that already solved this "problem".

Compiler stops after the first error. Eh?

No stack trace for natively compiled executables. Fixed.

Debugger sucks. I never used the debugger. Static type checking catches almost all of my bugs.

GC sucks. I found OCaml's GC to be superb except for one major problem: the global lock prevents parallel programming.

No implicit forward declarations. Mutual recursion is explicit by design in all MLs. The only wierdness is that type definitions are recursive by default whereas let bindings are non-recursive by default.

Function round is absent. OCaml still has a bare bones stdlib but third party libraries like Jane St's Core provide round and friends.

Lists. List.map is still not tail recursive. I submitted patches to fix serious bugs like this and had to wait years before they appeared in releases. Lists are still immutable, of course. And so they should be.

Speed. I believe the compile times for big polymorphic variants have been fixed.

Pattern matching. A triumph of hope over reality. The Lisp community have failed to do this. Hence my 10th rule: any sufficiently complicated Lisp program contains an ad-hoc, informally-specified and bug-ridden implementation of half of OCaml's pattern match compiler.

For instance: is it still true that it is impossible to print a generic object?

When he wrote that you could not simply do:

```<code>print value
</code>```

but you could invoke the pretty printer from the top-level as a library call, giving it the necessary type information. And there was a macro that you can use to annotate data structures in order to have pretty printers autogenerated.

Title: OCaml criticism: is it still valid?

Body:
Seeing that the page it quite old (2007): which of the bullets points listed there are still true today?

False Sense of Security. This is nonsense.

Few Basic Types. OCaml now has bytes and byte arrays but no built-in unicode strings, 16-bit integers, unsigned integers, 32-bit floats, vectors or matrices. Third-party libraries provide some of these.

Silent Integer Overflow. Unchanged but it was never a problem.

Module Immutability. His recommendation that functions and modules should be mutable is a grim throwback to Lisp and a really bad idea. You can supercede modules using include if you want to but you cannot mutate them, of course.

Polymorphism Causes Run-time Type Errors. This is a big problem with OCaml and it has not been fixed. As your types evolve polymorphic equality, comparison and hashing will start to fail when they encounter types like functions and debugging the problem is very hard. F# has a great solution to this problem.

No Macros. Ironically, when he wrote this OCaml actually had full support for macros but they have now decided to pull the feature out.

Wrappers. This was a real problem and it has not been fixed. There is still no try ... finally construct in the OCaml language and no wrapper implementing it in the stdlib.

Places. Unchanged but a non-problem.

Record field naming hell. Structure your code properly using modules.

Syntax. Unchanged but a non-problem.

No Polymorphism. This was mostly nonsense when he wrote it and nothing has changed.

Inconsistent function sets. OCaml still doesn't have a cons function. That's fine. I don't want Lisp stuff in my language, thank you.

No dynamic variables. Was a good thing about OCaml. Is still a good thing about OCaml.

Optional ~ arguments suck. Optional arguments rock. I badgered Microsoft to get them to add optional arguments to F#.

Partial argument application inconsistency. Eh?

Arithmetic's readability. This has changed since I stopped using OCaml ~8 years ago. Apparently now you can do Int64.((q * n - s * s) / (n - 1L)).

Silent name conflict resolution. He was trying to do full-blown software development in the REPL as you would in Lisp. Don't do that in OCaml. Use files and batch compilation resorting to the REPL only for testing, running disposable code and interactive technical computing.

Order of evaluation. This was wrong when he wrote it. Order of evaluation is undefined in OCaml.

No object input/output. He cited a third-party library that already solved this "problem".

Compiler stops after the first error. Eh?

No stack trace for natively compiled executables. Fixed.

Debugger sucks. I never used the debugger. Static type checking catches almost all of my bugs.

GC sucks. I found OCaml's GC to be superb except for one major problem: the global lock prevents parallel programming.

No implicit forward declarations. Mutual recursion is explicit by design in all MLs. The only wierdness is that type definitions are recursive by default whereas let bindings are non-recursive by default.

Function round is absent. OCaml still has a bare bones stdlib but third party libraries like Jane St's Core provide round and friends.

Lists. List.map is still not tail recursive. I submitted patches to fix serious bugs like this and had to wait years before they appeared in releases. Lists are still immutable, of course. And so they should be.

Speed. I believe the compile times for big polymorphic variants have been fixed.

Pattern matching. A triumph of hope over reality. The Lisp community have failed to do this. Hence my 10th rule: any sufficiently complicated Lisp program contains an ad-hoc, informally-specified and bug-ridden implementation of half of OCaml's pattern match compiler.

For instance: is it still true that it is impossible to print a generic object?

When he wrote that you could not simply do:

print value

but you could invoke the pretty printer from the top-level as a library call, giving it the necessary type information. And there was a macro that you can use to annotate data structures in order to have pretty printers autogenerated.


问:
Reason to use mingw win32 headers and libs with LLVM/Clang
Is there any good reason (except "GCC is better") to use the MinGW win32api/headers/libs with LLVM/Clang. Suppose that in two to three years, Clang has matured enough (in C++0x and performance) that it's a competitor/replacement and has its advantages over MSVC like GCC does on some accounts. Why on earth would one want to avoid using the MS library and header implementations of the win32 API, which is freely available in the form of the Windows SDK?</p>

答:
One reason for the MingW header files to exist is certainly copyright: while they are "free as in beer", you are not allowed to redistribute them. Neither could the LLVM authors redistribute them, instead, every LLVM/Clang user would have to download them on their own. So it would be reasonable for Clang to provide a set of header files, and it would then be reasonable to use the MingW code as a starting point.

In addition, another reason for the MingW header files to exist (IIRC) is that the SDK headers use C extensions that were not supported by gcc. They may be supported now, so that reason may have gone.

ContentLicense: CC BY-SA 2.5


问:
Why not just make non-parameterized queries return an error?
SQL injection is a very serious security issue, in large part because it's so easy to get it wrong: the obvious, intuitive way to build a query incorporating user input leaves you vulnerable, and the Right Way to mitigate it requires you to know about parameterized queries and SQL injection first.

Seems to me that the obvious way to fix this would be to shut down the obvious (but wrong) option: fix the database engine so that any query received that uses hard-coded values in its WHERE clause instead of parameters returns a nice, descriptive error message instructing you to use parameters instead.  This would obviously need to have an opt-out option so that stuff like ad-hoc queries from administrative tools will still run easily, but it should be enabled by default.

Having this would shut down SQL injection cold, almost overnight, but as far as I know, no RDBMS actually does this.  Is there any good reason why not?

答:
SQL injection occurs when a query is built by concatenating text from an untrusted and unvalidated source with other portions of a query.  While such a thing would most often occur with string literals, that would not be the only way it could occur.  A query for numeric values might take a user-entered string (that's supposed to only contain digits) and concatenate with other material to form a query without the quote marks normally associated with string literals; code which is overly trusting of client-side validation might have things like field names come from an HTML query string.  There's no way code looking at an SQL query string can see how it was assembled.

What's important is not whether an SQL statement contains string literals, but rather whether a string contains any sequences of characters from untrusted sources, and validation for that would be best handled in the library which builds queries.  There's generally no way in C# to write code that will allow a string literal but won't allow other kinds of string expression, but one could have a coding-practices rule that requires that queries be built up using a query-building class rather than string concatenation, and anyone passing a non-literal string to the query builder must justify such action.


问:
Visual Studio VC Project With Multiple Output Versus Multiple Projects
I am working in Visual Studio 2012. I have several C projects in a single Solution. Each project currently produces a single production output (dll/exe) and a single test (exe). I manage the multiple outputs through custom configurations and settings including ignoring files per configuration. My motivation for doing so is an attempt to more closely mimic the single project w/ test structure of object oriented languages. My questions is, is this approach better, worse or equivalent to having a project per output? I understand the subjective aspects of the question. </p>

<p>Edit: My research on the subject has been limited to searching the internet for known performance issues and anti-patterns. All of the search results from several permutations of the title above (and others) have been about the number of projects in a solution. I am not specifically concerned about that aspect as splitting my projects into two would still not produce the kinds of numbers being dealt with in the search results. In general, I don't believe performance would be an issue considering the size of the project. I'm mainly interested in whether there are accepted standards or known patterns/anti-patterns that I should be aware of in this approach. Microsoft's documentation here seems to hint at preferring a single project per solution but it isn't explicit. Other  MSDN information focuses more on solution management than project management. </p>

答:
YMMV, but in our environment, we prefer any test code automatically to be rebuild after a change to library on which the test code depends was made. Having to switch between configurations first makes it easier to forget the rebuild. And don't you run into trouble when you try to debug through the test applications, and step from the test application's code into the library code, where the libraries configuration is not the active one?

So IMHO using different configurations for compiling different components is probably technically possible, but - at least in our case - it would increase the administrative work to manage them. Different configurations are made for creating different variants of the same component, like a Debug and and Release configuration, or 32 bit and a 64 bit configuration. That's at least the default usage you get from standard Visual Studio project templates. I would not try to shoehorn a different use case into that feature.


问:
White Boards -- Who Uses Them?
So as both a full-time programmer and hobbyist as well (developing my own things for personal use and maybe to sell one day), I feel that me purchasing a big white board to hang in my room at home or something would be very useful.

Does anyone here have one as well, to use for high level designs (UML, Architecture, etc.) and things like very early UI mockups, etc.?

If you guys do have them, which ones have you bought? I can't seem to pin one that would be good for home use and I'm not sure of the pricing/other things.

Thanks!

答:
A white board is probably the most important collaboration tool available to people physically together.  The key reason is that it allows you to easily draw what you think of so others can read it, and then they can draw etc.

Personally I would like every flat surface in our offices to be whiteboards, but others disagree.  Hence the office I sit in have a single whiteboard, with space around it allowing for impromptu meetings, which has proven to work very well.

I consider a whiteboard to be essential in our daily work.

Title: White Boards -- Who Uses Them?


问:
Is a developer's ability to analyze code directly proportional to how well they can write code?
In my professional work I started noticing that the more advanced developer you are the more meaningful comments you leave on a code review.

Recently when I was asked to interview several candidates I came up with a fairly simple code snippet (these were inexperienced candidates) in several languages (so they can choose) and 'hide' well known issues in the code. For example, in a Java snippet I would use == instead of .equals(), duplicate some code, use meaningless variable names, for OOP, come up with a strange class hierarchy, etc... I came up with a range of issues with different difficulties. Then we were to discuss what is wrong with a code and how to improve it.

I found that this question gave me insight into several things. First, it was a red flag if a developer could not point out obvious issues with the code. Second, even if a developer could not find all the issues, I could point it out and they can say 'ah yeah' and talk about it in a meaningful way. It also allowed me hear them dig as deep as they wanted on certain things.

I personally find it intimidating to write code during an interview. I also find it strange when potential employees give you a 'homework' to complete at home and hand in before the actual interview. But then how else are you supposed to evaluate their programming potential? So in my limited experience, showing the code snippet worked real well.

Is there any issues with this approach or is it acceptable? Is it possible that someone does well with this task but would not be able to write quality code?

答:
I think to some extent, this should be a valid evaluation of their programming skills. If someone doesn't point out the use of == instead of .equals in their review of Java, or does but can't explain the difference/why you would want .equals, they probably do not have the level of understanding of the Java language to write good code.

Additionally, in a way this task is very akin to what a developer usually winds up doing when working with legacy code. Duplicated code and weird inheritance structures are opportunities to refactor, and a good developer WILL notice them and WILL come up with a good refactor or a better design. If a developer can do that, there's no reason they shouldn't be able to write good code.


答:
Having been through the job search process for several months, I can give you my perspective on the job search process as it relates to me.  First, some don'ts; these are all things that many employers are doing right now, and they shouldn't be doing them:

Don't ask people elaborate questions about things that they will never use on the job.

I'm not talking about FizzBuzz. FizzBuzz exists to weed out people who can't program at all.  I'm talking about asking people to design and implement a binary tree, when that problem has already been solved decades ago.  Instead, ask about complexity (Big O), and perhaps how to use recursion to walk a binary tree.

Don't ask people to write perfect code.

You're not going to get that in a coding interview, especially if it's via skype or over the phone.  Most people use IDE's nowadays, and you've robbed them of that tool.  If part of your job skill set requires people to code in Notepad, then by all means.  I doubt that's true, though.

Don't ask people to travel clear across the country for a six month commitment.

This is just a variation on "the interview that never ends."  Figure out how to find talented people to interview in the first or second contact to interview, and then make the interview relevant to your job.

Stop following the herd!

Some of the things that you are doing in your interviews you are doing because Google does them, or Facebook does them.  Your best hiring process is not necessarily coding contests between whiskey shots (if the lore is true).  Your best hiring process is the one that best fits your company, not the latest Google or Facebook fashion.

Finally, don't ask people about things you don't already know yourself.

If you're asking someone to improve performance on a string reversal algorithm when they've already written it in the most optimum way, you're just wasting everyone's time.

Now that that's out of the way....

For example, in a Java snippet I would use == instead of .equals(), duplicate some code...

This seems like a sensible approach.

I would expect every experienced developer to already know certain things about their language of choice.  I would expect a reasonably competent C# programmer to know how == differs from equals(), why strings are an exception, what IDisposable is and how it relates to using, etc.  I would personally favor crack skills in their language of choice over your preferred kitchen sink of desired technology flavors of the week, since someone with excellent coding skills can easily pick those up.

I found that this question gave me insight into several things. First, it was a red flag if a developer could not point out obvious issues with the code. Second, even if a developer could not find all the issues, I could point it out and they can say 'ah yeah' and talk about it in a meaningful way. It also allowed me hear them dig as deep as they wanted on certain things.

All true.

I personally find it intimidating to write code during an interview. I also find it strange when potential employees give you a 'homework' to complete at home and hand in before the actual interview. But then how else are you supposed to evaluate their programming potential?

By the time you grant someone an interview, you should already have a fair idea whether or not you're going to hire them.  When I interviewed for the job I have now, I wasn't even asked any technical questions.  The person who interviewed me spent most of his time selling me on his company.  He said "I already know you can do the job, subject to your references confirming that you've done the things you say you've done in your resume."

Title: Is a developer's ability to analyze code directly proportional to how well they can write code?

Body:
In my professional work I started noticing that the more advanced developer you are the more meaningful comments you leave on a code review.

Recently when I was asked to interview several candidates I came up with a fairly simple code snippet (these were inexperienced candidates) in several languages (so they can choose) and 'hide' well known issues in the code. For example, in a Java snippet I would use == instead of .equals(), duplicate some code, use meaningless variable names, for OOP, come up with a strange class hierarchy, etc... I came up with a range of issues with different difficulties. Then we were to discuss what is wrong with a code and how to improve it.

I found that this question gave me insight into several things. First, it was a red flag if a developer could not point out obvious issues with the code. Second, even if a developer could not find all the issues, I could point it out and they can say 'ah yeah' and talk about it in a meaningful way. It also allowed me hear them dig as deep as they wanted on certain things.

I personally find it intimidating to write code during an interview. I also find it strange when potential employees give you a 'homework' to complete at home and hand in before the actual interview. But then how else are you supposed to evaluate their programming potential? So in my limited experience, showing the code snippet worked real well.

Is there any issues with this approach or is it acceptable? Is it possible that someone does well with this task but would not be able to write quality code?


问:
Intro to C for an experienced programmer
This reply to the question "I don't know C. And why should I learn it?" has me interested in learning C. What is a good self-instruction program (textbook/website/OpenCourseWare, etc.) for someone who already has lots of experience in high-level languages?</p>

答:
If your goal truly is to understand what goes on under the hood, then perhaps, instead of learning C and writing a toy program in it, you instead look at a C compiler and understand how that works.  As far as compilers go, a C compiler is one of the simplest, as the language doesn't have all that many high-level features.

As for which compiler, I would take a simple compiler with an easy to understand machine architecture, so you're not mucking about too much with x86 instructions.

I'd suggest the C-- compiler (written in Java) which outputs MIPS assembly.


问:
Execute a get request periodically while application is inactive
I have a website that has full support for mobile devices but since opening a browser window seems too much and some people are obsessed with installing apps, I'm now creating an android app which is essentially just a browser inside of an activity.

I thought, I'm creating it anyway, so I might just go one step further and enable the app to notify the user when there are new events that may concern them such as new notifications in the site itself.

I've never developed an android application nor have I ever worked with java, I'm basically just googling and copy/pasting with little tweaks (I know my ways around programming, just not java), which made me think twice about how I should do this.

Basically my idea is when the activity is closed (onStop) I will start a service that then is going to send an HTTP GET request to my API site.com/notifications/countUnseen which simply returns an integer, and if there are any I'll create a new android notification for the user. When the activity is resumed (onStart) I will terminate the service. I am concerned mainly about the fact that I have to send an HTTP request every, say, 5 minutes and I'm not really sure how to do that. What I found is that I could use ScheduledThreadPoolExecutor suggested in this answer from within the service.

Do you think that what I have planned is a good idea at all? I just need a word of comfort about this, or better yet another suggestion if what I have is garbage, from someone more experienced than me.

答:
Create a runnable and call it with handler using postDelayed() method in your service.

```<code>private final Handler handler = new Handler();
private Runnable getResponceAfterInterval = new Runnable() {

        public void run() {

            try
            {
                new RequestTask().execute("URL of your GET request"); //RequestTask() is a AsynchTask requesting and handling response

            } catch (Exception e) {

            }

            handler.postDelayed(this, 5000*60);

        }
    };
</code>```

And in onStart() method paste these lines.

```<code>handler.removeCallbacks(getResponceAfterInterval);
handler.post(getResponceAfterInterval);
</code>```

Body:
Create a runnable and call it with handler using postDelayed() method in your service.

private final Handler handler = new Handler();
private Runnable getResponceAfterInterval = new Runnable() {

        public void run() {

            try
            {
                new RequestTask().execute("URL of your GET request"); //RequestTask() is a AsynchTask requesting and handling response

            } catch (Exception e) {

            }

            handler.postDelayed(this, 5000*60);

        }
    };

And in onStart() method paste these lines.

handler.removeCallbacks(getResponceAfterInterval);
handler.post(getResponceAfterInterval);


问:
Should I have a separate XML settings file for my application?
I want to be able to add some objects to my application by simply adding a XML node to a config file. Should I put it in the app.config file or should I make a separate XML config file? A node would look something like this

```<code><Books>
   <Book>
     <title></title>
     <author></author>
   </Book>
</Books>
</code>```

In that case I would add multiple books to my application by adding them in the config file. Is it bad practice to have 2 config files? I tried googling for solutions about the app.config file but it seems to not be the place to do it.

答:
Keeping a separate xml file is advisable because in future you may need to change these settings written in it and if it is in config then might be complex to change it...

But make sure while going live that make that file read only for security reasons..


问:
What are the differences between class variables and instance variables in Java?
I'm very new to Java and want to understand the difference between class variables and instance variables.

For example:

```<code>class Bicycle {
    static int cadence = 0;
    int speed = 0;
    int gear = 1;
}
</code>```

How are instance variables and class variables different from each other? Which variables here are class variables, and which are instance variables? How does this affect scope?

答:
It is explained here (with an example Bicycle class with class variable numberOfBicycles and instance variables cadence, speed, gear & id):

Sometimes, you want to have variables that are common to all objects. This is accomplished with the static modifier. Fields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory. Any object can change the value of a class variable, but class variables can also be manipulated without creating an instance of the class.

A class variable (declared static) is a location common to all instances.

In the example, numberOfBicycles is a class variable (since it is declared static). There is only one such variable (i.e. location) common to all instances and to the class. So if you modify numberOfBicycles in one method, other methods would see the new value (even for different Bicycle objects)

In contrast gear & id are instance variables (because their declaration has no static modifier). Every Bicycle object has its own one. If you modify gear for some Bicycle a, and if b is another instance, modifying a.gear has no effect on b.gear

Each Java object is a distinct memory zone with some meta data (e.g. some reference to its class) and its own instance variables (perhaps inherited from a superclass). But the class variables are common to the class and shared by all instances.

See also Object (computer science) & Instance variable wikipages.

ContentLicense: CC BY-SA 4.0


答:
They both are member variables, meaning that both are associated with a class. Now of course, there are differences between the two:

Instance variables:

These variables belong to the instance of a class, thus an object. And every instance of that class (object) has it's own copy of that variable. Changes made to the variable don't reflect in other instances of that class.

```<code>public class Product {
    public int Barcode;
}
</code>```

Class variables:

These are also known as static member variables and there's only one copy of that variable that is shared with all instances of that class. If changes are made to that variable, all other instances will see the effect of the changes.

```<code>public class Product {
    public static int Barcode;
}
</code>```

Full example:

```<code>// INSTANCE VARIABLE
public class Main {

    public static void main(String[] args) {

        Product prod1 = new Product();
        prod1.Barcode = 123456;

        Product prod2 = new Product();
        prod2.Barcode = 987654;

        System.out.println(prod1.Barcode);
        System.out.println(prod2.Barcode);
    }
}

public class Product {
    public int Barcode;
}
</code>```

The output will be:

123456

987654

Now, change the instance variable to a class variable by making it static:

```<code>//CLASS VARIABLE
public class Main {

    public static void main(String[] args) {

        Product prod1 = new Product();
        prod1.setBarcode(123456);
        Product prod2 = new Product();
        prod2.setBarcode(987654);

        System.out.println(prod1.getBarcode());
        System.out.println(prod2.getBarcode());
    }
}

public class Product {

    public static int Barcode;

    public int getBarcode() {
        return Barcode;
    }

    public void setBarcode(int value){
        Barcode = value;
    }
}
</code>```

I used non-static methods to get and set the value of Barcode to be able to call it from the object and not from the class. The output will be following:

987654

987654

Title: What are the differences between class variables and instance variables in Java?

Body:
I'm very new to Java and want to understand the difference between class variables and instance variables.

For example:

```<code>class Bicycle {
    static int cadence = 0;
    int speed = 0;
    int gear = 1;
}
</code>```

How are instance variables and class variables different from each other? Which variables here are class variables, and which are instance variables? How does this affect scope?

Body:
They both are member variables, meaning that both are associated with a class. Now of course, there are differences between the two:

Instance variables:

These variables belong to the instance of a class, thus an object. And every instance of that class (object) has it's own copy of that variable. Changes made to the variable don't reflect in other instances of that class.

public class Product {
    public int Barcode;
}

Class variables:

These are also known as static member variables and there's only one copy of that variable that is shared with all instances of that class. If changes are made to that variable, all other instances will see the effect of the changes.

public class Product {
    public static int Barcode;
}

Full example:

// INSTANCE VARIABLE
public class Main {

    public static void main(String[] args) {

        Product prod1 = new Product();
        prod1.Barcode = 123456;

        Product prod2 = new Product();
        prod2.Barcode = 987654;

        System.out.println(prod1.Barcode);
        System.out.println(prod2.Barcode);
    }
}

public class Product {
    public int Barcode;
}

The output will be:

123456

987654

Now, change the instance variable to a class variable by making it static:

//CLASS VARIABLE
public class Main {

    public static void main(String[] args) {

        Product prod1 = new Product();
        prod1.setBarcode(123456);
        Product prod2 = new Product();
        prod2.setBarcode(987654);

        System.out.println(prod1.getBarcode());
        System.out.println(prod2.getBarcode());
    }
}

public class Product {

    public static int Barcode;

    public int getBarcode() {
        return Barcode;
    }

    public void setBarcode(int value){
        Barcode = value;
    }
}

I used non-static methods to get and set the value of Barcode to be able to call it from the object and not from the class. The output will be following:

987654

987654


答:
There is no need to leave as service running to perform regular polling, and doing so may annoy your users, as it will consume memory for no good reason.

You should look at the AlarmManager API. This has three potential advantages:

it can be configured to send an Intent that will start your app in the background even if it is not running, meaning you don't need to waste memory

it can be configured to wait until the device is next awake after your selected time, which will save power

it is able to batch notifications with similar frequency together, meaning that if any of your users have another process that polls periodically the two will happen simultaneously, thus saving power.

Title: Execute a get request periodically while application is inactive

Body:
I have a website that has full support for mobile devices but since opening a browser window seems too much and some people are obsessed with installing apps, I'm now creating an android app which is essentially just a browser inside of an activity.

I thought, I'm creating it anyway, so I might just go one step further and enable the app to notify the user when there are new events that may concern them such as new notifications in the site itself.

I've never developed an android application nor have I ever worked with java, I'm basically just googling and copy/pasting with little tweaks (I know my ways around programming, just not java), which made me think twice about how I should do this.

Basically my idea is when the activity is closed (onStop) I will start a service that then is going to send an HTTP GET request to my API site.com/notifications/countUnseen which simply returns an integer, and if there are any I'll create a new android notification for the user. When the activity is resumed (onStart) I will terminate the service. I am concerned mainly about the fact that I have to send an HTTP request every, say, 5 minutes and I'm not really sure how to do that. What I found is that I could use ScheduledThreadPoolExecutor suggested in this answer from within the service.

Do you think that what I have planned is a good idea at all? I just need a word of comfort about this, or better yet another suggestion if what I have is garbage, from someone more experienced than me.


问:
Directory organization of a CMake (C++) repository containing several projects
I would like some advises on the organization of a set of related but independent C++ projects stored in a single (git) repository. The projects use CMake.

For a simplified example we imagine 2 projects A and B, A depending on B. Most people developing A will get B via the packaging system. Thus they will compile only A. However, we should allow developers to compile both A and B themselves (and install it), separately or together.

Here is a proposal :

```<code>└── Repo1
    ├── CMakeLists.txt (1)
    ├── A
    │   ├── CMakeLists.txt (2)
    │   ├── include
    │   │   ├── aaa.h
    │   │   ├── aaaa.h
    │   │   └── CMakeLists.txt (3)
    │   └── src
    │       ├── aaa.cpp
    │       ├── aaaa.cpp
    │       └── CMakeLists.txt (4)
    ├── B
    │   ├── CMakeLists.txt (2)
    │   ├── include
    │   │   ├── bbb.h
    │   │   ├── bbbb.h
    │   │   └── CMakeLists.txt (3)
    │   └── src
    │       ├── bbb.cpp
    │       ├── bbbb.cpp
    │       └── CMakeLists.txt (4)
    └── test
        ├── CMakeLists.txt (5)
        └── testaaaa.cpp
</code>```

Define the common cmake variables for all projects (if any) and includes the subdirectories.

Defines the project itself and the project's required cmake variables.

Defines the headers to install and the ones required for compilation.

Configures the library and binaries.

Configures the test executables and test-cases.

As I understand it, each project should produce a XXXConfig.cmake file and install it in /usr/local/share/cmake. Writing these files seem quite complicated when reading the documentation of CMake.

What do you think ? Does the structure make sense ?

Do you happen to have a working example of such a set of projects ?

答:
After quite some reading and tests, I have made a basic demo C++ project demonstrating the use of CMake, CTest + boost.test, CPack and Doxygen and using more or less the organization I mentioned in my question.

The project shows how to make subproject dependencies, how to compile the whole repo or only a subproject, how to package, how to test and how to produce documentation.

See here : https://github.com/Barthelemy/CppProjectTemplate


问:
Database design: manage permissions on multiple applications resources
Overview

A central web application to supports other web applications(A) for user and its role/permission management. Applications (A) call the central application via API to get the user roles/permissions.

1) Application(A) can have resources.

2) Resources can have permissions.

3) User can have access to resource/permissions.

Admin should able to create resources for an application, Permissions for that resource, assign access of a resource/permission to a user and the response should be something like this.

```<code>User
 - Resource
    - Permissions
 - Resource
    - Permissions
</code>```

Scenario

Admin for an application(A) wants to create resources say R1, R2 but not necessarily any permissions under them because it is sufficient for him if he get the response like this.

```<code> User
     - R1
     - R2
</code>```

Approach 1

Create these tables
1) Application

2) Resource (FK as appID)

3) Permissions(FK as resourceID)

4) User_Permissions(FK as permissionID)

In this case since there are no permissions for a resource so User_Permission table will be empty. But then admin wants to give access to the resources, so either the system creates a default permission OR admin has to create a default permission whenever he created a resource. So we enter the default permissions in the User_Permissions table and we can eventually find out the corresponding resources and return the below response.

User
     - R1
       - Default Permission
     - R2
       - Default Permission

Approach 2

Create these tables
1) Application

2) Resource (FK as appID)

3) Permissions(FK as resourceID)

4) User_Resources(FK as resourceID)

5) User_Permissions(FK as userResourceID)

In this case we have the extra table User_Resources which specifies the resources to which the user has access and then permissions on that resource.

Need you suggestion which approach to prefer.

答:
Certainly not the the approach 2, as it will require an extra overhead of keeping User_Resources and User_Permissions in sync. for eg. an entry in User_Resources would override everything in User_Permissions for a particular resource.

I think, solution lies in defining the terms more elaborately. If I think in terms of OOP I dont see how permissions can be defined/owned by resource creator. Instead what can be/must be defined by the resource creator are the "Operations" that can be performed on the resource, If a resource can not be operated upon its not a resource at all, hence it will be a good design to make it mandatory that each resource have some operations defined.

Then you can define an Entity/Table called Permissions (User_ID,Operation_ID,Type) which will define the kind of access a user have on the resource.

For Eg. As a Resource Definer I might Define (Resource) Fan -> (Operations) TurnOn, TurnOff, setSpeed Then I can define permissions like

userA   turnOn READ
userA     turnOff WRITE
userA setSpeed UPDATE

meaning userA can only turnOff or change te speed of the Fan, or check if the Fan is ON but that user can not turn the fan ON.

You can have resourceIds in the table as well for the performance reasons, my suggestions were more around the design.


问:
Would a statically typed alternative to JavaScript on webpages be practical?
Preference for dynamic and static typing is largely a matter of taste, and different people find them more or less suitable in different situations.

My question is, would it be technically possible to have a statically-typed alternative to JavaScript for client-side web page augmentation etc.?

答:
Maybe you find your answer here: https://stackoverflow.com/questions/86426/why-require-javascript-rather-than-supporting-a-standard-browser-virtual-machine

Note: In my opinion more recent answers are more insightful despite their lower score.


问:
RIOT-OS and multiple executables?
I am brand new to embedded programming and am wondering if RIOT-OS has the capabilities that my small project requires.

I have 3 executables, fizz, buzz and foo. They all do separate - but very important - things. My understanding with real-time OSes is that you typically:

Take your app’s source code and somehow merge/splice it with the RTOSes source code; then

You cross-compile this conglomerated source code (again your app + RTOS source) into a binary that is compatible with the ultimate platform/architecture you will run it on; then

You flash the binary to the chip using something like UART or SPI, etc.

First, if this understanding is incorrect, can someone please help correct/clarify things for me?

Assuming I'm more or less on target, then I’m wondering if RIOT-OS supports the concept of "multiple executables" running when the chip/OS starts up? In other words, is it possible for RIOT-OS to be cross-compiled with, and then at runtime execute, all 3 executables (fizz, buzz and foo)?

答:
Read the RIOT-OS introduction and the RIOT: One OS to rule them all in the IoT report.

It looks like you'll make a single application (linked with RIOT runtime); this can be your mixture of the three executables, each running it its own threads.

Having an OS supporting several executables seem to require some file system (or something to separate the executables) and some notion of process, which apparently RIOT-OS does not have.

If you have full access to the C source code of your executables (i.e. your three programs), mixing them is in principle easily possible: you just ensure that every program has unique names. You could for example write some script to get the names in each public function (e.g. aa, ab, foo in program fizz) and generate a header fizznames.h with #define aa fizz__aa, #define ab fizz__ab etc... to be included in every translation unit of fizz, etc... This header could be generated with nm feeding some simple awk script (or perhaps by your MELT customizing extension to GCC....); then you write a gluing application which would start each fizz, buzz, foo main function in its own thread.
Alternatively, you could play ld tricks (e.g. ld -r) with your own GNU ld script (perhaps using the visibility function attribute) to mix your three programs in a single executable (and you'll still need your own starting function).

You still have to care about communication and synchronization (between fizz, buzz, foo)

Title: RIOT-OS and multiple executables?


问:
How to avoid using service location when using dependency injection?
I am trying to use dependency injection in a WPF application, and I really can't figure how to avoid using service location, which is considered to be an anti-pattern in many articles. I am using the MVVM Light framework.

Interface I
  Property N As Integer
End Interface
Class A
  Private _i As I
  Sub New(i As I)
    _i = i
  End Sub
  Sub DoWork()
    _i.N = 1
  End Sub
End Class
Class B
  Implements I
  Property N As Integer Implements I.N
End Class
Class C
  Sub DoSomething()
    REM IS THIS ANTI-PATTERN???
    Dim instanceA = SimpleIoc.Default.GetInstance(Of A)()
    instanceA.DoWork()
  End Sub
End Class
Module M
  Sub Main()
    SimpleIoc.Default.Register(Of A)()
    SimpleIoc.Default.Register(Of I, B)()
    Dim c As New C
    c.DoSomething()
  End Sub
End Module
```

When I need to use an instance of A in class C, is it an anti-pattern to use IoC container as service locator? Is there any other way to autoconstruct an instance of A with the required dependencies?

答:
The problem is that you are using 'Dim c As New C', instead of registering C in the IoC container and requesting it from there. The dependency C requests in DoSomething should be passed in the constructor, which IoC wires for you. What makes it a bit hard is the fact that your IoC container seems to be a Singleton and is therefore accessible from everywhere. You should try and avoid this.

Service location is indeed an antipattern, but you need to use service location at least ONCE for your application to work, as you rightly put in your question. This is done by creating a main application class that is manually retrieved from the IoC container. The rest of your application goes from there. If you do things right, you get a single main class from the IoC container and the rest is wired in by the container itself. It only turns into an antipattern when you start interspersing this IoC code into other application code.

Thinking about the dependencies actually helps your code. It's a lot easier to see where you are going wrong with the design of a class if you are adding the seventh dependency to the constructor, instead of New'ing up the seventh class in a method. Once you get your head around to thinking in terms of IoC you start to write small, focused and well-testable classes, but you have to sink your teeth into it for a bit until you really start to see the advantages.


问:
Possible alternatives to copy constructors
In my C++ project I am relying on some libraries that do memory management for me. I make wrapper classes, for ease of use and memory safety, for example the class below. Note that this is a much simplified example, to demonstrate my problem.

```<code>#include <library>

class Wrapper {
private:
    lib_type* data;
public:
    Wrapper() : data(library_new()) {
    }
    Wrapper(const Wrapper& orig) = delete;
    ~Wrapper() {
        library_free(data);
    }
    const lib_type* getData() const {
        return data;
    }
    /* ... */
    /* Lots of functions for using the wrapped object */
};
</code>```

I needed to delete the copy constructor, because otherwise a copy going out of scope would invalidate the original object. Not being allowed to have copies makes the object very impractical to use - everywhere it is used I now need to hold a reference, and I need to manage the object centrally, which partially defeats the purpose of the wrapper class.

Possible solutions I have tried/thought of:

Copying the data. This is normally not an option though, because it is either not allowed by the library or the data is huge.

Move constructors. I tried solving the lack of a copy constructor by using a move constructor, but depending on the implementation, either this did not solve the problem or it became effectively a copy constructor, reintroducing the related problems.

Smart pointers. Then I realized it might be solved by using smart pointers to the wrapper instead of references, as this removes the need to maintain a central copy.

Wrapping a smart pointer. Or I could wrap a smart pointer to the data instead of a raw pointer. This makes the implementation of the wrapper a little bit more complicated, but also makes it easier to use, giving the classes using it a cleaner interface.

My attempt at the second smart pointer solution applied to the example above:

```<code>#include <library>

class Deleter {
public:
    void operator()(lib_type* p) const {
        library_free(p);
    }
};

class Wrapper {
private:
    shared_ptr<lib_type> data;
public:
    Wrapper() : data(library_new(), Deleter()) {
    }
    Wrapper(const Wrapper& orig) : data(orig.data) {
    }
    ~Wrapper() {
    }
    const lib_type* getData() const {
        return *data;
    }
    /* ... */
    /* Lots of functions for using the wrapped object */
};
</code>```

Now for the concrete question: is this a good solution? Or are there other, perhaps better solutions?

I am particularly worried about the getData implementation; whether I should return a copy of the shared pointer or a naked pointer and why.

答:
I think these implementations are reasonable and a generally good solution. Adding an appropriate move constructor and move assignment may help deal with your copy concerns - the default should be appropriate with the shared wrapper.

Some may argue (or advise) that you do not need to wrap the Standard Library facilities that you use here; whilst this is true, the semantics of the getData() function may be quite specific for your target code - using the library facility or wrapping it is really a design tradeoff.

You may need a few tweaks on the assignment operators; and possibly be more explicit on the other special member functions (I would favour this here - it makes the intent of the code clearer). By way of example;

```<code>#include <library>

class UniqueWrapper {
private:
    lib_type* data;
public:
    UniqueWrapper() : data(library_new()) {}
    UniqueWrapper(const UniqueWrapper&) = delete;
    UniqueWrapper& operator=(const UniqueWrapper&) = delete;
    UniqueWrapper(UniqueWrapper&&) = delete;
    UniqueWrapper& operator=(UniqueWrapper&&) = delete;

    ~UniqueWrapper() {
        library_free(data);
    }
    const lib_type* getData() const {
        return data;
    }
};
</code>```

And as a shared wrapper;

```<code>#include <library>

class Deleter {
public:
    void operator()(lib_type* p) const {
        library_free(p);
    }
};

class SharedWrapper {
private:
    shared_ptr<lib_type> data;
public:
    SharedWrapper() : data(library_new(), Deleter()) {}

    SharedWrapper(const SharedWrapper& orig) = default;
    SharedWrapper& operator=(const SharedWrapper& orig) = default;
    SharedWrapper(SharedWrapper&& orig) = default;
    SharedWrapper& operator=(SharedWrapper&& orig) = default;

    ~SharedWrapper() = default;

    const lib_type* getData() const {
        return data.get(); // a reference return could also be used.
    }
    const lib_type& getDataAlt() const {
        // alternative for a reference
        return *data;
    }
};
</code>```

On your last question;

I am particularly worried about the getData implementation; whether I should return a copy of the shared pointer or a naked pointer and why?

When you expose some of the internals of an object, you give up some control over how that data is used - essentially this is not a bad thing, you just need to bear that in mind.

Having said that, there are ways you can make the code easy to use properly and hard to use incorrectly. Returning a const in this case would probably be advised, since the method is const - it is saying to the client of your code, don't change it. If changes are to be allowed, then a non-const version is also required.

The wrapper class you have is there to manage the resource, so I would advise returning a reference (hence for observation) over a pointer; a pointer can be a nullptr so if there is an "optional" nature to the value, a nullptr pointer can be used to indicate that.

If the shared and const-ness of the return type is to be maintained, David Hammen's solution of shared_ptr<const lib_type> is neat.

Body:
I think these implementations are reasonable and a generally good solution. Adding an appropriate move constructor and move assignment may help deal with your copy concerns - the default should be appropriate with the shared wrapper.

Some may argue (or advise) that you do not need to wrap the Standard Library facilities that you use here; whilst this is true, the semantics of the getData() function may be quite specific for your target code - using the library facility or wrapping it is really a design tradeoff.

You may need a few tweaks on the assignment operators; and possibly be more explicit on the other special member functions (I would favour this here - it makes the intent of the code clearer). By way of example;

#include <library>

class UniqueWrapper {
private:
    lib_type* data;
public:
    UniqueWrapper() : data(library_new()) {}
    UniqueWrapper(const UniqueWrapper&) = delete;
    UniqueWrapper& operator=(const UniqueWrapper&) = delete;
    UniqueWrapper(UniqueWrapper&&) = delete;
    UniqueWrapper& operator=(UniqueWrapper&&) = delete;

    ~UniqueWrapper() {
        library_free(data);
    }
    const lib_type* getData() const {
        return data;
    }
};

And as a shared wrapper;

#include <library>

class Deleter {
public:
    void operator()(lib_type* p) const {
        library_free(p);
    }
};

class SharedWrapper {
private:
    shared_ptr<lib_type> data;
public:
    SharedWrapper() : data(library_new(), Deleter()) {}

    SharedWrapper(const SharedWrapper& orig) = default;
    SharedWrapper& operator=(const SharedWrapper& orig) = default;
    SharedWrapper(SharedWrapper&& orig) = default;
    SharedWrapper& operator=(SharedWrapper&& orig) = default;

    ~SharedWrapper() = default;

    const lib_type* getData() const {
        return data.get(); // a reference return could also be used.
    }
    const lib_type& getDataAlt() const {
        // alternative for a reference
        return *data;
    }
};

On your last question;

I am particularly worried about the getData implementation; whether I should return a copy of the shared pointer or a naked pointer and why?

When you expose some of the internals of an object, you give up some control over how that data is used - essentially this is not a bad thing, you just need to bear that in mind.

Having said that, there are ways you can make the code easy to use properly and hard to use incorrectly. Returning a const in this case would probably be advised, since the method is const - it is saying to the client of your code, don't change it. If changes are to be allowed, then a non-const version is also required.

The wrapper class you have is there to manage the resource, so I would advise returning a reference (hence for observation) over a pointer; a pointer can be a nullptr so if there is an "optional" nature to the value, a nullptr pointer can be used to indicate that.

If the shared and const-ness of the return type is to be maintained, David Hammen's solution of shared_ptr<const lib_type> is neat.


问:
Sign up user using Microsoft Exchange Account in Node.js MongoDB
I have a question about whether a programming technique is at all possible.
Most of the apps these days come with sign up with Facebook, Twitter or gmail functionality.

My company has its domain name (for example www.mydomain.com) and our email address are as (john.smith@mydomain.com) and we use outlook to access the account.

My question is whether it is at all possible for users to be able to sign up to an app or system using the company address such as (john.smith@mydomain.com) similar what google or Facebook does. Keeping in Mind my app is an API which developed on Node.js and MongoDB.

If this is a wrong place to ask this question please let me know and i will move my question.

I am not looking for you to give me a exact solution, just asking whether its possible and if you can point me in the right direction.

答:
Most apps come with a standard email signup feature.

You ask users to giver their email address, chose a password, and possibly also a username. Then you send an email with a random token (usually embedded in a link to your site for convenience), which the users must give back to you in order to prove that they own the email. Any user can use this method, no matter what email provider they use.

You can add sign-in solutions from specific vendors like Gmail, Twitter and Facebook on top of this solution, in order to let the users of those services sign in without a new password.


答:
Instance Variable:

Instance variables are declared in a class, but outside a method,
constructor or any block.

Instance variable belongs to the instance of a class or you can say
that instance variable belongs to the object.

Instance variable have separate value of each and every instance of
the class.

```<code>Class InstanceDemo {

     // this instance variable is visible for any child class.
       public String name = "Testing";

     // count variable is visible in Demo class only.
       private int count = 2;
}
</code>```

Method to access instance variable:

```<code>InstanceDemo demo = new InstanceDemo ();

System.out.println("Access Instance variable: " + demo.count + " , "+demo.name );
</code>```

Output: 2 , Testing

Class Variable:

Class variable belongs to the class.

class variable is created by adding “static” keyword before the
variable.

Also called static variable.

And most important class variable maintain a single shared value for
all instance of a class, even if no instance object of the class
exists.

```<code>    Class ClassDemo {

     // count variable is Same for all instance of this class
       public static int count = 2;
}
</code>```

Method to access class variable:

```<code>System.out.println("Access Class variable: " + ClassDemo.count );
//class variable is directly refer with class name
</code>```

Output: 2

Brief Difference Between Class Variable and Instance Variable:

Instance variables have separate values for each instance of a class.
Class variables maintain a single shared value for all instances of
the class, even if no instance object of that class exists.

You would use the static keyword to change an instance variable into
a class variable.

Both instance and class variables are declared at the class level,
not within methods.

Body:
Instance Variable:

Instance variables are declared in a class, but outside a method,
constructor or any block.

Instance variable belongs to the instance of a class or you can say
that instance variable belongs to the object.

Instance variable have separate value of each and every instance of
the class.

Class InstanceDemo {

     // this instance variable is visible for any child class.
       public String name = "Testing";

     // count variable is visible in Demo class only.
       private int count = 2;
}

Method to access instance variable:

InstanceDemo demo = new InstanceDemo ();

System.out.println("Access Instance variable: " + demo.count + " , "+demo.name );

Output: 2 , Testing

Class Variable:

Class variable belongs to the class.

class variable is created by adding “static” keyword before the
variable.

Also called static variable.

And most important class variable maintain a single shared value for
all instance of a class, even if no instance object of the class
exists.

    Class ClassDemo {

     // count variable is Same for all instance of this class
       public static int count = 2;
}

Method to access class variable:

System.out.println("Access Class variable: " + ClassDemo.count );
//class variable is directly refer with class name

Output: 2

Brief Difference Between Class Variable and Instance Variable:

Instance variables have separate values for each instance of a class.
Class variables maintain a single shared value for all instances of
the class, even if no instance object of that class exists.

You would use the static keyword to change an instance variable into
a class variable.

Both instance and class variables are declared at the class level,
not within methods.


问:
What is the point of an Expr in vanilla F#? How can it be applied?
Without using the power pack to convert Expr to C# expressions, it seems like once I create an Expr, the only thing I can do with it is either print out a string representation of it, or...create another Expr.

If I print out a code quotation of an expression, I see that it prints out calls to static Expr methods. How can I use these for something useful?

答:
It sounds like you're missing the ability to be able to parse an expression using pattern matching. For example:

```<code>open Microsoft.FSharp.Quotations.Patterns
open Microsoft.FSharp.Quotations.DerivedPatterns

let x = <@@ fun y -> y + 100 @@>

let extractConstantValue = function
    | Lambda(_, SpecificCall <@@ (+) @@> (_, _, _ :: Value(:? int as constant, _) :: _)) -> constant
    | _ -> 0

printfn "Value of constant is %O" (extractConstantValue x)
// prints "Value of constant is 100"
</code>```

This gives you all the power to interpret and process expressions, including those generated via the query computation expression (clauses in query blocks are auto-quoted, i.e. turned into expressions by the compiler). So bearing that in mind, most type providers, such as OdataService and SqlEntityConnection, are parsers and consumers of query expressions.

Also, providers like Websharper translate expressions into Javascript.

You can't, as you alluded to, compile or evaluate expressions without the Powerpack. Other than that, the possible uses for F# expressions are the same as for .NET expressions. In simple cases, you could use them to describe operations, or to parse a mathematical expression, or to translate simple F# code into some other syntax.

Body:
It sounds like you're missing the ability to be able to parse an expression using pattern matching. For example:

open Microsoft.FSharp.Quotations.Patterns
open Microsoft.FSharp.Quotations.DerivedPatterns

let x = <@@ fun y -> y + 100 @@>

let extractConstantValue = function
    | Lambda(_, SpecificCall <@@ (+) @@> (_, _, _ :: Value(:? int as constant, _) :: _)) -> constant
    | _ -> 0

printfn "Value of constant is %O" (extractConstantValue x)
// prints "Value of constant is 100"

This gives you all the power to interpret and process expressions, including those generated via the query computation expression (clauses in query blocks are auto-quoted, i.e. turned into expressions by the compiler). So bearing that in mind, most type providers, such as OdataService and SqlEntityConnection, are parsers and consumers of query expressions.

Also, providers like Websharper translate expressions into Javascript.

You can't, as you alluded to, compile or evaluate expressions without the Powerpack. Other than that, the possible uses for F# expressions are the same as for .NET expressions. In simple cases, you could use them to describe operations, or to parse a mathematical expression, or to translate simple F# code into some other syntax.


问:
Is there any evidence that one of the current alternate JVM languages might catch on?
There's been a lot of enthusiasm about JRuby, Jython, Groovy, and now Scala and Clojure as the language to be the successor to Java on the JVM.

But currently only Groovy and Scala are in the TIOBE top 100, and none are in the top 50.  Is there any reason to think that any of this bunch will ever gain significant adoption?

My question is not primarily about TIOBE, but about any evidence that you might see that could indicate that one of these languages could get significant backing that goes beyond the enthusiasts.

答:
You're assuming that Java will decline (or is it declining already?).  Maybe it will, maybe not.

But at the same time, you're assuming both JVM and the Java libraries would survive (since none of these languages have any advantage without both).  How could that happen?

hum.... I think what I think is that both Scala and Groovy might grow but stay forever under the Java shadow, or die with it.

The other languages mentioned are just reimplementations, maybe one of them could be as popular as the main one; but if Java declines, it would return very quickly to the main platform, or a newer bytecode (LLVM? Parrot? CLR?)

Clojure seems to be in-betwen, it might be popular in a Java-friendly world; without Java, it could either die, or influence other Lisp variants without JVM dependency.  But i don't think it has any desirable feature over more mainline Lisps beyond JVM compatibility (which is a big drag, IMHO)


问:
Functions whose parameters are implicitly supplied
Callback functions are able to accept some parameters, but they are not explicitly declared when calling the function.

How does this actually work? What is going on that allows us to pass a function as a parameter to another function, and implicitly include a parameter in there?

For example:

Javascript

```<code>$.get('somefile.php', {func : 'getUserNames'}).done(function(data){
    if(data)
       console.log(data); // '{"0" : "billy", "1" : "bobby"}'
    // This is a js ajax call to a php file.
    // How exactly am I retrieving "data" ?
}, 'json');
</code>```

C#

```<code>private void BeginReadingData(){
    NetworkStream stream = tcpClient.GetStream();
    stream.BeginRead(buffer, 0, bufferSize, MyCallBack, tcpClient);
}

private void MyCallBack(IAsyncResult ar){
    // Now I can operate on 'ar'
    // why and how?
}
</code>```

This is something I understand how to use, just not how to explain or correctly describe the process.

答:
In C#, the callbacks are mere delegates. Delegates wrap your callback method inside a object and that object is passed as a parameter. So, whenever you are passing a callback function, lets say an event handler, that event handler is wrapped in a delegate object. Now when the proper time of invocation comes, the corresponding element, in your example, the 'NetworkStream' object checks whether any callback is registered. If found (in your case - 'MyCallback' is registered), it then invokes the registered callback.

In JavaScript, by design, methods are nothing but objects itself. so, whenever you are passing a callback function, you are passing a object. As JavaScript does compile, it does not check the signature of the callback you are passing. If it has the proper signature (e.g. - having proper number of parameters) the callback will receive all the values, if the signature is mismatched, your callback will miss the result values.


答:
The difference between class variables and instance variables, is simply a question of who knows what?.

An instance variable is only known (= bound) to that concrete instance - hence the name.

```<code>  public class Person {
       private String firstName;
       private String lastName;
  [...]
  }
</code>```

The definition of a class is like a blueprint for building concrete objects. Perhaps this point confuses you a bit. But writing it this way, every variable would be bound to its concrete object: e.g. Every person has its own firstName

A class variable on the other hand is - as the name says - known to each and every member of a class; or technically: It is known/ bound at class level. The typical example is a counter of how many objects, you have created - although it is a very problematic example; but that doesn't matter at this early stage.

```<code>  public class Person {
       private String firstName;
       private String lastName;
  [...]
       static int numberOfPersons = 0
  }
</code>```

numberOfPersons is declared static which is the keyword to distingush between class variables and instance variabes. The variable is declared like the others within the class definition. But the static keyword signals, that it is different.

firstName, lastName are instance variables and bound to that concrete instance

numberOfPersons is bound to the class, so that every instance could access this variable.

tl;dr

The place where variables are defined is the class definition.

Class variables are known at/bound to the class level, i.e. each concrete instance has access to it. To define a class variable, you use the keyword static.

Instance variables are only known at an instance level. You define them without the static keyword.

Further documentation for Java is here

Body:
The difference between class variables and instance variables, is simply a question of who knows what?.

An instance variable is only known (= bound) to that concrete instance - hence the name.

  public class Person {
       private String firstName;
       private String lastName;
  [...]
  }

The definition of a class is like a blueprint for building concrete objects. Perhaps this point confuses you a bit. But writing it this way, every variable would be bound to its concrete object: e.g. Every person has its own firstName

A class variable on the other hand is - as the name says - known to each and every member of a class; or technically: It is known/ bound at class level. The typical example is a counter of how many objects, you have created - although it is a very problematic example; but that doesn't matter at this early stage.

  public class Person {
       private String firstName;
       private String lastName;
  [...]
       static int numberOfPersons = 0
  }

numberOfPersons is declared static which is the keyword to distingush between class variables and instance variabes. The variable is declared like the others within the class definition. But the static keyword signals, that it is different.

firstName, lastName are instance variables and bound to that concrete instance

numberOfPersons is bound to the class, so that every instance could access this variable.

tl;dr

The place where variables are defined is the class definition.

Class variables are known at/bound to the class level, i.e. each concrete instance has access to it. To define a class variable, you use the keyword static.

Instance variables are only known at an instance level. You define them without the static keyword.

Further documentation for Java is here


答:
Just use shared_ptr directly, with your custom deleter. Maybe typedef it if you prefer.

This way you get correct move & copy constructors and assignment operators with no typing. You also get weak_ptr for free, if you want it.

Unless your code will add some actual functionality - or at least an interface compatible with some external requirement you didn't mention - the best thing you can possibly do is just not write it in the first place.

Look at Niall's SharedWrapper for a good example: unless you need that getData signature, it's a lot of code for no actual benefit. (This isn't a criticism: that was clearly written on the assumption that you do need the getData signature).

Title: Possible alternatives to copy constructors

Body:
In my C++ project I am relying on some libraries that do memory management for me. I make wrapper classes, for ease of use and memory safety, for example the class below. Note that this is a much simplified example, to demonstrate my problem.

```<code>#include <library>

class Wrapper {
private:
    lib_type* data;
public:
    Wrapper() : data(library_new()) {
    }
    Wrapper(const Wrapper& orig) = delete;
    ~Wrapper() {
        library_free(data);
    }
    const lib_type* getData() const {
        return data;
    }
    /* ... */
    /* Lots of functions for using the wrapped object */
};
</code>```

I needed to delete the copy constructor, because otherwise a copy going out of scope would invalidate the original object. Not being allowed to have copies makes the object very impractical to use - everywhere it is used I now need to hold a reference, and I need to manage the object centrally, which partially defeats the purpose of the wrapper class.

Possible solutions I have tried/thought of:

Copying the data. This is normally not an option though, because it is either not allowed by the library or the data is huge.

Move constructors. I tried solving the lack of a copy constructor by using a move constructor, but depending on the implementation, either this did not solve the problem or it became effectively a copy constructor, reintroducing the related problems.

Smart pointers. Then I realized it might be solved by using smart pointers to the wrapper instead of references, as this removes the need to maintain a central copy.

Wrapping a smart pointer. Or I could wrap a smart pointer to the data instead of a raw pointer. This makes the implementation of the wrapper a little bit more complicated, but also makes it easier to use, giving the classes using it a cleaner interface.

My attempt at the second smart pointer solution applied to the example above:

```<code>#include <library>

class Deleter {
public:
    void operator()(lib_type* p) const {
        library_free(p);
    }
};

class Wrapper {
private:
    shared_ptr<lib_type> data;
public:
    Wrapper() : data(library_new(), Deleter()) {
    }
    Wrapper(const Wrapper& orig) : data(orig.data) {
    }
    ~Wrapper() {
    }
    const lib_type* getData() const {
        return *data;
    }
    /* ... */
    /* Lots of functions for using the wrapped object */
};
</code>```

Now for the concrete question: is this a good solution? Or are there other, perhaps better solutions?

I am particularly worried about the getData implementation; whether I should return a copy of the shared pointer or a naked pointer and why.


答:
Note: This answer addresses the final part of the question. The bulk of the question has already been nicely addressed in Niall's answer.

I am particularly worried about the getData implementation; whether I should return a copy of the shared pointer or a naked pointer and why.

Suppose some code calls getData() and saves that pointer in some persistent object, and that the last remaining Wrapper object that references this pointer goes out of scope before this persistent object does. That persistent object now contains an invalid pointer.

To solve this problem, it would be much better to return the shared pointer. This runs into another problem, which is that your getData() currently returns a pointer to const lib_type. Returning a const shared_ptr<lib_type> will not do what you want, for two reasons. One is that this makes it possible for the caller of getData() to modify the data, something you don't want to happen. The other is that const is meaningless; it's like returning a const int. The compiler ignores that const. Instead, use

```<code>shared_ptr<const lib_type> getData() const {
    return data;
}
</code>```

The above takes advantage of the fact that a shared_ptr<some_type> automatically converts to a shared_ptr<const some_type>. The reverse (converting a shared_ptr<const some_type> to a shared_ptr<some_type>) is illegal (which is presumably the behavior you want).

One last remark: Those type names can get long and clunky. Presumably you are using std::shared_ptr rather than shared_ptr, and lib_type is presumably something like some_namespace::AMoreDescriptiveNameThanLibType. To specify the type of the value received from a call to getData, a user of your code would have to write

```<code>std::shared_ptr<const some_namespace::AMoreDescriptiveNameThanLibType> data =
    wrapper.getData();
</code>```

One way around this is to use auto:

```<code>    auto data = wrapper.getData();
</code>```

Another option is to provide some type definitions (or some type aliases) in your definition of Wrapper:

```<code>class Wrapper {
public:
    typedef std::shared_ptr<lib_type> dataT;
    typedef std::shared_ptr<const lib_type> const_dataT;
    // Rest of code elided
};
</code>```

Then your users only have to type

```<code>Wrapper::const_dataT data = wrapper.getData();
</code>```

Body:
Note: This answer addresses the final part of the question. The bulk of the question has already been nicely addressed in Niall's answer.

I am particularly worried about the getData implementation; whether I should return a copy of the shared pointer or a naked pointer and why.

Suppose some code calls getData() and saves that pointer in some persistent object, and that the last remaining Wrapper object that references this pointer goes out of scope before this persistent object does. That persistent object now contains an invalid pointer.

To solve this problem, it would be much better to return the shared pointer. This runs into another problem, which is that your getData() currently returns a pointer to const lib_type. Returning a const shared_ptr<lib_type> will not do what you want, for two reasons. One is that this makes it possible for the caller of getData() to modify the data, something you don't want to happen. The other is that const is meaningless; it's like returning a const int. The compiler ignores that const. Instead, use

shared_ptr<const lib_type> getData() const {
    return data;
}

The above takes advantage of the fact that a shared_ptr<some_type> automatically converts to a shared_ptr<const some_type>. The reverse (converting a shared_ptr<const some_type> to a shared_ptr<some_type>) is illegal (which is presumably the behavior you want).

One last remark: Those type names can get long and clunky. Presumably you are using std::shared_ptr rather than shared_ptr, and lib_type is presumably something like some_namespace::AMoreDescriptiveNameThanLibType. To specify the type of the value received from a call to getData, a user of your code would have to write

std::shared_ptr<const some_namespace::AMoreDescriptiveNameThanLibType> data =
    wrapper.getData();

One way around this is to use auto:

    auto data = wrapper.getData();

Another option is to provide some type definitions (or some type aliases) in your definition of Wrapper:

class Wrapper {
public:
    typedef std::shared_ptr<lib_type> dataT;
    typedef std::shared_ptr<const lib_type> const_dataT;
    // Rest of code elided
};

Then your users only have to type

Wrapper::const_dataT data = wrapper.getData();


问:
Do you actually write 'clean code'?
I have seen some programmers tweaking their code over and over again not only to make it 'work good', but also to make it 'look good'.

IMO, 'clean code' is actually a compliment indicating your code is elegant, perfectly understandable and maintainable. And the difference comes out when you have to choose between an aesthetically appealing code vs. code that's stressful to look at.

So, how many of you actually write 'clean code'? Is it a good practice? What are the other benefits or drawbacks of this?

答:
I would say I make an effort to write cleaner code, but that can change because of time constraints or if I'm working on something difficult. It tends to get messy when focusing on making it work. Then I'll go back and clean up as I review it. If you return to code and have to spend too much time refreshing your memory, you didn't comment it enough.

Clean code is good but like everything else, it just needs to be clean enough. Indenting 5 lines of code 4 spaces and one line 5 spaces doesn't increase the reading difficulty.

Title: Do you actually write 'clean code'?