答:
Citing @YannisRizos here:

That's an instinctual approach and it's probably correct, as what's more probable to
  change is the business logic of managing ledgers. If that happens, it'd be a lot easier
  to maintain one class than three.

I disagree, at least now, after about 30 years of programming experience.  Smaller classes IMHO are better to maintain in almost every case I can think of in cases like this one. The more functions you put into one class, the less structure you will have, and the quality of your code degrades - each day a little bit. When I understood Tarun correctly, each of these 3 operations

```<code>LedgerLandingPage

CreateNewLedgerEntryPage

ViewLedgerEntryPage
</code>```

is a use case, each of these classes consist of more than one function to perform the related task, and each one can be developed and tested separately. So creating classes for each of them groups things together which belong together, making it much easier to identify the part of the code to be changed if something is to change.

If you have common functionalities between those 3 classes, they belong either in a common base class, the Ledger class itself (I assume you have one, at least, for the CRUD operations) or in a separate helper class.

If you need more arguments for creating lots of smaller classes, I recommend to have a look into Robert Martin's book "Clean Code".

Body:
Citing @YannisRizos here:

That's an instinctual approach and it's probably correct, as what's more probable to
  change is the business logic of managing ledgers. If that happens, it'd be a lot easier
  to maintain one class than three.

I disagree, at least now, after about 30 years of programming experience.  Smaller classes IMHO are better to maintain in almost every case I can think of in cases like this one. The more functions you put into one class, the less structure you will have, and the quality of your code degrades - each day a little bit. When I understood Tarun correctly, each of these 3 operations

LedgerLandingPage

CreateNewLedgerEntryPage

ViewLedgerEntryPage

is a use case, each of these classes consist of more than one function to perform the related task, and each one can be developed and tested separately. So creating classes for each of them groups things together which belong together, making it much easier to identify the part of the code to be changed if something is to change.

If you have common functionalities between those 3 classes, they belong either in a common base class, the Ledger class itself (I assume you have one, at least, for the CRUD operations) or in a separate helper class.

If you need more arguments for creating lots of smaller classes, I recommend to have a look into Robert Martin's book "Clean Code".


问:
Meaningful concise method naming guidelines
Recently I started releasing an open source project, while I was the only user of the library I did not care about the names, but know I want to assign clever names to each methods to make it easier to learn, but I also need to use concise names so they are easy to write as well.

I was thinking about some guidelines about the naming, I am aware of lots of guidelines that only care about letters casing or some simple notes. Here, I am looking after guidelines for meaningful but yet concise naming.

For example, this could be part of the guidelines I am looking after:

Use Add when an existing item is going to be added to a target, Use
Create when a new item is being created and added to a target.

Use Remove when an existing item is going to be removed from a target,
Use delete when an item is going to be removed permanently.

Pair AddXXX methods with RemoveXXX and Pair CreateXXX methods with
DeleteXXX methods, but do not mix them.

As the above samples show,I would like to find some online material helping me with naming methods and other item complying with English grammar and word meanings.

The above guidance may be intuitive for native English speakers, but for me that English is my second language I need to be told about things like this.

答:
The temptation to codify a style or convention for naming can in some cases lead to habits that are considered poor practice nowadays, such as using Hungarian Notation for example. The simple answer is to forget about naming convention and style as if it were some separate thing to be determined separately, and instead to focus on naming everything in your system based on what it actually represents. Method names will be naturally tend to be concise if you limit the functionality of each method so that it does only one thing notionally, and if your method name actually describes the one thing that the method is supposed to do.

Variables, fields, class and file names are something else.  I'd suggest that if the variable names are getting too long, then you are trying to either describe these items in too great a detail, or they represent something complex that should either be broken into smaller parts, or perhaps described in a more abstract manner.

At the end of the day, you want to avoid ugly code with names that take up an entire row, or that are so glib as to rob them of their value.

ContentLicense: CC BY-SA 3.0


问:
How do regular expressions actually work?
Say you have a document with an essay written. You want to parse this essay to only select certain words. Cool.

Is using a regular expression faster than parsing the file line by line and word by word looking for a match?  If so, how does it work?  How can you go faster than looking at each word?

答:
It is plausible that in some high-level languages (perhaps javascript), using a regex library implemented in a low-level language (perhaps C) would be faster than writing parser logic in the high-level language.

Plausible - I have no idea if this is ever actually the case.


问:
How to organize functional programs

Possible Duplicate:

  Functional Programming vs. OOP

  How to write manageable code with functional programming?

In OOP, your basic unit of organization for code is the class. A frequently used methodology in Java, C# and similar languages is to organize your code around having one file for each class with the file name following the class name.

You can consider each of these class as a unit of organization to group a single concept.

These classes are in in namespaces which often follow the directory structure of the files in the solution/project. Namespaces are another level of organization.

How are large projects in functional languages typically organized?

How to you determine how to split your functions into different files?

Are other units of grouping beside files used?

How is code typically organized within a single file?

答:
I suspect this depends on language. As far as functional programming, I have mostly dabbled in Haskell, so I'm going to explain how it works there.

Haskell code is organized into "modules" which are basically just collections of functions and data types. Each module is a single file. A module is something of a mix between a Java class and a Java package--the exact scope of what a module does varies. A module also has control over which functions and type constructors to export, and which ones to hide; this is similar to private and public in Java.

In my own programs, I like to have modules do one thing, semantically; this makes them like a Java class except that they might define multiple data types. The modules I use from the standard library, like Data.List, are more like packages--they provide a set of similar utility functions. This is also very similar to static Java classes like java.util.Arrays.

The modules are also like Java packages in that they can be nested for clarity (I do not think this has any effect on the code itself). In general, for a single project, I give it a name (say Project) and have all of my modules be part of this (e.g. Project.Parse and Project.Run). If I was writing code that was more like a library than an application, I would organize it based on what it was doing, like Data.List or Control.Monad. One major difference from other languages is that Haskell encourages limiting IO and putting it all in one place. A large number of modules do no IO at all, and for any given project, I like to have as many modules be pure as possible.

As an example, I am working on a simple programming language I'm calling TPL (for no good reason). For this I have created two simple modules: TPL.Parse which defines the internal representation of the language and how to parse it, and TPL.Run which runs the interpreter and deals with variables and IO. For actually compiling and running the code, there is generally a Main module which is what ends up being the entry point of the program.

There is significant freedom in organizing the functions within a file; this is just what I like to do. I define my data types towards the top, before they are used elsewhere. Right after defining the data types, I implement whatever I need to make them part of their appropriate typeclasses--this is sort of like implementing an interface. Then I follow with logic and various helper functions, as appropriate. Finally, I like to have all of my IO functions at the very bottom ending with main. This makes it clear exactly what is doing any IO and where the program starts.

So, in summary: functions are contained in modules, each of which is made up of a single file. Several modules can make up a program or library; the former generally includes a Main module that is its entry point. Within a file, there are different options for organization, but I prefer to group data types near the top, IO near the bottom and logic in the middle.

Title: How to organize functional programs


答:
How does it work?

Take a look at automata theory

In short, each regular expression has an equivalent finite automaton and can be compiled and optimized to a finite automaton. The involved algorithms can be found in many compiler books. These algorithms are used by unix programs like awk and grep.

However, most modern programming languages (Perl, Python, Ruby, Java (and JVM based languages), C#) do not use this approach. They use a recursive backtracking approach, which compiles a regular expression into a tree or a sequence of constructs representing various sub-chunks of the regular expression. Most modern "regular expression" syntaxes offer backreferences which are outside the group of regular languages (they have no representation in finite automata), which are trivially implementable in recursive backtracking approach.

The optimization does usually yield a more efficient state machine. For example: consider aaaab|aaaac|aaaad, a normal programmer can get the simple but less efficient search implementation (comparing three strings separately) right in ten minutes; but realizing it is equivalent to aaaa[bcd], a better search can be done by searching first four 'a' then test the 5th character against [b,c,d]. The process of optimization was one of my compiler home work many years ago so I assume it is also in most modern regular expression engines.

On the other hand, state machines do have some advantage when they are accepting strings because they use more space compared to a "trivial implementation". Consider a program to un-escape quotation on SQL strings, that is: 1) starts and ends with single quotation marks; 2) single quotation marks are escaped by two consecutive single quotations. So: input ['a'''] should yield output [a']. With a state machine, the consecutive single quotation marks are handled by two states. These two states serve the purpose of remembering the input history such that each input character is processed exactly only once, as the following illustrated:

```<code>...
S1->'->S2
S1->*->S1, output *, * can be any other character
S2->'->S1, output '
S2->*->END, end the current string
</code>```

So, in my opinion, regular expression may be slower in some trivial cases, but usually faster than a manually crafted search algorithm, given the fact that the optimization cannot be reliably done by human.

(Even in trivial cases like searching a string, a smart engine can recognize the single path in the state map and reduce that part to a simple string comparison and avoid managing states.)

A particular engine from a framework/library may be slow because the engine does a bunch of other things a programmer usually don't need. Example: the Regex class in .NET create a bunch of objects including Match, Groups and Captures.

Title: How do regular expressions actually work?

Body:
Say you have a document with an essay written. You want to parse this essay to only select certain words. Cool.

Is using a regular expression faster than parsing the file line by line and word by word looking for a match?  If so, how does it work?  How can you go faster than looking at each word?

Body:
How does it work?

Take a look at automata theory

In short, each regular expression has an equivalent finite automaton and can be compiled and optimized to a finite automaton. The involved algorithms can be found in many compiler books. These algorithms are used by unix programs like awk and grep.

However, most modern programming languages (Perl, Python, Ruby, Java (and JVM based languages), C#) do not use this approach. They use a recursive backtracking approach, which compiles a regular expression into a tree or a sequence of constructs representing various sub-chunks of the regular expression. Most modern "regular expression" syntaxes offer backreferences which are outside the group of regular languages (they have no representation in finite automata), which are trivially implementable in recursive backtracking approach.

The optimization does usually yield a more efficient state machine. For example: consider aaaab|aaaac|aaaad, a normal programmer can get the simple but less efficient search implementation (comparing three strings separately) right in ten minutes; but realizing it is equivalent to aaaa[bcd], a better search can be done by searching first four 'a' then test the 5th character against [b,c,d]. The process of optimization was one of my compiler home work many years ago so I assume it is also in most modern regular expression engines.

On the other hand, state machines do have some advantage when they are accepting strings because they use more space compared to a "trivial implementation". Consider a program to un-escape quotation on SQL strings, that is: 1) starts and ends with single quotation marks; 2) single quotation marks are escaped by two consecutive single quotations. So: input ['a'''] should yield output [a']. With a state machine, the consecutive single quotation marks are handled by two states. These two states serve the purpose of remembering the input history such that each input character is processed exactly only once, as the following illustrated:

...
S1->'->S2
S1->*->S1, output *, * can be any other character
S2->'->S1, output '
S2->*->END, end the current string

So, in my opinion, regular expression may be slower in some trivial cases, but usually faster than a manually crafted search algorithm, given the fact that the optimization cannot be reliably done by human.

(Even in trivial cases like searching a string, a smart engine can recognize the single path in the state map and reduce that part to a simple string comparison and avoid managing states.)

A particular engine from a framework/library may be slow because the engine does a bunch of other things a programmer usually don't need. Example: the Regex class in .NET create a bunch of objects including Match, Groups and Captures.


问:
What's the worst programming book you've ever read?
What's the worst programming-related or technical book you've ever read? This can be any book which one way or another can be connected to programming, as long as it's not fiction.</p>

答:
Worst. Book. Ever.

It's the size of a phone book, and it's laid out like a sort of recipe book. It's basically a massive collection of thousands of code snippets for accomplishing various tasks, taken completely out of context and often wrong or broken or dated.

The only thing more hilarious is their follow-up book, Jamsa's C/C++/C# Programmers Bible. Because those languages are totally interchangeable, right?

Would you buy a book on programming from this man?

ContentLicense: CC BY-SA 2.5


问:
Converting Fortran 77 code to C#
I'm trying to convert a Fortan77 program to C#. I have a subroutine with about 650 lines of code and horrific GOTO statements all over the place. I'm having a lot of trouble even starting to visualise the flow of the subroutine to figure out what it does.

Is there anybody with experience in this sort of thing who could give me any advice on how to get an overview of this subroutine? Are there some tools available to speed up or facilitate this type of conversion?

答:
In addition to what Daniel B wrote above, I would say the following:

First, get your Fortran code to work with Fortran for DotNet. Not if you "can't get anywhere with the reprogramming", but before you attempt any reprogramming. It will be a small step, but in the right direction.

Then, write a test suite in C# which feeds the Fortran code with whatever input it was made to munch on, and stores the output. Run the test suite once, and save the output. Then, extend the test suite to test the produced output against the saved output. Assuming that the Fortran code always produces the same output when fed the same input, the test should of course succeed.

Then, while you are rewriting the code in C#, you will be running your code under the test suite, and it will be telling you whether your code is working properly or not, meaning, whether it is producing the exact same output as the Fortran code given the same input. Without it, you will be lost.

I do not agree with @SK-logic, you should NOT have to use any gotos at all in your C# code.

(But hopefully once you have made the Fortran code work under DotNet you will see no reason to continue wasting your time converting a piece of spaghetti code to C#.)

Title: Converting Fortran 77 code to C#


答:
Your task is tricky. You really need to know Fortran well. You have to be careful about how similar/different Fortran does calculations and what rules of truncation and rounding apply. Also, you need to be careful about the primitive types meaning in C# and Fortran.

Another approach from what has been suggestion (not necessarily a better one, it is just another one):

A - Consider re-writing the code in C# based on the business knowledge and the function, use the Fortran code just as a reference

B -Consider using a commercial tool that does the conversion job - Example: DataTek

If the routine represents a standard function or a function that you can buy a ready  made dll for (such as numerical integration), use the standard function or the commercial product instead of manual translation, and your problem is solved.

If the above does not cut it, answer this question:

Do I need to optimize the code or just make it run. In other words, what is the business value of spending 500 hours to make the code better?

if there is no value in optimization, translate the code line by line and you are done.

If this is still not good, then:

0-Convert the Fortran code line by line into C# (or use Fortan CLR)

1-Do a quick test make sure it runs

2-Use a re-factoring (commercial tools are available) to help you write the code in a more optimized fashion.

Good luck.

Title: Converting Fortran 77 code to C#

Body:
I'm trying to convert a Fortan77 program to C#. I have a subroutine with about 650 lines of code and horrific GOTO statements all over the place. I'm having a lot of trouble even starting to visualise the flow of the subroutine to figure out what it does.

Is there anybody with experience in this sort of thing who could give me any advice on how to get an overview of this subroutine? Are there some tools available to speed up or facilitate this type of conversion?


问:
How can I deal with the cargo-cult programming attitude?
I have some computer science students in a compulsory introductory programming course who see a programming language as a set of magic spells, which must be cast in order to achieve some effect (instead of seeing it as a flexible medium for expressing their idea of solution).

They tend to copy-paste code from previous, similar-looking assignments without considering the essence of the problem.

Are there some exercises or analogies to make these students more confident that they can, and should, understand the structure and meaning of each piece of code they write?

答:
You could present them a series of exercises, each one building on the previous while adding some extra element or twist to the problem, or investigating the issue from a different perspective, which reveals a weakness of the previous solution, requiring a new, different approach. This forces them to think about, analyse, modify and experiment with each solution, instead of just copy-pasting a ready-made piece of code.

Another possibility - although not strictly a programming task - is to ask them to estimate various things. E.g. how much water flows through the Mississippi delta per second? Such questions don't have a set answer, especially because one needs to make certain assumptions to get to a convincing (range of) value(s). And - although answers to many of these "classic" ones can be googled indeed - you can easily make up new ones which aren't (yet) found anywhere on the net.

Examples to both of these kinds of exercises can be found in e.g. Programming Pearls by Jon Bentley. Also The Pragmatic Programmer has some good challenges.

A third kind of task would be to present them some piece of code with (one or more) bugs in it, which they must find and fix. This again forces them to use their analytical skills and reason about how the program is actually working.

Update

Feedback from a comment by Billy ONeal:

The problem with the "series of exercises" is that students who have a problem with an earlier exercise are completely screwed for remaining exercises.

You are right, although I feel this is more about the general problem of setting course difficulty to the right level / grouping students of similar skill level together. Moreover, one can arrange the students into smaller groups where they are required to discuss and debate about the problems and solutions, and solve the problems together. If someone doesn't get it, the others can help (this setup would improve teamwork skills too). And if someone tries to be lazy and let the others do all the work, it is surely noticed by the teacher (who is supposed to be walking around, supervising and mentoring the students, not playing WoW on his laptop in the corner ;-)

And one can also adjust the exercises to accommodate students with different skill levels. Beginners can go slower, experienced ones faster.


问:
How should data be passed between client-side Javascript and C# code behind an ASP.NET app?
I'm looking for the most efficient / standard way of passing data between client-side JavaScript code and C# code behind an ASP.NET application. I've been using the following methods to achieve this but they all feel a bit of a fudge.

To pass data from JavaScript to the C# code is by setting hidden ASP variables and triggering a postback:

```<code><asp:HiddenField ID="RandomList" runat="server" />

function SetDataField(data) {
      document.getElementById('<%=RandomList.ClientID%>').value = data;
}
</code>```

Then in the C# code I collect the list:

```<code>protected void GetData(object sender, EventArgs e)
{
      var _list = RandomList.value;
}
</code>```

Going back the other way I often use either ScriptManager to register a function and pass it data during Page_Load:

```<code>ScriptManager.RegisterStartupScript(this.GetType(), "Set","get("Test();",true);
</code>```

or I add attributes to controls before a post back or during the initialization or pre-rendering stages:

```<code>Btn.Attributes.Add("onclick", "DisplayMessage("Hello");");
</code>```

These methods have served me well and do the job, but they just don't feel complete. Is there a more standard way of passing data between client side JavaScript and C# back-end code?

I've seen some posts like this one that describe HtmlElement class; is this something I should look into?

答:
Microsoft have implimented the UpdatePanel control to do ajax so that is arguably the "standard" way. I wouldn't personally recommend using it though, it has nowhere near the rich feature set and control you have when using JavaScript directly.

This is the way I personally do it:

Create hidden fields for any client side values you want to use in a standard page postback (ie when user hits submit)

```<code><asp:HiddenField ID="selectedProduct" runat="server" />
</code>```

In the code behind register the controls you want to use client side.

```<code>    /* Register the controls we want to use client side */

    string js = "var productBox = document.getElementById('" + selectedProduct.ClientID + "'); ";
    js += "var macCodeBoxBE = document.getElementById('" + beMacCode.ClientID + "'); ";

    ClientScript.RegisterStartupScript(this.GetType(), "prodBox", js, true);
</code>```

Use a javascript library* to do your ajax post/get then use JavaScript to update the page based on the response

```<code>$.get("../ajax/BTBookAppointment.aspx?dsl=" + telNumberBox.value + "&date=" + requiredDate.value + "&timeslot=" + ddTimeslot.value, function (response, status, xhr) {

    if (response.indexOf("not available") > -1) {
        loaderImage.src = "../images/cross.png"
        output.innerHTML = response;
    } });
</code>```

Write a seprate "ajax" page that overrides the render method to do the work.

```<code>protected override void Render(HtmlTextWriter writer)
{
    if (string.IsNullOrEmpty(Request["mac"])) { return; }
    if (string.IsNullOrEmpty(Request["dsl"])) { return; }
    DataLayer.Checkers.BTmacCheckResponse rsp = DataLayer.Checkers.Foo.CheckMAC(Request["dsl"], Request["mac"]);

    writer.Write(rsp.Valid.ToString());
}
</code>```

* There are plenty of libraries to choose from, you can even roll your own. I would recomend jQuery, its stable and has an extensive feature set.

Body:
Microsoft have implimented the UpdatePanel control to do ajax so that is arguably the "standard" way. I wouldn't personally recommend using it though, it has nowhere near the rich feature set and control you have when using JavaScript directly.

This is the way I personally do it:

Create hidden fields for any client side values you want to use in a standard page postback (ie when user hits submit)

<asp:HiddenField ID="selectedProduct" runat="server" />

In the code behind register the controls you want to use client side.

    /* Register the controls we want to use client side */

    string js = "var productBox = document.getElementById('" + selectedProduct.ClientID + "'); ";
    js += "var macCodeBoxBE = document.getElementById('" + beMacCode.ClientID + "'); ";

    ClientScript.RegisterStartupScript(this.GetType(), "prodBox", js, true);

Use a javascript library* to do your ajax post/get then use JavaScript to update the page based on the response

$.get("../ajax/BTBookAppointment.aspx?dsl=" + telNumberBox.value + "&date=" + requiredDate.value + "&timeslot=" + ddTimeslot.value, function (response, status, xhr) {

    if (response.indexOf("not available") > -1) {
        loaderImage.src = "../images/cross.png"
        output.innerHTML = response;
    } });

Write a seprate "ajax" page that overrides the render method to do the work.

protected override void Render(HtmlTextWriter writer)
{
    if (string.IsNullOrEmpty(Request["mac"])) { return; }
    if (string.IsNullOrEmpty(Request["dsl"])) { return; }
    DataLayer.Checkers.BTmacCheckResponse rsp = DataLayer.Checkers.Foo.CheckMAC(Request["dsl"], Request["mac"]);

    writer.Write(rsp.Valid.ToString());
}

* There are plenty of libraries to choose from, you can even roll your own. I would recomend jQuery, its stable and has an extensive feature set.


问:
What are the pros and cons of multiple inheritance?
What are the consequences of allowing multiple inheritance in a programming language?

What characteristics of multiple inheritance create an environment such that the use of multiple inheritance tends to result in source code that violates one or more principles of Object Oriented Programming and quality software engineering?

How does the lack of multiple inheritance in Java and other OOP languages that do not allow multiple inheritance provide the opportunity for better software quality than a language that does allow multiple inheritance like C++?

Explain and illustrate.

答:
The main consequence of multiple inheritance is the diamond problem:

In object-oriented programming languages with multiple inheritance and knowledge organization, the diamond problem is an ambiguity that arises when two classes B and C inherit from A, and class D inherits from both B and C. If a method in D calls a method defined in A (and does not override the method), and B and C have overridden that method differently, then from which class does it inherit: B, or C?

In C++ the problem is solvable via virtual inheritance:

This feature is most useful for multiple inheritance, as it causes that subobject of the virtual base will be always a common subobject for all classes that are derived in the deriving class (as well as this class itself). This can be used to avoid the problem of ambiguous hierarchy composition (known as the "diamond problem") by clarifying ambiguity over which ancestor class to use, as from the perspective of the deriving class (B in the example above) the virtual base (V) looks as if it was its direct base class, not a class being derived indirectly through its bases (A).

OOP languages of the single inheritance flavour provide some degree of multiple inheritance by multiple inheritance of interfaces and / or via traits / mixins (similar concepts). The diamond problem  occurs in those languages too, and it's dealt with mostly language specific techniques.

Now as for Java being a "pure OOP language", that's more Sun's marketing speak (and Java fanboys speak) than truth. I've seen "OOP pureness" measured by the degree a language provides / satisfies the following criteria:

All predefined and user defined types are objects,

Operations are perfomed by message passing,

Polymorphism, encapsulation, inheritance (the holy triad of OOP)

Abstraction

Following that "logic", Java supports primitive datatypes such as int and byte, hence less pure than let's say Smalltalk, where everything is truly an object. But measuring the "purity" of any characteristic of a language has no actual value, it's a juvenile "mine is better than yours" type of discussion.

Update:

I found this very interesting question on StackOverflow: How is Ruby more object-oriented than Python?:

Matz, who invented Ruby, said that he designed the language to be more object-oriented than Python. How is Ruby more object-oriented than Python?

The highest voted answer provides some great insight:

If you take the Python from 1993 and compare it with Ruby then the later is more object oriented. However, after the overhaul in Python 2.2 this is no longer true. I would say that modern Python is as object oriented as it gets.

I've often seen Ruby cultists starting holy wars based around Matz's comments on the initial design of Ruby. As the answer I reference says: You shouldn't dismiss historical context. Something that may have been true in 1993, doesn't necessarily have to be true now. The same goes for C++ cultists referencing Bjarne Stroustrup out of context, Java cultists referencing James Gosling out of context and so on.

To add to the confusion the word "pure" has mostly positive connotations:

free from anything of a different, inferior, or contaminating kind; free from extraneous matter: pure gold; pure water.

unmodified by an admixture; simple or homogeneous.

of unmixed descent or ancestry: a pure breed of dog.

free from foreign or inappropriate elements: pure Attic Greek.

clear; free from blemishes: pure skin.

But in the context of programming languages, it just means homogeneous:

composed of parts or elements that are all of the same kind; not heterogeneous: a homogeneous population.

of the same kind or nature; essentially alike.

Mathematics.

having a common property throughout: a homogeneous solid figure.

having all terms of the same degree: a homogeneous equation.

relating to a function of several variables that becomes multiplied by some power of a constant when each variable is multiplied by that constant: x 2 y 3 is a homogeneous expression of degree 5.

relating to a differential equation in which a linear combination of derivatives is set equal to zero.

Having said all that, there's only one truly pure programming language.

ContentLicense: CC BY-SA 4.0


答:
Wikipedia has a section on Criticisms for multiple inheritance, which is as good a starting point as any. Just for reference, here are the main points:

semantic ambiguity

you cannot inherit multiple times from a single class

order of inheritance changes the semantics

But more importantly, you should be careful, when talking about the very essence of OOP and languages like C++ and Java. Neither of these is a pure OOP language. Take a look at languages like Smalltalk for comparison.

Another recent trend are mixins (C#) or traits (Scala), which kind of revived multiple inheritance in a way that tries to eliminate the above criticisms to some point.

This isn't an all-out answer really, which is intentional, as from your questions I sense a lack in foundational knowledge (plus the question being potentially homework). So instead I vouched to provide you with pointers on where to go for learning more about this.

Title: What are the pros and cons of multiple inheritance?

Body:
What are the consequences of allowing multiple inheritance in a programming language?

What characteristics of multiple inheritance create an environment such that the use of multiple inheritance tends to result in source code that violates one or more principles of Object Oriented Programming and quality software engineering?

How does the lack of multiple inheritance in Java and other OOP languages that do not allow multiple inheritance provide the opportunity for better software quality than a language that does allow multiple inheritance like C++?

Explain and illustrate.


问:
Self-documenting code vs Javadocs?
Recently I've been working on refactoring parts of the code base I'm currently dealing with - not only to understand it better myself, but also to make it easier for others who are working on the code.

I tend to lean on the side of thinking that self-documenting code is nice. I just think it's cleaner and if the code speaks for itself, well... That's great.

On the other hand we have documentation such as javadocs. I like this as well, but there's a certain risk that comments here gets outdated (as well as comments in general of course). However, if they are up-to-date they can be extremely useful of say, understanding a complex algorithm.

What are the best practices for this? Where do you draw the line between self-documenting code and javadocs?

答:
Code says how.  Comments say why, and perhaps even why not.

It is your job to provide both to future readers and maintainers of your code.  Put all you can in the code, and the rest in the comments.

Note that the things hardest to capture are the design decisions - remember those too.

Title: Self-documenting code vs Javadocs?


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

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

Is there a name for this kind of logic?

Am I a tad too OCD?

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

答:
One possibility:

boolean handled = false;

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

<p>Of course, this makes the code slightly more complex in a different way. So it is largely a style question.</p>

<p>A different approach would be using exceptions, e.g.:</p>

<pre class="lang-cs prettyprint-override"><code>try
{
    contents = OpenFile(file); // throws IO exception if file not found
    DoSomething(contents); // calls SomeTest() and throws exception on failure
}
catch(Exception e)
{
    DefaultAction();
    // and the exception should be at least logged...
}
</code>```

This looks simpler, however it is only applicable if

we know precisely what kind of exceptions to expect, and DefaultAction() fits to each

we expect the file processing to succeed, and a missing file or a failing SomeTest() is clearly an erroneous condition, thus it is suitable to throw an exception on it.

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

Body:
One possibility:

boolean handled = false;

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

Of course, this makes the code slightly more complex in a different way. So it is largely a style question.

A different approach would be using exceptions, e.g.:

try
{
    contents = OpenFile(file); // throws IO exception if file not found
    DoSomething(contents); // calls SomeTest() and throws exception on failure
}
catch(Exception e)
{
    DefaultAction();
    // and the exception should be at least logged...
}

This looks simpler, however it is only applicable if

we know precisely what kind of exceptions to expect, and DefaultAction() fits to each

we expect the file processing to succeed, and a missing file or a failing SomeTest() is clearly an erroneous condition, thus it is suitable to throw an exception on it.


答:
Extract it to separate function (method) and use return statement:

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

DefaultAction();
```

<p>Or, maybe better, separate getting contents and its processing:</p>

<pre class="lang-cs prettyprint-override"><code>contents_t get_contents(name_t file)
{
    if(!FileExists(file))
        return null;

    contents = OpenFile(file);
    if(!SomeTest(contents)) // like IsContentsValid
        return null;

    return contents;
}

...

contents = get_contents(file)
contents ? DoSomething(contents) : DefaultAction();
</code>```

Upd:

Why not exceptions, why OpenFile doesn't throw IO exception:

I think that it's really generic question, rather than question about file IO. Names like FileExists, OpenFile can be confusing, but if to replace them with Foo, Bar, etc, - it would be clearer that DefaultAction may be called as often as DoSomething, so it may be non-exceptional case. Péter Török wrote about this at end of his answer

Why there is ternary conditional operator in 2nd variant:

If there would be [C++] tag, I'd wrote if statement with declaration of contents in its condition part:

if(contents_t contents = get_contents(file))
    DoSomething(contents);
else
    DefaultAction();
```

But for other (C-like) languages, if(contents) ...; else ...; is exactly the same as expression statement with ternary conditional operator, but longer. Because the main part of the code was get_contents function, I just used the shorter version (and also omitted contents type). Anyway, it's beyond this question.

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

Body:
This is a minor niggle, but every time I have to code something like this, the repetition bothers me, but I'm not sure that any of the solutions aren't worse.

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

Is there a name for this kind of logic?

Am I a tad too OCD?

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

Body:
Extract it to separate function (method) and use return statement:

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

DefaultAction();

Or, maybe better, separate getting contents and its processing:

contents_t get_contents(name_t file)
{
    if(!FileExists(file))
        return null;

    contents = OpenFile(file);
    if(!SomeTest(contents)) // like IsContentsValid
        return null;

    return contents;
}

...

contents = get_contents(file)
contents ? DoSomething(contents) : DefaultAction();

Upd:

Why not exceptions, why OpenFile doesn't throw IO exception:

I think that it's really generic question, rather than question about file IO. Names like FileExists, OpenFile can be confusing, but if to replace them with Foo, Bar, etc, - it would be clearer that DefaultAction may be called as often as DoSomething, so it may be non-exceptional case. Péter Török wrote about this at end of his answer

Why there is ternary conditional operator in 2nd variant:

If there would be [C++] tag, I'd wrote if statement with declaration of contents in its condition part:

if(contents_t contents = get_contents(file))
    DoSomething(contents);
else
    DefaultAction();

But for other (C-like) languages, if(contents) ...; else ...; is exactly the same as expression statement with ternary conditional operator, but longer. Because the main part of the code was get_contents function, I just used the shorter version (and also omitted contents type). Anyway, it's beyond this question.


答:
I have taught introductory classes in the past and as I recall looking back now:

Some students think programming is like that for different reasons. I remember once a good kid that cargo-culted a lot
what I did:

Believing that it was not an isolated issue, but other students in the same class might have similar behaviour or approaching to the problem and not express it, I was always addressing the class.

Some time was spent to explain some stuff such as determinism, which meant for them that in the same environment with the same data and code, they will have the same results (dispell the "randomness"),

Since problem solving is up to what the student's actions and not anything else, the attention should be in solving the problem and not finding the right spell,

They are in an education environment, so the problems are crafted in order to offer a learning experience, the outcome is to learn how to program (or in some cases like classes for System Administrators, how programs work, which is different) and not to give me a solution. ("World does not need another calculator, it is an exercise"), so their problems could be solved with the materials available (example: notes provided),

I think it is in Code Complete: "Even if you copy and paste, the code is yours". If someone did it, it should not be cargo-style. Every line had to be explained to me (individually) or to another student (same) or to the class.

Title: How can I deal with the cargo-cult programming attitude?

Body:
I have some computer science students in a compulsory introductory programming course who see a programming language as a set of magic spells, which must be cast in order to achieve some effect (instead of seeing it as a flexible medium for expressing their idea of solution).

They tend to copy-paste code from previous, similar-looking assignments without considering the essence of the problem.

Are there some exercises or analogies to make these students more confident that they can, and should, understand the structure and meaning of each piece of code they write?


答:
function FileContentsExists(file) {
    return FileExists(file) ? OpenFile(file) : null;
}
```

<p>...</p>

<pre class="lang-js prettyprint-override"><code>contents = FileContentExists(file);
if(contents && SomeTest(contents))
{
    DoSomething(contents);
}
else
{
    DefaultAction();
}
</code>```

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

Body:
function FileContentsExists(file) {
    return FileExists(file) ? OpenFile(file) : null;
}

...

contents = FileContentExists(file);
if(contents && SomeTest(contents))
{
    DoSomething(contents);
}
else
{
    DefaultAction();
}


答:
Using Javadocs does not make a real difference - since the generated docs contain the name of your functions together with the text from the comments, there is absolutely no reason why you should repeat anything in the comments that is clear from the function name itself.

If, on the other hand, you have a function where one has to look at the implementation first to understand what it is good for (thus not making this information available to Javadocs) , then the code is IMHO not self-documenting, no matter how clear the implementation is.

Title: Self-documenting code vs Javadocs?

Body:
Recently I've been working on refactoring parts of the code base I'm currently dealing with - not only to understand it better myself, but also to make it easier for others who are working on the code.

I tend to lean on the side of thinking that self-documenting code is nice. I just think it's cleaner and if the code speaks for itself, well... That's great.

On the other hand we have documentation such as javadocs. I like this as well, but there's a certain risk that comments here gets outdated (as well as comments in general of course). However, if they are up-to-date they can be extremely useful of say, understanding a complex algorithm.

What are the best practices for this? Where do you draw the line between self-documenting code and javadocs?


答:
Never give them similarly sounding assignments.

Or, more crazy, learn them TDD from the beginning. It pushes for writing (not copying, writing) a lot of code (namely tests) that actually helps to formulate the problem that is being solved.


答:
I think that javadocs is appropriate for the parts that should stay stable (API) so that the risk of the comments going out of date is minimized, whereas self documenting code is great for what is subject to frequent change (implementation).
Of course, APIs may change during the course of the project, but having the header just before the declaration, keeping both in sync is not that hard (compared to a comments on multiple lines explaining several lines of code)

Title: Self-documenting code vs Javadocs?


答:
Several things that come to my mind:

Give them assignments where they actually have to explain the code someone else (you) wrote. Understanding of the previous code or more specifically lack of it is both the largest cause and danger of cargo cult programming. Ask them to use comments, line by line if necessary, to explain your program in plain English (or whichever human language you use).

Only after they've explained the code, ask them to modify it in order to make a certain change. For example, if you gave them a sort function that sorts descending, ask  them to make it sort ascending. Or something more demanding. But make sure it's something that requires understanding of the given code.

You can, if you like, put some easter eggs in code. A line or two that does nothing useful or even related to the problem at all. Give them a hint that such lines exist and grant extra points to those who remove them.

Then and only then you can give them an assignment to write a piece of code from scratch on their own. At this point they should have a much better understanding of what code really is. They might even find it a little easier to do it themselves.

The basic idea is that programming is not just writing code, it's also reading it. Reading code should also be taught.


问:
What's the most effective way to perform code reviews?
I've never found the ideal way to perform code reviews and yet often my customers require them. Each customer seems to do them in a different way and I've never felt satisfied in any of them.

What has been the most effective way for you to perform code reviews?

For example:

Is one person regarded as the gatekeeper for quality and reviews the code, or do the team own the standard?

Do you do review code as a team exercise using a projector?

Is it done in person, via email or using a tool?

Do you eschew reviews and use things like pair programming and collective code ownership to ensure code quality?

答:
If you are working on a project where multiple people will contribute to the code base a standard needs to be established.

At this point, in my experience it is best to designate one person as the "king" of code review if you will and what he/she says goes.  In this regard, if one user is not adhering to standards the king will take care of it.

As a dev myself, I review my own code many many times to be readable, sensible and everything else.  Usually we use javadoc or similar in given languages we code with and use @author tag to attach ownership to functions, classes etc.

If a function is not correct we talk to owner, same with class etc.


答:
Self-documenting code (and in-code comments) and Javadoc comments have two very different target audiences.

The code and comments that remain in the code file are for developers. You want to address their concerns here - make it easy to understand what the code does and why it is the way it is. The use of appropriate variable names, methods, classes, and so on (self-documenting code) coupled with comments achieves this.

Javadoc comments are typically for users of the API. These are also developers, but they don't care about the system's internal structure, just the classes, methods, inputs, and outputs of the system. The code is contained within a black box. These comments should be used to explain how to do certain tasks, what the expected results of operations are, when exceptions are thrown, and what input values mean. Given a Javadoc-generated set of documentation, I should fully understand how to use your interfaces without ever looking at a line of your code.

Title: Self-documenting code vs Javadocs?


答:
Obviously:

Whatever(Arguments)
{
    if(!FileExists(file))
        goto notexists;
    contents = OpenFile(file); // <-- prevents inclusion in if
    if(!SomeTest(contents))
        goto notexists;
    DoSomething(contents);
    return;
notexists:
    DefaultAction();
}
```

You said you are open even to evil solutions, so using evil goto counts, no?

In fact depending on context this solution might well be less evil than either evil doing the action twice or evil extra variable. I wrapped it in a function, because it would definitely not be OK in the middle of long function (not least due to the return in the middle). But than long function is not OK, period.

When you have exceptions, they will be easier to read, especially if you can have the OpenFile and DoSomething simply throw exception if the conditions are not satisfied, so you don't need explicit checks at all. On the other hand in C++, Java and C# throwing an exception is a slow operation, so from performance point, the goto is still preferable.

Note on "evil": C++ FAQ 6.15 defines "evil" as:

It means such and such is something you should avoid most of the time, but not something you should avoid all the time. For example, you will end up using these "evil" things whenever they are "the least evil of the evil alternatives."

And that applies to goto in this context. Structured flow control constructs are better most of the time, but when you get in the situation where they accumulate too many of their own evils, like assignment in condition, nesting more than about 3 levels deep, duplicating code or long conditions, goto may simply end up being less evil.

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

Body:
Obviously:

Whatever(Arguments)
{
    if(!FileExists(file))
        goto notexists;
    contents = OpenFile(file); // <-- prevents inclusion in if
    if(!SomeTest(contents))
        goto notexists;
    DoSomething(contents);
    return;
notexists:
    DefaultAction();
}

You said you are open even to evil solutions, so using evil goto counts, no?

In fact depending on context this solution might well be less evil than either evil doing the action twice or evil extra variable. I wrapped it in a function, because it would definitely not be OK in the middle of long function (not least due to the return in the middle). But than long function is not OK, period.

When you have exceptions, they will be easier to read, especially if you can have the OpenFile and DoSomething simply throw exception if the conditions are not satisfied, so you don't need explicit checks at all. On the other hand in C++, Java and C# throwing an exception is a slow operation, so from performance point, the goto is still preferable.

Note on "evil": C++ FAQ 6.15 defines "evil" as:

It means such and such is something you should avoid most of the time, but not something you should avoid all the time. For example, you will end up using these "evil" things whenever they are "the least evil of the evil alternatives."

And that applies to goto in this context. Structured flow control constructs are better most of the time, but when you get in the situation where they accumulate too many of their own evils, like assignment in condition, nesting more than about 3 levels deep, duplicating code or long conditions, goto may simply end up being less evil.


答:
If the programing language you're using (0) short circuits binary comparisons (i.e. if doesn't call SomeTest if FileExists returns false) and (1) assignment returns a value (the result of OpenFile is assigned to contents and then that value is passed as an argument to SomeTest), you can use something like the following, but it would still be advised to you to comment the code noting that the single = is intentional.

if( FileExists(file) && SomeTest(contents = OpenFile(file)) )
{
    DoSomething(contents);
}
else
{
    DefaultAction();
}
```

Depending on how convoluted the if is, it might be better to have a flag variable (which separates the testing of success/failure conditions with the code that handles the error DefaultAction in this case)

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

Body:
If the programing language you're using (0) short circuits binary comparisons (i.e. if doesn't call SomeTest if FileExists returns false) and (1) assignment returns a value (the result of OpenFile is assigned to contents and then that value is passed as an argument to SomeTest), you can use something like the following, but it would still be advised to you to comment the code noting that the single = is intentional.

if( FileExists(file) && SomeTest(contents = OpenFile(file)) )
{
    DoSomething(contents);
}
else
{
    DefaultAction();
}

Depending on how convoluted the if is, it might be better to have a flag variable (which separates the testing of success/failure conditions with the code that handles the error DefaultAction in this case)


问:
What are the essential things one needs to know about UML?
I want my scribbles of a program's design and behaviour to become more streamlined and have a common language with other developers.

I looked at UML and in principle it seems to be what I'm looking for, but it seems to be overkill. The information I found online also seems very bloated and academic.

How can I understand UML in plain-English way, enough to be able to explain it to my colleagues? What are the canonical resources for understanding UML at a ground level?

答:
Liked the questions - same ones as I've asked myself:

How can I understand UML in plain-English way, enough to be able to
explain it to my colleagues? What are the canonical resources for
understanding UML at a ground level?

Here is what I have found:

For a kick-start: my choice would be Fowler’s *UML Distilled*.
It really is a distillation of the basics, as has been mentioned: definitions, examples, advice on when a certain type of diagram should or should not be used. It is also a good reference, if you want to focus on a certain part of UML without reading the book cover-to-cover.

For a more detailed, yet plain-English introduction: UML 2 for Dummies has done for my colleagues and me.
It not only introduces UML, its syntax and uses at length, but has a lot of advice on good programming and design practices.

There are occasional differences between the two books on what syntax belongs to which version of the UML standard. These however are minute and definitely not essential for using UML diagrams to communicate design ideas.
(For example: whether UML 2 allows discrete multiplicities, i.e. showing that a certain property may have exactly X, Y or Z objects, rather than just zero, one, many or more than X, say; when participants’ names should be underlined...)

For a totally non-academic and less wordy introduction: this blog has articles on various bits of UML:
<s>http://blog.diadraw.com/category/uml/</s>
https://web.archive.org/web/20121104015548/http://blog.diadraw.com:80/category/uml

It's not a textbook, so is far from exhaustive, but also uses non-textbook stories and examples, which are relatable to. The few available posts are focused on introducing UML concepts visually, so you can skip the reading of the text altogether.


问:
Where does jQuery fit-in with frameworks like JavaScriptMVC, BackboneJS, SproutCore and Knockout?
I have been happily using JQuery for the last 2 years and have been quite sucessful creating some really cool functionality with it...so I am very comfortable with it.  I also beleive the future of the web will continue on the current client-side path.

However...

The next challenge seems to be coming in the form of various controller frameworks: KnockoutJS, BackboneJS, SproutCore, JavaScriptMVC (the list goes on).

Additonally, there are some great AMD Loader tools for use like RequireJS or LabJS etc. However, jQuery now has define and then capabilities baked-in.

It's getting harder-and-harder to keep track of it all...

And now, my task seems to be to evaluate/decide-on a strategic-direction for using some form of either an MVC or MVVM framework client-side...but I have so many questions.

Where does JQuery fit-in with the various controller-frameworks mentioned above?

Is JQuery used alongside each or do some of them have their own 'JQuery-styled version' baked-in?

Are tools like RequireJS still needed if you implement one of the various controller-frameworks mentioned above?

Does the define and then capabilities baked-into JQuery now supercede the AMD Loader mentioned above?

Which one seems most modular? (see notes below)

NOTES:

One thing I don't want in any future-framework is the requirement of having to take-in vast amounts of functionality that I don't use.  Meaning, I would rather use a framework that is truly modular. For example, to use jQuery UI you have to take-in a lot other core libraries that you might not actually use.

I will be experimenting with each one, but some REAL feedback would be great.  I've seen some 'similar' questions, but none have really answered the above skew.

Thanks in advance!

答:
jQuery a cross browser normalization tool. It gives you the following

DOM utilities

Event system

Ajax

Animations

ES5 utilities

some other thinge

Backbone/knockout/yada/yada are MVC-like libraries that are there to help you structure and write modular application. You only need these if you want their structure.

RequireJS/yada/yada are module loaders. You need some form of module loader if you want to write a modular application.

Where does JQuery fit-in with the various controller-frameworks mentioned above?

As mentioned, jQuery normalizes browsers. controller frameworks do not. You don't need jQuery but you need some way to normalize browsers.

Is JQuery used alongside each or do some of them have their own 'JQuery-styled version' baked-in?

Backbone / knockout /  JavaScriptMVC do not have browser normalization baked in so you need a tool for that. I'm not sure about SproutCore it does seem to have a lot in there.

Are tools like RequireJS still needed if you implement one of the various controller-frameworks mentioned above?

These are only needed if you write to write modular applications. So pretty much yes.

There are three flavours of modular applications

async require loaders like requireJS

sync require loaders like modul8

using namespaces and just including files

packages like ender

Does the define and then capabilities baked-into JQuery now supercede the AMD Loader mentioned above?

No. the define capability baked into jQuery allows you to use it with an AMD loader without wrapping jQuery. You still need an AMD loader. The "then" capability is just some sugar of jQuery deferreds.

Which one seems most modular? (see notes below)

That's an opinionated question. My personal opinion is that all these frameworks including jQuery are bloated and not modular.

You want modular, write your own library, write your own architecture.

However if you want the lesser of evils I would choose backbone because it's simple and small or spine which is similar


答: Teach the class using a programming language that is technically good but is so obscure they won't be able to find any existing code to copy.</p>


答:
Before you get started, make a test suite to test the existing code. Be very thorough as this will help shed light on the behavior. You can then use this suite to gauge tne effectiveness of your conversion.

Beyond that, be methodical, don't rush, and use lots of paper to trace out the functionality.

Title: Converting Fortran 77 code to C#


答:
Did your students start at the correct 'abstraction level' at the beginning of the course? E.g. a homework that introduces them to the main programming structures like loops and conditionals without writing a single line of code?

When I took intro to programming, our first assignment was called 'Rick the Robot'. We had a piece of paper with an aerial map of a city with interesting points, like banks, grocery stores, etc... We had a dude called 'Rick' and had actions like 'take one step',  'look left', 'look right', 'cross the road' and we could use things like 'repeat' and 'if something, then do something'. (This is not 100%, as I could not find this assignment) The idea was that Rick could only use what he was given and he had to get to different places on the map.

This was a fun exercise and something that introduced you to the basics (which are sometimes the hardest to grasp to newcomers). There is no one good answer to this problem (its a game) and there are no solutions to copy and paste from. Something like this might also allow you to play with their creativity a bit more without intimidating them with code.

Finally, the idea is that you start with the abstract and move towards the concrete. They cannot copy paste abstract. They have to understand it to solve a problem.


问:
Struggling with the Single Responsibility Principle
Consider this example:

I have a website. It allows users to make posts (can be anything) and add tags that describe the post. In the code, I have two classes that represent the post and tags. Lets call these classes Post and Tag.

Post takes care of creating posts, deleting posts, updating posts, etc.
Tag takes care of creating tags, deleting tags, updating tags, etc.

There is one operation that is missing. The linking of tags to posts. I am struggling with who should do this operation. It could fit equally well in either class.

On one hand, the Post class could have a function that takes a Tag as a parameter, and then stores it in a list of tags. On the other hand, the Tag class could have a function that takes a Post as a parameter and links the Tag to the Post.

The above is just an example of my problem. I am actually running into this with multiple classes that are all similar. It could fit equally well in both. Short of actually putting the functionality in both classes, what conventions or design styles exist to help me solve this problem. I am assuming there has to be something short of just picking one?

Maybe putting it in both classes is the correct answer?

答:
As I read this question the first thing that came to mind was a Many To Many database relationship. Posts can have many Tags... Tags can have many Posts.... It appears to me that both classes need the ability to manage this relationship to some extent.

From the Post point of view...

If your editing or creating a Post a secondary activity becomes managing Tag relationships.

Add Existing Tag to Post

Revove Tag from Post

IMO, the creation of a completely new TAG does not belong here.

From the Tag point of view...

You can create a Tag without having to assign it to a Post. The only activity I see that involves interacting with a Post is a Delete Tag function. However, this function should be an independent stand alone function.

This will only work if there is a database linking table that resolves the Many to Many relationship


答:
Have you considered supplying them with some code to start with?  Whatever simple scaffolding the assignment needs, like an empty main function (I don't know what language you're using).  Something that compiles and runs and does nothing.  Then they can start adding their code with some degree of confidence that at least part of it works.

This is actually pretty common in the "real world"; lots of IDEs and other tools create empty projects with typical libraries/templates/configuration files already in place.


答:
This conforms to DRY, no-goto and no-multiple-returns rules, is scalable and readable in my opinion:

success = FileExists(file);
if (success)
{
    contents = OpenFile(file);
    success = SomeTest(contents);
}
if (success)
{
    DoSomething(contents);
}
else
{
    DefaultAction();
}
```

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


答: Similar to JoelFans idea is have them do the initial assignments on paper using a pseudo code (language) that you create. You can add the structures as you see fit and they don't worry about the magic box.</p>


答:
What you're asking them to do is demonstrate analysis and synthesis in the cognitive domain of Bloom's Taxonomy, where they're currently only demonstrating application.

Unfortunately, it's sort of a "lead the horse the water" type of situation.  Analysis and synthesis are also very difficult to do when you are still struggling with comprehension.  Without the comprehension in place, analysis and synthesis activities are going to act more as weed outs than learning activities.

My personal opinion is that it's okay not to expect anything more than application in intro to programming classes.  This is the first time students have been exposed to these concepts, so it's like teaching kids to read before asking them to write an essay.  Those higher order skills will follow in their later classes.


答:
You could ask them questions about pieces of code that require written responses? Like "What is this code doing?" "Why did the programmer solve it like this?" "Is there a better way?", etc?

That will actually get them thinking about the problem, which is something they can do without even touching code.


答:
I doubt that this behavior is because of a belief that programs are magic spells - more likely it's laziness and lack of motivation.

So I think your job as a teacher is to motivate your students - no student who's genuinely motivated will cut and paste a solution (that's only for working programmers with deadlines and bottom-lines to meet...)


问:
Is browser fingerprinting a viable technique for identifying anonymous users?
Is browser fingerprinting a sufficient method for uniquely identifying anonymous users? What if you incorporate biometric data like mouse gestures or typing patterns?

The other day I ran into the Panopticlick experiment EFF is running on browser fingerprints.

Of course I immediately thought of the privacy repercussions and how it could be used for evil. But on the other hand, this could be used for great good and, at the very least, it's a tempting problem to work on.

While researching the topic I found a few companies using browser fingerprinting to attack fraud. And after sending out a few emails I can confirm at least one major dating site is using browser fingerprinting as but one mechanism to detect fake accounts. (Note: They have found it's not unique enough to act as an identity when scaling up to millions of users. But, my programmer brain doesn't want to believe them).

Here is one company using browser fingerprints for fraud detection and prevention:

http://www.bluecava.com/

Here is a pretty comprehensive list of stuff you can use as unique identifiers in a browser:

http://browserspy.dk/

答: Browser fingerprinting relies on a very heterogeneous browser/device-ecosystem. One thing to consider is that we are moving towards a more and more homogenous ecosystem as more and more surfing is done on smartphones and tablets/pads which tend to be a lot less fragmented in this sense. IPhones/iPads will for instance all look essentially identical.</p>


答:
Look at it in another way. This cargo-cult phenomenon is the novice stage of the Dreyfus Model of skill acquisition. This is how we learn. When I first learned to program, all I was doing was typing in pages of code from the back of Compute! magazine. Repetition is key. Babies learn to talk by copying the sounds they hear their parents make. Everything we learn is through imitation. We just have to be taught how to go from imitation to mastery.

The problem you have is your students aren't repeating anything, they're copying it from the Internet. There is some benefit to that but gains are minimal. The act of actually typing out the code is what got me to a place of understanding. I started to see patterns in what I was typing and gained an understanding of what I was doing.

One option is to structure your lab as a code dojo. Have students take turns pairing with each other on the same problem. Pick a problem that takes about 10 to 15 minutes to solve. Repeat that problem over a few labs and introduce a new twist to the problem as the class' proficiency grows. Perhaps start the lab by having the students watch you program the solution, and have them repeat it. Switching pairs with each iteration.

For your tests have a code kata where each student works through the problems from the semester in front of the rest of the class. Focus not only on correctness but form and creativity. I think this would provide a deeper understanding of how to program than giving take home assignments.


问:
On the frontier between work and home
I think we've all been there:

You hear of someone say "hey, wouldn't it be nice if platform X had feature Y?" You look around (on SO!), the feature really doesn't exist, even though it probably would be useful in many contexts. So it's pretty generic.

Your mind wanders for a bit. "How tough would it be? Well, it'd probably be just a snippet. And an ad-hoc function. And maybe a wrapper." And boom, before you know it, you've spent a dozen hours of your free time implementing a FooFeature that's really neat and generic. The kind of code you might not even have the time to spit and shine at work, that would be a bit rushed and not so documented.

So now you wonder "wouldn't this be useful to others?" And you've got your blog, maybe a CodeProject account, and your colleague who asked if FooFeature exists might, haphazardly, come accross that blog entry, had it existed before they told you. On the otherhand, the NDA agreement. It's sort of vague and general. It doesn't forbid you from coding at home, but it's clear on sharing company code, that's a big NO.

But this isn't company code. Or is it? Or will it be?

So, what do you do with code (that's more than just a snippet) you wrote in your off time with universality in mind but an idea that came from work, and that will most likely be used at work? Can it be published?

答:
Questions similar to this have been asked before. It really depends on the employment agreement (contract) you have with your employer. My personal opinion is that if you did it on your own time outside of work hours, then you can do whatever you want with it, including publishing it as an open source project.

Your safest bet is to talk to your employer about what you have done and get their approval if you are unsure about how to proceed.

Title: On the frontier between work and home


答:
Consult your HR, legal, and/or ethics departments and review your contract.

For me, I can work on anything that I want to at home. I can even make libraries, publish them, and use them at work. However, I can't work on those projects at work. I also can't make products targeted toward our customers, especially those that compete with a product made by the company, even if I release them as open source products.

I've had plenty of ideas generated at work that I have or want to work on at home. For me, it's perfectly acceptable. However, depending on the terms of your contract, it might not be.

Title: On the frontier between work and home

Body:
I think we've all been there:

You hear of someone say "hey, wouldn't it be nice if platform X had feature Y?" You look around (on SO!), the feature really doesn't exist, even though it probably would be useful in many contexts. So it's pretty generic.

Your mind wanders for a bit. "How tough would it be? Well, it'd probably be just a snippet. And an ad-hoc function. And maybe a wrapper." And boom, before you know it, you've spent a dozen hours of your free time implementing a FooFeature that's really neat and generic. The kind of code you might not even have the time to spit and shine at work, that would be a bit rushed and not so documented.

So now you wonder "wouldn't this be useful to others?" And you've got your blog, maybe a CodeProject account, and your colleague who asked if FooFeature exists might, haphazardly, come accross that blog entry, had it existed before they told you. On the otherhand, the NDA agreement. It's sort of vague and general. It doesn't forbid you from coding at home, but it's clear on sharing company code, that's a big NO.

But this isn't company code. Or is it? Or will it be?

So, what do you do with code (that's more than just a snippet) you wrote in your off time with universality in mind but an idea that came from work, and that will most likely be used at work? Can it be published?


问:
Should back end processes be included in use cases in requirements document?
We're writing a requirements document for our client and need to include the use cases of the system. We're following this template:

```
ID
Description
Actors
Precondition
Basic Steps
Alternate Steps
Exceptions
Business validations/Rules
Postconditions
```

In the Basic Steps section, should we include steps that the system performs in the back end or should we only include steps that the user directly interacts with?

Example:

Basic Steps for Search 1:

```<code>User goes to search page
User enters term
User presses search
System matches search term with database entries
System displays results
</code>```

vs

Basic Steps for Search 2:

```<code>User goes to search page
User enters term
User presses search
System displays results
</code>```

答:
A use case document should describe the actions taken by the user, and the resulting actions taken by the system. Each step should have a user action and the system response, so a single step would look something like this.

user clicks search button

system will display results of search, results will be paginated if over ten, results will include title and price


答:
Just post up on your blog. If you employer complains take it down and let them keep the code.

Then start looking for a new job because you are working for jerks.
It’s not like you are looking to monitorize this thing, Why waste money on lawyers?
(My bet is you post it and nobody says a word.)

PS: Sometimes this place is just tad too politically correct.

Title: On the frontier between work and home


问:
Saying "I don't know" in a technical interview
If asked a series of technical questions in a programming interview, does it look bad to admit when you don't know the answer to a question?

In other words, does admission make you look incompetent or ill prepared?  Or, is it assumed that no one will know the answer to every question? Does admitting it instead of taking a shot in the dark make you look honest or like you're a know-it-all?

答: I would rather someone admits that they don't know then try to make up an answer. One of the greatest skills that a person can have is to know what they know and know what they don't know. It's also a great start to a discussion if you indicate what you would do to find the answer if you needed to know something to do your job.</p>


答:
You could also treat them the hard way.

Find a way to make a copy-paste harmful to them. I don't have precise example but if you craft a first exercise whose solution, if pasted in a similar looking second exercise, bring the cargo-cult students in a very long and painful "unstable instability" or "silent data corruption" bug. Meanwhile a "non cargo-cult" 2 mn thinking would have brought an obvious solution to even the worst student (hadn't he seen the first exercise solution). Then, maybe there is some possibility they could learn the lesson, and think twice before copy pasting code into the third exercise.


答:
Consider using a very high-level language that requires a minimum of boilerplate code.

To me, it's often the boilerplate code in large frameworks or verbose languages that feel like magic spells and hinders comprehension.

I was personally taught ML at my CS introductory programming course. For many years, Lisp was taught as introduction to programming at MIT. Both are excellent choices. Some of the benefits they have are

Interactive interpreter. Very important, as this allows exploration.

Very succinct. No boilerplate at all. It allows the students to concentrate on the ideas they are trying to express.

Relatively obscure and alien (at least compared to Java, C or other mainstream languages that the students may already have some experience with). Yes, I list that as a pro. It levels the playing field for the students, since likely noone will have prior experience. And it makes it less likely that they will be able to just copy-paste solutions to homework form the web.


答:
This varies widely based on location. In the US, there are generally two criteria: one of them (as @Bernard already mentioned) is whether you did the work during normal work hours. Another (that's often more important) is whether you did the work at the office or at home, and whether you used their computer or your own to do it. Generally speaking, if you did it on your own equipment outside of normal work hours, the employer would have to show specific clauses in an employment contract that said it would be theirs anyway to have any claim to it. If you did it on their computer at the office, the opposite would be true: you'd need to show some specific reason it was excluded from being theirs to have any claim to it. Using their computer at home would, from what I've seen, make it more of a gray area.

Throughout most of Europe, even writing it at home on your own computer gives you considerably less claim to the code. If what you've done is even vaguely similar to what you normally do for work, there's a pretty good chance that the courts would consider it their property.

I suspect Canadian law is somewhere between those, but offhand I don't know whether it's closer to US or European laws in this respect.

Regardless of the legality, I'd think a bit about how it's likely to affect your current job, and whether you're willing to put up with that. Even if it's technically legal, if it gets everybody who supervises you thoroughly angry, it's probably not worth it unless you really want to get a new job.

Title: On the frontier between work and home


问:
MVC Validation with ModelState.isValid through a wizard
I'm working on a small educational project on MVC 3, and I'm facing a small problem, when attempting to handle validation in my application through a wizard.

I tried to get benefit from the ability of MVC3 to deliver content of a different view using the same URL, when handling an [HttpPost] method on a page.

I my case,my main model's class contains about ten [Required] properties, that I would like to expose through a small wizard in 3 steps , So I want that the user may be able to enter his personal informations in the first step, then respond to some questions in the second stepp and finally receive a confirmation mail from the web application whit his credentials in the last step.

I can't access the last step, because of the ModelState.isValid method that I use to handle validations, and which can't perform properly if I define some properties as [Required], but don't put them on the first view.

As the replies to those questions remain in a couple of choices, I've thinked that I may use some nullable bool? for in order to avoid validation issues, but know that it's not the proper way.

Are there someone who would like to help me find a way to extend my validation to those three steps ?
Thanks in advance and sorry for my english, I'm not a native speaker.

答: Make a model for each page of the wizard rather than using the domain models you are probably using. Then you can separate the validation as appropriate.</p>


答:
Challenge them to create the shortest possible solutions to the
problem.

Reward the more succinct solutions with an incentive.

Create exercises that revolve entirely around refactoring code

Have the students trade assignments, and mock grade them for
efficiency and code cleanliness, and use some of the least
efficient ones as examples, on an overhead projector.


答: Teach subroutines.  Have them take the code they are grabbing from previous assignments and turn it into a subroutine.  Teach them about function documentation to help them understand what the subroutine is actually doing.</p>


答:
As Wyatt Barnett wrote, the most immediate solution that comes to mind is to have a specific object (one class) for each page of the wizard. If you ware using the Required annotations to make your ModelState.IsValid work, I don't think you can do it another way.

However, I think there is another way to do it as I remember I've done something very similar in Java/Struts some time ago. You could create a new class inheriting from your domain model class and add to that class just one additional property, the current step in the wizard. Now, you can't do your validation using annotations, that's the trade-off. You will have to write your own code for validating your new model (I think you have to implement the IValidatable interface) but you will be able to perform partial validations that depend on the current step in the wizard. Anyway, regardless of the chosen solution (multiple classes or one inheriting class), I think you can't use your existing annotations. The main advantage of this solution is that your wizard matches one class, so whether your wizard spans 10 different pages, or just two, the model to validate does not change, only the validation code.

Maybe you can even write some generic validation rules that will link a property to a step, and then use reflection to validate only properties of that particular step.

Also, remember that you can't really trust a "currentStep" property that comes from the client!

Title: MVC Validation with ModelState.isValid through a wizard

Body:
I'm working on a small educational project on MVC 3, and I'm facing a small problem, when attempting to handle validation in my application through a wizard.

I tried to get benefit from the ability of MVC3 to deliver content of a different view using the same URL, when handling an [HttpPost] method on a page.

I my case,my main model's class contains about ten [Required] properties, that I would like to expose through a small wizard in 3 steps , So I want that the user may be able to enter his personal informations in the first step, then respond to some questions in the second stepp and finally receive a confirmation mail from the web application whit his credentials in the last step.

I can't access the last step, because of the ModelState.isValid method that I use to handle validations, and which can't perform properly if I define some properties as [Required], but don't put them on the first view.

As the replies to those questions remain in a couple of choices, I've thinked that I may use some nullable bool? for in order to avoid validation issues, but know that it's not the proper way.

Are there someone who would like to help me find a way to extend my validation to those three steps ?
Thanks in advance and sorry for my english, I'm not a native speaker.


问:
How can I justify a technology over another? (Java over .NET)
We are working in a Java/.NET company and my team and I are planning a project for a client.

One of the requirements is that the project has to be done in .NET

I've asked about this requirement, and the client said that it doesn't matter, and that if I have a good reason we can use other technology. But, I have to justify the decision.

As a Project Manager / Analyst I'm interested in making the project in Java because:

The team knows java much better, regarding the language and frameworks

I don't know anything about .NET technology (and maybe we could make bad decisions thinking in a Java way to do things)

There are other people in company that have more skills in .NET but they have other projects with more priority.

For experience, I'm sure that if we use Java, the project will have much more quality. But this arguments could be weak from the client perspective.

How can I justify making the project in Java?

EDIT: I'm not asking if one technology is better than other. "It's not a technology war" question.

答:
I would rather answer, not as a programmer, but as a manager.  I am responsible for a future within my department where development continues to be affordable and flexible.

I prefer Java, not because Java can work on multiple platforms (who actually migrates Java apps across platforms?) but because my developers (with Java as just one of the environments) can work across multiple platforms.  I am much more concerned about nurturing developers with many skills who have an itch to learn technology.

If I buy .Net just because it lets me hire a cheap programmer or help me to stick with Windows (arguably easy to manage) then I lock my developer community to one platform.  The only guaranteed future there is that Microsoft will find a way to change it and then charge me more for the privilege.


答:
You are battling the students' balancing act of their need to care about your subject and their need to get passing grades.  Many students feel that:

(Get it Wrong || Experiment) == (Failing Grade && Waste Time)

As soon as a student feels that their time or grade is at risk, even for an interesting subject, they stop learning and jump straight to "I don't care, just give the teacher the right answer".  Your students are trying to cut corners (or so they think) by thinking as little as possible about the problem and just hacking away at it by copying and pasting.

Here are my suggestions on how to deal with this:

Use the Bob Ross method: Prove to them that it is both possible and faster to start anew vs. copying and pasting.  Create new programs before their eyes during class - really show them that programming can be like painting a picture.

Provide assignments that require creativity.  For example, have each student create their own data structures (what are the objects required to create a Zoo, Pet Store, Town, College etc.) on paper to use throughout the course.  Assignment #2 can be converting those structures to classes or objects, etc.  Basically, entice them into thinking abstractly - reward them for being creative, and then reward them for turning their creativity into a computer program.

Use the least amount of syntax possible.  Boilerplate stuff like creating classes and language syntax is so prevalent in the introduction of programming that it often misleads students into thinking that all of programming is just knowing where to put curly braces - they don't realize that what is in the middle of the curly braces is where creativity flows.  Pick a simple language, and provide sample files (such as an empty class file) for the students who still want to copy and paste something.  You can gradually become more strict about syntax and compilable assignments as the course progresses.


答:
I'm going to assume that by 'cargo cult', you mean that they're inserting stuff that think is necessary, but actually does absolutely nothing towards solving the problem.

If that's the case, you can always add some factor into the grading that's based on conciseness -- leaving unnecessary or redundant code in your program is asking for problems in the future, as it may break, or just make it more difficult to maintain.

They'd be judged similarly in an writing exercise in an English class -- no one wants stuff that goes off in a random tangent or is just generally rambling without getting to the point.

When I took an assembly class, the teacher would tell us for each exercise if he wanted us to write the code for speed, size, or memory usage, and he'd mark off if you didn't come close to optimizing what he asked for.

...

If they're copy & pasting code from previous similar assignments, and it's actually something to solve the new problem ... well, that's just code re-use, and unless they made bad assumptions about the suitability for the code for re-use, I think it's perfectly reasonable for them to do. (eg, reading from a file, propting for input ... all modular parts that can be re-used.  If you didn't want them doing it, you need to make the exercises dissimilar.


答:
Ideally in the first lecture, start them out with something completely abstract: have them (as a group, with you as the leader) write up the instructions on how to go grocery shopping from a list, and break down the high-level instructions progressively until they reach enlightenment.

It helps to tell them that these instructions are going to be followed literally by a robot, who doesn't know how to infer things.  It has to be a very hands-on activity where you are in charge of guiding them, though.


答:
Functions should do one thing.  They should do it well.  They should do it only.

  — Robert Martin in Clean Code

Some people find that approach a little extreme, but it's also very clean.  Allow me to illustrate in Python:

def processFile(self):
    if self.fileMeetsTest():
        self.doSomething()
    else:
        self.defaultAction()

def fileMeetsTest(self):
    return os.path.exists(self.path) and self.contentsTest()

def contentsTest(self):
    with open(self.path) as file:
        line = file.readline()
        return self.firstLineTest(line)
```

When he says functions should do one thing, he means one thing.  processFile() chooses an action based on the result of a test, and that's all it does.  fileMeetsTest() combines all the conditions of the test, and that's all it does.  contentsTest() transfers the first line to firstLineTest(), and that's all it does.

It seems like a lot of functions, but it reads practically like straight English:

To process the file, check if it meets the test.  If it does, then do something.  Otherwise, take the default action.  The file meets the test if it exists and passes the contents test.  To test the contents, open the file and test the first line.  The test for the first line ...

Granted, that's a little wordy, but note that if a maintainer doesn't care about the details, he can stop reading after just the 4 lines of code in processFile(), and he will still have good high level knowledge of what the function does.

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

Body:
Functions should do one thing.  They should do it well.  They should do it only.

  — Robert Martin in Clean Code

Some people find that approach a little extreme, but it's also very clean.  Allow me to illustrate in Python:

def processFile(self):
    if self.fileMeetsTest():
        self.doSomething()
    else:
        self.defaultAction()

def fileMeetsTest(self):
    return os.path.exists(self.path) and self.contentsTest()

def contentsTest(self):
    with open(self.path) as file:
        line = file.readline()
        return self.firstLineTest(line)

When he says functions should do one thing, he means one thing.  processFile() chooses an action based on the result of a test, and that's all it does.  fileMeetsTest() combines all the conditions of the test, and that's all it does.  contentsTest() transfers the first line to firstLineTest(), and that's all it does.

It seems like a lot of functions, but it reads practically like straight English:

To process the file, check if it meets the test.  If it does, then do something.  Otherwise, take the default action.  The file meets the test if it exists and passes the contents test.  To test the contents, open the file and test the first line.  The test for the first line ...

Granted, that's a little wordy, but note that if a maintainer doesn't care about the details, he can stop reading after just the 4 lines of code in processFile(), and he will still have good high level knowledge of what the function does.


问:
What would you do if your client required you not to use object-oriented programming?
I am writing a program to simulate the activity of ants in a grid (PDF). The ant can move around, pick up things and drop things.

The problem is while the action of the ants and the positions of each ant can be tracked by class attributes easily (and we can easily create many instances of such ants) my client said that since he has a background in functional programming he would like the simulation to be made using functional programming.

To be clear, the original words from the client is "no class" only, but not "functional programming". So I assume he doesn't mean functional programming and I can do it imperatively. Additionally, I have no prior experience in functional programming.

However, I think it's beneficial to focus on this question being particularly about a functional programming requirement than just simply "do it imperatively."

How would you handle this situation? Would you try to persuade your client that using object-oriented programming is much cleaner, try to follow what he required and give him poor-quality code, or do something else?

答:
Umm... am I the only one here thinking "this is obviously a test job/assignment"?.

Firstly - the assignment itself is kind of "academic" in nature (simulate an aspect of behavior of ants).

Secondly - a request to implement requirements using (or avoiding) a very specific programming paradigm smells of the "client" who can read code and make such assertions.

If this is the case, you better do what is required of you - it will be rather nice learning experience and if you can do it, you'll learn a lot in the process...

If this is not the case, you should indeed ask yourself and/or the customer for the reasoning about the assignment. If the reasoning is solid, then do it - you'll learn and you'll be better as a programmer for the experience. Who knows - you might even learn to like functional style over OO.

If the explanation is lacking, then all bets are off.. I can not recommend you what to do.

You might want to try regardless to implement the requirements in functional language/style or you might politely turn down the offer if you sense something fishy.

The main thing is - once you understand the motivation behind the requirements, the proper course of action becomes evident.

EDIT: After taking a diagonal look at the referenced PDF, the algorithms described there surely seem like a good fit for functional style rather than OO


问:
What are some useful resources for learning tuple calculus?
I've been trying to go over my tuple calculus over and over again. What's worse is that my professor and tutors are not much help during their hours.

Does anyone know a good place to learn about tuple calculus? I'm having a hard time understanding how to "speak" the language in terms of what I want to get from a database.

答:
Here are some good resources on the web where you can learn about Tuple Calculus:

http://en.wikipedia.org/wiki/Tuple_relational_calculus

http://www.youtube.com/watch?v=EUzsy3W4I0g


问:
How can I deal with the cargo-cult programming attitude?
I have some computer science students in a compulsory introductory programming course who see a programming language as a set of magic spells, which must be cast in order to achieve some effect (instead of seeing it as a flexible medium for expressing their idea of solution).

They tend to copy-paste code from previous, similar-looking assignments without considering the essence of the problem.

Are there some exercises or analogies to make these students more confident that they can, and should, understand the structure and meaning of each piece of code they write?

答:
Change your idea of projects!

In the programming world, rarely do we actually create new projects for every solution that comes around.  Most of the time we modify old ones.

Change your idea of a project from one solution for each assignment to one solution for the entire semester.  Each assignment builds on the previous assignment.

Example

Project: Build an elevator system

Assignment 1: Print out the current floor

Assignment 2: Create the data structures for an elevator class and print out the floor based on the elevator

Assignment 3: Create code that "moves the elevator", printing out the floor.  Accept keyboard input (>enter floor: )

Assignment 4: Handle multiple elevators

The point is that you build on the previous assignment instead of recycling old assignments for a new task.


答:
This is at a higher level of abstraction:

if (WeCanDoSomething(file))
{
   DoSomething(contents);
}
else
{
   DefaultAction();
}
```

<p>And this fills in the details.</p>

<pre class="lang-cs prettyprint-override"><code>boolean WeCanDoSomething(file)
{
    if FileExists(file)
    {
        contents = OpenFile(file);
        return (SomeTest(contents));
    }
    else
    {
        return FALSE;
    }
}
</code>```

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

Body:
This is at a higher level of abstraction:

if (WeCanDoSomething(file))
{
   DoSomething(contents);
}
else
{
   DefaultAction();
}

And this fills in the details.

boolean WeCanDoSomething(file)
{
    if FileExists(file)
    {
        contents = OpenFile(file);
        return (SomeTest(contents));
    }
    else
    {
        return FALSE;
    }
}