答:
In your example of the horse prediction strategy, you have mixed strategy and history analysis.

The solution is to record the horse history somewhere else, and simply replace the existing strategy with one created from different parameters calculated  (by another, factory class) from past performance.

That way you have three distinct classes:

Strategy (stateless and immutable)

Prediction history collector

Strategy factory (that analyses the history to fine tune the parameters used to create a new Strategy)

Each with their own independent, and unrelated, concerns. You can chose how often to swap out the strategy instance with a new (hopefully better) one.

Title: Design Patterns (java) -- Strategy with fields. Ever acceptable?

Body:
Both here on stack overflow and on Java Effective it is suggested that strategy design patterns should be stateless. In fact in the book it is also suggested to make each strategy object a singleton.

The problem I have is that some strategies I envision for my program need states/fields. Either because they are path-dependent in their behavior or because I want them heterogeneous (a statistical distribution of similar strategies, if you prefer).

This forces me to break both Java Effective suggestions: I instantiate a new strategy for each user class AND each of these strategies contain its own fields.

Is that very bad? Should it be done differently?

It was suggested to me to keep the fields that make the strategy heterogeneous in the class that uses it and then pass it as an argument. I find that very anti-oo. Those fields don't belong to the user class. In fact, if that class uses another strategy it might not need those fields at all. That seems to run against the reason I am using the strategy pattern in the first place.

Mostly I am just very confused

I make a simple example here. Imagine you have a class Gambler, which represents somebody making bets on horses. Now this class will require a strategy predictStrategy that will work something like this:

```<code>interface predictStrategy{
    public Horse predictWinningHorse(HorseRace r);
}
</code>```

Now, I can have many implementations where the strategy is to choose at random, or pick the white horse or whatever. That's easy.

Imagine though that I implement a strategy that looks at past predictions and somewhat "learns" from its past mistakes. Clearly each strategy will have to have its own memory on which to learn. I might have to add one more method to the interface (or make an extension)

```<code>interface predictStrategy{
    public Horse predictWinningHorse(HorseRace r);

    public void addObservation(HorseRace r, Horse oldPrediction, Horse actualWinner);
}
</code>```

So that the Gambler class calls "strategy.addObservation(...)" at the end of each race to improve its predictive power.

Can this be really be done with a stateless strategy object? It seems impossible to me.

OwnerDisplayName: Bohemian


问:
why control + alt + delete couldn't be intercepted by any application
The secure attention key is designed to make login spoofing impossible, as the kernel will suspend any program, including those masquerading as the computer's login process, before starting a trustable login operation.

Why cannot other programs simulate control+alt+del?

What is the reason behind this?

答:
Larry Osterman wrote about "Why is Control-Alt-Delete the secure attention sequence (SAS)?" back in 2005. The answer is so short that there is no real need to summarize it, although I am eliding a few side notes.

When we were designing NT 3.1, ... we needed to have a keystroke sequence that couldn't be intercepted by any application. ...

It turned out that the only keystroke combination that wasn't already being used by a shipping application was control-alt-del, because that was used to reboot the computer. And thus was born the Control-Alt-Del to log in.

So there you have it, the reason why Ctrl+Alt+Del was chosen for the secure attention sequence.

Most likely on DOS there was no real technical reason why you couldn't possibly have caught Ctrl+Alt+Del and used it for some other purpose, but nobody in their right mind would have done that in a DOS application since it would break so much of users' expectations of how their computers worked. Note that Windows 3.x (when running in 386 Enhanced Mode; I don't think it did so when running in Standard Mode, and certainly not Win 3.0 in Real Mode) caught and handled Ctrl+Alt+Del, which demonstrates that it could be done even when running on top of BIOS + DOS. Probably the code that did the grunt work for that was just a few assembly language instructions, hooked to the appropriate interrupt vector, which looked for DEL with the CTRL and ALT modifiers set, doing a bit of magic if it found that particular combination.

As for simulating it, I'd go with "why would you want to?". I do recall reading somewhere (maybe it was at Larry Osterman's blog, maybe it was somewhere completely different) that technically the secure desktop is a separate session started and maintained by the Windows initialization code, and thus inaccessible to any non-privileged process. That said, apparently there is a SendSAS() function in SAS.DLL (which on Win7 is in System32) wich will simulate the user pressing Ctrl+Alt+Del; see SendSas Step by Step for a short code example. Caveat: I haven't tried that one myself.

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
What are some good End-User Programming solutions you have seen?
End-User Programming is where regular end users, i.e. non-programmers, are able to customize a program, or create a new one, with minimal training or instruction.

App Inventor for Android is one recent example, but perhaps the most popular example of end-user programming is the spreadsheet.

What examples of end-user programming have you seen used, or believe to be useful? What's the philosophy of the system? What challenges remain?

答:
Tecplot

Has support for Python scripting (modifying input data, Fourier analysis, ...)

Autocad

VBA and LISP scripting

Would these count as end user programming?

ContentLicense: CC BY-SA 2.5


问:
Strategy/algorithm to divide pot to chips
I want to split poker pot to chips.

Example:

Pot = $17.500.

I have the endless piles of chips. I have the following types of chips: ChipsTypes = [$1, $5, $10, $25, $100, $500, $1.000, $5.000, $10.000, and so on]. Index starts from 0.

I want to get an array that says which chips I have to take to divide the pot and in which order to have minimum number of denominations and chips after pot-to-chips conversion. For example Result = [7, 5] means that I have to take 3 * $5.000 + 5 * $500 which $17.500.

Is there is any strategy or algorithm that would suit my need?

答:
O(n*c) dynamic programming algorithm in pseudocode, where n is the amount of money in dollars (or cents, if there are any chip values with a cent portion), and c is the number of chip sizes.
Returns 0 if no chip formulation is found.  This only provides the count of the chips.  To get the actual chip counts, replace MoneyArray with an array of Lists of chipsizes, and mincount with a List of chipsizes.</p>

```<code>fun GetMinChipCount(Array ChipSizes, Int MoneyCount)
    MoneyArray = Int[1..MoneyCount]
    for i = 1 to MoneyCount:
        Int mincount = 0
        foreach Chip in ChipSizes:
            if Chip < i: continue
            if Chip = i: mincount = 1
            if Chip > i
                Int CountVal = MoneyArray[Chip-i]
                if CountVal = 0: continue;
                if mincount == 0 or mincount > CountVal + 1: mincount = CountVal + 1
        MoneyArray[i] = mincount;
    return MoneyArray[MoneyCount]
</code>```

Body:
O(n*c) dynamic programming algorithm in pseudocode, where n is the amount of money in dollars (or cents, if there are any chip values with a cent portion), and c is the number of chip sizes.
Returns 0 if no chip formulation is found.  This only provides the count of the chips.  To get the actual chip counts, replace MoneyArray with an array of Lists of chipsizes, and mincount with a List of chipsizes.

fun GetMinChipCount(Array ChipSizes, Int MoneyCount)
    MoneyArray = Int[1..MoneyCount]
    for i = 1 to MoneyCount:
        Int mincount = 0
        foreach Chip in ChipSizes:
            if Chip < i: continue
            if Chip = i: mincount = 1
            if Chip > i
                Int CountVal = MoneyArray[Chip-i]
                if CountVal = 0: continue;
                if mincount == 0 or mincount > CountVal + 1: mincount = CountVal + 1
        MoneyArray[i] = mincount;
    return MoneyArray[MoneyCount]


答:
In a comment to another answer you said the answer explained why it shouldn't be intercepted, but you are asking why it can't, not why it shouldn't be intercepted.

Maybe I'm pointing out the obvious, but it can't be intercepted simply because that's how windows was designed. The OS obviously intercepts it, and it simply refuses to pass that event on to applications. It was a design decision by the makers of the OS.

Title: why control + alt + delete couldn't be intercepted by any application

Body:
The secure attention key is designed to make login spoofing impossible, as the kernel will suspend any program, including those masquerading as the computer's login process, before starting a trustable login operation.

Why cannot other programs simulate control+alt+del?

What is the reason behind this?


问:
What is "toolkit design"?
What does "toolkit design" mean and what are the basic steps to design a toolkit for a specific task/project?

It appears in a task description which says: "This task deals with the design of detailed specification of the various tools that are employed in order to implement [insert some development task here]"

So what I understand is that: it's required to design and provide the specifications of a toolkit which will be used for doing some specific tasks. But how is toolkit design done?

Searching Google hardly gives any meaningful result. They are mostly about "design toolkits" which is not what I'm looking for.

For example this guy has designed a software toolkit in some of his previous projects http://logonpro.com/resume.doc

答:
If you ask this question, you should not start designing toolkits ;-)

Putting jokes away, my view is the following (home made, no big names referred).

You have to build a software, which will solve a certain task. You have some specifications about different data objects, associated business logic, workflow, appearance, performance, etc. Requirements that your application have to meet in a certain environment (desktop or server, OS, frameworks, ...)

However, to achieve this goal, you probably will spend more time on "housekeeping" than implementing the actual algorithm, workflow, etc: you will store and read persistent data, process configuration information, command line parameters, scripts, manage the communication between the GUI and the business logic, handle errors. In more complex scenarios (like game development), you spend huge amount of time not on coding, but just building configurations (like design a level map, actors, etc), enable scripting and write scripts, ... Sometimes it is beneficial to create independent helper apps for doing such things. This latter stuff is what I would call "toolkit layer": not directly specified as a request, but you need them to do your job. And the better you design the toolkit layer, the more efforts it requires, but finally, when you have to solve your task, the tools make that pretty straightforward.

To put it simple: you can solve your tasks one by one independently - or extract the similarities, solve them once, and solving a "real" task means using the common layer in the specific environment. The problem: the common layer is

inherently more complex, as it should answer "any" question instead of "one",

hard to modify because many other codes depend on them,

and when it breaks, it may crash just about anything.

Nice theory, tough stuff.

If you don't have a vision of the toolkit behind your current task, I think you should not design it. Design your application in a nice, object oriented way instead: interfaces, abstract classes, shared helper components. The latter will be your "toolkit layer" for this application. If you have designed it well, this layer will help you when adding "one last new feature" or component to the app just before the deadline. If you can estimate the required time well in this situation, your toolkit is good.

... and if you live on this toolkit-drug for 20 years, you will not see the application, only the toolkit layer. This is why I create an automatic JSON serializer with a common persistence layer, and a data binding GUI toolkit for my ever first iOS application. I simply can't do in another way (and Objective C / Cocoa rocks)...

Title: What is "toolkit design"?


问:
I am a git user confused by mercurial's branching. How am I supposed to track small changes?
I've always used git before, but I want to contribute to python so now I have to learn mercurial and I find it very frustrating.

So, I've made a couple of small patches and I wanted to track them as commits in my local mercurial repository. Apparently there are 4 ways to handle branching in mercurial.
1 and 4 looked completely ridiculous to me, named branches seem to be heavyweight and I feel that I'm not supposed to use them for quick 1-commit fixes, so I used bookmarks.

Now, my patch gets rejected and I want to remove one of my bookmark-branches from my repository.
OK, in git I would just force-delete my branch and forget about it, so I delete my bookmark and now I have following problems:

TortoiseHG and hg log still show that commit and default branch has 2 heads. And if I understand correctly, you can't delete commits in hg without additional plugins.

Mercurial has not only hashes, but also revision numbers. As I've added a couple of my own commits, all commits pulled after that have different revision numbers from the main central
repo.

I do hg update after pulling to move my master bookmark to the latest commit automatically, but I couldn't find a way to do that in TortoiseHG.

What am I doing wrong? Is this normal and expected and should I just ignore these issues?
Or how am i supposed to work with my branches?

答:
I find with mercurial it easiest not to worry about branches. I just find where in history I want to edit from and create commits as required (a.k.a. anonymous branches). Sometimes bookmarks might be useful if I'm having to jump between heads in different contexts but most often I don't bother with them. Named branches are OK for long-lived branches (bug-fix branches, project-branches) but for 1- or 2-commit fixes, they are not the right tool for the job.

The trick with anonymous branches is to set their phase to "secret" if you don't want to push them i.e. if you want to keep them local. If you do want to push them, but you don't want any more commits based on them, you just commit a "--close-branch" on top of them which means they no longer appear in the 'heads' list and mercurial will stop complaining about multiple heads on that branch.


答: Any domain-specific language worth it's salt ought to be considered a viable example of end-user programming, since that is its primary objective...to be familiar enough to the user that they don't have to be a software engineer to use it.</p>

Title: What are some good End-User Programming solutions you have seen?

Body:
End-User Programming is where regular end users, i.e. non-programmers, are able to customize a program, or create a new one, with minimal training or instruction.

App Inventor for Android is one recent example, but perhaps the most popular example of end-user programming is the spreadsheet.

What examples of end-user programming have you seen used, or believe to be useful? What's the philosophy of the system? What challenges remain?


问:
Why should I add CHECK CONSTRAINT?
Following is a table creating script created by Entity Framework using the model shown in https://codereview.stackexchange.com/questions/14077/is-it-proper-tpt-inheritance.

In this script, there are two alter statements. What is the need for the second ALTER statement?

SCRIPT

```<code>CREATE TABLE [dbo].[SellingItems_Book](
[Title] [nvarchar](max) NULL,
[Id] [int] NOT NULL,
 CONSTRAINT [PK_SellingItems_Book] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
</code>```

First Alter

```<code> ALTER TABLE [dbo].[SellingItems_Book]  WITH CHECK ADD  CONSTRAINT [FK_Book_inherits_SellingItem] FOREIGN KEY([Id])
REFERENCES [dbo].[SellingItems] ([Id])
GO
</code>```

Second Alter

```<code>ALTER TABLE [dbo].[SellingItems_Book] CHECK CONSTRAINT [FK_Book_inherits_SellingItem]
GO
</code>```

答: The second ALTER statement is superfluous because the WITH CHECK ADD will enable it. I believe they do that to make sure the check is enabled, which what the second statement does.</p>

Title: Why should I add CHECK CONSTRAINT?


问:
Can the Strategy pattern be implemented without significant branching?
The Strategy pattern works well to avoid huge if...else constructs and make it easier to add or replace functionality. However, it still leaves one flaw in my opinion. It seems like in every implementation there still needs to be a branching construct. It might be a factory or a data file. As an example take an ordering system.

Factory:

```<code>// All of these classes implement OrderStrategy
switch (orderType) {
case NEW_ORDER: return new NewOrder();
case CANCELLATION: return new Cancellation();
case RETURN: return new Return();
}
</code>```

The code after this doesn't need to worry, and there is only one place to add a new order type now, but this section of code still isn't extensible. Pulling it out into a data file helps readability somewhat (debatable, I know):

```<code><strategies>
   <order type="NEW_ORDER">com.company.NewOrder</order>
   <order type="CANCELLATION">com.company.Cancellation</order>
   <order type="RETURN">com.company.Return</order>
</strategies>
</code>```

But this still adds boilerplate code to process the data file - granted, more easily unit testable and relatively stable code, but additional complexity nontheless.

Also, this sort of construct doesn't integration test well. Each individual strategy may be easier to test now, but every new strategy you add is addition complexity to test. It's less than you would have if you hadn't used the pattern, but it's still there.

Is there a way to implement the strategy pattern that mitigates this complexity? Or is this just as simple as it gets, and trying to go further would only add another layer of abstraction for little to no benefit?

答:
In talking with other developers where I work, I found another interesting solution - specific to Java, but I'm sure the idea works in other languages. Construct an enum (or a map, it doesn't matter too much which) using the class references and instantiate using reflection.

```<code>enum FactoryType {
   Type1(Type1.class),
   Type2(Type2.class);

   private Class<? extends Type> clazz;

   private FactoryType(Class<? extends Type> clazz) {
      this.clazz = clazz;
   }

   public Class<? extends Type> getTypeClass() {
      return clazz;
   }
}
</code>```

This drastically reduces the factory code:

```<code>public Type create(FactoryType type) throws Exception {
   return type.getTypeClass().newInstance();
}
</code>```

(Please ignore the poor error handling - example code :))

It's not the most flexible, as a build is still required...but it reduces the code change to one line. I like that the data is separated from the factory code. You can even do things like setting parameters either by using abstract classes/interfaces to provide a common method or creating compile-time annotations to force specific constructor signatures.

Body:
In talking with other developers where I work, I found another interesting solution - specific to Java, but I'm sure the idea works in other languages. Construct an enum (or a map, it doesn't matter too much which) using the class references and instantiate using reflection.

enum FactoryType {
   Type1(Type1.class),
   Type2(Type2.class);

   private Class<? extends Type> clazz;

   private FactoryType(Class<? extends Type> clazz) {
      this.clazz = clazz;
   }

   public Class<? extends Type> getTypeClass() {
      return clazz;
   }
}

This drastically reduces the factory code:

public Type create(FactoryType type) throws Exception {
   return type.getTypeClass().newInstance();
}

(Please ignore the poor error handling - example code :))

It's not the most flexible, as a build is still required...but it reduces the code change to one line. I like that the data is separated from the factory code. You can even do things like setting parameters either by using abstract classes/interfaces to provide a common method or creating compile-time annotations to force specific constructor signatures.


问:
Should architect or dev lead tell teammate where to add their code before coding a new feature?
I have experienced with two kinds of team. After a feature is assigned to me, one kind of dev lead tell me the exact file or class to add my code, another kind of team just say the story or requirement to me.

The latter job is hard, if the software I am working on is too big to grasp the structure. Should senior guys tell the place to add the code before coding?

答:
The team (or lead if your team is less democratic) should generally come to some sort of agreement on design. There's other ways of getting stuff done though, so I imagine it will vary depending on where you're coding.

If you're having trouble grasping the structure of the codebase or don't know how best to design the new feature, ask your lead or peers. Part of making good process is collaboration with your team.


答:
I think it's OK for a senior developer to suggest what the best place for changes would be, if they know the code well enough to do that, and the more junior developer doesn't know the code that well.

If it's a very complex change that needs to be applied in many parts of the system, then trying to micromanage all of it will most likely make everyone miserable. In that case, they should provide more general guidance and let the junior developer learn on their own.

Title: Should architect or dev lead tell teammate where to add their code before coding a new feature?

Body:
I have experienced with two kinds of team. After a feature is assigned to me, one kind of dev lead tell me the exact file or class to add my code, another kind of team just say the story or requirement to me.

The latter job is hard, if the software I am working on is too big to grasp the structure. Should senior guys tell the place to add the code before coding?


答:
I think it depends on the devs skill level.  Trust me, it's usually not easy for the senior dev either.  I would take it as compliment that they trust you to determine how things are done.  Just make sure you run your design passed someone else before doing the work.

As a note, you shouldn't blindly trust what the senior guy is telling you.  Do your own analysis and if what he tells you doesn't make sense, push back and ask questions.


答: Never be afraid to ask for clarification on something. CYA, always. If it's a job too big to grasp, chances are you aren't meant to. Ask the lead developer "I understand what I need to do, but since I haven't needed to work on the architecture, I don't know where I need to do it for sure. Can you please help point me to at least the general area?"


问:
Developing an iOS app for a single device - licensing issue
I'm developing an iOS app for a museum as a freelancer. It's a very simple video player, to be installed on a single iPad that will be part of a permanent exhibition, basically acting as a kiosk. It turns out the iPad is the ideal device for that if you're looking for a small and affordable touchscreen.

The problem is: as far as I can tell, none of the Apple Developer Program options available will allow me to distribute an app like that. The relevant options are (from the link above):

iOS Developer Program ($99/year)
Select this program if you would like to distribute apps on the App Store as an individual, sole proprietor, company, organization, government entity or educational institution.

iOS Developer Enterprise Program ($299/year)
Select this program if you would like to develop proprietary apps for internal distribution within your company, organization, government entity or educational institution.

The regular program requires distribution through the App Store. The Enterprise version is for internal distribution within my own organization. Neither is the case here! It seems like I'm doomed to violate Apple's terms of service (and I can think of at least two ways of doing that: jailbreaking, or changing the iPad's date so it won't know the provisioning profile expired).

Is that really so, or did I get the descriptions wrong? Has anyone here been in a similar situation?

答: I think jailbreaking is a good option for your use-case. In addition to resolving the licensing issue (assuming jailbreaking remains legal), it would also enable you to block OTA updates. I think blocking them is a good precaution for your use case, as OS or library updates may cause your software to break in the future even if you don't change it.</p>


答:
There might be different reasons to explain why second alter statement is in the scripts:

It is checking back that first alter constraint has been added.

That script was automatically added by script generation tool for verification purposes.

Title: Why should I add CHECK CONSTRAINT?

Body:
Following is a table creating script created by Entity Framework using the model shown in https://codereview.stackexchange.com/questions/14077/is-it-proper-tpt-inheritance.

In this script, there are two alter statements. What is the need for the second ALTER statement?

SCRIPT

```<code>CREATE TABLE [dbo].[SellingItems_Book](
[Title] [nvarchar](max) NULL,
[Id] [int] NOT NULL,
 CONSTRAINT [PK_SellingItems_Book] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
</code>```

First Alter

```<code> ALTER TABLE [dbo].[SellingItems_Book]  WITH CHECK ADD  CONSTRAINT [FK_Book_inherits_SellingItem] FOREIGN KEY([Id])
REFERENCES [dbo].[SellingItems] ([Id])
GO
</code>```

Second Alter

```<code>ALTER TABLE [dbo].[SellingItems_Book] CHECK CONSTRAINT [FK_Book_inherits_SellingItem]
GO
</code>```


答:
None of them

Ideally, there should be a design meeting of technical details that you are planned to implement in a team environment. That is the right place and time to identify most of the questions.

Another point is - Communicating clearly what developer does not know is very important. Never be afraid to ask questions on domain specific details and requirements. This will assure that you are on a right path :)

In important thing that newbies forget to do is, to Google for technical problems first before asking to the Team lead or Senior developer for help.


问:
event source calls methods in a interface
I am using Java.

How does an event source like a (button in a GUI) knows which method to call in an interface?

For example, I am listening to Mouse Events and have implemented a Mouse Listener interface in my class then how would the event source know whether it should call mousePressed(), mouseReleased() or some other abstract method in the in the interface?

I am aware that using addMouseListener(this), provides a way for the event source to call the method of an interface.

答:
For the observable design pattern, see http://en.wikipedia.org/wiki/Observer_pattern

Roughly, when the user clicks the button of the mouse and your Java Application is active, the OS notifies the application (in this case, the JVM) about the click. Then the JVM creates the MouseEvent object, as well as other necessary objects for handling the event and searches for the listeners of that event (think that the Button object has a collection of MouseListener objects, and you added your listener to that collection). Then it iterates through all the listeners in that collection and calls the appropriate method. It knows what is the appropriate method because it's defined in the MouseListener interface, thus it knows all objects in that collection implements the methods defined in the interface.

For example, suppose there's this code in a Button class (it's probably somewhere else, but it serves as an example):

```<code>// suppose mouseListenerCollection contains all the mouse listeners in the component
for(MouseListener listener : mouseListenerCollection){
    listener.mouseClicked(event);
}
</code>```

It invokes the mouseClicked(MouseEvent e) method because the mouse have been clicked and all objects that implements the MouseListener interface implements the mouseClicked method, and it's specified that when a mouse is clicked, the mouseClicked method must be called.

For further information, always refer to the API javadoc.

Body:
For the observable design pattern, see http://en.wikipedia.org/wiki/Observer_pattern

Roughly, when the user clicks the button of the mouse and your Java Application is active, the OS notifies the application (in this case, the JVM) about the click. Then the JVM creates the MouseEvent object, as well as other necessary objects for handling the event and searches for the listeners of that event (think that the Button object has a collection of MouseListener objects, and you added your listener to that collection). Then it iterates through all the listeners in that collection and calls the appropriate method. It knows what is the appropriate method because it's defined in the MouseListener interface, thus it knows all objects in that collection implements the methods defined in the interface.

For example, suppose there's this code in a Button class (it's probably somewhere else, but it serves as an example):

// suppose mouseListenerCollection contains all the mouse listeners in the component
for(MouseListener listener : mouseListenerCollection){
    listener.mouseClicked(event);
}

It invokes the mouseClicked(MouseEvent e) method because the mouse have been clicked and all objects that implements the MouseListener interface implements the mouseClicked method, and it's specified that when a mouse is clicked, the mouseClicked method must be called.

For further information, always refer to the API javadoc.


问:
Is functional spec a "design document"?
So I have been a bit lost in the terms, so first of all I present you what I have learned so far:

System requirements specification - what users want, what the system should do
Functional requirement - how the things, which users want, will actually work in the application

Also I would say that the latter is a design document. Is that right or is there another document in addition to these?

答:
Term design document is too broad

Besides the Software Requirements Specification (SRS), there are different design documents and their number increases with the complexity of the project.

For software design document may contain different sections like Data, Architecture, Interface, Structured Programming concepts, etc..

There is also an article How to Write an Effective Design Document that you may want to look and of course a wiki reference Software design document - that might be helpful to look.

Title: Is functional spec a "design document"?


问:
.Net Language Interoperability Gotchas
I hope this is the appropriate forum to ask this question.

A group of colleagues and I just starting learning C# a few weeks ago and we are planning on having a discussion about language interoperability.

So, I am looking for known/classical examples of .Net language interoperability issues. Like this one, where the case-insensitiveness of VB.Net makes an overloaded C# method incompatible.

In C#

```<code>public class Foo
{
    public void foo() { }
    public void fOO() { }
}
</code>```

In VB.Net

```<code>Public Class Bar
   Sub Bar()
      Dim foo As Foo
      foo = New Foo()
      foo.foo(); //compiler error
   End Sub
End Class
</code>```

Or this one in which a VB.Net keyword is used in a C# method name:

In C#

```<code>public class Foo
{
   public virtual void Stop() { }
}
</code>```

In VB.Net

```<code>Public Class Bar
    Inherits Foo

    Public Overrides Sub Stop() 'compiler error
    End Sub

End Class
</code>```

I would love to gather a few more examples of this type of issues.

Does anyone know any other interesting cases of language interoperability gotchas?

I used C# and VB.Net in these examples, but any .Net language interoperability issue will be just as good to enrich a discussion on the subject.

答:
Common Language Specification is a key

It would be better to enhance your understanding of how to write a Common Language Specification (CLS) compliant code. I believe that would resolve most of the issues that you have faced or found.

Basically, CLS compliance refers to CLS rules and restrictions that being followed. However, the concept has a more specific meaning depending on whether you are describing CLS-compliant code or CLS-compliant development tools, such as a compiler. CLS-compliant tools can help you write CLS-compliant code.

There are numerous articles on MSDN and elsewhere that I would suggest to follow:

Cross-Language Interoperability

Handling Language Interoperability with the Microsoft .NET Framework

Writing CLS-Compliant Code

Language Interoperability

Title: .Net Language Interoperability Gotchas


问:
What is the best way to handle last minute changes to product scope?
What is the best way to handle changes to product requirements or scope during or after User Acceptance Testing (UAT)?  How dangerous is it to make those changes, and how can the danger be mitigated?</p>

答:
I think the best way to deal with these change requests is to present a revised schedule including the change. And if it's after UAT, then the new schedule includes a second run through UAT.

When they go 'but we don't need that' you can ask why not? Doesn't the product need to be accepted by the user? If they haven't seen it, they can't accept it, right?


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

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

答: The best code is no code at all</p>

LastEditorDisplayName: Roger Pate

Body: The best code is no code at all


问:
Should I use switch statements or long if...else chains?
Often when I hear about the switch statement, its put off as a way to replace long if...else chains. But it seems that when I use the switch statement I'm writing more code that I would be just writing if...else. You also have other issues like keeping all variables for all calls in the same scope.

Here's some code that represents the flow I normally write (thanks to diam)

```<code>String comment;   // The generated insult.
int which = (int)(Math.random() * 3);  //  Result is 0, 1, or 2.

if (which == 0) {
    comment = "You look so much better than usual.";
} else if (which == 1) {
    comment = "Your work is up to its usual standards.";
} else if (which == 2) {
    comment = "You're quite competent for so little experience.";
} else {
    comment = "Oops -- something is wrong with this code.";
}
</code>```

Then they want me to replace that with this:

```<code>String comment;   // The generated insult.
int which = (int)(Math.random() * 3);  //  Result is 0, 1, or 2.

switch (which) {
    case 0:
             comment = "You look so much better than usual.";
    break;
    case 1:
             comment = "Your work is up to its usual standards.";
    break;
    case 2:
             comment = "You're quite competent for so little experience.";
    break;
    default:
             comment = "Oops -- something is wrong with this code.";
}
</code>```

Seems like a lot more code in a much more awkward syntax. But is there really an advantage to using the switch statement?

答:
```<code>switch (which) {
  case 0: comment = "String 1"; break;
  case 1: comment = "String 2"; break;
  case 2: comment = "String 3"; break;
  default: comment = "Oops"; break;
}
</code>```

The above way of writing this type of switch case is fairly common. The reason why you felt the switch case if bulkier is because your body was only one line and with a switch case you also needed the break statement. So the switch case had twice the body size of if else. With more substantial code, the break statement will not add much to the body. For single line body, it is a common practice to write the code in the same line as the case statement.

As others have already mentioned, a switch case makes the intent more clear, you want to make a decision based on the value of a single variable/expression. My comments are purely from a readability point of view and not performance based.

Body:
switch (which) {
  case 0: comment = "String 1"; break;
  case 1: comment = "String 2"; break;
  case 2: comment = "String 3"; break;
  default: comment = "Oops"; break;
}

The above way of writing this type of switch case is fairly common. The reason why you felt the switch case if bulkier is because your body was only one line and with a switch case you also needed the break statement. So the switch case had twice the body size of if else. With more substantial code, the break statement will not add much to the body. For single line body, it is a common practice to write the code in the same line as the case statement.

As others have already mentioned, a switch case makes the intent more clear, you want to make a decision based on the value of a single variable/expression. My comments are purely from a readability point of view and not performance based.


答: The scope can be changed at anytime, provided those changing accept the required changes to budget and schedule. You can't stop people from continually trying to change the scope until they realize it costs money, providing a few estimates of the cost for requested changes from higher-ups will help them make that connection. Doing this is unlikely to stop them from requesting changes, but it is likely to stop them from complaining when you deny those changes, and will help you identify the changes you need to make when they understand the cost of that change.</p>

Title: What is the best way to handle last minute changes to product scope?

Body: What is the best way to handle changes to product requirements or scope during or after User Acceptance Testing (UAT)?  How dangerous is it to make those changes, and how can the danger be mitigated?</p>


答:
Basically, yes. Software Requirements Specification states what the business users want the system to do, while Functional specification describes the actual functions of the system, usually linked to the business requirements.

E.g:
Business requirement (User): I want to see the number of trades and their exposures

Functional spec: A grid displaying in one column Trade with its ID and in the other column its exposure. The exposure is taken from the table TRADE_EXPOSURES...

The design should be separated from the requirements. FS is just lower level of SRS. FS is used for test case derivation in functional testing, SRS usually for acceptance testing. SRS is also used as a base for system testing, where the implenentation is validated against it (does it fit what the customer wanted?)

Title: Is functional spec a "design document"?

Body:
So I have been a bit lost in the terms, so first of all I present you what I have learned so far:

System requirements specification - what users want, what the system should do
Functional requirement - how the things, which users want, will actually work in the application

Also I would say that the latter is a design document. Is that right or is there another document in addition to these?


问:
What is a good design strategy for retaining history of user activities and files like Visual Studio projects?
OK so I'm not so sure that "project" is the right term, but for my purposes, I define "project" as similar to what Visual Studio uses, or Microsoft word - files that the user can open and work on and then save, and when the user runs the application again the program is aware of the files that were worked on last time the application was open.

So I ask, what is a good design strategy for retaining history of user activities and files like Visual Studio projects?

答:
Persistence of user activity and preferences

There are different approaches depending what technology is used at client side. In your case of Windows forms it has very good support from .NET Framework itself.

In short, it is all about creating, loading, and saving user settings.

More detailed posts and walk through are available:
- Application Settings Architecture
- How To Persist Windows Form State
- Painless Persistence of Windows Forms Positions

A good source to Enhancing Windows Forms Applications can be referenced in MSDN article.


问:
What do you look at first: the code or the design?
If you've just been introduced to a new project, what's the first thing you look for to get an idea of how it works?

Do you look for the design first?  If there is a design, what do you look for in it? Class diagrams or deployment diagrams or sequence diagrams or something else?

Or do you go straight for the code? If so, how do you understand how the different layers interact?

答:
I start with the design documentation. In particular, the specification - that tells the intent of the thing being looked at.

If possible, I then look at design notes and documentation to get a general flavour of how it has been done, the thought process, the style and nature of the people concerned.

If possible I then talk to the people who worked on it - what does it do? How? Why? Where are the bodies buried?

There's a tendency amongst developers to leap into code: "Let me show you this code". This is fine for them but tends to hijack my needs - which is to understand the high level which gives context to the low level stuff.

It uses vast amounts of brain power to look at little bits of code, out of complete context, and understand anything meaningful. So if possible, getting the developers to talk about the PRINCIPLE, structure, units, modules, whatever all leads to an appreciation of the task.

Only then is it worth trying to get into the code.

In the big scheme of things, looking at the code is like looking at a page full of 0's and 1's. There is meaning but it takes a long time to figure it out. Getting a flavour of where to look and which parts are meaningful helps narrow the search space.

All that said - when there is no doco, no people, and only code - then there is nothing for it but to look at the code.

In that case, I normally don't try and understand it by a slow deep reading, I do a quick pass, skim reading over everything. Sometimes this is just open files and sit with pressing the page-down key. You can get an amazing appreciation of a big picture just by doing this. (And in some cases I even string-dump executable files and trawl those, looking for signatures and patterns. This has been amazingly fruitful over the last 20-odd years.)


答:
What you describe is less a "pot to chips" algorithm (in real poker, the winner simply rakes in the chips from the center of the table) and more of a "coloring up" algorithm (once a player's ready to leave, he gives his stash to the banker who reduces the chips to the minimum number required), which is basically a "change-making" algorithm using amounts larger than $1.00.

Here's how I would write it in C#:

```<code>//I convert this enum to an array of its values, so you could skip this
public enum ChipDenom : int
{
   One = 1,
   Five = 5,
   Ten = 10,
   TwentyFive = 25,
   OneHundred = 100,
   FiveHundred = 500,
   OneThousand = 1000,
   FiveThousand = 5000,
   TenThousand = 10000
}

public Dictionary<ChipDenom, int> ColorUp(int chipAmount)
{
   int remainingAmount = chipAmount;

   //you could instead define an int[] containing the dollar values;
   var chipValues = Enum.GetValues()
                    .OfType<ChipDenom>()
                    .OrderByDescending(cd=>cd)
                    .ToArray();

   //If you do, the return value of this method should be Dictionary<int,int>
   var result = new Dictionary<ChipDenom, int>();

   while(remainingAmount > 0)
   {
      //find the largest chip denomination less than the remaining amount
      var highest = chipValues.First(cd=>(int)cd < remainingAmount);

      //determine how many of that chip can be used
      var quantity = remainingAmount / (int)highest;

      //and add it to the chip stack
      result.Add(highest, quantity);

      //and repeat with whatever's left over
      remainingAmount %= (int)highest;
   }

   return result;
}

...

//Usage:

var winnings = 13579;

//to determine the chips to give to a single player:
var chips = ColorUp(winnings);

foreach(var kvp in chips)
   Console.Writeline(String.Format("{0} : {1}", kvp.Key.ToString(), kvp.Value)

//to determine the chips to give to X players who split the pot:
var splitPlayers = 3;
var winnings = 13579;

var leftOver = winnings % splitPlayers;

var winningsPerPlayer = winnings / splitPlayers;

var playerChips = ColorUp(winningsPerPlayer);
var tableChips = ColorUp(leftOver);

Console.WriteLine("Each player receives:");

foreach(var kvp in playerChips)
   Console.Writeline(String.Format("{0} : {1}", kvp.Key.ToString(), kvp.Value);

Console.WriteLine("Leave in pot:");

foreach(var kvp in tableChips)
   Console.Writeline(String.Format("{0} : {1}", kvp.Key.ToString(), kvp.Value);
</code>```

Title: Strategy/algorithm to divide pot to chips

Body:
I want to split poker pot to chips.

Example:

Pot = $17.500.

I have the endless piles of chips. I have the following types of chips: ChipsTypes = [$1, $5, $10, $25, $100, $500, $1.000, $5.000, $10.000, and so on]. Index starts from 0.

I want to get an array that says which chips I have to take to divide the pot and in which order to have minimum number of denominations and chips after pot-to-chips conversion. For example Result = [7, 5] means that I have to take 3 * $5.000 + 5 * $500 which $17.500.

Is there is any strategy or algorithm that would suit my need?

Body:
What you describe is less a "pot to chips" algorithm (in real poker, the winner simply rakes in the chips from the center of the table) and more of a "coloring up" algorithm (once a player's ready to leave, he gives his stash to the banker who reduces the chips to the minimum number required), which is basically a "change-making" algorithm using amounts larger than $1.00.

Here's how I would write it in C#:

//I convert this enum to an array of its values, so you could skip this
public enum ChipDenom : int
{
   One = 1,
   Five = 5,
   Ten = 10,
   TwentyFive = 25,
   OneHundred = 100,
   FiveHundred = 500,
   OneThousand = 1000,
   FiveThousand = 5000,
   TenThousand = 10000
}

public Dictionary<ChipDenom, int> ColorUp(int chipAmount)
{
   int remainingAmount = chipAmount;

   //you could instead define an int[] containing the dollar values;
   var chipValues = Enum.GetValues()
                    .OfType<ChipDenom>()
                    .OrderByDescending(cd=>cd)
                    .ToArray();

   //If you do, the return value of this method should be Dictionary<int,int>
   var result = new Dictionary<ChipDenom, int>();

   while(remainingAmount > 0)
   {
      //find the largest chip denomination less than the remaining amount
      var highest = chipValues.First(cd=>(int)cd < remainingAmount);

      //determine how many of that chip can be used
      var quantity = remainingAmount / (int)highest;

      //and add it to the chip stack
      result.Add(highest, quantity);

      //and repeat with whatever's left over
      remainingAmount %= (int)highest;
   }

   return result;
}

...

//Usage:

var winnings = 13579;

//to determine the chips to give to a single player:
var chips = ColorUp(winnings);

foreach(var kvp in chips)
   Console.Writeline(String.Format("{0} : {1}", kvp.Key.ToString(), kvp.Value)

//to determine the chips to give to X players who split the pot:
var splitPlayers = 3;
var winnings = 13579;

var leftOver = winnings % splitPlayers;

var winningsPerPlayer = winnings / splitPlayers;

var playerChips = ColorUp(winningsPerPlayer);
var tableChips = ColorUp(leftOver);

Console.WriteLine("Each player receives:");

foreach(var kvp in playerChips)
   Console.Writeline(String.Format("{0} : {1}", kvp.Key.ToString(), kvp.Value);

Console.WriteLine("Leave in pot:");

foreach(var kvp in tableChips)
   Console.Writeline(String.Format("{0} : {1}", kvp.Key.ToString(), kvp.Value);


答:
IME, system specs define the hardware and software environment that the new application will operate in, while functional specs define what the application will do (my experience may not be typical, however).

Design documents are a different animal.  They define the structure of the application, breaking it into components, specifying the implementation of each component, the interfaces between components, the order in which components perform their operations, etc. ("component" is meant to be a very high-level, abstract term here; it could correspond to classes, modules, or even individual functions or methods).  Design documents also often have a "traceability matrix" showing which requirements are satisfied by particular elements of the design.

For a stupidly simple example:

System specification: The application will run on Linux as a command-line app in a bash shell.

Functional specification: The application will print the text "Hello, World" to the console and then terminate.

Design document: The application will be implemented as a single C program consisting of the function main, taking no arguments.  Upon entry, it will call the standard library function printf with the string literal "Hello, World\n" as its sole argument.  After the printf call, the application will return a 0 to the execution environment.

The "design document" isn't usually so detailed as to specify individual lines of code, but you should get the idea.

Title: Is functional spec a "design document"?


答:
When I was a dev lead last time (full of juniors, most of them were last year students on CS MSc), I had a third approach:

Give the story to the junior dev

Tell him to come back with a plan how it would be solved

After reviewing the plan, but only after, start editing files.

I don't say it worked quite well.

For simple tasks, like, add a new column to a report table, they did a huge mess, editing all the files, then they said "it's already done", then we reviewed it, turned out it's not the way it should've been done, they had to revert nearly everything (1) and then start again.

On big tasks (5+ classes involved), it was on the other side: they were simply silent for a day or two, then we had to go through it together, and basically I drew up a design which they had to implement.

Although I was there and for every single decision I explained it to them fully, and they had the required readings before, and it was more like a demonstration (2), at the end of the day, they still had to implement my design mostly, and they weren't that happy about it as when they're let free.

I know it's hard to differentiate planning from doing, but I guess it's called software engineering because there are still a few individuals left who know what they do, as opposed to craftsmen. My duty as their trainer was not to create another average coder, but someone who excels in his profession. Luckily, today, all of these are teamleaders (or were, but joined a different, more "agile" company with no leadership)

So, all in all, I don't know what's best, I only know that code quality is more important than junior's convenience - they're there to learn, not to let any kind of code to be commited to prod...

(1)  ("Why? It works, doesn't it?" "Yes, but you're querying database from the view layer or such")

(2) ("you see? we need this, and we usually use this pattern for this as you seen in this other similar module; here, our coding guideline (which was 2 pages long) says, do this, so, let's do this, and then ,let's draw a sequence diagram on how it would work... ok, now let's draw a class diagram about it")


答:
Keep in mind that you are not restricted in the code that is internal to your assembly, only things that are exposed publicly need to be CLS compliant.

Don't expose unsigned variables.

Don't expose identifiers that only differ by case.

Operator overloading, some languages can't use overloaded operators, so provide a method to achieve the same function as your overloaded operator.

Avoid unmanaged pointers.

Keep names unique, for example don't name a types method and field the same thing.

Don't expose boxed value types.

Don't overload fields or events.

Don't overload properties by type.

Don't overload methods by return type.

Expose alternative methods for implicit and explicit casts.

Don't expose variable length argument lists (params keyword in C#).

Don't use arrays with a nonzero lower bound (https://stackoverflow.com/a/5733008/279999).

Don't throw objects that don't inherit from System.Exception.

Mark your assembly with (System.ClsCompliant) attribute.

Title: .Net Language Interoperability Gotchas

Body:
I hope this is the appropriate forum to ask this question.

A group of colleagues and I just starting learning C# a few weeks ago and we are planning on having a discussion about language interoperability.

So, I am looking for known/classical examples of .Net language interoperability issues. Like this one, where the case-insensitiveness of VB.Net makes an overloaded C# method incompatible.

In C#

```<code>public class Foo
{
    public void foo() { }
    public void fOO() { }
}
</code>```

In VB.Net

```<code>Public Class Bar
   Sub Bar()
      Dim foo As Foo
      foo = New Foo()
      foo.foo(); //compiler error
   End Sub
End Class
</code>```

Or this one in which a VB.Net keyword is used in a C# method name:

In C#

```<code>public class Foo
{
   public virtual void Stop() { }
}
</code>```

In VB.Net

```<code>Public Class Bar
    Inherits Foo

    Public Overrides Sub Stop() 'compiler error
    End Sub

End Class
</code>```

I would love to gather a few more examples of this type of issues.

Does anyone know any other interesting cases of language interoperability gotchas?

I used C# and VB.Net in these examples, but any .Net language interoperability issue will be just as good to enrich a discussion on the subject.


问:
Multiple readers on FIFO
I've asked a question here before about multiple writers on a FIFO, and I know now that the write is thread safe as long as I write less than the PIPE_BIF, here is the link for that limit.

What about read? what if have two(or more) readers in multiple threads for reading from the same fifo, do I need locks here? or all I need is to read less than the PIPE_BUF?

BTW, I'm talking about Linux FIFO, And I'm using C.

答:
Updated answer

Per the manual, you are NOT guaranteed atomic reads.  However, their intent is for reads with FIFOs to be atomic.  From paragraphs 2 and 4 of Rationale | Input and output

```
The standard developers considered adding atomicity requirements to a pipe or FIFO, but
 recognized that due to the nature of pipes and FIFOs there could be no guarantee of
atomicity of reads of {PIPE_BUF} or any other size that would be an aid to applications
portability.```

```I/O is intended to be atomic to ordinary files and pipes and FIFOs.```

Until you see evidence otherwise, I would still be willing to say that you are fine.

Original answer

Based upon your previous question, I'm assuming all of your reads will be less than PIPE_BUF as well.

I don't believe you'll need any additional serialization around the reads since your unit of consumption is less than the guaranteed atomic, thread-safe write amount.  If you had sequences of objects that needed to be read, then you would need some additional mechanism for serialization.

Title: Multiple readers on FIFO

Body:
Updated answer

Per the manual, you are NOT guaranteed atomic reads.  However, their intent is for reads with FIFOs to be atomic.  From paragraphs 2 and 4 of Rationale | Input and output

The standard developers considered adding atomicity requirements to a pipe or FIFO, but
 recognized that due to the nature of pipes and FIFOs there could be no guarantee of
atomicity of reads of {PIPE_BUF} or any other size that would be an aid to applications
portability.

I/O is intended to be atomic to ordinary files and pipes and FIFOs.

Until you see evidence otherwise, I would still be willing to say that you are fine.

Original answer

Based upon your previous question, I'm assuming all of your reads will be less than PIPE_BUF as well.

I don't believe you'll need any additional serialization around the reads since your unit of consumption is less than the guaranteed atomic, thread-safe write amount.  If you had sequences of objects that needed to be read, then you would need some additional mechanism for serialization.


答:
For a complex piece of software I would approach it roughly as if it were a new development project. Start with the big ideas- vision, context, scope, stakeholders. Read through some user documentation and get an idea of how it is used. Get some user training with the software if possible (or applicable). Then start looking into the requirements and design documentation to get an idea of how it works at a high level. Talk to the designers if they are still around. Look at the system architecture in different perspectives. From there, start digging into the core functionality and looking at some code, returning to requirements and design as needed. As you look at code, run the software to see it in action. All the while, compile some summary documentation for future reference- you own Cliffs Notes. Branch out until you have a pretty good idea of how it all works and fits together, but concentrate on the parts that you will be working with. By now you have a top-to-bottom understanding of the whole system, or at least the parts that are applicable to you.

Of course, in the real world you may not have the time to go through all of this before you have to start getting your hands dirty, especially on the larger projects. But this is how I would do it if it were up to me.

Title: What do you look at first: the code or the design?

Body:
If you've just been introduced to a new project, what's the first thing you look for to get an idea of how it works?

Do you look for the design first?  If there is a design, what do you look for in it? Class diagrams or deployment diagrams or sequence diagrams or something else?

Or do you go straight for the code? If so, how do you understand how the different layers interact?


答:
There is no need for the second alter statement, for the first one will already enable the constraint. It may be there because the script was automatically generated, to make sure it will be enabled if you've changed the default server settings (which makes new constraint enabled), or if you decide to change the first alter script.

For more information on Alter Statements see http://msdn.microsoft.com/pt-br/library/ms190273.aspx

Title: Why should I add CHECK CONSTRAINT?


问:
Use a partial in a partial?
I'm a Rails newbie, so bear with me.

I have a few places, some pages, some partials that use:

```<code><%= link_to "delete", post, method: :delete,
                                 data: { confirm: "You sure?" },
                                 title: post.content %>
</code>```

Would it make sense to make this a partial since it is used repeatedly, sometimes in other partials too?

Is it o.k. to put partials in partials?

答: I think a template is overkill for such a small smippet.  I would write a helper method instead.</p>

Title: Use a partial in a partial?


问:
GCC: assembly listing for IA64 without an Itanium machine
I need to try the following thing: I would like to compile some simple C code samples and see the assembly listing generated by GCC for IA64 architecture, i.e. I just want to run GCC with the -S switch and see the resultant .s file. I don't have an Itanium machine, so in order to do it myself I'll probably need a cross-compiling version of GCC built for x86 RedHat. I'm not interested in full cross-compilation, meaning that I don't need to generate the binaries at all.

The easiest way, of course, would be to find an Itanium machine with with GCC and just try it there. Unfortunately, I don't seem to have access to any. Another option is to build a cross-compiling version GCC on my RedHat, but apparently that's quite an endeavor for someone who hasn't done it before (I assume that the fact that I only need .s output doesn't make it simpler).

What other options are there, if any? Maybe there's some sort of a web front to an Itanium GCC compiler on the Net (something like Comeau Online or ideone.com, but with .s output)? Anything else? I would appreciate any help.

答: umm, building a cross-compile tool-chain is not that hard. If you do binutils together with gcc, figuring out the configuration options is the only hard part. See cross-compiled linux from scratch for some ideas.</p>


问:
Pros and Cons of holding all the business logic in stored procedures in web application
In some organization I worked for web applications are developed basing all the business logic in Database stored procedures. For example, use html for view and servlet as controllers to divert the client request to appropriate Database stored procedures.

What are the advantages and disadvantages of this kind of designs? In my opinion if the business logic highly depends on the database than better follow this kind of design!!!!!

答:
It depends

It all depends on your team's experience and your project's requirements. Bring in a DBA to your team and decide what should you do to meet the requirements.However, with multitier application design it might not be the good decision to encapsulate business logic in stored procedure.

It will NOT matter

As long as business logic:

lives in one place

where it is properly documented

proper access is provided through services that can be loosely coupled

through a published abstracted interface

I think that business logic in programming space makes more sense when Power of Expression is important in your team/project.

I belief that SQL space is not as expressive, but it can do the job. Use the best tools you have on hand for the most appropriate tasks. Fiddling with logic and higher order concepts is best done at the highest level. Consequently, storage and mass data manipulation is best done at the server level, probably in stored procedures.


问:
How to avoid the pitfalls of static analysis
I'm working at a company that would score 11 on Joel Test - at least on paper.

In practice, however, nothing works quite as well as expected, and the project has been on DEFCON 1 for half a year. Now, most of my peers are happy if they can go back home at 6pm - on Sunday.

One of the apparently good practices that struck me as not working is the use of static analysis tools. The project both tracks gcc -Wall warnings and a proprietary and very expensive "C/C++" tool.

Gcc warnings do more often than not point to real(if most of the time inoffensive) bugs.

The proprietary tools, however, list things such as implicit casts and sizeof'ing a string literal. Implicit casts are also blacklisted on their stylebook.

The standard practice is that people is pressed to make every single warning shut up. Note that this does exclude warnings that are predominantly false positives, this is not the problem.

The result is:

People add type casts to every rvalue and to every argument hiding real problematic type mismatches in the process.

People introduce off by one bugs, or use a different problematic language feature.(strlen instead of sizeof, strncpy instead of strcpy, etc.)

The warnings are silenced.

The bug reports start rolling in.

The main point is the original code was working and written by people who were playing safe within their language abilities whereas the fixes were not.

Now, I don't really think this company can be saved. However, I would like to know if there is a better, preferably working, way to use the "pro" tools or if I should just avoid using them altogether in case I am the one making the decision in the future.

A solution which doesn't assume all programmers are geniuses that can't err. Because well, if they are, then there is no need to use the tools in the first place.

答:
In practice, however, nothing works quite as well as expected, and the
  project has been on DEFCON 1 for half a year. Now, most of my peers
  are happy if they can go back home at 6pm - on Sunday.

This is certainly a good chunk of your problem. A software engineer cannot work productively for more than 40hours/week. If you go above that, you do serious damage to your capacity to work- to the point at which even working 80 hours/week brings very little of value to the project, and sometimes, projects can even regress because the team introduces more errors than they can fix. If you've been doing 60 hours/week or more for half a year, then your whole team needs a good long break, and to come back at 40hours/week. You can't solve anything with a workforce that's hardly capable of bashing on the keyboard because they're so overworked.

The proprietary tools, however, list things such as implicit casts and
  sizeof'ing a string literal. Implicit casts are also blacklisted on
  their stylebook.

You really need to either just drop the tool entirely, or reconfigure/replace it. Warning on every implicit cast is far too much for anyone to deal with.


答:
Pros of holding all the business logic on stored procedures in web application
for:

One place is easier to maintain than multiple

Databases are fast and optimized and can be scaled well.

The same procedures can be called from mutiple, different frameworks and languages.

The logic is decoupled from the implementation in particular applications.

Rework may be reduced for changing applications when the database stays the same.

Cons of holding all the business logic on stored procedures in web application:
against:

Good SQL knowledge can be hard to find in many locations.

Good SQL coders can be expensive.

All application developers will need to be able to either change it or request a quick change.

Some data that is less well suitable to a SQL database, e.g. image data or document data may not be available in the database and it may be hard to integrate it with the stored procedures..

Title: Pros and Cons of holding all the business logic in stored procedures in web application

Body:
In some organization I worked for web applications are developed basing all the business logic in Database stored procedures. For example, use html for view and servlet as controllers to divert the client request to appropriate Database stored procedures.

What are the advantages and disadvantages of this kind of designs? In my opinion if the business logic highly depends on the database than better follow this kind of design!!!!!


问:
Any tips to learn how to program with severe ADHD?
I have a difficult time trying to learn how to program from straight text-books. Video training seems to work well for me in my past experiences with PHP. I am trying my hardest to stay focussed and push through. Specifically I am looking to start indie game development.

Over the last two weeks I have been trying to pick the "right" language and framework to develop with. I started going through Python, but I am not really enjoying the language so far. I am constantly looking through this website to compare this language to that, and keep getting distracted.

Aside from all of this, is it possible to become a programmer when you have trouble focussing? Has anyone been through this that can recommend some advice?

答:
The best way to avoid wasting time, is to have an experienced person mentor you.

At this particular point, his most important task is to figure out what you need to do, and what technologies would suit you best, so you don't have to spend a lot of effort doing that yourself.  The research role is very time consuming - especially if you are easily distracted.

If you don't have a mentor IRL, and cannot locate one, then I would suggest putting up a question providing very detailled information about what you want to do, what you can do, and what resources you have available to you.  This would allow others to give you feedback on your situation and may save you quite a bit of time.

If you still dislike Python when you do that, then write WHY you dislike Python, and WHY you like PHP.  It is perfedtly fine to have personal preferences, and you may find that there is an approach that you have never heard of that suits you fine.


答:
I'd say (without knowing the details) that your company has made more significant mistakes and this is just the symptom: it failed to properly determine the domain of the software produced, to manage the team properly and to define reasonable goals.

If the software your team is writing is something critical that human lives depend on, static analysis tools are important and useful. Since the "cost" of a bug, measured in money (ignoring how cynical that is) is high, there are special tools required for the job. There are guidelines for both C and C++ for safely using the language features (read what to avoid and how far to go in avoiding it).

However, in such a situation having employees work on Sunday is a very bad idea, moreover from the context you've provided, I extrapolate that sloppy work is not infrequent. So if this is the case, the problem is very very big, and your management is trying to solve it by using "better" tools. Unfortunately, that's not how things work. If I'm even close to correct, I'd go as far as suggesting that you start looking for a different job. Mission-critical software done bad is something that can haunt you and ruin your professional reputation, not to mention lawsuit prospects.

If, on the other hand, your team is writing something that is far less critical, 'static analysis' tools with a high false-positive rate will only slow you down, and, as you've noted, people usually react to this by finding the local maximum in their effectiveness, in this case by simply cheating their way around the warnings, instead of trying to fix the underlying reason. So in your situation, using these tools may actually deteriorate the quality of the source code, and they should generally be avoided.

If you need to manage a software team that is writing some C or C++ code, I'd say first determine what are the main project goals. If writing bug-free code is of utmost importance (e.g., the new super awesome social app for iOS and Android doesn't fit this), then use static analysis, maybe even go as far as formal specification and formal verification. But if this is the case, choosing good programmers and having them work in a sane environment with adequate workload and proper 40 hour week is far more important.

People cannot work responsibly if they're treated like slaves (and someone occupying my holidays is exactly this) and good programmers will simply refuse to do this on a regular basis, unless they know no better (and if they're good, chances are they do).

Bottom point: Figure your goals, then determine the tools and the process you use, don't let the available tools define the process (ergo the goals) as (bad) management might want to force you.

Title: How to avoid the pitfalls of static analysis

Body:
I'm working at a company that would score 11 on Joel Test - at least on paper.

In practice, however, nothing works quite as well as expected, and the project has been on DEFCON 1 for half a year. Now, most of my peers are happy if they can go back home at 6pm - on Sunday.

One of the apparently good practices that struck me as not working is the use of static analysis tools. The project both tracks gcc -Wall warnings and a proprietary and very expensive "C/C++" tool.

Gcc warnings do more often than not point to real(if most of the time inoffensive) bugs.

The proprietary tools, however, list things such as implicit casts and sizeof'ing a string literal. Implicit casts are also blacklisted on their stylebook.

The standard practice is that people is pressed to make every single warning shut up. Note that this does exclude warnings that are predominantly false positives, this is not the problem.

The result is:

People add type casts to every rvalue and to every argument hiding real problematic type mismatches in the process.

People introduce off by one bugs, or use a different problematic language feature.(strlen instead of sizeof, strncpy instead of strcpy, etc.)

The warnings are silenced.

The bug reports start rolling in.

The main point is the original code was working and written by people who were playing safe within their language abilities whereas the fixes were not.

Now, I don't really think this company can be saved. However, I would like to know if there is a better, preferably working, way to use the "pro" tools or if I should just avoid using them altogether in case I am the one making the decision in the future.

A solution which doesn't assume all programmers are geniuses that can't err. Because well, if they are, then there is no need to use the tools in the first place.


问:
Confusion regarding def function within Python
I've been learning Python for about 2 months now (Started with Learn Python The Hard Way, now reading Dive Into Python), and within both books, I still seem to be confused over this one bit of code.

Lets just take the default code that Dive Into Python uses as an example:

```<code>def buildConnectionString(params):
    """Build a connection string from a dictionary of parameters.

    Returns string."""
    return ";".join(["%s=%s" % (k, v) for k, v in params.items()])

if __name__ == "__main__":
    myParams = {"server":"mpilgrim",
                "database":"master",
                "uid":"sa",
                "pwd":"secret"
               }

print buildConnectionString(myParams)
</code>```

How does the function buildConnectionString with the argument (params) know to get its data from the variable myParams?  Or params.items(), too within the return line?  Wouldn't the argument in buildConnectionString need to be set as buildConnectionString(myParams) in order for it to read properly?  How can you set the variable of your data to myParams, but have the argument of your function be params and have it read?  How does it know to read myParams as params?

And is there a reason behind not naming your variable params, or vice versa naming your argument in your function myParams?  It's just been extremely confusing seeing the argument set as one word, and then having the variable named something completely different, but having the function still be able to read your code, even when the argument name is different from your variable with the data you're printing from.

答:
Maybe it would be clearer if the arguments were differently named?</p>

```<code>def buildConnectionString(placeholder_for_whatever_is_passed_in):
    return ";".join(["%s=%s" % (k, v) for k, v in placeholder_for_whatever_is_passed_in.items()])

if __name__ == "__main__":
    what_I_actually_pass in = { "server":"mpilgrim",
                                "database":"master",
                                "uid":"sa",
                                "pwd":"secret"   }

print buildConnectionString(what_I_actually_pass_in)
</code>```

Body:
Maybe it would be clearer if the arguments were differently named?

def buildConnectionString(placeholder_for_whatever_is_passed_in):
    return ";".join(["%s=%s" % (k, v) for k, v in placeholder_for_whatever_is_passed_in.items()])

if __name__ == "__main__":
    what_I_actually_pass in = { "server":"mpilgrim",
                                "database":"master",
                                "uid":"sa",
                                "pwd":"secret"   }

print buildConnectionString(what_I_actually_pass_in)


答:
There are 2 big cons that I usually encounter:

Inability to unit test your stored procedures. Sure there are some unit test frameworks out there, but you usually run into issues of running more than 1 set of tests at once (concurrency and transaction troubles).

Most companies will want to put a lot of login in to stored procs, but then hire 5x more application programmers (be it C#, Ruby, Java, whatever) than database programmers or DBAs, and for some reason expect that all their app coders should fully understand and be able to write performant, scalable database procedures (in PL/SQL, T-SQL, or whatever). Management usually doesn't realize that doing that is a lot like hiring a C# expert to write you some Python code, and wondering why they aren't writing amazing applications.


问:
Should architect or dev lead tell teammate where to add their code before coding a new feature?
I have experienced with two kinds of team. After a feature is assigned to me, one kind of dev lead tell me the exact file or class to add my code, another kind of team just say the story or requirement to me.

The latter job is hard, if the software I am working on is too big to grasp the structure. Should senior guys tell the place to add the code before coding?

答:
I like this question. As a software architect, my manager pulled me into his office for a 1.5 hour "chat" about how it IS MY RESPONSIBILITY to ensure that every line of code that any other developer on the team commits conforms 100% to the coding standards and architecture of the application, and basically that logic is in the right place (i.e. if a dev commits code that contains business logic coded into a button click handler instead of a business layer, then its my fault). However I was also told that we a) can't do peer programming, because it is inefficient, and b) I don't have time to do code reviews. (yes, I'm looking for a new job now).

Anyway, what I told him is that no, it is NOT my job to tell developers where to put their code exactly, but rather it is the architect's job to make the application framework and layout as intuitive as possible for the devs to determine where code should go, and to make it as easy as possible for them to put that code there.

Some software architectures can do a good job of guiding this too, for example in an "onion architecture", the UI would not have a reference (at a project level) to the DB, so you couldn't possibly put DB code in the UI button click handler (unless the developer adds the missing reference of course, which you usually also can't really prevent).

What I do consider a good technique:

Peer programming. Especially when senior level people are paired with junior level people. If one person doesn't know where code goes, the other might. Or a peer might notice someone slipping code into a place that doesn't conform to good software craftsmanship principals or patterns.

If you can't peer up to code an entire feature, then one good way to go is to get the requirements (or acceptance criteria for a story / feature), and have the architect and the feature programmer peer up for a couple hours and write all the unit tests to cover the spec. Yep, I'm talking test-driven development here. Those unit tests are usually set up to indicate the design and where code would have to be to make the tests pass. Then the (broken) tests can be handed off to the feature programmer to code alone, but his design will be largely guided by the tests, which the architect helped arrange. It really does work out well when you can't to full-time peer programming, and have programmers familiar enough with or willing to learn unit testing and TDD!


答:
It is not clear whether you are asking how to fix the problem, or how you could have avoided it in the first place.  I'm assuming the latter.

It sounds like you have been relying on static analysis as your primary means of detecting and avoiding bugs.  Maybe you would have been better off focussing more on unit tests, and dynamic tools ... such as memory checkers.

It is a bad idea to rely on a tool that generates lots of false positives, especially if you can't suppress those false positives.  It encourages tired / overworked (or lazy) programmers to make "fixes" to make the warnings go away.  If you can't selectively suppress false positives (e.g. with comments) or tailor the ruleset, then you need a better tool.  Or at least, you should only use it sparingly.

It sounds like you have a problem with people being careless and / or making mistakes due to overwork.  Maybe you should have spent more time / effort in code reviews.  This directly addresses your observation that programmers are not geniuses.

Finally, it sounds like you may have been suffering under unrealistic deadlines, poor people resourcing and / or shifting requirements.  This is a management problem, and has to be addressed at that level ... or else there is a significantly elevated risk of project failure, and long-term damage to staff productivity and morale.


问:
How to protect source code from remote developers?
My company is going to hire an external developer to create some new modules and fix some bugs in our PHP software.

We have never hired an external developer by the hour before. How can we protect the source code? We are not comfortable giving out source code and were thinking that everything remained under a surveillance enabled VPN which external developer would log in to.

Has anyone solved this problem before? If so, how?

Edit: We want the developer to see/modify the code but under surveillance and on our machine remotely. Does anybody have a similar setup?

Edit 2: NDA is just a formality. IMO, even people who are in favor of NDAs know that it'll do nothing to protect their property.

Edit 3: Let me clarify that we aren't worried about the developer copying an algorithm or a solution from the code. Code is coming out of his brain, so naturally he is the creator and he can create that again. But our code is built over several years with tens of developers working on it. Let's say I hire an incompetent programmer by mistake, who steals our years of work and then sells it to the competitor. That can make us lose our cutting edge. I know this is rare, but such a threat has to be taken under consideration if you're in business. I'll make points of my comments so its easy for everyone to communicate:

Why NDA sucks? Take this scenario, if anyone is capable of suggesting a solution to this scenario I will consider the NDA effective. Ok, here goes:
We hire 2 external developers, one of them sells our code as it is to someone else after a year. You are no longer in touch with any of the developers, how are you supposed to find out who ripped you off? NDA does provide a purpose, but you can't rely completely on that. At least we cannot.

I did not meant to offend anyone while I was posting this question, even though unintentionally I did. But again to people answering/commenting like 'I will never ever work with you' or that Men-in-black-gadget thingy: It's not about you, it's a thread about how feasible a given technical solution would be. And if anyone in this community has worked under such an environment.

About 'Trust', of course we won't hire anyone we do not trust. But is that it? Can't someone be deceitful at first? We all trusted a lot of politicians to run our country, did they not fail us ever? So, I'm saying 'trust' is a complete other layer of protection like NDA, and my question was not directed to it. My question is rather directed towards technical measures we can take to avoid such a thing from happening.

答:
Microsot did protected it's code, has anyone any idea how? well here is the thought, Microsoft paid it's employees so well that they never thought about leaving the company, the ones who left certainely tool the code with them, look at the example of Iron Python and it's development team, no one could do anything about it, it was taken to google, besides you can just get the NDA's and documents which can say that you cannot get the intellectual property, but then again

a) it's hard to proove, a developer may easily say that they had the code before they even started your company, how would you proove that wrong. I have read a lot of legal books which makes it impossible to determine that the code belonged to a certain organization.

b) There is no law in the book which prohibits writing a competitive software, if this happens it's called antitrust( there are a lot of IP lawyers who deal in antitrust cases), which means monoply in promoting open and fair competition, in england it could be reported to OFT (office of fair trading) not sure what they do in USA, from what I heard the district attorney(attorney general) or public prosecutor deals with these cases.


答:
It depends on the core architecture of the system. Some of them (including some really big that I have seen from inside) have NO internal structure, to me they merely are collections of parallel solutions to a bunch of tasks, eventually forming a system or framework. In these cases, it can be an open question if the senior should or should not tell such things - and the answer likely depends on taste and habits. I prefer another way (which is a subjective judgement, it took me several years to create this architecture).

I was a lead programmer in a country-wide data management system. This means a rather "horizontal" application structure: lots of guided data management on hierarchical data structures (like personal data, property information, ...) and higher level actions: tender application and progress workflow, filing, notification letters, etc. I am sure that without a clear internal structure such systems just collapse in time because of their own weight (keep all old stuff but constantly change all existing tenders, letters, while adding new ones; most of the time working under irrational deadline pressure).

So we have created support components ("toolkit") for database access, direct data manipulation screens, forms, letters, workflows, ...; and high level services, like a filing system capable of collecting, displaying any document of any type for a case of a client, or the form manager that was responsible for let the client fill a specific type of form, it (and not the form business logic) managed the filing, storing, etc.

Behind this structure we had configuration tables where the individual gui declaration, the associated business logic, etc. had to be registered, and if it was there, the feature was integrated to the system. Of course all components had clever abstract base classes, so most of them were ready to use (like managing the new hierarchical data type in sometimes multiple data tables) by configuration, without any coding.

Consequentially, the mentioned question NEVER even appeared.

NO, I have never told anyone the name of the classes (I would have done it in case of name collision among the multiple modules - this never happened).

NO, never told where to put it (it was the responsibility of the team working on that specific area, designing their own package and protection scheme).

YES there were exact configuration settings that they had to make to have their components and codes work in the system.

YES, there were several base classes to derive from, with exact locations where they should add their specific code, and API to access other system components. All created based on experience of developers working on that field for say 5-10 years (not on my personal ideas), and eventually had tens or maybe hundred working examples to similar tasks in the same system.

NO, there were absolutely no "shortcuts" allowed. If they were really important (without an acceptable workaround), they were also integrated to the toolkit layer. In some cases, months or years ago :-)

and sorry, YES, the wiki documentation was always behind the features, because most of the stuff was designed and implemented "backwards", by grabbing the initial features from actual tasks and constantly adding new services, instead of planning forwards.

The system lives today, many years after I have left the company (therefore this is only my subjective opinion, they may think differently), and as far as I know, reused in new systems. The only problem is that working in this environment is boring. (Or they are too polite to tell the truth... :-) )


问:
Are XAML UI designers common today?
I am thinking about creating a silverlight application, and I lack the skills to create a good looking UI.

Today's graphic designers usually know HTML and CSS and thus save me the trouble of doing something I am not very good with.

Is this the same case with XAML?

Do I have to hire two employees for this job?

答:
Silverlight is a pretty cool technology, but I'm seriously concerned about its future. However, if you want a cool UI done in XAML... you have several options.

Hire a Silverlight/WPF dev and hope they also design / See #3

Hire a UX designer with XAML skillz

Hire a great graphic designer and then hire #1 OR you can use the built-in Ai/PSD to XAML tools in Expression Studio (design).

Tons of options, if you are a small company you may even qualify for Bizspark ( a free version of Expression Studio).

Good luck.

Title: Are XAML UI designers common today?


问:
why control + alt + delete couldn't be intercepted by any application
The secure attention key is designed to make login spoofing impossible, as the kernel will suspend any program, including those masquerading as the computer's login process, before starting a trustable login operation.

Why cannot other programs simulate control+alt+del?

What is the reason behind this?

答: The answer is that it can be intercepted -- you just have to do it before it gets to Windows (i.e at the driver level or the firmware of the device).  The reason you can't intercept it once the OS has it is because the OS doesn't allow it.


答:
The latter job is hard, if the software I am working on is too big to grasp the structure. Should senior guys tell the place to add the code before coding?

Part of the job a lead to help grow the skills of those around him.  Growth is not possible if you are never given a chance to solve the hard problems.  The lead should be there to help, answer questions, and put you back on track if you need it.  In general they should not give you the solutions. You should come up with the solutions, possibly with their help, and certainly with their guidance.


问:
Is "Mapper" a valid design pattern or is it a variation of the "Factory" pattern?
A common pattern I see is what's known as the Mapper pattern (not to be confused with DataMapper which is something else entirely), which takes as an argument some kind of "raw" data source (e.g. an ADO.NET DataReader or DataSet) and maps the fields to properties on a business/domain object.  Example:

```<code>class PersonMapper
{
    public Person Map(DataSet ds)
    {
        Person p = new Person();
        p.FirstName = ds.Tables[0].Rows[0]["FirstName"].ToString();
        // other properties...
        return p;
    }
}
</code>```

The idea being your Gateway/DAO/Repository/etc. will call into the Mapper before it returns, so you get a rich business object versus the underlying data container.

However, this seems to be related, if not identical, to the Factory pattern (in the DDD parlance, anyways), which constructs and returns a domain object.  Wikipedia says this re: the DDD Factory:

Factory: methods for creating domain objects should delegate to a specialized Factory object such that alternative implementations may be easily interchanged.

From that quote the only difference I could think of is that the DDD-style Factory could be parameterized so it could return a specialized type of object if the need arose (e.g. BusinessCustomer versus ResidentialCustomer) while the "Mapper" is keyed to a specific class and only does translation.

So is there a difference between these two patterns or are they essentially the same thing with different names?

答:
the answer to your question : Is “Mapper” a valid design pattern ? is yes.
Mapper pattern, is also known like Translator Pattern and is a documented pattern :
http://www.iro.umontreal.ca/~keller/Layla/translator.pdf</p>


答:
In theory, the pros and cons are as so:

Pros:

One place to contain all of the business logic

Possibly faster applications because multiple SQL queries and such can be performed in one "round trip" to the database

Trivial to make use of the stored procedures from multiple applications

Cons:

A DBA will be required for performance tuning

All developers will have to be very well versed in your particular SQL dialect(T-SQL, Pl/SQL, etc)

SQL code isn't as expressive and thus harder to write when covering higher level concepts that aren't really related to data

A lot more unnecessary load on the database

Now, practically, only a fool would have all business logic in the database.

Very few developers will be able to create a consistent stored procedure interface that works easily across applications. Usually this is because certain assumptions are made of that calling application

Same goes for documenting all of those stored procedures

Database servers are generally bottlenecked enough as it is. Putting the unnecessary load on them just further narrows this bottleneck. Intricate load balancing and beefy hardware will be required for anything with a decent amount of traffic

SQL is just barely a programming language. I once had the pleasure of maintaining a scripting engine written as a T-SQL stored procedure. It was slow, nearly impossible to understand, and took days to implement what would have been a trivial extension in most languages

What happens when you have a client that needs their database to run a different SQL server? You'll basically have to start from scratch -- You're very tied to your database. Same goes for when Microsoft decides to deprecate a few functions you use a couple hundred times across your stored procedures

Source control is extremely difficult to do properly with stored procedures, more so when you have a lot of them

Databases are hard to keep in sync. What about when you have a conflict of some sort between 2 developers that are working in the database at the same time? They'll be overwriting each others code not really aware of it, depending on your "development database" setup

The tools are definitely less easy to work with, no matter which database engine you use.

So, to objectively answer the question. In most cases, stored procedures are only needed in some cases. For instance, if you have a report to generate where you need to do a lot of conditional processing across a couple of big tables, you wouldn't want your application to be making a couple hundred SQL queries to the database. You'd want to make a stored procedure so you didn't have the network lag overhead. And, you'll usually only want to make stored procedures otherwise for when clients want to run a custom-ish query across your database. Stored procedures and views can make this easily possible without your clients being a database whiz.


问:
Do some best practices depend on skill?
Is there evidence that some software development best practices depend on programming skill level? I mean, these methods are good, but maybe the way the are used or the extent might vary?

This question arose after I read Paul Graham's commentary about OOP, and the last bullet point of this accepted answer. It proposes that where, how, and how much to use unit tests might depend on your programming skill.

So do top programmers use different approaches than average programmers?

答:
An approach does depend on one's skills and especially experience. A novice programmer is using the methods he knows to solve a problem, and usually there isn't a wide variety of methods that a novice can suggest. On the other hand, more experienced programmers have solved more problems, they know many solutions and know when each of them will works best.

In addition, novice programmers aren't usually given tasks where they have to apply various techniques and patterns. The more experienced the developer is, the harder (and more interesting, as a consequence) tasks they get.

The problem is that many programmers just don't know how to apply their knowledge correctly. They might know a lot of design patterns, techniques, but have little (or no) experience applying them. So they only make their code more complicated and less maintanble trying to give a "smart" solution.

But of course if some bright newcomer suggests a nice approach requiring a lot of skills, no one will tell him it's too good for him. Vice verse, he/she will be encouraged to keep working the same way.

Title: Do some best practices depend on skill?


答:
Short Answer: Yes, that is why it is good for novice developer to learn and follow common programming practices.

Actually, understanding the inner-workings (business process flow) of a project and fixing bugs is a good starting point for novice developer. Learning from code is also good with good debugging skills as pre-condition. That said, it is a common approach that experienced one would also follow.

It is also true that understanding of programming problem challenge varies by experience. The novice programmer just gets the requirements and start to code, while experienced developer take time to read requirements and clarify them with BA or PM before starting to code.

Thus, getting advice from experienced developers is very essential learning process.

What is advice in nerd language? - In aspect and functional programming, advice describes a class of functions which modify other functions when the latter are run; it is a certain function, method or procedure that is to be applied at a given join point of a program.

Title: Do some best practices depend on skill?

Body:
Is there evidence that some software development best practices depend on programming skill level? I mean, these methods are good, but maybe the way the are used or the extent might vary?

This question arose after I read Paul Graham's commentary about OOP, and the last bullet point of this accepted answer. It proposes that where, how, and how much to use unit tests might depend on your programming skill.

So do top programmers use different approaches than average programmers?