问:
Testing Java as Groovy
We're looking into improving our testing process for some of our applications, and the idea that's been put forward it to write unit tests in Groovy and automatically run them with Maven.

The first application to get this treatment is written in Java, but I've been told that some of the classes being tested need to be renamed as ".groovy" files * and they will then be compiled as Groovy classes, not as Java classes. This renaming can all be done using Maven and Ant, but I'm concerned that if we compile our classes as Groovy classes, we're not actually testing them as Java classes, which is how they will be deployed.

During the demo, it was also shown that Groovy does not compile to the same bytecode that Java does. There was at least one Groovy-specific member that was added, called "metaClass" (there were others, I didn't get a good enough look at the screen). Apparently this is necessary for the testing framework they want to use, which is named Spock.

Am I right to be concerned about this? Does it matter?

  * I've been told this is for technical reasons that have to do with the way the application is built. I've been told that this does not apply to all classes, but to some.

答:
As far as I know, it is possible to write your unit tests in Groovy (.groovy files) while your actual application code stays pure Java, as long as your tests do not assume the use of advanced groovy features on top of Java application classes (such as mixins and categories - which decorate the Java class with a metaClass). From Groovy you can test POJO's getters and setters using standard java calls, without having the the boilderplate testing code that you often have in Java.  Groovy also allows you to easily implement mock objects of specific classes for testing (useful when testing API compliance for instance).

Groovy always has access to Java classes on the classpath. You just need the right libraries in the classpath used for testing and enable groovy compilation on your test sources. Just like the JUnit jar files are only used for unit tests, so can the groovy-all binary distribution be included during testing, but not be included in the class path at compile or run time of the application source itself.

I have no history with the Spock framework itself though, so I cannot comment on the validity of the information in that regard.

What it boils down to: as long as you compile your application classes using a java compiler (and not a groovy compiler), you will have the same byte-code, no matter what testing framework you use.

Title: Testing Java as Groovy


问:
Is there an idiom for a loop that executes some block of instructions between iterations? (In Ruby in particular)
I often need to do some operations in a loop and some other operations between the iterations.  A simple example would be collecting words from an array into a string, spelled backwards and separated with commas. Is there an idiom or language support for this in any language? (For now i am mostly interested in Ruby.)

I usually do something like

a = ['foo', 'bar', 'baz']
s = ''
n = a.size - 1
i = 0
loop do
  s << a[i].reverse
  break if i == n
  s << ', '
  i += 1
end
```

<p>But i know no way to save this half iteration if using a ruby iterator:</p>

<pre class="lang-rb prettyprint-override"><code>s = ''
['foo', 'bar', 'baz'].each do |w|
  s << w.reverse
  # ???
end
</code>```

答:
This is called the loop-and-a-half problem.  You've described a popular solution.

People who are into functional programming solve many instances of this with a function that is usually called reduce, which takes a list and performs a binary operation for every element but the first with the result of the previous calculation, and the next value.  This function is available in Ruby under both the names inject and reduce.  See http://ruby-doc.org/core-2.0/Enumerable.html#method-i-reduce for more.

ContentLicense: CC BY-SA 3.0


问:
Coding Guideline : Methods shouldn't contain more than 7 statements?
I was looking through the AvSol Coding Guidelines for C# and I agree with nearly everything but I'm really curious to see what other think of one specific rule.

AV1500

Methods should not exceed 7 statements  A method that requires more
  than 7 statements is doing too much, or has too many responsibilities.
  It also requires the human mind to analyze the exact statements to
  understand what the code is doing. Break it down in multiple small and
  focused methods with self-explaining names.

Do most of you follow this rule? Even if there's little to be saved from creating a new method (Your code is still DRY) aside from greatly increasing readability?  And is your number still as low as 7?    I would tend more toward 10.

I'm not saying I violate this rule all over the place--on the contrary, my methods are 95% small and focused but saying you should never violate this rule really blew me away.

I really just want to know what everyone thinks of NEVER violating this rule (It's a '1' on the coding standard--meaning NEVER do this).  But I think you'd have trouble finding a codebase that doesn't.

答:
All junior programmers should be forced to adhere to this principle. That would force them to think about the structure of what they're busy with, instead of just adding more and more lines code.

I'm currently looking at a method of 550 lines of code with lots of if else statements and continues and returns weaved into it. It's crap. Had the programmer only been forced to think about what he was doing...


答:
This is how you could do it in haskell:

```<code>let a = ["foo", "bar", "baz"]  --I've defined my "a" just like you defined it
Data.List.intercalate "," (map reverse a)  --here's the call that does what you want
"oof,rab,zab"  --this is the output
</code>```

The code in the parenthesis calls the reverse function on every element of "a" (eg: "foo" becomes "oof").  You take the result of that, and in another function you concatenate the elements together with "," in between them.

Here's the key thing to take away here:  Sometimes you have functions that change every element and returns another list (eg: map reverses every element, but it still returns a list).  Other times you have functions that take a list and returns one element (eg: intercalate will generate one string out of the list of strings you pass in).

These are two separate steps and your code will be easier to reuse if you keep them separate.

I know this isn't answered in ruby, but I'm hoping it's somewhat helpful.

Title: Is there an idiom for a loop that executes some block of instructions between iterations? (In Ruby in particular)

Body:
I often need to do some operations in a loop and some other operations between the iterations.  A simple example would be collecting words from an array into a string, spelled backwards and separated with commas. Is there an idiom or language support for this in any language? (For now i am mostly interested in Ruby.)

I usually do something like

a = ['foo', 'bar', 'baz']
s = ''
n = a.size - 1
i = 0
loop do
  s << a[i].reverse
  break if i == n
  s << ', '
  i += 1
end
```

<p>But i know no way to save this half iteration if using a ruby iterator:</p>

<pre class="lang-rb prettyprint-override"><code>s = ''
['foo', 'bar', 'baz'].each do |w|
  s << w.reverse
  # ???
end
</code>```

Body:
This is how you could do it in haskell:

let a = ["foo", "bar", "baz"]  --I've defined my "a" just like you defined it
Data.List.intercalate "," (map reverse a)  --here's the call that does what you want
"oof,rab,zab"  --this is the output

The code in the parenthesis calls the reverse function on every element of "a" (eg: "foo" becomes "oof").  You take the result of that, and in another function you concatenate the elements together with "," in between them.

Here's the key thing to take away here:  Sometimes you have functions that change every element and returns another list (eg: map reverses every element, but it still returns a list).  Other times you have functions that take a list and returns one element (eg: intercalate will generate one string out of the list of strings you pass in).

These are two separate steps and your code will be easier to reuse if you keep them separate.

I know this isn't answered in ruby, but I'm hoping it's somewhat helpful.


问:
Is the term 'Front-End' synonymous with 'Client-Side'? If so, is this always the case?
As a relatively new (self-taught) web developer, I've heard the terms front-end, client-side, back-end, and server-side quite often. To me, front-end and back-end were always synonymous with client-side and server-side, respectively.

However, as I've begun working with MVC frameworks like CodeIgniter, I've come across a few instances of front-end referring to basically anything the end user sees (including server-side code), while back-end has referred to anything the end-user doesn't see (including CMSs). Client-side and server-side, to me, are much more concrete in their meanings; they have a very distinct line separating them. Front-end and back-end, on the other hand, do not.

In a conversation I remember having with another web developer, he referred to CodeIgniter (in its entirety) as a front-end, and this threw me for a loop. I wasn't sure whether to correct him and say that CodeIgniter was my back-end, or if my definitions of the two terms were completely wrong.

Searching for definitions of front- and back-end confused me a bit more in some respects, though they did clarify a few things. I'd just like to know where the lines are drawn between these four terms, and how they piece together in the context of web development (specifically on a LAMP stack).

答:
I don't believe there is a formal definition for those terms, and as you noted there is overlap in some cases.

front-end and client-side overlap.

server-side and back-end also overlap.

If I were to split hairs, I would offer these rough boundaries:

client-side is an application that runs at the users' computer.  It could be a stand-alone application (more often) or it could refer to a web browser based interface (less likely).

front-end also faces the end-user and generally runs in a web browser based interface.  I haven't heard of thick clients being referred to as a front-end.

back-end refers to processes and services that are running either on another server or in the background of the users' computer.  More often than not, it refers to processes that are not on the end users' computer.  But the key, as you mentioned, is that the end user is not necessarily aware of the processes running.

server-side is an extension of back-end but explicitly reinforces the fact that the processes are running somewhere else and not on the end users' computers.

By way of example, and to highlight the confusion between the terms, I'll use Minecraft as an example.

Minecraft has a

client-side application when you run the jar files locally with your own JVM.

front-end if you choose to run the client application in your web browser

back-end process that can be running locally on your machine if you are in stand-alone mode

server-side process if you choose to log into a server hosting the Minecraft server application.

If you dig into some of Minecraft's statistics, you'll see that they simply designate a client and server component to the game; they don't necessarily care where those components are run.

To directly answer your questions:

Is the term 'Front-End' synonymous with 'Client-Side'?

Sort of, but not really.  There's a nuance between the terms if you are discussing things outside of the web based world.  If you're strictly within the web based world, then yes, they are functionally synonymous.

If so, is this always the case?

In the web world, I would say yes.  In other realms, I would say no as explained in the rough definitions I offered.


答:
Server-side runs on the server.  Client-side runs on the client.  Back-end is crunching data.  Front-end is displaying it.

Look at this web page.  Pulling all the comments from the database is server-side, back-end work.  Laying that data out in a template is front-end, server-side work.  The AJAX voting widgets and the fancy text input box are front-end, client-side.

Title: Is the term 'Front-End' synonymous with 'Client-Side'? If so, is this always the case?

Body:
As a relatively new (self-taught) web developer, I've heard the terms front-end, client-side, back-end, and server-side quite often. To me, front-end and back-end were always synonymous with client-side and server-side, respectively.

However, as I've begun working with MVC frameworks like CodeIgniter, I've come across a few instances of front-end referring to basically anything the end user sees (including server-side code), while back-end has referred to anything the end-user doesn't see (including CMSs). Client-side and server-side, to me, are much more concrete in their meanings; they have a very distinct line separating them. Front-end and back-end, on the other hand, do not.

In a conversation I remember having with another web developer, he referred to CodeIgniter (in its entirety) as a front-end, and this threw me for a loop. I wasn't sure whether to correct him and say that CodeIgniter was my back-end, or if my definitions of the two terms were completely wrong.

Searching for definitions of front- and back-end confused me a bit more in some respects, though they did clarify a few things. I'd just like to know where the lines are drawn between these four terms, and how they piece together in the context of web development (specifically on a LAMP stack).


问:
How to explain OOP to a matlab programmer?
I have a lot of friends who come from electrical / physical / mechanical engineering background, and are curious about what is "OOP" all about. They all know Matlab quite well, so they do have basic programming background; but they have a very hard time grasping a complex type system which can benefit from the concepts OOP introduces.

Can anyone propose a way I can try to explain it to them? I'm just not familiar with Matlab myself, so I'm having troubles finding parallels. I think using simple examples like shapes or animals is a bit too abstract for those engineers. So far I've tried using a Matrix interface vs array-based / sparse / whatever implementations, but that didn't work so well, probably because different matrix types are already well-supported in Matlab.

答:
I am an electrical engineer, but I have more in common with CS programmers than EE programmers. Specifically I have tried, without success, to persuade my fellow students to write at least half-way structured and modular code, let alone object-oriented code.

When I tried to use MATLAB's OO features, I quickly ran into very annoying issues. A method in a class HAS to take an object of that class as its first argument, and HAS to return the object if it's modifying the object. That makes for code like

```<code>methods
     function obj_new = modi_object(obj,some_other_data)
     ...
     end
...
end
</code>```

and usage like

```<code>new_obj = objec.modi_object(some_piece_of_data);
</code>```

I have almost given up. I suggest you leave them alone, until some decent OO support goes into MATLAB. Ask them instead to give up MATLAB and try to use Python or the like. I am attempting (and failing) to do that.

At the very least, MATLAB OO is in no way a nice gateway to learn OO. You might just put them off for life.

Body:
I am an electrical engineer, but I have more in common with CS programmers than EE programmers. Specifically I have tried, without success, to persuade my fellow students to write at least half-way structured and modular code, let alone object-oriented code.

When I tried to use MATLAB's OO features, I quickly ran into very annoying issues. A method in a class HAS to take an object of that class as its first argument, and HAS to return the object if it's modifying the object. That makes for code like

methods
     function obj_new = modi_object(obj,some_other_data)
     ...
     end
...
end

and usage like

new_obj = objec.modi_object(some_piece_of_data);

I have almost given up. I suggest you leave them alone, until some decent OO support goes into MATLAB. Ask them instead to give up MATLAB and try to use Python or the like. I am attempting (and failing) to do that.

At the very least, MATLAB OO is in no way a nice gateway to learn OO. You might just put them off for life.


问:
Should I use a parser generator or should I roll my own custom lexer and parser code?
What specific advantages and disadvantages of each way to working on a programming language grammar?

Why/When should I roll my own? Why/When should I use a generator?

答:
There are three options really, all three of them preferable in different situations.

Option 1: parser generators, or 'you need to parse some language and you just want to get it working, dammit'

Say, you're asked to build a parser for some ancient data format NOW. Or you need your parser to be fast. Or you need your parser to be easily maintainable.

In these cases, you're probably best off using a parser generator. You don't have to fiddle around with the details, you don't have to get lots of complicated code to work properly, you just write out the grammar the input will adhere to, write some handling code and presto: instant parser.

The advantages are clear:

It's (usually) quite easy to write a specification, in particular if the input format isn't too weird (option 2 would be better if it is).

You end up with a very easily maintainable piece of work that is easily understood: a grammar definition usually flows a lot more natural than code.

The parsers generated by good parser generators are usually a lot faster than hand-written code. Hand-written code can be faster, but only if you know your stuff - this is why most widely used compilers use a hand-written recursive-descent parser.

There's one thing you have to be careful of with parser-generators: the can sometimes reject your grammars. For an overview of the different types of parsers and how they can bite you, you may want to start here. Here you can find an overview of a lot of implementations and the types of grammars they accept.

Option 2: hand-written parsers, or 'you want to build your own parser, and you care about being user-friendly'

Parser generators are nice, but they aren't very user (the end-user, not you) friendly. You typically can't give good error messages, nor can you provide error recovery. Perhaps your language is very weird and parsers reject your grammar or you need more control than the generator gives you.

In these cases, using a hand-written recursive-descent parser is probably the best. While getting it right may be complicated, you have complete control over your parser so you can do all kinds of nice stuff you can't do with parser generators, like error messages and even error recovery (try removing all the semicolons from a C# file: the C# compiler will complain, but will detect most other errors anyway regardless of the presence of semicolons).

Hand-written parsers also usually perform better than generated ones, assuming the quality of the parser is high enough. On the other hand, if you don't manage to write a good parser - usually due to (a combination of) lack of experience, knowledge or design - then performance is usually slower. For lexers the opposite is true though: generally generated lexers use table lookups, making them faster than (most) hand-written ones.

Education-wise, writing your own parser will teach you more than using a generator. You have to write more and more complicated code after all, plus you have to understand exactly how you parse a language. On the other hand, if you want to learn how to create your own language (so, get experience at language design), either option 1 or option 3 is preferable: if you're developing a language, it will probably change a lot, and option 1 and 3 give you an easier time with that.

Option 3: hand written parser generators, or 'you're trying to learn a lot from this project and you wouldn't mind ending up with a nifty piece of code you can re-use a lot'

This is the path I'm currently walking down: you write your own parser generator. While highly nontrivial, doing this will probably teach you the most.

To give you an idea what doing a project like this involves I'll tell you about my own progress.

The lexer generator

I created my own lexer generator first. I usually design software starting with how the code will be used, so I thought about how I wanted to be able to use my code and wrote this piece of code (it's in C#):

```<code>Lexer<CalculatorToken> calculatorLexer = new Lexer<CalculatorToken>(
    new List<StringTokenPair>()
    { // This is just like a lex specification:
      //                    regex   token
        new StringTokenPair("\\+",  CalculatorToken.Plus),
        new StringTokenPair("\\*",  CalculatorToken.Times),
        new StringTokenPair("(",    CalculatorToken.LeftParenthesis),
        new StringTokenPair(")",    CalculatorToken.RightParenthesis),
        new StringTokenPair("\\d+", CalculatorToken.Number),
    });

foreach (CalculatorToken token in
             calculatorLexer.GetLexer(new StringReader("15+4*10")))
{ // This will iterate over all tokens in the string.
    Console.WriteLine(token.Value);
}

// Prints:
// 15
// +
// 4
// *
// 10
</code>```

The input string-token pairs are converted into a corresponding recursive structure describing the regular expressions they represent using the ideas of an arithmetic stack. This is then converted into a NFA (nondeterministic finite automaton), which is in turn converted into a DFA (deterministic finite automaton). You can then match strings against the DFA.

This way, you get a good idea how exactly lexers work. In addition, if you do it the right way the results from your lexer generator can be roughly as fast as professional implementations. You also don't lose any expressiveness compared to option 2, and not much expressiveness compared to option 1.

I implemented my lexer generator in just over 1600 lines of code. This code makes the above work, but it still generates the lexer on the fly every time you start the program: I'm going to add code to write it to disk at some point.

If you want to know how to write your own lexer, this is a good place to start.

The parser generator

You then write your parser generator. I refer to here again for an overview on the different kinds of parsers - as a rule of thumb, the more they can parse, the slower they are.

Speed not being an issue for me, I chose to implement an Earley parser. Advanced implementations of an Earley parser have been shown to be about twice as slow as other parser types.

In return for that speed hit, you get the ability to parse any kind of grammar, even ambiguous ones. This means you never need to worry about whether your parser has any left-recursion in it, or what a shift-reduce conflict is. You can also define grammars more easily using ambiguous grammars if it doesn't matter which parse tree is the result, such as that it doesn't matter whether you parse 1+2+3 as (1+2)+3 or as 1+(2+3).

This is what a piece of code using my parser generator can look like:

```<code>Lexer<CalculatorToken> calculatorLexer = new Lexer<CalculatorToken>(
    new List<StringTokenPair>()
    {
        new StringTokenPair("\\+",  CalculatorToken.Plus),
        new StringTokenPair("\\*",  CalculatorToken.Times),
        new StringTokenPair("(",    CalculatorToken.LeftParenthesis),
        new StringTokenPair(")",    CalculatorToken.RightParenthesis),
        new StringTokenPair("\\d+", CalculatorToken.Number),
    });

Grammar<IntWrapper, CalculatorToken> calculator
    = new Grammar<IntWrapper, CalculatorToken>(calculatorLexer);

// Declaring the nonterminals.
INonTerminal<IntWrapper> expr = calculator.AddNonTerminal<IntWrapper>();
INonTerminal<IntWrapper> term = calculator.AddNonTerminal<IntWrapper>();
INonTerminal<IntWrapper> factor = calculator.AddNonTerminal<IntWrapper>();

// expr will be our head nonterminal.
calculator.SetAsMainNonTerminal(expr);

// expr: term | expr Plus term;
calculator.AddProduction(expr, term.GetDefault());
calculator.AddProduction(expr,
                         expr.GetDefault(),
                         CalculatorToken.Plus.GetDefault(),
                         term.AddCode(
                         (x, r) => { x.Result.Value += r.Value; return x; }
                         ));

// term: factor | term Times factor;
calculator.AddProduction(term, factor.GetDefault());
calculator.AddProduction(term,
                         term.GetDefault(),
                         CalculatorToken.Times.GetDefault(),
                         factor.AddCode
                         (
                         (x, r) => { x.Result.Value *= r.Value; return x; }
                         ));

// factor: LeftParenthesis expr RightParenthesis
//         | Number;
calculator.AddProduction(factor,
                         CalculatorToken.LeftParenthesis.GetDefault(),
                         expr.GetDefault(),
                         CalculatorToken.RightParenthesis.GetDefault());
calculator.AddProduction(factor,
                         CalculatorToken.Number.AddCode
                         (
                         (x, s) => { x.Result = new IntWrapper(int.Parse(s));
                                     return x; }
                         ));

IntWrapper result = calculator.Parse("15+4*10");
// result == 55
</code>```

(Note that IntWrapper is simply an Int32, except that C# requires it to be a class, hence I had to introduce a wrapper class)

I hope you see that the code above is very powerful: any grammar you can come up with can be parsed. You can add arbitrary bits of code in the grammar capable of performing lots of tasks. If you manage to get this all working, you can re-use the resulting code to do a lot of tasks very easily: just imagine building a command-line interpreter using this piece of code.

ContentLicense: CC BY-SA 2.5

Body:
There are three options really, all three of them preferable in different situations.

Option 1: parser generators, or 'you need to parse some language and you just want to get it working, dammit'

Say, you're asked to build a parser for some ancient data format NOW. Or you need your parser to be fast. Or you need your parser to be easily maintainable.

In these cases, you're probably best off using a parser generator. You don't have to fiddle around with the details, you don't have to get lots of complicated code to work properly, you just write out the grammar the input will adhere to, write some handling code and presto: instant parser.

The advantages are clear:

It's (usually) quite easy to write a specification, in particular if the input format isn't too weird (option 2 would be better if it is).

You end up with a very easily maintainable piece of work that is easily understood: a grammar definition usually flows a lot more natural than code.

The parsers generated by good parser generators are usually a lot faster than hand-written code. Hand-written code can be faster, but only if you know your stuff - this is why most widely used compilers use a hand-written recursive-descent parser.

There's one thing you have to be careful of with parser-generators: the can sometimes reject your grammars. For an overview of the different types of parsers and how they can bite you, you may want to start here. Here you can find an overview of a lot of implementations and the types of grammars they accept.

Option 2: hand-written parsers, or 'you want to build your own parser, and you care about being user-friendly'

Parser generators are nice, but they aren't very user (the end-user, not you) friendly. You typically can't give good error messages, nor can you provide error recovery. Perhaps your language is very weird and parsers reject your grammar or you need more control than the generator gives you.

In these cases, using a hand-written recursive-descent parser is probably the best. While getting it right may be complicated, you have complete control over your parser so you can do all kinds of nice stuff you can't do with parser generators, like error messages and even error recovery (try removing all the semicolons from a C# file: the C# compiler will complain, but will detect most other errors anyway regardless of the presence of semicolons).

Hand-written parsers also usually perform better than generated ones, assuming the quality of the parser is high enough. On the other hand, if you don't manage to write a good parser - usually due to (a combination of) lack of experience, knowledge or design - then performance is usually slower. For lexers the opposite is true though: generally generated lexers use table lookups, making them faster than (most) hand-written ones.

Education-wise, writing your own parser will teach you more than using a generator. You have to write more and more complicated code after all, plus you have to understand exactly how you parse a language. On the other hand, if you want to learn how to create your own language (so, get experience at language design), either option 1 or option 3 is preferable: if you're developing a language, it will probably change a lot, and option 1 and 3 give you an easier time with that.

Option 3: hand written parser generators, or 'you're trying to learn a lot from this project and you wouldn't mind ending up with a nifty piece of code you can re-use a lot'

This is the path I'm currently walking down: you write your own parser generator. While highly nontrivial, doing this will probably teach you the most.

To give you an idea what doing a project like this involves I'll tell you about my own progress.

The lexer generator

I created my own lexer generator first. I usually design software starting with how the code will be used, so I thought about how I wanted to be able to use my code and wrote this piece of code (it's in C#):

Lexer<CalculatorToken> calculatorLexer = new Lexer<CalculatorToken>(
    new List<StringTokenPair>()
    { // This is just like a lex specification:
      //                    regex   token
        new StringTokenPair("\\+",  CalculatorToken.Plus),
        new StringTokenPair("\\*",  CalculatorToken.Times),
        new StringTokenPair("(",    CalculatorToken.LeftParenthesis),
        new StringTokenPair(")",    CalculatorToken.RightParenthesis),
        new StringTokenPair("\\d+", CalculatorToken.Number),
    });

foreach (CalculatorToken token in
             calculatorLexer.GetLexer(new StringReader("15+4*10")))
{ // This will iterate over all tokens in the string.
    Console.WriteLine(token.Value);
}

// Prints:
// 15
// +
// 4
// *
// 10

The input string-token pairs are converted into a corresponding recursive structure describing the regular expressions they represent using the ideas of an arithmetic stack. This is then converted into a NFA (nondeterministic finite automaton), which is in turn converted into a DFA (deterministic finite automaton). You can then match strings against the DFA.

This way, you get a good idea how exactly lexers work. In addition, if you do it the right way the results from your lexer generator can be roughly as fast as professional implementations. You also don't lose any expressiveness compared to option 2, and not much expressiveness compared to option 1.

I implemented my lexer generator in just over 1600 lines of code. This code makes the above work, but it still generates the lexer on the fly every time you start the program: I'm going to add code to write it to disk at some point.

If you want to know how to write your own lexer, this is a good place to start.

The parser generator

You then write your parser generator. I refer to here again for an overview on the different kinds of parsers - as a rule of thumb, the more they can parse, the slower they are.

Speed not being an issue for me, I chose to implement an Earley parser. Advanced implementations of an Earley parser have been shown to be about twice as slow as other parser types.

In return for that speed hit, you get the ability to parse any kind of grammar, even ambiguous ones. This means you never need to worry about whether your parser has any left-recursion in it, or what a shift-reduce conflict is. You can also define grammars more easily using ambiguous grammars if it doesn't matter which parse tree is the result, such as that it doesn't matter whether you parse 1+2+3 as (1+2)+3 or as 1+(2+3).

This is what a piece of code using my parser generator can look like:

Lexer<CalculatorToken> calculatorLexer = new Lexer<CalculatorToken>(
    new List<StringTokenPair>()
    {
        new StringTokenPair("\\+",  CalculatorToken.Plus),
        new StringTokenPair("\\*",  CalculatorToken.Times),
        new StringTokenPair("(",    CalculatorToken.LeftParenthesis),
        new StringTokenPair(")",    CalculatorToken.RightParenthesis),
        new StringTokenPair("\\d+", CalculatorToken.Number),
    });

Grammar<IntWrapper, CalculatorToken> calculator
    = new Grammar<IntWrapper, CalculatorToken>(calculatorLexer);

// Declaring the nonterminals.
INonTerminal<IntWrapper> expr = calculator.AddNonTerminal<IntWrapper>();
INonTerminal<IntWrapper> term = calculator.AddNonTerminal<IntWrapper>();
INonTerminal<IntWrapper> factor = calculator.AddNonTerminal<IntWrapper>();

// expr will be our head nonterminal.
calculator.SetAsMainNonTerminal(expr);

// expr: term | expr Plus term;
calculator.AddProduction(expr, term.GetDefault());
calculator.AddProduction(expr,
                         expr.GetDefault(),
                         CalculatorToken.Plus.GetDefault(),
                         term.AddCode(
                         (x, r) => { x.Result.Value += r.Value; return x; }
                         ));

// term: factor | term Times factor;
calculator.AddProduction(term, factor.GetDefault());
calculator.AddProduction(term,
                         term.GetDefault(),
                         CalculatorToken.Times.GetDefault(),
                         factor.AddCode
                         (
                         (x, r) => { x.Result.Value *= r.Value; return x; }
                         ));

// factor: LeftParenthesis expr RightParenthesis
//         | Number;
calculator.AddProduction(factor,
                         CalculatorToken.LeftParenthesis.GetDefault(),
                         expr.GetDefault(),
                         CalculatorToken.RightParenthesis.GetDefault());
calculator.AddProduction(factor,
                         CalculatorToken.Number.AddCode
                         (
                         (x, s) => { x.Result = new IntWrapper(int.Parse(s));
                                     return x; }
                         ));

IntWrapper result = calculator.Parse("15+4*10");
// result == 55

(Note that IntWrapper is simply an Int32, except that C# requires it to be a class, hence I had to introduce a wrapper class)

I hope you see that the code above is very powerful: any grammar you can come up with can be parsed. You can add arbitrary bits of code in the grammar capable of performing lots of tasks. If you manage to get this all working, you can re-use the resulting code to do a lot of tasks very easily: just imagine building a command-line interpreter using this piece of code.


问:
How do I transparently cache data in intermediate stages of processing?
I am working with MATLAB on a model reduction algorithm. It is basically a data processing pipeline.

```<code>ckt = generate_ckt(ckt_properties);
freq = generate_fpoints(fconfig);
result = freq_dom_sim(ckt,freq);
red_ckt = run_PRIMA(ckt, red_order);
</code>```

Each of these are potentially time consuming activities, being that the data I work with is pretty big (10000 × 10000 matrices). So in a previous implementation I had all of these as separate scripts that I had to execute one by one (manually or run a master script). Each of these stored the data in .mat files. The next program would read from this and write its own result in another directory. And so on.

What I would like to use is a framework that can store the dependencies between various pieces of data, such that at any point of time I can just ask it to generate the output.

It should :

Check if the variable is present in the workspace.

If it is, check if its consistent with the expected properties (check with the config data)

If not, load from file (the exact path to the file will be pre-specified).

Check if its consistent with the expected properties.

If not, compute it from the command associated with it. (pre-specified)

I would like this to be recursive, so that effectively I run the last module and it automatically runs checks and actually computes only those pieces of data that are not already available and consistent.

Can you give some suggestions on how to design this? If it is already called something (I assume it must) please point me to it.

答:
What you are describing in your ideal solution is very similar to what is provided by the make program and makefiles. A makefile essentially expresses a dependency graph from a set of output files, through a set of intermediate files, to a set of input files, along with commands to transform a file at one step to the next.

Inferring names for the various functions you mention above, you might get something like this:

```<code>ckt.mat : ckt_properties.mat
    matlab -r generate_ckt.m ckt_properties.mat

freq.mat : fconfig.mat
    matlab -r generate_fpoints.m fconfig.mat

result.mat : ckt.mat freq.mat
    matlab -r freq_dom_sim.m ckt.mat freq.mat

red_ckt.mat : ckt.mat red_order.mat
    matlab -r run_PRIMA.m ckt.mat red_order.mat
</code>```

This says that ckt.mat depends on ckt_properties.mat, and you can generate ckt.mat when you need to by running matlab generate_ckt.m ckt_properties.mat on the command line. "When you need to" means when the modification time of the source (ckt_properties.mat) is newer than that of the target (ckt.mat).

Now maybe you can do everything with files and makefiles, but this keeps you largely outside of Matlab's IDE. You could also do something purely within Matlab by creating a structure that mimics the aspects of the filesystem that make relies upon, namely file names, modification times, and contents. In other words, create structures that bind a matrix and a modification time (perhaps held as a simple scalar) under a name. Then you would need another structure that encodes the dependency relationships, which is essentially a list of tuples containing a target structure, a list of source structures, and a transformation function. All this is doable (and might even have been done, I don't know), but it might be easier to just use makefiles.

Body:
What you are describing in your ideal solution is very similar to what is provided by the make program and makefiles. A makefile essentially expresses a dependency graph from a set of output files, through a set of intermediate files, to a set of input files, along with commands to transform a file at one step to the next.

Inferring names for the various functions you mention above, you might get something like this:

ckt.mat : ckt_properties.mat
    matlab -r generate_ckt.m ckt_properties.mat

freq.mat : fconfig.mat
    matlab -r generate_fpoints.m fconfig.mat

result.mat : ckt.mat freq.mat
    matlab -r freq_dom_sim.m ckt.mat freq.mat

red_ckt.mat : ckt.mat red_order.mat
    matlab -r run_PRIMA.m ckt.mat red_order.mat

This says that ckt.mat depends on ckt_properties.mat, and you can generate ckt.mat when you need to by running matlab generate_ckt.m ckt_properties.mat on the command line. "When you need to" means when the modification time of the source (ckt_properties.mat) is newer than that of the target (ckt.mat).

Now maybe you can do everything with files and makefiles, but this keeps you largely outside of Matlab's IDE. You could also do something purely within Matlab by creating a structure that mimics the aspects of the filesystem that make relies upon, namely file names, modification times, and contents. In other words, create structures that bind a matrix and a modification time (perhaps held as a simple scalar) under a name. Then you would need another structure that encodes the dependency relationships, which is essentially a list of tuples containing a target structure, a list of source structures, and a transformation function. All this is doable (and might even have been done, I don't know), but it might be easier to just use makefiles.


问:
Is there a proper way to create a file format?
I'm building a proprietary file format for an application I wrote in C# .NET to store save information and perhaps down the line project assets. Is there a standard on how to do this in any way? I was simply going to Serialize my objects into binary and create a header that would tell me how to parse the file. Is this a bad approach?

答:
The most straight-forward method is probably to serialize your structure to XML using the XMLSerializer class. You probably wouldn't need to create a separate header and body structure - but serialize all assets into XML. This allows you to easily inspect / edit your file structure outside of your own program, and is easily manageable.

However, if your file structure is really complex, containing many different assets of different types, such that serializing the entire structure to XML is too burdensome, you might look at serializing each asset separately and compiling them into a single package using the Packaging library in C#. This is essentially how .docx, .xslx, .pptx, and other office file formats are constructed.

OwnerDisplayName: Corylulu


问:
How relevant are Brainbench scores when evaluating candidates?
I've seen many companies using certification services such as Brainbench when evaluating candidates. Most times they use it as a secondary screen prior to interview or as a validation to choose between candidates.

What is your experience with Brainbench scores? Did you try the tests yourself, and if so do you feel the score is meaningful enough to be used as part of a hiring process?

Difficult choice.

Consensus seems to be that BB cert are not very good as a certification.  The biggest argument was around the fact that some of the questions are too precise to form a good evaluation.  This view can probably be tempered somewhat but still, to hold someone's future solely on the results of this evaluation would be irresponsible.

That said, I still think it is possible to use them properly to gain additional objective knowledge on a candidate's level of expertise provided the test is done in a controlled environment ensuring that all taking it stand on equal footing.

Thus I went with the answer that best reflected this view keeping in mind that it is still just an hour long 50ish multiple choice question to evaluate skills and knowledge that take years to acquire.  To be taken with a grain of salt !

In short, the tests have value but whether or not they are worth the money is another debate.

Thanks all for your time.

答: I've worked in to the Information Technology fields for 20+ years. I started when there were not "any" IT Certifications. I actually have a few BrainBench certifications as well as other "Vendor Neutral" certifications, and I use them on my resume or on web sites. My Information Technology experience spans not only security, networking and hardware and software but also programming. My real world experience is what companies look for first, followed by the certifications that I have. The tests are comparable to other IT vendors, and are worth taking, no matter what your current skill set is.   </p>


答:
I generally find using client-side and server-side for describing development/developers is less vague. That portion of the client side where we're juggling/formatting data can be seen as being a back-end component. On the flip-side there's all the templating that tends to happen on the back end which being "for the front end" tends to result in people talking about them as front end Java or C# development. It's rare, but I've seen it in job descriptions.

But yes, generally speaking the front end is the part where the interaction happens. The back end is the part where all that interaction gets turned into something useful.


问:
Using the mouse as a multi-tool creates heavy conditional logic for executing commands, how do I change this?
The feature is in many different types of editing programs where a mouse click may have completely different commands to execute (using the Command Pattern)

Currently I have an overarching determineClickCommand(clickFocus) function.
The body essentially looked like this:

```<code>var command = null;
var args    = null;

if (clickFocus == x) {
    if (x.state == state) {
        args = // Code to detemine args
        command = new CommandA(args)
    } else {
        command = new CommandB()
    }
} else if (clickFocus == y) {
    args = blahablah;
    command = new CommandC(args)
} else if (clickFocus == z) {
    command = new CommandD()
} ...etc..etc...etc...

command.execute()
</code>```

Which was fine when I was prototyping, but I'd like a more elegant solution. Particularly since at some point, I'm going to want to take advantage of right-click/middle-click, which could add a third nested if statement

My first idea is to create a AbstractClickScope class with a determineClickCommand() method to be overridden in each concrete scope subclass. This breaks the problem into more maintainable classes, but the extensive conditional logic is the exact same. And if I were to decide to have many 'scopes' then a new class each time would be very annoying.

Or maybe have some sort of command factory class as opposed to a method? This isolates Command creation to a very specific part of the code.

Any other ideas? Or known implementations? Just throwing ideas out there and looking for more info as I think through this.

答:
You're looking for a way to eliminate some code bloat and simplify your interface, which is great. My suggestion is, instead of using if/else statements or switch/case blocks, use something more maintainable like a Dictionary/hashmap.

Here's the general idea of using a lookup hash. (This is pseudocode, so please excuse any syntax discrepancies and omitted code blocks.) Let's say you have the following classes:

```<code>class A {
    method1 () {}
    method2 () {}
}

class B {
    method3 () {}
    method4 () {}
}
</code>```

Instead of saying this:

```<code>if (clickFocus == x) {
    if (x.state == state) {
        // execute A.method1
    } else {
        // execute A.method2
    }
} else if (clickFocus == y) {
    // execute B.method3
} else if (clickFocus == z) {
    // execute B.method4
} ...etc..etc...etc...
</code>```

...you could store these calls in a hashmap with key/value pairs, like so:

```<code>class MouseHandler {
    public myHashMap = new Hashmap;
    myHashMap.x = A.method1; // Reference (or pointer) to function
    myHashMap.y = A.method2; // or possibly function body itself
    myHashMap.z = B.method3;
}
</code>```

Then, you can simply pass your clickFocus to the map as a parameter, which will return the function you want. So you'd have something like:

```<code>function getCommandForMouseEvent(clickFocus) { // return a function reference
    return MouseHandler.myHashMap[clickFocus];
}
</code>```

Note that this is really simplified, but doing something like this should cut down on your code a bit. (This may actually match one of the design patterns you mentioned. I really need to read up on those.) The other nice thing about this is that you can add keys to your hash during runtime, so you can register new functionality.

I hope that made some sense, and I hope it serves as a good starting point.

Body:
You're looking for a way to eliminate some code bloat and simplify your interface, which is great. My suggestion is, instead of using if/else statements or switch/case blocks, use something more maintainable like a Dictionary/hashmap.

Here's the general idea of using a lookup hash. (This is pseudocode, so please excuse any syntax discrepancies and omitted code blocks.) Let's say you have the following classes:

class A {
    method1 () {}
    method2 () {}
}

class B {
    method3 () {}
    method4 () {}
}

Instead of saying this:

if (clickFocus == x) {
    if (x.state == state) {
        // execute A.method1
    } else {
        // execute A.method2
    }
} else if (clickFocus == y) {
    // execute B.method3
} else if (clickFocus == z) {
    // execute B.method4
} ...etc..etc...etc...

...you could store these calls in a hashmap with key/value pairs, like so:

class MouseHandler {
    public myHashMap = new Hashmap;
    myHashMap.x = A.method1; // Reference (or pointer) to function
    myHashMap.y = A.method2; // or possibly function body itself
    myHashMap.z = B.method3;
}

Then, you can simply pass your clickFocus to the map as a parameter, which will return the function you want. So you'd have something like:

function getCommandForMouseEvent(clickFocus) { // return a function reference
    return MouseHandler.myHashMap[clickFocus];
}

Note that this is really simplified, but doing something like this should cut down on your code a bit. (This may actually match one of the design patterns you mentioned. I really need to read up on those.) The other nice thing about this is that you can add keys to your hash during runtime, so you can register new functionality.

I hope that made some sense, and I hope it serves as a good starting point.


问:
Ledger or log design for a point-based system?
Right now creating a new service that will integrate into our company's existing platform. The service will be responsible for tracking "points" that a user can generate over time through certain activities.

I am caught between two different methods of approach. I'm not sure whether to choose one of the following structures to continually manage points:

Create a "log" of points and instead keep one running total in the database, like a key/value field, where the value is the current points balance that is simply adjusted during each transaction.

Create a "ledger" system where each time the points are recalculated after a certain condition, but the entire ledger is assessed to determine the most up-to-date points balance.

Don't think it's relevant, but the backend DB is Riak.

Which has the least drawbacks, or is there a better way? How does the StackExchange point system work in relation to the above? Many thanks for the input!

答:
This isn't an either/or matter.

One thing that is pretty common in accounting systems is to implement a log-based system, but one with historical "closing balances" listed periodically, often in another table.  The closing balances can then serve as a roll-forward point in a report.  The benefits of such an approach is:

You can purge old data if you need to after x years.

Your reports don't have to aggregate more than an amount of data since the last data maintenance window closed and the old data is now read only).

In an RDBMS (not so sure about Riak), one would also have to have logic to prevent older records from being inserted before the roll-forward points.


问:
How can I cleanly separate first open tutorial code from my regular display code under OOP?
I have a MVC architecture, and I have the basic views completed. I now need to add the first user tutorial mode into the project. I don't want to add checks for first user state in all the views that need it, but the only alternative I can think of is to subclass everything and use those subclasses on first open. Is there a standard or widely-used practice for adding support for tutorials, etc. without making a mess of everything?

EDIT: I was unclear in my question.

I'm talking about tutorials that a user encounters when first using the app -- in our case we want to add visual effects to direct their attention to key UI elements. I wrote "first user state" to mean we store state about the number of uses on a local machine and use that to determine if display is necessary. Usually I would add some kind of edge case code to the views, say, if User.firstUse() arrowView.show();, but I was wondering if there's a cleaner way to partition that kind of code from regular code.

答:
The main thing here is that you want to decouple the "first view" tutorial content from the rest of your program, so that you can remove that content cleanly from the UI after the user has seen it once. There are a number of design patterns that would let you do that; here are three:

decorator: Augment the functionality of an object foo by containing it in another object bar (the decorator) that has a similar interface and calls through to foo for each method. bar is used in the program in place of foo, so every time a method in the interface is called bar gets a chance to take some action, including modifying the way foo responds to the method.

delegation: A "helper" object is used to modify the behavior of the delegating object(s). For example, if you're following MVC, your view object could employ a delegate that inserts the tutorial material. When certain interesting events happen (view appears, user clicks a subview, view disappears, etc.) the view could offer the delegate a chance to respond. Once the user has seen the tutorial you can just skip creating the delegate and the tutorial material won't show up.

observer: Your view would send messages to any registered observer objects at interesting points in the program. Objects using the observer pattern are so loosely coupled that it's usually difficult for the observer to modify the behavior of the observed object, but that may not be necessary. For example, if you can provide a transparent view that overlays the regular UI, that view could observe what's happening in the UI and display tutorial content as necessary. When you don't want the tutorial, don't create the overlay.

Some of these patterns have potential to help you do more than just provide the tutorial content. If you were to implement my example in observer, for instance, you could use the same mechanism to display diagnostic information instead of tutorial content, so that debugging becomes easier.


问:
Nested Enum type in C++ or C#?
I've come across a recurring issue in a few of my recent projects in which I find myself using enums to represent state, or type, or something else, and I need to check against a few conditions. Some of these conditions span multiple enums, so I end up with a load of logic in switch and if blocks, which I don't like. This is a particular problem when having to cast things to and from the enum, like when the enum is being used to check an int that you're getting from a web request or a calculation.

Is there something in C++ or C# that can be used as a nested enum? Something like this:

```<code>enum Animal
{
    Mammal
    {
        Cat,
        Dog,
        Bear
    },
    Bird
    {
        Pigeon,
        Hawk,
        Ostrich
    },
    Fish
    {
        Goldfish,
        Trout,
        Shark
    },
    Platypus    //srsly what is that thing
};
</code>```

Obviously, it may or may not be declared like that, but you get the idea. The point is that in code you could use it like Animal thisAnimal = Animal.Mammal.Cat and then later check if (thisAnimal.IsMember(Animal.Mammal)) or something like that.

I've seen Java's EnumSet, and found them pretty useful, but I don't think they're an exact match for the functionality I'm after. For this example, you'd have to declare an enum with all the animals at one level, and then add them all to the relevant sets. That would mean that when using the original enum, higher-level things like Mammal or Invertebrate would appear on the same "level" as something very specific like African Swallow, which would imply that they were (to some degree) interchangeable, which isn't true. In theory, a nested structure as above might allow you to specify the level of "specificness" needed, so you could get this:

```<code>enum Animal::Kingdom.Order.Family.Genus.Species
{ /*stuff*/ }

Organism::Kingdom.Phylum.Class.Order.Family thisThing;

thisThing = Animalia.Cordata;                               //compiler error
thisThing = Animalia.Chordata.Aves.Passeri.Hirundinidae;    //compiles OK
</code>```

Does a structure like this exist anywhere? If not, how might I build one for C++ and/or C# and have it remain as generic and re-usable as possible?

答:
My solution would be to use bit flags. If you are not familiar see here. The general idea is simple yet still falls in line with your need to use enums.

Each grouping of, for lack of a better work, classes, is just a span of bits. So for mammals you just delegate a stretch of bits. In your case you would have your None(0x0) organism, perhaps the Platypus. Then 0x1 is Cat, 0x2 is dog, 0x4 is bear. To check for inclusion in the Mammals category just AND it with a 7 and be sure the result is the value being checked.

To check for inclusion in the Animal kingdom you would just AND it with the all bit flagged stretch of values you have.

This is not exactly the best technique for scalability but it may be the functionality you are looking for.

Title: Nested Enum type in C++ or C#?


问:
How Should "Undo Typing" Behave?
I'm implementing a Java app that includes an Undo/Redo stack. I've noticed that some apps (such as TextEdit on Mac OS X) let you choose "Undo Typing" from the Edit Menu after typing some text. I'd like to implement that sort of thing into my app as well, but I'm having a really hard time finding guidelines about how it should behave.

With some trial and error, my best guess about how TextEdit's Undo Typing behaves is:

When the user types a new character (or types the delete key), merge it into the previous Undo Typing item if one is at the top of the Undo stack, unless one of the following situations occurs

Always create a new Undo Typing item after the user continues to type after at least 15 seconds of inactivity

Always create a new Undo Typing item after the user is typing for an extended period of time and some condition is met (couldn't figure out if this was time based or character count based).

Always create a new Undo Typing item when any text is selected and then deleted or overwritten (selecting text, not making a change, then returning to the original insertion point and continuing to type does not trigger this)

In practice, Apple's strategy seems to work (at least it works for me when I type), but as noted by the last point, I haven't really been able to figure out the rules. Also, it seems like other programs follow different rules, such as Microsoft Word. Google has not turned up a defined list of rules for any implementation of Undo Typing and I haven't come across any best practices for how it should behave. So how should it behave? Or is it just up to the whims of the programmer?

EDIT: Just to clarify, I'm not interested in implementation details right now. I'm especially curious as to whether or not an authoritative reference (e.g. best practices or user interface document) exists describing this or a description of how it is implemented across multiple products.

答:
on keydown -> timer representing your idle starts

on keydown/timer-running -> reset timer

on keydown/no timer-running -> readjust cell blocks to prepare for a new preserved state as position changes

idle-timer runs down -> Establish a new undo state

I wouldn't track keypress identities. I'd split into cellular blocks of text (by character count) that allow you to track position by offsets from the nearest cell's beginning positions so you don't have to save the entire state of a tolstoy novel every time an idle timer runs down. Readjusting those offsets when cells before other cells get edited is the tricky part.

Title: How Should "Undo Typing" Behave?


答:
This is one of the jobs that graphical user interface frameworks do for you. A typical GUI framework will employ a hierarchy of views and a way to find the particular view for a given coordinate. When the mouse does something (moves, button down, button up, etc.) the framework finds the relevant view and sends it an appropriate message, like "the left mouse button went down at local coordinates (127, 225)". It's then up to the view to decide what to do with that information, and each view is free to take whatever action is necessary. For example, a button might ignore the coordinates and just redraw itself in a selected state, while a text view might move the insertion point.

If you're working with a GUI framework, you shouldn't have to worry too much about dealing directly with the mouse. Find out how your framework does it and employ that mechanism. If you're trying to write your own framework, it'd probably be a good idea to survey two or three existing frameworks and find out how they work -- you'll find that there's a lot of commonality, and you'll probably want your framework to do roughly the same thing.

Title: Using the mouse as a multi-tool creates heavy conditional logic for executing commands, how do I change this?

Body:
The feature is in many different types of editing programs where a mouse click may have completely different commands to execute (using the Command Pattern)

Currently I have an overarching determineClickCommand(clickFocus) function.
The body essentially looked like this:

```<code>var command = null;
var args    = null;

if (clickFocus == x) {
    if (x.state == state) {
        args = // Code to detemine args
        command = new CommandA(args)
    } else {
        command = new CommandB()
    }
} else if (clickFocus == y) {
    args = blahablah;
    command = new CommandC(args)
} else if (clickFocus == z) {
    command = new CommandD()
} ...etc..etc...etc...

command.execute()
</code>```

Which was fine when I was prototyping, but I'd like a more elegant solution. Particularly since at some point, I'm going to want to take advantage of right-click/middle-click, which could add a third nested if statement

My first idea is to create a AbstractClickScope class with a determineClickCommand() method to be overridden in each concrete scope subclass. This breaks the problem into more maintainable classes, but the extensive conditional logic is the exact same. And if I were to decide to have many 'scopes' then a new class each time would be very annoying.

Or maybe have some sort of command factory class as opposed to a method? This isolates Command creation to a very specific part of the code.

Any other ideas? Or known implementations? Just throwing ideas out there and looking for more info as I think through this.


问:
How do I learn linking compiling, makefile quickly? Any book recommendations?
I'm very good at programming in C++ but when it gets to linking and the other important stuffs I feel very ignorant. I want to learn allegro without wasting time. So please suggest a book or a resource to learn the concepts mentioned above. Thanks a lot in advance.</p>

答:
Linkers and Loaders by Levine was very good.  We use this textbook at OSU in our Assembler, Linker, Loader, Compiler Design course.

link here to amazon


答:
Well, there are times what you describe can be a very bad approach.  This is assuming when you say 'serialize' you're talking about using a language/framework's ability to simply take an object and output directly to some sort of binary stream.  The problem is class structures change over the years.  Will you be able to reload a file made in a previous version of your app if all your classes change in a newer one?

For long term stability of a file format, I've found it better to roll up your sleeves a little bit now and specifically write your own 'serializing'/'streaming' methods within your classes.  ie, manually handle the writing of values to a stream.  Write a header as you state that describes the format version, and then the data you want saved in the order you want it in.  On the reading side, handling different versions of the file format becomes a lot easier.

The other option of course is XML or JSON.  Not necessarily the greatest for binary heavy content, but simple and human readable... a big plus for long term viability.

Title: Is there a proper way to create a file format?

Body: I'm building a proprietary file format for an application I wrote in C# .NET to store save information and perhaps down the line project assets. Is there a standard on how to do this in any way? I was simply going to Serialize my objects into binary and create a header that would tell me how to parse the file. Is this a bad approach?


问:
Should every front-end developer understand the basic aspects of design?
I'd say that we're developing software in a world where the front-end of an application is probably the most important. The increasing ability for a user to access and interact with software almost instantly in the cloud is making the first few minutes of user interaction crucial in determining whether the application will get any further attention, making UI design and the "intuitiveness" of the application extremely important factors.

As a developer, I've never really appreciated the important of the design of my applications. I usually write the code that works, and take advice from either a graphics designer or project leader on ways to improve the usability / look of the app. But maybe this isn't the way to develop any more. I can't help but wonder the time and resources wasted on a developer being told by a graphics designer to move a button 2 pixels to the left (for example) when, if that developer had a basic understanding of software front-end design, they'd be able to make the decision themselves.

I can understand large design decisions, such as the overall look of an application and the global fonts used etc, are all jobs that should be done by someone with the appropriate knowledge of such an arena, but should we, as the developers of the front-end, know enough of design theory to be able to make smaller design decisions by ourselves?

Should the front-end design of
software and some basics of user
interaction be taught alongside the
current programming package?

What level of knowledge should a developer expect to have in regards to user interaction & design?

Should an understanding of design hold a higher ground than it does at present in the context of resumés and qualifications?

The subject is somewhat of a hobby for me, I find it fascinating studying users' interaction with a program, but it should it be part of the core of software development?

Just to clarify, when I talk about "design" I'm talking about front-end design, rather than the design of the software architecture (something which every developer should understand).

答:
Like aesthetic design? It's kind of hard not to learn a thing or two when you spend most of your Jr. career converting PSDs into perfect HTML/CSS replicas but I've never felt bad for my inability to pick a color scheme or design a logo to save my life.

Where every front end dev should devote a fair amount of thought (and they generally do in my experience) is more on general  usability and practical user-interaction design. If you're not really interested in those things I can't imagine how you could possibly want to actually work on UI for a living.

That said, I'll be the first to jump on a graphic designer trying to put two overly similar background and font colors together or who doesn't appear to get that paragraphs are a lot easier to read when they're not spread too far out horizontally. But usually the designers get it too. In my experience it's critical we consider this stuff in part because sometimes self-proclaimed UI nerds of the non-coding/designing variety (i.e. managers/business owners with Steve Jobs complexes) forget the user for the elaborate snazzy UI they've imagined will be ever so wonderful and somebody has to be a champion for the user.

IMO, the worst way to have front end devs and designers work together is to have the designer and/or user-interaction specialists (who are sometimes a bit overly academic for my taste) draw up a blueprints and then hand them off waterfall-style without any feedback from experienced UI devs. We should be building prototypes from biz reqs before we ever see designs and UI devs should always be involved in initial design conversations where anything more than static content is involved. Not just so we can cast no-votes but also so we can make people aware of the things that might be more in our grasp than they realize on the complexity front.

Ultimately however, there's nothing I love more than working with a strong designer with good instincts. Using space supremely well takes a mix of talent, knowledge and experience-honed instincts that I suspect I could never develop to the levels I've seen among more proficient designers out there.

OwnerDisplayName: EMMERICH


问:
How to avoid giant glue methods?
In my current job, I've been tasked with cleaning up old code a few times.  Often the code is a labyrinth and the data behind it is even more tangled.  I find myself combing out things into nice, neat, modular methods.  Each method does one thing and does it well.  That's when things start to go south...

Invariably, I end up with a clean API and no real way to tie it all together.  The solution has been to write a big ugly "glue" method (generally full of conditional statements) that eventually calls all of my "clean" methods.

The glue method usually ends up being a terse version of the tangle of code/data that I was attempting to clean up.  It's generally more readable, but it's still annoying.

How can I avoid such methods?  Is this a symptom of the tangled data or a reflection of something that I'm doing wrong?

答:
I will give you our experience refactoring LedgerSMB.  We made a decision to do things differently early on and are still doing exactly what you describe but without a lot of glue methods (we have a few glue methods btw, just not a lot).

Life with Two Codebases

LedgerSMB has survived with two codebases for about 5 years and it will be several more before the old codebase is eliminated.  The old codebase is a true horror to behold.  Bad db design, Perl constructs like IS->some_func(\%$some_object); along with code which shows exactly why the spaghetti metaphor is sometimes used (execution paths meandering between modules and back, and between languages, with no rhyme or reason).  The new codebase avoids this by moving db queries into stored procedures, having a cleaner framework for request handling, and much more.

The first thing we decided to do was to try to refactor module by module.  This means moving all functionality in a specific area into a new module and then hooking the old code into the new module.  If the new API is clean, this isn't a big deal.  If the new API is not things get hairy and that's an invitation to work a little harder at the new API....

The second thing is that there are plenty of times when new code has to access logic in old code.  This is to be avoided to the extent possible because it leads to glue methods that are ugly but one can't always avoid it.  In this case the glue methods should be minimized and avoided to the extent possible but used when necessary.

To make this work you have to commit to rewriting all functionality in a specific area.  If you can, for example, rewrite all customer information tracking code at once, that means that the code which calls this from the old code is not hard to work with, and dispatching to the old code from the new code is minimized.

The second thing is that if you have reasonable abstractions in your place, you should be able to choose which level of the API to call and how to keep that clean.  However, you should think about rewriting the portions that are calling your API so that they are quite a bit cleaner as well.

There are many areas of business tools that are irreducibly complex.  You can't get rid of all complexity.  But you can manage it by focusing on clean API's which specifically do what you need to do, and modules which utilize that API constructively.  Glue should be a last resort only after considering that rewriting the rest of the calling code may be faster.

Title: How to avoid giant glue methods?


问:
How to organise Website CSS
I understand the concept of CSS. But on many projects I've found that I tend to lose myself and end up with a millions CSS files for a millions different pages!

I realise that the point of CSS is that it cascades. Otherwise it would just be a style sheet!

I would just like people to shed some light on how they use CSS to its full potential! On my current website I've got a MasterPage and one css file for that. then for all the sub pages i tend to write a separate css for every 5 pages or so. I dont like my css files to be HUGE cos then i just get confused.

How do you do it? I find it hard to comprehend that some people use one css file for the WHOLE website. or is that the done thing?

答:
Here. Where I ranted at the ID thing and then basically answered this question:

https://stackoverflow.com/a/12102693/450222

Also, it's okay if it's just a style sheet and doesn't cascade at every opportunity.

Title: How to organise Website CSS


问:
A simple definition of client-server
I'm looking for a simple definition of the concept of “client-server”

I'd like something similar to this definition of state.

... That "thing/information" that you need to remember is called "state".

Edit - This isn't a homework question (nor am I a student). My goal is to come up with a compact way of explaining REST to average developers. I didn't want to prejudice the response though.

答:
One possibility is something like:

A client-server scheme is one in which the consumer (client) and producer (server) of a resource are designed to communicate by passing messages (intelligible objects that can exist independently of the client and server).

Title: A simple definition of client-server


答: You could use the State design pattern for this. It looks like you have a different situation for each value of clickFocus, so you could put the code to handle the click onto those objects. This removes that huge chain of if-else cases in the method.


答:
From Wikipedia:

A server is a computer system that selectively shares its resources; a client is a computer or computer program that initiates contact with a server in order to make use of a resource.

Title: A simple definition of client-server

Body:
I'm looking for a simple definition of the concept of “client-server”

I'd like something similar to this definition of state.

... That "thing/information" that you need to remember is called "state".

Edit - This isn't a homework question (nor am I a student). My goal is to come up with a compact way of explaining REST to average developers. I didn't want to prejudice the response though.


答:
client/server refers to a relationship between two networked computers in which one machine (the client) initiates a connection and makes requests of the other machine (the server), which in turn to fulfill those requests. Servers exist to provide a service which clients consume.

Also, have you checked the Wikipedia article on REST? The second paragraph gives a similar definition which may help:

REST-style architectures consist of clients and servers. Clients
  initiate requests to servers; servers process requests and return
  appropriate responses. Requests and responses are built around the
  transfer of representations of resources. A resource can be
  essentially any coherent and meaningful concept that may be addressed.
  A representation of a resource is typically a document that captures
  the current or intended state of a resource.

Title: A simple definition of client-server


问:
How to invoke anonymous functions in testing?
Below is Java code.

I need to cover the below function. I searched for many websites, but I still have no ideas. Is there any methods to cover the override anonymous classes?

```<code>  public static void addEnterListener(Text text, final String methodName, final Object callee) {
    text.addKeyListener(new KeyListener() {
    @Override
    public void keyReleased(KeyEvent arg0) {
    if (arg0.keyCode == '\r') {
      try {
        Method method = callee.getClass().getMethod(methodName, KeyEvent.class);
        method.invoke(callee, arg0);
      } catch (Exception e) {e.printStackTrace();}
    }
  }

  @Override
  public void keyPressed(KeyEvent arg0) {
  }
});
}
</code>```

答:
No, there is no way to do that with annonymous classes.

You can refactorize your code so:

```<code>  public static void addEnterListener(Text text, final String methodName, final Object callee) {
    text.addKeyListener(new MyKeyListener());
  }

  class MyKeyListener implements KeyListener {
    @Override
    public void keyReleased(KeyEvent arg0) {
      if (arg0.keyCode == '\r') {
        try {
          Method method = callee.getClass().getMethod(methodName, KeyEvent.class);
          method.invoke(callee, arg0);
        } catch (Exception e) {e.printStackTrace();}
      }
    }

    @Override
    public void keyPressed(KeyEvent arg0) {
    }
  }
</code>```

Body:
No, there is no way to do that with annonymous classes.

You can refactorize your code so:

  public static void addEnterListener(Text text, final String methodName, final Object callee) {
    text.addKeyListener(new MyKeyListener());
  }

  class MyKeyListener implements KeyListener {
    @Override
    public void keyReleased(KeyEvent arg0) {
      if (arg0.keyCode == '\r') {
        try {
          Method method = callee.getClass().getMethod(methodName, KeyEvent.class);
          method.invoke(callee, arg0);
        } catch (Exception e) {e.printStackTrace();}
      }
    }

    @Override
    public void keyPressed(KeyEvent arg0) {
    }
  }


答:
There are now tools available to organize scripts and stylesheets, what you need depends totally on what development environment you're running it in. What is clear is that you don't need to maintain one gigantic file.

Bundling and minification

In a deployed environment you want to keep the number of requests that users do on a web page as low as possible. The reason for this is that you get faster page loads if less requests are done.

However that doesn't mean that you need to develop it as one file; you can use a build tool to concatenate the source files as one. And once you have a build tool to concatenate you might as well want to minify it (so that it takes less bytes send, which is a good thing).

The easiest way to get started is to write some batch script or a build script that concatenates the files and runs the concatenated file through a minifier such as the YUI Compressor. There might however already exist in your development environment tools that do this already.

Superset languages

Other than that I prefer to use superset languages such as Less or Sass/Compass to create my stylesheets. The extra features you get is awesome, such as: variables, arithmetic, mixins, helper functions. Once you use it you rarely want to go back to write vanilla css. Here the process is the same as above, you compile (or have the tool watch for changes) the source down to the file that eventually will be used.

There are also superset languages for javascript such as coffeescript and typescript that works the same way; augument with new features and compile down to the actual file that will be used by the web site.

My tools

In MVC4.NET I prefer to use the built-in System.Web.Optimizations bundling feature with BundleTransformer so I can use superset languages (it also works in MVC3 but requires some configuration to do). It is pretty much automatic, you can see the actual sources while developing and once the debug flag is unset it will compile and minify the files automatically for production environment.

I also use superset languages in other environments, mostly the ones that are easiest to use:

nodejs have stylus pretty much natively for stylesheets, and coffeescript is quite easy to get it working

ruby/rails has sass/compass natively and coffeescript has been supported by the community for a long while

Other tools worth mentioning

YUI compressor - compresses javascript and css files

Closure Compiler - compiles javascript

Title: How to organise Website CSS

Body:
I understand the concept of CSS. But on many projects I've found that I tend to lose myself and end up with a millions CSS files for a millions different pages!

I realise that the point of CSS is that it cascades. Otherwise it would just be a style sheet!

I would just like people to shed some light on how they use CSS to its full potential! On my current website I've got a MasterPage and one css file for that. then for all the sub pages i tend to write a separate css for every 5 pages or so. I dont like my css files to be HUGE cos then i just get confused.

How do you do it? I find it hard to comprehend that some people use one css file for the WHOLE website. or is that the done thing?


问:
Is there an idiom for a loop that executes some block of instructions between iterations? (In Ruby in particular)
I often need to do some operations in a loop and some other operations between the iterations.  A simple example would be collecting words from an array into a string, spelled backwards and separated with commas. Is there an idiom or language support for this in any language? (For now i am mostly interested in Ruby.)

I usually do something like

a = ['foo', 'bar', 'baz']
s = ''
n = a.size - 1
i = 0
loop do
  s << a[i].reverse
  break if i == n
  s << ', '
  i += 1
end
```

<p>But i know no way to save this half iteration if using a ruby iterator:</p>

<pre class="lang-rb prettyprint-override"><code>s = ''
['foo', 'bar', 'baz'].each do |w|
  s << w.reverse
  # ???
end
</code>```

答:
Unfortunately, there is no intercalate like in @tieTYT's answer in ruby. Array#reduce can be used but - e.g. in your example - you have to keep an eye on the order of the elements (reversal of the accumulator memo).

an example in ruby could look like this:

```<code>arr = ["foo", "bar", "baz", "goo"]
puts arr.inspect
red = arr.reduce {|memo, item, err|
    "#{memo == arr.first ? memo.reverse : memo}, #{item.reverse}"
}
puts red # -> oof, rab, zab, oog
</code>```

your example - joining the elements of an array together into a string - can easily accomplished with Array#map followed by Array#join (join is like haskell's intercalate, but it does not accept a block in ruby) like:

```<code>arr.map{|ele| ele.reverse}.join(", ")
</code>```

after your comment to @btilly:

IMHO, both look acceptably clear as one-liners in e.g. erb, though the second one is clearly more readable.

```<code><%= arr.reduce{|memo, item| "#{memo == arr.first ? memo.reverse : memo}, #{item.reverse}" } %>
<%= arr.map{|ele| ele.reverse}.join(", ") %>
</code>```

anyway you can always assign the result to a variable upstream.

Body:
Unfortunately, there is no intercalate like in @tieTYT's answer in ruby. Array#reduce can be used but - e.g. in your example - you have to keep an eye on the order of the elements (reversal of the accumulator memo).

an example in ruby could look like this:

arr = ["foo", "bar", "baz", "goo"]
puts arr.inspect
red = arr.reduce {|memo, item, err|
    "#{memo == arr.first ? memo.reverse : memo}, #{item.reverse}"
}
puts red # -> oof, rab, zab, oog

your example - joining the elements of an array together into a string - can easily accomplished with Array#map followed by Array#join (join is like haskell's intercalate, but it does not accept a block in ruby) like:

arr.map{|ele| ele.reverse}.join(", ")

after your comment to @btilly:

IMHO, both look acceptably clear as one-liners in e.g. erb, though the second one is clearly more readable.

<%= arr.reduce{|memo, item| "#{memo == arr.first ? memo.reverse : memo}, #{item.reverse}" } %>
<%= arr.map{|ele| ele.reverse}.join(", ") %>

anyway you can always assign the result to a variable upstream.


问:
Is this an appropriate use of Mockito's reset method?
I have a private method in my test class that constructs a commonly used Bar object. The Bar constructor calls someMethod() method in my mocked object:

```<code>private @Mock Foo mockedObject; // My mocked object
...

private Bar getBar() {
  Bar result = new Bar(mockedObject); // this calls mockedObject.someMethod()
}
</code>```

In some of my test methods I want to check someMethod was also invoked by that particular test. Something like the following:

```<code>@Test
public void someTest() {
  Bar bar = getBar();

  // do some things

  verify(mockedObject).someMethod(); // <--- will fail
}
</code>```

This fails, because the mocked object had someMethod invoked twice. I don't want my test methods to care about the side effects of my getBar() method, so would it be reasonable to reset my mock object at the end of getBar()?

```<code>private Bar getBar() {
  Bar result = new Bar(mockedObject); // this calls mockedObject.someMethod()
  reset(mockedObject); // <-- is this OK?
}
</code>```

I ask, because the documentation suggests resetting mock objects is generally indicative of bad tests. However, this feels OK to me.

Alternative

The alternative choice seems to be calling:

```<code>verify(mockedObject, times(2)).someMethod();
</code>```

which in my opinion forces each test to know about the expectations of getBar(), for no gain.

答:
Smart Mockito users hardly use reset feature because they know it
  could be a sign of poor tests. Normally, you don't need to reset your
  mocks, just create new mocks for each test method.

Instead of reset() please consider writing simple, small and focused
  test methods over lengthy, over-specified tests. First potential code
  smell is reset() in the middle of the test method.

Extracted from the mockito docs.

My advise is that you try to avoid using reset(). In my opinion, if you call twice to someMethod, that should be tested (maybe it is a database access, or other long process that you want to take care about).

If you really don't care about that, you could use:

```<code>verify(mockedObject, atLeastOnce()).someMethod();
</code>```

Note that this last could cause a false result, if you call someMethod from getBar, and not after (this is a wrong behaviour, but the test will not fail).

Body:
Smart Mockito users hardly use reset feature because they know it
  could be a sign of poor tests. Normally, you don't need to reset your
  mocks, just create new mocks for each test method.

Instead of reset() please consider writing simple, small and focused
  test methods over lengthy, over-specified tests. First potential code
  smell is reset() in the middle of the test method.

Extracted from the mockito docs.

My advise is that you try to avoid using reset(). In my opinion, if you call twice to someMethod, that should be tested (maybe it is a database access, or other long process that you want to take care about).

If you really don't care about that, you could use:

verify(mockedObject, atLeastOnce()).someMethod();

Note that this last could cause a false result, if you call someMethod from getBar, and not after (this is a wrong behaviour, but the test will not fail).

ContentLicense: CC BY-SA 4.0


答:
Client/server describes the relationship between two computer programs in which one program, the client, makes a service request from another program, the server, which fulfills the request.

For more information see: What is a client/server?

Title: A simple definition of client-server


答: You should clean up the big ugly glue method the same way you cleaned up the original code base. Split it up in neat modular methods. You probably have groups of lines of code that do some task split these lines up in methods, if you share some variables you could consider putting the shared variables and the new methods in one class.</p>

Title: How to avoid giant glue methods?

Body:
In my current job, I've been tasked with cleaning up old code a few times.  Often the code is a labyrinth and the data behind it is even more tangled.  I find myself combing out things into nice, neat, modular methods.  Each method does one thing and does it well.  That's when things start to go south...

Invariably, I end up with a clean API and no real way to tie it all together.  The solution has been to write a big ugly "glue" method (generally full of conditional statements) that eventually calls all of my "clean" methods.

The glue method usually ends up being a terse version of the tangle of code/data that I was attempting to clean up.  It's generally more readable, but it's still annoying.

How can I avoid such methods?  Is this a symptom of the tangled data or a reflection of something that I'm doing wrong?


答:
Well, for THAT code, you could inject a mocked Text-object and fetch the keyListener after return and call keyReleased on this, e.g. using mockito

```<code>@Test
void doTest(){
  Text mock = mock(Text.class);
  StaticClass.addEnterListener(mock, ....);
  ArgumentCaptor<KeyListener> captor = ArgumentCaptor.forClass(KeyListener.class);
  verify(mock).addKeyListener(captor.capture());
  KeyListener theListener = captor.getValue();

  theListener.keyReleased(...);
}
</code>```

I did not test this, but this should be the way...
though i would encourage to refactor this...

Title: How to invoke anonymous functions in testing?

Body:
Below is Java code.

I need to cover the below function. I searched for many websites, but I still have no ideas. Is there any methods to cover the override anonymous classes?

```<code>  public static void addEnterListener(Text text, final String methodName, final Object callee) {
    text.addKeyListener(new KeyListener() {
    @Override
    public void keyReleased(KeyEvent arg0) {
    if (arg0.keyCode == '\r') {
      try {
        Method method = callee.getClass().getMethod(methodName, KeyEvent.class);
        method.invoke(callee, arg0);
      } catch (Exception e) {e.printStackTrace();}
    }
  }

  @Override
  public void keyPressed(KeyEvent arg0) {
  }
});
}
</code>```

Body:
Well, for THAT code, you could inject a mocked Text-object and fetch the keyListener after return and call keyReleased on this, e.g. using mockito

@Test
void doTest(){
  Text mock = mock(Text.class);
  StaticClass.addEnterListener(mock, ....);
  ArgumentCaptor<KeyListener> captor = ArgumentCaptor.forClass(KeyListener.class);
  verify(mock).addKeyListener(captor.capture());
  KeyListener theListener = captor.getValue();

  theListener.keyReleased(...);
}

I did not test this, but this should be the way...
though i would encourage to refactor this...


答:
It sounds like what you've done is taken a tangled mess of a precedural codebase and created a lovely modular precedural codebase.

Invariably, I end up with a clean API and no real way to tie it all together. The solution has been to write a big ugly "glue" method (generally full of conditional statements) that eventually calls all of my "clean" methods.

With procedural code (even if it's disguised as OO), you're always going to end up with some kind of sequential workflow defined somewhere, often filled with complex conditional branches as you describe. I suspect it's this procedural nature of the code which is making you feel that something is wrong. This is not necessarily a bad thing, and when working with legacy code may be entirely unavoidable

Title: How to avoid giant glue methods?


答:
My teacher said once something like this (somehow it wont dissapear from my head):

In the real world, businesses have clients. In the computer world, servers have clients. The "client-server" architecture is common in both local and wide area networks. For example, if an office has a server that stores the company's database on it, the other computers in the office that can access the database are "clients" of the server.

Title: A simple definition of client-server


问:
Validating Emails in PHP
I wrote the following function to validate emails for a web app I'm working on:

```<code>function validate_email($email) {
    $valid = true;

    if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $valid = false;
    }

    $email_parts = explode("@", $email);

    if(count($email_parts) < 2) {
        $valid = false;
    }
    else {
        if(!checkdnsrr($email_parts[1], "MX")) {
            $valid = false;
        }
    }

    return $valid;
}
</code>```

It's not intended to replace the validation email sent to the user with a link to complete the registration. I know it wont catch all invalid ones, it will just reduce them. Hence reduce the amount of bounced emails received. My questions are:

Will it flag a valid emails as a false positive?

Is it okay to depend on a DNS check to validate the domain?

Any help is appreciated. Thanks.

答:
Yes, it will flag valid e-mails incorrectly. An e-mail address can legally contain an escaped @ in the local part, in which case your code would fail to correctly extract the domain name.

Rather than re-invent the wheel, check out IsEmail.

Title: Validating Emails in PHP


答:
That MX DNS record is needed to send any email to the domain. So the check will only flag emails to which it is not possible to deliver email at this time.

The mail transfer agent (MTA) will normally try again, though. It usually retries for about a week. So MTA would deliver the email if there was either temporary misconfiguration of the domain or temporary problem with your local DNS that will cause the check to fail where it would succeed at another time.

Such case would be very rare and if the user expects to be sent confirmation email immediately, they wouldn't be getting it anyway.

See also Peter Taylor's answer for bug in the parsing itself.

Title: Validating Emails in PHP

Body:
I wrote the following function to validate emails for a web app I'm working on:

```<code>function validate_email($email) {
    $valid = true;

    if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $valid = false;
    }

    $email_parts = explode("@", $email);

    if(count($email_parts) < 2) {
        $valid = false;
    }
    else {
        if(!checkdnsrr($email_parts[1], "MX")) {
            $valid = false;
        }
    }

    return $valid;
}
</code>```

It's not intended to replace the validation email sent to the user with a link to complete the registration. I know it wont catch all invalid ones, it will just reduce them. Hence reduce the amount of bounced emails received. My questions are:

Will it flag a valid emails as a false positive?

Is it okay to depend on a DNS check to validate the domain?

Any help is appreciated. Thanks.