问:
Beginners guide to developing optimization software
I am novice in "serious" programming i.e. applications that deal with real-life applications and software projects that go beyond school assignments.

My interests include optimization, operations research, algorithms and lately i discovered how much I do like software design/development/engineering.

I have already developed some simple desktop applications for some "famous" problems like TSP using heuristc approaches, a VRP solver (in progress) and so on.

While developing this kind of software I actually used basic concepts taught at school such as object-orientation analysis and design. But, I found these courses rather elementary and quite boring (for my expectations).

So I decided to go a little further and start developing "real" software (and this is where I realized how important and interesting software engineering/design is.)

Now, here's my issue: I can not find a "study guide" for developing software of this kind.

Currently, there are numerous resources out there (books, websites, tutorials) in designing and developing complex IS, web applications, smartphone apps but I can't find a book for example entitled "optimization software development". Definetly, someone could claim that "design patterns apply to software in general" but that's not my point.

My point is that I could simply use my imagination for "simple" implementations, but what happens, when my imagination can not go further?

In other words I'm looking for a guide/path to bridge the gap between:
Mathematics-Algorithm Design-Software Engineering-Optimization-Software development

答:
The free Machine Learning online class from Stanford University may be exactly what you are looking for. It includes programming assignments as homework and covers:

This course provides a broad introduction to machine learning,
  datamining, and statistical pattern recognition. Topics include: (i)
  Supervised learning (parametric/non-parametric algorithms, support
  vector machines, kernels, neural networks). (ii) Unsupervised learning
  (clustering, dimensionality reduction, recommender systems, deep
  learning). (iii) Best practices in machine learning (bias/variance
  theory; innovation process in machine learning and AI). The course
  will also draw from numerous case studies and applications, so that
  you'll also learn how to apply learning algorithms to building smart
  robots (perception, control), text understanding (web search,
  anti-spam), computer vision, medical informatics, audio, database
  mining, and other areas.


问:
How to write a command interpreter/parser?
Problem: Run commands in the form of a string.

command example:

/user/files/ list all;
equivalent to:
/user/files/ ls -la;

another one:

post tw fb "HOW DO YOU STOP THE TICKLE MONSTER?;"

equivalent to:
    post -tf "HOW DO YOU STOP THE TICKLE MONSTER?;"

Current solution:

```<code>tokenize string(string, array);

switch(first item in array) {
    case "command":
        if ( argument1 > stuff) {
           // do the actual work;
        }
}
</code>```

The problems I see in this solution are:

No error checking other than nested ifs-else inside each case. The
script becomes very big and hard to mantain.

Commands and responses are hardcoded.

No way of knowing if flags are correct or missing parameters.

Lack of intelligence to suggest "you might wanted to run $command".

And the last thing I can't address is synonyms in different encodings, example:

```<code>case command:
case command_in_hebrew:
    do stuff;
break;
</code>```

The last one might be trivial, but well, what I want to see is the solid fundations of this kind of program.

I'm currently programming this in PHP but might do it in PERL.

答: Check out Apache CLI, it's entire purpose seems to be doing exactly what you want to do, so even if you can't use it, you can check out its architecture and copy that.</p>

ContentLicense: CC BY-SA 3.0


答:
If you can get an algorithim in code to O(1) then it is fully optimized and you have reached the holy grail of algorithmic programming, however, usually the time and effort it takes to get to that level of optimization is not worth it as today's computers are fast enough to handle just about anything.  But there are times that one would need to optimize the algorithum to make it more efficient. So understanding the complexity of the code and how it executes is a good start.

Here's a good article to get you started:

http://rob-bell.net/2009/06/a-beginners-guide-to-big-o-notation/

Title: Beginners guide to developing optimization software

Body:
I am novice in "serious" programming i.e. applications that deal with real-life applications and software projects that go beyond school assignments.

My interests include optimization, operations research, algorithms and lately i discovered how much I do like software design/development/engineering.

I have already developed some simple desktop applications for some "famous" problems like TSP using heuristc approaches, a VRP solver (in progress) and so on.

While developing this kind of software I actually used basic concepts taught at school such as object-orientation analysis and design. But, I found these courses rather elementary and quite boring (for my expectations).

So I decided to go a little further and start developing "real" software (and this is where I realized how important and interesting software engineering/design is.)

Now, here's my issue: I can not find a "study guide" for developing software of this kind.

Currently, there are numerous resources out there (books, websites, tutorials) in designing and developing complex IS, web applications, smartphone apps but I can't find a book for example entitled "optimization software development". Definetly, someone could claim that "design patterns apply to software in general" but that's not my point.

My point is that I could simply use my imagination for "simple" implementations, but what happens, when my imagination can not go further?

In other words I'm looking for a guide/path to bridge the gap between:
Mathematics-Algorithm Design-Software Engineering-Optimization-Software development


问:
Alternate string formatting options in C++?
I'm looking at optimizing some string formatting code that's hit a lot in our code. We had been using ostringstream, and I converted the code to use sprintf (actually Microsoft's more secure sprintf_s). I've traded type safety for run-time performance. But I've debugged enough sprintf related weird crashes to know that sprintf has its own serious flaws that the compile time checking of ostringstream catch. But ostringstream is more than an order-of-magnitude slower then sprintf by my measure, and that's not tolerable in this code. I'm also not thrilled with the readability of C++ stream string formatting, but this may be entirely subjective.

So unfortunately when formatting strings in C++ I've got several "standard" options that are suboptimal:

sprintf -- fast, but not type safe. Can have insidious bugs when the wrong format string is not used.

ostringstream -- slow, but type safe. IMO Ugly, too verbose, and difficult to read.

boost::format -- a little more readable then ostringstream IMO, but in my performance benchmarks appears to be even slower then ostringstream, so this is out.

To summarize, I'm not really satisfied with the "standard" options. I'd like something that takes both performance and type safety seriously. What other string formatting options are out there for C++?

答:
I suspect you are looking for a silver bullet. It's really  is a triangle, (fast, powerful, safe). You need fast, so your only choice is powerful or safe, you cannot have both. sprintf is fast and powerful, at the expense of safety.  </p>

<p>You should be able to wrap sprintf in ways that restrict it's use (making it less powerful, more safe), and though run-time checks and rigorous code review, ensure your performance and safety targets are met. If this cannot be achieved, think carefully why not before choosing another option.  </p>

Body:
I suspect you are looking for a silver bullet. It's really  is a triangle, (fast, powerful, safe). You need fast, so your only choice is powerful or safe, you cannot have both. sprintf is fast and powerful, at the expense of safety.

You should be able to wrap sprintf in ways that restrict it's use (making it less powerful, more safe), and though run-time checks and rigorous code review, ensure your performance and safety targets are met. If this cannot be achieved, think carefully why not before choosing another option.


问:
Does syntax matters for a (Lispy) Domain Specific Language (MELT, inside GCC)?
I am the main author and designer of MELT, a domain specific language to extend GCC (the Gnu Compiler Collection). The implementation is available free software (GPLv3 licensed). If you want a detailed description, from the point of view of a Domain Specific Language, read my DSL2011 paper on MELT.

I have chosen a Lisp-like syntax for MELT, so as in Lisp or in Scheme, every operation is written with "Lots of Insipid Stupid Parenthesis" so the application of function f to arguments a and b is written (f a b) (like it is in Scheme or in Lisp). Of course, (f) -a function application without argument- is not the same as f -a simple thing denoted by a variable-.

MELT shares with many other Lisp-s and with Scheme the usual "control" operators like let if defun define cond lambda letrec list definstance etc...
MELT does not use the common names for primitive operations (no car or + in MELT, which has pair_head list_first +i +iv  with different meanings). And MELT deals with both first-class values (like in Scheme) and "stuff" (for raw GCC data like Gimple, details are in the DSL2011 paper)

The reasons I have chosen a Lisp-like syntax includes:

first, I am lame, and wanted to have a quick implementation. Parsing Lisp is trivial;

I was (and am) able to use e.g. Emacs lisp-mode for MELT without trouble.

A small MELT implementation was originally prototyped in Common Lisp

Current MELT translator is bootstrapped so is written in MELT

The implementation uses classical Lisp tricks: S-expressions are expanded by a macro mechanism (into a sort of internal abstract syntax tree), then normalized, and finally translated to C code.

GCC has several Lisp like formalisms inside (notably for the back-end, for "machine description" files).

the GNU projects have Emacs Lisp and Guile as Lisp-like dialects (I was not able to use them for technical reasons detailed in my DSL2011 paper).

My question is: should I offer an alternative, infix-like syntax (a bit Pythonic or Lua-esque)?

One one hand, I am afraid that some people (particularly young ones, who never met any Lisp-like programming languages; I had a course on Lisp in the 1980-s) are completely allergic to Lisp and won't even try MELT because of its look.

On the other hand, the only thing I could do is some simple parser producing the same AST as MELT has today, and the syntax will be ad-hoc (but infixed) and probably not pretty.

Also, working on an alternative syntax which I won't use will distract me (or take time) from other efforts (writing documentation & tutorial, making good examples of MELT, debugging and improving the implementation).

Some young persons (in particular Jeremie Salvucci and Pierre Vittet) have been able to learn and code MELT without prior exposure to MELT, to Lisp dialects (or Scheme) or even to compilation.

Would an alternative syntax attract people allergic to Lisp? A nice guy told me that syntax does not matter really for DSL-s. They can be adopted if they bring some value, even with a not very sexy syntax.

答:
What makes sense to you? After all, it is your product and you can do with it as you please. The real question is this: will there be any reward for your work? You'll end up with two variants to support and if you introduce features they may not be compatible with each style (in a nice way).

If it was up to me, I'd stick with the lisp like syntax but that is because I enjoy that syntax. At the very least, I would ask the people that use your project what they think as they would be the ones who know and would be the ones most affected by your decision (if you are working on the alternative syntax, it is time away from feature enhancements etc).


答:
Learning a new syntax is not a big deal. However, by syntactic similarities, you associate yourself strongly with other languages in that field- even if your semantics are different, you will have a tough time showing people that they aren't that similar. C syntax is about the only syntax that doesn't have this problem, because when compare for example C to Java, they're radically different- anyone who's done more than a couple C syntax languages knows that it's a popular syntax with little semantic meaning.

However, with LISP, this is not a good thing. Not because LISP's syntax is terrible, but because programming in this decade involves flipping between data structures like pages in a book. When I see list_first, my reaction isn't "Great, you can do linked-lists and it's gonna be easy", it's "What if I need a deque, a queue, a stack, an array, a hash table, a binary search tree? What if I want the second element of my list? What if I need to invent my own data structure that needs a very specific implementation for reasonable performance? This language isn't going to support the expressiveness I need.". Compared to C++ or even C# or Java (to a lesser extent) or... where I can just change the name of the class I'm using and voila, new data structure, works with my old generic code.

As a young person who was never taught "LISP is slow" or anything like that, I'm definitely allergic to it, because it's fundamental building blocks are one of the slowest, least useful data structures, and there's no reason to even build a language on a data structure in the first place.

Title: Does syntax matters for a (Lispy) Domain Specific Language (MELT, inside GCC)?

Body:
I am the main author and designer of MELT, a domain specific language to extend GCC (the Gnu Compiler Collection). The implementation is available free software (GPLv3 licensed). If you want a detailed description, from the point of view of a Domain Specific Language, read my DSL2011 paper on MELT.

I have chosen a Lisp-like syntax for MELT, so as in Lisp or in Scheme, every operation is written with "Lots of Insipid Stupid Parenthesis" so the application of function f to arguments a and b is written (f a b) (like it is in Scheme or in Lisp). Of course, (f) -a function application without argument- is not the same as f -a simple thing denoted by a variable-.

MELT shares with many other Lisp-s and with Scheme the usual "control" operators like let if defun define cond lambda letrec list definstance etc...
MELT does not use the common names for primitive operations (no car or + in MELT, which has pair_head list_first +i +iv  with different meanings). And MELT deals with both first-class values (like in Scheme) and "stuff" (for raw GCC data like Gimple, details are in the DSL2011 paper)

The reasons I have chosen a Lisp-like syntax includes:

first, I am lame, and wanted to have a quick implementation. Parsing Lisp is trivial;

I was (and am) able to use e.g. Emacs lisp-mode for MELT without trouble.

A small MELT implementation was originally prototyped in Common Lisp

Current MELT translator is bootstrapped so is written in MELT

The implementation uses classical Lisp tricks: S-expressions are expanded by a macro mechanism (into a sort of internal abstract syntax tree), then normalized, and finally translated to C code.

GCC has several Lisp like formalisms inside (notably for the back-end, for "machine description" files).

the GNU projects have Emacs Lisp and Guile as Lisp-like dialects (I was not able to use them for technical reasons detailed in my DSL2011 paper).

My question is: should I offer an alternative, infix-like syntax (a bit Pythonic or Lua-esque)?

One one hand, I am afraid that some people (particularly young ones, who never met any Lisp-like programming languages; I had a course on Lisp in the 1980-s) are completely allergic to Lisp and won't even try MELT because of its look.

On the other hand, the only thing I could do is some simple parser producing the same AST as MELT has today, and the syntax will be ad-hoc (but infixed) and probably not pretty.

Also, working on an alternative syntax which I won't use will distract me (or take time) from other efforts (writing documentation & tutorial, making good examples of MELT, debugging and improving the implementation).

Some young persons (in particular Jeremie Salvucci and Pierre Vittet) have been able to learn and code MELT without prior exposure to MELT, to Lisp dialects (or Scheme) or even to compilation.

Would an alternative syntax attract people allergic to Lisp? A nice guy told me that syntax does not matter really for DSL-s. They can be adopted if they bring some value, even with a not very sexy syntax.


问:
Drag and drop application design
I am hoping to create a mind-mapping like application and it needs to have a central workspace that will hold the map. Users should be able to drag items (like rectangles, texts, etc.) from a container to the workspace. The important thing is when a user is dragging an element to the workspace, the element should move with the mouse, not just the text.

What I'm looking for is something like the web apps LucidChart, Cacoo, MindMeister, etc. So is this possible to do in Java without too much hassle? And if yes, what is the application design (algorithm)?

I have searched many resources but have only found ways to drag only the text, images or the like. Not the entire element itself. It would be even better if I could make it to drag an entire JButton, so the users can create a map of JButtons.

Sorry if this is not the place to post this (should I post it in StackOverflow or here?).

答:
Here is a starting point/idea for the design:

```<code>// Your framework probably provides this
class Point {
     private int x, y; // x,y coordinates of top left of View
}

// Your framework probably provides something like this

/** Container class for all other types */
abstract class MindMapView {
    public MindMapView(int width, int height, Point position) {
          // Initialize fields
    }

    /** Top-Left */
    private Point mPosition;

    /** Width, Height */
    private int mWidth, mHeight; // Width and height of view

    /** Implement this to fulfill a request to draw the view on the screen */
    abstract void onDraw();

    /** Implement this to fulfill a request to move the view across the screen */
    abstract void onMove(Point delta);

    /** Implement this to fulfill a request to resize the view */
    abstract void onResize(int width, int height);

    /**
        Implement this to fulfill a request to drag this view. Can be similar
        to onMove, except you will want to hook the point where the view is
        "dropped", which would be the last point in the drag.

        We'd consider a drag to be a left mouse click, mouse movement, and mouse
        un-click.
      */
    abstract void onDrag(Point delta);

    /** Called by other classes that desire to draw this View */
    public final void draw() {
        onDraw();
    }

    /** Called by other classes that desire to move this view */
    public final void move(Point delta) {
        onMove(delta);
    }

    /** Called by other classes that desire to resize this view */
    public final void resize() {
        onResize();
    }

    public final void drag(Point delta) {
        onDrag(delta);
    }

    /** Implement this to
    public Point getPosition() {
       return mPosition;
    }
}
</code>```

You will hook your framework to funnel the various events into this view, but more than likely, your framework has a similar class ready for you.. Once you have that, you can extend it to make your other elements

Much like MindMapView, except it can contain other MindMapViews

```<code> abstract class MindMapContainer extends MindMapView {

    private ArrayList<MindMapView> mViews;

    public ArrayList<MindMapView> getViews() {
        return mViews;
    }

    public MindMapThought(...) {
        super(...);
    }

    public void addView(MindMapView view) {
        mViews.add(view);
    }

    public void removeView(int index) {
        ...
    }

    // Subclasses must call super() if these are overridden!

    @Override
    protected void onMove(Point delta) {
        for (MindMapView view : mViews) {
            view.move(delta);
        }
    }

    // Do similar for the following
    implement onDraw();

    implement onResize(int width, int height);

    implement onDrag(Point delta);
 }
</code>```

Once you have the base classes defined, you can LOOP over each sub-view to move it along with the others

```<code>public class MindMapThought extends MindMapView {
    /** Implement this to fulfill a request to draw the view on the screen */

    @Override
    protected void onDraw() {
        canvas.draw(...);
    }

    // Do similar for the following

    implement onMove(Point delta);

    implement onResize(int width, int height);

    implement onDrag(Point delta);
}
</code>```

Finally, you can create something that moves as a group

```<code>public class MindMapThoughtContainer extends MindMapViewContainer {
    ...
}

MindMapThought thought1 = new MindMapThought();
MindMapThought thought2 = new MindMapThought();
MindMapThoughtContainer thoughts = new MindMapThoughtContainer();

thoughts.add(thought1);
thoughts.add(thought2);

Point delta = new Point(5,5);

// Move the thoughts container, its' onMove event will iterate its sub-views
// and move them along by the same delta
thoughts.move(delta);
</code>```

You can have any number of concrete (actual implementations) types as long as they extend MindMapView so that they use the same interface.

As for the specifics of wiring up the design, consult your frameworks documentation.

Title: Drag and drop application design

Body:
Here is a starting point/idea for the design:

// Your framework probably provides this
class Point {
     private int x, y; // x,y coordinates of top left of View
}

// Your framework probably provides something like this

/** Container class for all other types */
abstract class MindMapView {
    public MindMapView(int width, int height, Point position) {
          // Initialize fields
    }

    /** Top-Left */
    private Point mPosition;

    /** Width, Height */
    private int mWidth, mHeight; // Width and height of view

    /** Implement this to fulfill a request to draw the view on the screen */
    abstract void onDraw();

    /** Implement this to fulfill a request to move the view across the screen */
    abstract void onMove(Point delta);

    /** Implement this to fulfill a request to resize the view */
    abstract void onResize(int width, int height);

    /**
        Implement this to fulfill a request to drag this view. Can be similar
        to onMove, except you will want to hook the point where the view is
        "dropped", which would be the last point in the drag.

        We'd consider a drag to be a left mouse click, mouse movement, and mouse
        un-click.
      */
    abstract void onDrag(Point delta);

    /** Called by other classes that desire to draw this View */
    public final void draw() {
        onDraw();
    }

    /** Called by other classes that desire to move this view */
    public final void move(Point delta) {
        onMove(delta);
    }

    /** Called by other classes that desire to resize this view */
    public final void resize() {
        onResize();
    }

    public final void drag(Point delta) {
        onDrag(delta);
    }

    /** Implement this to
    public Point getPosition() {
       return mPosition;
    }
}

You will hook your framework to funnel the various events into this view, but more than likely, your framework has a similar class ready for you.. Once you have that, you can extend it to make your other elements

Much like MindMapView, except it can contain other MindMapViews

 abstract class MindMapContainer extends MindMapView {

    private ArrayList<MindMapView> mViews;

    public ArrayList<MindMapView> getViews() {
        return mViews;
    }

    public MindMapThought(...) {
        super(...);
    }

    public void addView(MindMapView view) {
        mViews.add(view);
    }

    public void removeView(int index) {
        ...
    }

    // Subclasses must call super() if these are overridden!

    @Override
    protected void onMove(Point delta) {
        for (MindMapView view : mViews) {
            view.move(delta);
        }
    }

    // Do similar for the following
    implement onDraw();

    implement onResize(int width, int height);

    implement onDrag(Point delta);
 }

Once you have the base classes defined, you can LOOP over each sub-view to move it along with the others

public class MindMapThought extends MindMapView {
    /** Implement this to fulfill a request to draw the view on the screen */

    @Override
    protected void onDraw() {
        canvas.draw(...);
    }

    // Do similar for the following

    implement onMove(Point delta);

    implement onResize(int width, int height);

    implement onDrag(Point delta);
}

Finally, you can create something that moves as a group

public class MindMapThoughtContainer extends MindMapViewContainer {
    ...
}

MindMapThought thought1 = new MindMapThought();
MindMapThought thought2 = new MindMapThought();
MindMapThoughtContainer thoughts = new MindMapThoughtContainer();

thoughts.add(thought1);
thoughts.add(thought2);

Point delta = new Point(5,5);

// Move the thoughts container, its' onMove event will iterate its sub-views
// and move them along by the same delta
thoughts.move(delta);

You can have any number of concrete (actual implementations) types as long as they extend MindMapView so that they use the same interface.

As for the specifics of wiring up the design, consult your frameworks documentation.


问:
Why is C++ known as 'premature optimizaton'?
"Programming in C++ is premature optimization"

Why does everyone do some people say this?

答: People often say this (somewhat tongue-in-cheek, in my experience) as a dig against C++ as a choice of language.  People typically choose C++ because it is, in most cases, faster than an alternative like Python or Java.  However, most of the time, the additional speed gained is not really needed.  When a person says "Programming in C++ is premature optimization" they are saying that you could have programmed your application in some other language, been done much faster, then if you needed to make some part of your code really fast, you could simply code that part in C++ and call that routine from the other language.</p>


答:
Because they don't know how to program in C++.

Generally speaking, such people simply don't understand how to program safely (and quickly) in C++ and suggest that doing so takes up an inordinate amount of time or somesuch rubbish. If it really was significantly slower, then people would only do it to make their programs run faster, as C++ is easily the fastest mainstream language. That would make it an optimization- "I'd rather program in C#, but I have to use C++ because it's faster.", and usually premature because most optimizations are.

However, this is usually ignorant. C++ hasn't been a hassle to program in since shared_ptr and std::vector were invented.

Edit: Sorry, I wasn't sufficiently clear. I forget when speaking to non-C++'ers how little they generally know about the language, as I usually just stick in the C++ channel on SO. First, shared_ptr is hardly the only smart pointer, I use unique_ptr a lot more often, and Boost has more. Second, garbage collection is nothing like shared_ptr. Try to garbage collect GPU memory, or a file handle, or a database connection, or an HWND. Good luck. Third, the customizability of shared_ptr is vastly above what you can get from a garbage collected system. Recently, I replaced my memory allocations with a memory arena allocator that I wrote myself. It was like, a hundred lines of code and an hour to test. But I didn't have to re-write a single line of my shared_ptr code, because I just dropped in a custom deleter and it just worked. Try replacing your allocator or inventing a new smart pointer in C# or Java and tell me how long that takes. Oh wait, if you look at using, then even special language power can't make another kind of resource management work in C#. If garbage collection doesn't suit your needs, then you're screwed. That's not my definition of a higher-level language.

Now, I'll be the first to admit that I'm not on the cutting edge of languages like Python, Java, or C#. But as far as I know, Java and C# have nothing as strong as templates. Java's generics are hardly good for anything, and C#'s aren't that much better. For example, I use an expression template to automatically generate a finite state machine. I've never seen anything like that. If I was coding in Java, I'd have to code it manually.

Title: Why is C++ known as 'premature optimizaton'?

Body:
"Programming in C++ is premature optimization"

Why does everyone do some people say this?


答: Well, that's because programming in C++ does not magically give you any performance boost over, for example, Java. You need to do it very well, and doing that in C++ is definitely not an easy task. Also time consuming and programmer's time is not cheap...


问:
Best practice modelling an active record entity using Linq-To-SQL as DAL
Currently I'm starting a new system on my company, and we are using a good separation between models, views and controllers, basically using Asp.Net MVC 3 for the user UI, and a C# class library for the model.

The question is about "modelling a model".

We are using Linq-to-SQL as a Data Access Layer, and modelling entities over this DAL. Example:

```<code>    // DAL, an autogenerated .dbml file
    ...
    public System.Data.Linq.Table<TB_USER> TB_USERs {
       get {
          return this.GetTable<TB_USER>();
       }
    }
    ...
</code>```

And we are mapping this table on an entity, like below:

```<code>    public class User {
       // Entity, mirroring a .dbml table
       public static IEnumerable<User> GetAll() {
           var db = new MyDataContext();
           var userList = (from u in db.TB_USERs select u).ToList();
           IEnumerable<User> retorno = lista.ConvertAll(u => (User)u);
           return retorno;
       }

       // Active Record ?
       public static User Save(User user) { ... }
    }
</code>```

Is this kind of modelling correct ? It feels like I'm repeating myself by having 2 entities meaning the same thing (User and TB_USER), but TB_USER is the raw representation of the database table that persists the User entity.

And the GetAll method, a static method created on the entity with the sole purpose of retrieving all of them. That means that if I want to retrieve data using a filter, for example, I have to create another GetDataBy... method.

And what about the Save method ? I know it's supposed to save the state of one User, but what if I have to save some random User object along with other objects to make a transaction ?

Shouldn't this kind of transaction control be in the database ?

答:
If you are going to stick with LINQ-to-SQL you probably want to use  the linq-to-sql classes as your entities. That is rename TB_USER to User and you then wrap the interaction with LINQ-to-sql in repositories, i.e. a UserRepository with a GetById, GetByUserName, Save, and similar methods - depending on your specific needs. This keeps the data access in one place.

With LINQ-to-sql beware of the temptation to have LINQ expressions that go off and query the DB scattered across your code base. LINQ-to-sql seems to encourage that in my experience. But that leads to very tight coupling.

If you want a cleaner cut between your domain entities and the DB, I'd really recommend moving to another ORM. My personal preference with a SQL Server on the backend would be NHibernate.


答:
I haven't used C++ in a long time (and never templates), so this is from memory based on other questions on Programmers.SE and on StackOverflow:

Templates are handled at compile time, and C++ allows you do do some crazy tricks with complicated ones.

Because they're handled at compile time instead of runtime, all that execution is "optimized" away, leading to compiled code that could in some cases be faster than C, because the optimizations done are complicated and hard to to by hand.

And it's "premature" optimization because this is done before any testing for speed ;)

If anyone with experience wants to add/fix what I remember, please do.  Don't just downvote.


问:
How do I report software vulnerabilities found in an open source library that are widely used but have a dilapidated team structure?
For most open source project, there is a well-founded project team and corporate sponsorship, and a lot of active contributors. The procedure for filing bug reports are clearly documented.

However, there are also some open source project(s) that have been in existence for more than 10 years (maybe 15), and were included in all sorts of free and commercial products (OSes and linux distros, etc), and everyone just assumes it is correct, despite some parts of it in a state of despair and full of bugs.

It appears to me that the real users (programmers in-the-know) simply choose to use the library in a certain way as not to trigger the bug. Few choose to speak up.

There are also big-name companies that fix the bugs quietly (in their own products) without giving out any patches. And use that to their business advantage.

There is no leading developer. There is no information as to who are the active developers, except that you can browse the mailing list and see who has recently submitted patches, and assume that they might know someone who is helpful.

How should I handle a vulnerability case, without leaking information in a way that gives ammunition to the bad guys?

This question is a spin-off from: https://softwareengineering.stackexchange.com/questions/5168/whats-the-biggest-software-security-vulnerabilty-youve-personally-discovered

答:
To the coordinator(s).

If there is no clear info, I suggest you to pick one random contributor and ask him who is in charge.

Pick another contributor until you have a clear answer.

In any case, send the details about the problem to each person you contact.

ContentLicense: CC BY-SA 2.5


问:
How/where would I best advertise my open source project, in order to maximize my odds of finding collaborators?
I'm working on an open source project, and am looking to find collaborators. What's my best bet, in terms of advertising my project, with an eye specifically towards finding other developers interested in contributing?</p>

答:
Use Github to host your project, Github is the de facto service these days. It is easy and free to register, thus you are lowering the bar for the new participants.

Create Twitter and G+ accounts for your project, This is really important.

You can use them to communicate with other developers and for announcement.

Why G+? because according to my personal observation, G+ is trending between developers mainly because we already have GMail accounts.

Post about your project at sites like DZone.

Many programming languages have sites named like language-planet.org

For example, I add an aggregator called ClojurePlanet to my RSS reader, I'm literally hearing/reading about new open source projects written in Clojure every day.

Use those aggregators to inform the world about your project.


答:
I agree with Chiron but I must add something more important: Your local LUG or whatever open source software you are using.

Also keep in mind, you are making a tool for a specific purpose, offer the solution to the users, some of them will probably encourage the development by testing it, making suggestions or actively developing the project.

Keep in mind that it must be useful, and it must be functional. Failing in one of those areas won't get you free man hours or compliments.

Title: How/where would I best advertise my open source project, in order to maximize my odds of finding collaborators?

Body: I'm working on an open source project, and am looking to find collaborators. What's my best bet, in terms of advertising my project, with an eye specifically towards finding other developers interested in contributing?</p>


问:
What is OpenCL?
I've been looking around, but I'm still not sure on the what OpenCL is. Other than multi processor stuff...

Is it another graphics API like OpenGL and DirectX? Or something that works alongside OpenGL?

I'm planning on learning OpenGL soon (with java if it makes a difference) so I want to know how/which direction to learn it with.

Also, I hear things about CUDA which confuses me further. Just looking for some simple clarifying statements. Thanks.

答:
OpenCL is a language/API for doing general purpose highly parallel calculations on a graphics card, but can also be used to generate computed images which are displayed by openGL or directX

It's an open standard (like openGL), CUDA is the NVIDIA only competitor.

Why? Because your $100 graphics card can do 1000s of tasks in parallel - turning it in a mini-supercomputer!

Title: What is OpenCL?


问:
Finding an agile coach
I'm hoping that this is the right place to ask this question, but my company has recently started a process to look at how we build software, from the tools we use to the methodology. As you can imagine we have the kind of endless meetings where we sit around a table and split hairs.

In an effort to actually get something done I've suggested we hire in a professional to take a look at how we do what we do and maybe guide us into a more agile approach to delivering software.

My problem is that I'm not sure how to find a consultant we could bring in and get us started?

I was thinking of approaching someone like ThoughtWorks, but I think finding someone who isn't going to push an agenda or product on us would be better.

In the meantime I've picked up a few books and will do a bit of reading on the beach over the holiday vacation.

答:
guide us into a more agile approach to delivering software.

finding someone who isn't going to push an agenda ... would be better.

Um.  Which do you want?  Change?  Or no change?

If you want to change, then someone has to "push an agenda" on you.

Indeed, you can only change when someone "pushes an agenda" on you.

You should relax your requirements and find someone with a strong agenda who will push you in a new direction.

Title: Finding an agile coach


问:
Want to learn C++, and have prior web programming knowledge
I am actually considering learning C++. I want to become a quantitative financial analyst, and going to pursue my CFQ soon. Java is not heavily used in this field, but C++ is for its complexity. For someone who already has knowledge in HTML, CSS, JavaScript (intermediate), and PHP (intermediate), how hard would the switch be to pick up C++ over the course of a year? How long would it take to get certified in C++? And how hard is it to learn? I have built CMS websites, and some decent applications for the web.

I took a college course of beginning programming in Java as well.

Basically switching positions as a web designer to a C++ programmer and use Matlab.

I have heard the language is very complex, but easier to program than languages like Java.

答:
C++ is substantially "harder" than Java because of explicit memory management. It's easier to program in the sense that you can do exactly what you want to in the language and you don't have to wait for the JVM's garbage collection algorithm to trigger (a non-deterministic process) in order to free up memory. C++'s explicit memory management makes it very powerful but it's also much much easier to do real damage than it is in Java or C#.

The language is hugely complex though it tends to fall into "domains" where you wind up using relevant chunks of it rather than the whole thing. Matlab doesn't require you to know C++ as it is its own environment and language and the underlying software is proprietary anyway. I've heard templates are particularly difficult but as I understand it most "quant" code is imperative numerical routines rather than complex objects and views and what not.


答:
I had one answer in mind when I read the title of this question, and then obliterated that answer once I read your actual “question.”

If I were you, I wouldn’t even bother applying for these jobs if you don’t have a lot of experience in the things they’re looking for. I was a consultant for many high-speed trading firms and they aren’t going to have much patience with you if you don’t absolutely 100% know your stuff. To wit, they also don’t really care about programming languages… they care about latency. Yes, you technically said you were looking at jobs in quantitative finance; but if that’s the case, you should spend your time getting a degree in math, not learning C++.

And to answer your question specifically: C++ is going to be very hard for you if you only know HTML (not a programming language), CSS (not a programming language) and sundry bits of PHP and JavaScript.

Maybe try again in 5 years?

Title: Want to learn C++, and have prior web programming knowledge

Body:
I am actually considering learning C++. I want to become a quantitative financial analyst, and going to pursue my CFQ soon. Java is not heavily used in this field, but C++ is for its complexity. For someone who already has knowledge in HTML, CSS, JavaScript (intermediate), and PHP (intermediate), how hard would the switch be to pick up C++ over the course of a year? How long would it take to get certified in C++? And how hard is it to learn? I have built CMS websites, and some decent applications for the web.

I took a college course of beginning programming in Java as well.

Basically switching positions as a web designer to a C++ programmer and use Matlab.

I have heard the language is very complex, but easier to program than languages like Java.


答:
If your needs are simple, and you both have the time and are interested in it, I'll go against the grain here and say dont shy away from writing your own parser.  Its a good learning experience, if nothing else.  If you have more complex requirements - nested function calls, arrays, etc - just be aware that doing so could take a good chunk of time.  One of the big positives of rolling your own is that there wont be an issue of integrating with your system.  The downside is, of course, all the screw ups are your fault.

Work against tokens, though, dont use hard coded commands.  Then that problem with similar sounding commands goes away.

Everyone always recommends the dragon book, but I've always found "Writing Compilers and Interpreters" by Ronald Mak to be a better intro.

Title: How to write a command interpreter/parser?

Body:
Problem: Run commands in the form of a string.

command example:

/user/files/ list all;
equivalent to:
/user/files/ ls -la;

another one:

post tw fb "HOW DO YOU STOP THE TICKLE MONSTER?;"

equivalent to:
    post -tf "HOW DO YOU STOP THE TICKLE MONSTER?;"

Current solution:

```<code>tokenize string(string, array);

switch(first item in array) {
    case "command":
        if ( argument1 > stuff) {
           // do the actual work;
        }
}
</code>```

The problems I see in this solution are:

No error checking other than nested ifs-else inside each case. The
script becomes very big and hard to mantain.

Commands and responses are hardcoded.

No way of knowing if flags are correct or missing parameters.

Lack of intelligence to suggest "you might wanted to run $command".

And the last thing I can't address is synonyms in different encodings, example:

```<code>case command:
case command_in_hebrew:
    do stuff;
break;
</code>```

The last one might be trivial, but well, what I want to see is the solid fundations of this kind of program.

I'm currently programming this in PHP but might do it in PERL.


问:
How do you know when to stop adding features?
Some time ago I wrote a very small python script that periodically checked an xml feed for new entries, and alerted the user to new entries when present.
I wrote this for myself, so it was essentially a console based program that anyone comfortable with a console interface could have used.

After a while I decided it could be of more use to other people and began to tidy it up, sanitize inputs, remove bugs. It occurred to me that because I'd written the script I knew how to use it efficiently, accurately etc. Others might not, so I started adding a GUI. This started out as a simple menu, and then expanded to a more full GUI with both an interface and options menu. I then added stored user preferences and also storage for previously searched xml feeds to speed up repeat searches.

I added logging to help debug the application in case things go wrong, brought the application up to the latest available stable python codebase for my chosen platform and improved dialog features.

I've bugfixed and commented my code clearly, and yet I still have things I think can be done to improve the app before I make it available to alpha testers. It's a far far cry from my original 20-30 line script. What I anticipated would take me just an hour or two to go from proof of concept to an acceptable use program has taken 10-20 times that. (I'm still a noob, and stuff takes me a long time, but still....)

How do you know when to stop adding/tweaking/fixing stuff and let your baby crawl out in the open?

答:
When you hit the deadline.

If you have no deadline, this is your problem...

Here is how I work:

I add new features/bugs in my product backlog.

I prioritize the whole product backlog on business value and estimated (the last is optional in case of personnal project).

I allocate work time to myself. The release date is the end of that time.

I start with the very first in the list. I work on a feature a time. To be completed, a feature must be really complete including documentation (at the end of a feature, I can potentially ship the product).

I take the next one until my allocated time is consumed.

If the time is consumed when I'm building a feature, I discard it temporaly.

When the allocated time is consumed, I take the latest build and make a release with it.

I repeat the process from point 1.


问:
Is software development an engineering discipline?
Can software development be considered engineering? If no, what are the things that it lacks in order to be qualified as an engineering discipline? Related to this is this question on Stack Overflow about the difference between a programmer and a software engineer.

There is the Software Engineering Institute at Carnigie Mellon University that prescribes and maintains the CMMI standards. Is this something that will turn development into engineering?

答:
From Wiki:

Engineering :

Software engineering is the application of a systematic, disciplined, quantifiable approach to the development, operation, and maintenance of software, and the study of these approaches; that is, the application of engineering to software.

Software Development

Software development is the set of activities that results in software products. Software development may include research, new development, modification, reuse, re-engineering, maintenance, or any other activities that result in software products.[1]

Especially the first phase in the software development process may involve many departments, including marketing, engineering, research and development and general management.

So they are pretty similar and can also mean the same thing.

OwnerDisplayName: Vaibhav Garg

OwnerDisplayName: Ólafur Waage


答:
Yes I'd guess that development is a subset of engineering:

Software engineering includes the initial specification ("what kind of software do we need here?"), which arguably precedes the development

"Engineering" might also include e.g. defining the Quality Assurance Process, which is certainly related to development but also arguably outside the scope of the 'construction' itself.

Code Complete defines "construction" as being synonymous with coding and debugging (and commenting), also with detailed design before-hand and with unit- and integration-testing afterwards. Chapter 1, Welcome to Software Construction (PDF) starts by listing many topics in the overall Software Development Lifecycle (including Problem Definition, Software Architecture, Corrective Maintenance, etc.), and then says,

As the figure indicates, construction
  is mostly coding and debugging but
  also involves detailed design,
  construction planning, unit testing,
  integration, integration testing, and
  other activities. If this were a book
  about all aspects of software
  development, it would feature nicely
  balanced discussions of all activities
  in the development process. Because
  this is a handbook of construction
  techniques, however, it places a
  lopsided emphasis on construction and
  only touches on related topics. If
  this book were a dog, it would nuzzle
  up to construction, wag its tail at
  design and testing, and bark at the
  other development activities.

Title: Is software development an engineering discipline?

Body:
Can software development be considered engineering? If no, what are the things that it lacks in order to be qualified as an engineering discipline? Related to this is this question on Stack Overflow about the difference between a programmer and a software engineer.

There is the Software Engineering Institute at Carnigie Mellon University that prescribes and maintains the CMMI standards. Is this something that will turn development into engineering?

OwnerDisplayName: ChrisW


问:
Hiring programmers for small companies?
I've been running a company for nearly 10 years, and all this time it's been just myself, another programmer (who's a great friend and cofounder), and a salesman (who's also a friend). Together, we've managed to do decent business and we've all managed to make a living, but we've been trying to expand for a long time now.

Unfortunately, there are a few problems:

The technology we use is not obsolete, but it's also not as popular
compared to other web development options like PHP

We work in a competitive market, competing against multi-million
dollar companies

We can't afford to pay new programmers or salesmen very well. We make
enough money for ourselves, but unless we got a significant number of
new customers we wouldn't be able to pay much.

Because of the fact we can't pay much, we use a slightly more rare
technology, and we compete against large companies, we find it
difficult to find new programmers or salesman.

We desperately need to expand, but when we try to get more customers, we can't support them with so few people (or their demands grow outside of our range of expertise) and when we try to hire new programmers and salesman, we usually don't get a high quality and they usually don't provide a major benefit for our company.

Does anyone have some suggestions or tips on how we could expand?

答: Where do you do your banking? Have you checked into taking out a small business loan? If you've been profitable for 10 years you should have a good business case for borrowing money. Hire the best and forget crossing your fingers that a rookie will work out.</p>

Title: Hiring programmers for small companies?


答:
I have been teaching C++ to a group of students. I have been quite happy with Programming: Principles and Practice Using C++ by Bjarne Stroustrup.

Bjarne Stroustrup teaches programming using C++. PPP teaches practical aspects of programming, real world problems, and how they would be approached as a programmer.


答:
I disagree with all the other answers1, it's not going to be as easy as they tell you. There's quite a lot more to the shift, it's a:

Domain shift: Web development to quantitative financial analysis. Extremely different mindsets, approaches, etc.

Philosophy shift: From the easy going attitude of PHP to something that could only have come out of the darkest corners of Stroustrup's mind. A particularly disturbed individual, judging from his hellspawn2.

Talent shift: I've been working with PHP since version 3.0, and still loving it, and I can tell from experience that PHP does not require talent, you can be successful without it3. It's always nice when you have it, but it's not a requirement. C++ on the other hand requires talent. Real actual hardcore talent.

One good thing, though. I want to become a quantitative financial analyst is a very specific goal. From that sentence I'm deducing that:

You've done your research - you know the proper lingo,

You actually want this - you've done your research,

You are probably in contact with people in the sector - no one really wants to be something that ugly, if they haven't had a peek inside.

I'm no Sherlock of course, but I see some hope. Technically it's possible, if you are extremely talented, extremely dedicated, somewhat lucky and go for an entry level job at the field. And if you are all those things, best ignore anyone pissing on your parade, and just go for it. Or you might regret it for a lifetime.

1 Not really, great advice, upvoted each and every one of them

2 To be fair, that was long time ago. It took an asylum of people to get to where we are today.

3 I've met more than a few people that consider themselves web developers (and who am I to say they aren't?), when what they actually do is scrap together a ready made blog platform with a ready made theme. Some of them are extremely successful, and by that I mean mostly financially. It takes a lot of other talents to get there, of course, I'm only referring to programming talents.


问:
How to license a script/package if it uses multiple 3rd-party components with different licenses?
I have already searched but didn't managed to find a suitable answer.

My problem is this: I use different software packages with different licenses to develop a free and open-source (not commercial) piece of software (a simple data visualization web app that reads data from a specific mysql db and draws graphs and stuff) that I want to release to the public as well.

It all started with me writing some simple PHP code using a chart drawing library which is under the GPL. That was the initial version that I simply released through by blog without any license notice.

On the next stage I integrated the results (chart images etc) within a free web template from os-templates.com  which comes under a license of their own (they simply say that they allow usage for non-commercial and commercial projects with proper attribution to them, fine by me), in order to have a nice looking presentation/interface for them. I released that updated version without any license as well.

Next, I expanded the script by using a google visualization api library which is under the BSD license to draw some additional google maps/charts. Still no license notice on my new release.

I now want to continue working on this project but I think it's time to license it under an open-source license because it's getting bigger and bigger.

Do you have any ideas at all of how can I do this? My work is the php code I wrote and all the other changes I have made to the template (html/css). Must I license it as a whole? Or can I just say that so-and-so libraries and other stuff included have their so-and-so respective licenses, while I release my code and only that under a license of my choice?

Any suggestions would be nice.

Edit: By the way, I know that "discuss it with a lawyer" can be a common answer, but we're talking about a small personal/hobby project that due to its nature (application-specific) no more than ~50 people will download/use (ever I guess). So I'm mostly looking for an easy solution, not something complicated like consulting a professional (and pay for it).

Edit 2: Something else I want to note so there won't be any confusion is that apart from the template which I altered for obvious reasons, I just use the libraries' API by calling their specific functions etc. I haven't build upon them or altered them in any way. I'm saying this because as I understand it, building upon and extending an existing open source project is considered making a derivative and you should follow specific licensing guidelines (eg release the new code under the same license). In my case I just use the libraries as-is, nothing more.

答:
Depending on what BSD version the library is, you might have an issue using a GPL library in combination. If you are using the incompatible form, you can not release the software at all, because it will not satisfy the GPL requirements.

Two variants of the license, the New BSD License/Modified BSD License, and the Simplified BSD License/FreeBSD License have been verified as GPL-compatible free software licenses by the Free Software Foundation, and have been vetted as open source licenses by the Open Source Initiative, while the original, 4-clause license has not been accepted as an open source license and, although the original is considered to be a free software license by the FSF, the FSF does not consider it to be compatible with the GPL due to the advertising clause.

  Wikipedia

This graph Will give you a rough idea of what is compatible. Note that the graph is directional. Essentially, as soon as you get something GPL, you can't go back to non-GPL.

As always, this is general guidance, and not actual legal advice.


答: Make a SRS then code according to the requirements. When you've achieved all the goals mentioned in the SRS it's time to stop and test your product. </p>

Title: How do you know when to stop adding features?

Body:
Some time ago I wrote a very small python script that periodically checked an xml feed for new entries, and alerted the user to new entries when present.
I wrote this for myself, so it was essentially a console based program that anyone comfortable with a console interface could have used.

After a while I decided it could be of more use to other people and began to tidy it up, sanitize inputs, remove bugs. It occurred to me that because I'd written the script I knew how to use it efficiently, accurately etc. Others might not, so I started adding a GUI. This started out as a simple menu, and then expanded to a more full GUI with both an interface and options menu. I then added stored user preferences and also storage for previously searched xml feeds to speed up repeat searches.

I added logging to help debug the application in case things go wrong, brought the application up to the latest available stable python codebase for my chosen platform and improved dialog features.

I've bugfixed and commented my code clearly, and yet I still have things I think can be done to improve the app before I make it available to alpha testers. It's a far far cry from my original 20-30 line script. What I anticipated would take me just an hour or two to go from proof of concept to an acceptable use program has taken 10-20 times that. (I'm still a noob, and stuff takes me a long time, but still....)

How do you know when to stop adding/tweaking/fixing stuff and let your baby crawl out in the open?


问:
Design Document From Code
I am not much familiar with documenting/System designing stuff.

I have to maintain an application written in C# - working as windows service.

However there is no documentation for this system which makes it really pathetic to find where some problem (conceptually) occurred.

I would like to know the best way to design/document it (using current code) manually or preferably automatically so that I can identify the exact problems.

Like I feel as if sequence diagram won't much help probably.

Also, please guide me if I am taking it on wrong side?

答:
Do you have appropriate testing (including, but not only, unit tests) for the system? It seems like you don't, in which case I would start by adding enough tests to be sure that the application behaves as expected (since it fails to fulfill the requirements for the moment, if I understand well your question).

Then, documentation's purpose is to introduce the code to the new developer who doesn't know anything about the architecture of the existent codebase. It means that documentation is not really intended to find where a problem occurred.

When the piece of code behaves unexpectedly, you often start reading code, not the actual documentation, which can be obsolete, or just totally wrong or misleading. In practice, when systems I debugged had documentation, it was obsolete or wrong all the time (concerning the debugged point). No exceptions. Either the documentation was written from requirements and the error was introduced in the code, without reflecting the documentation, or the error was the consequence of slight changes at code level, while documentation stayed the same.

Following the comments, I see that I slightly misunderstood your question, which is more about "How I understand the existent codebase which has no documentation at all". It depends. In my case for example, generating class diagrams is something precious. This is the first thing I do before starting to work on someone else's code, and sometimes the only thing. But I also know people who don't bother generating those diagrams, because they find it totally unhelpful.

Title: Design Document From Code


问:
Pattern for user interaction and confirmation
Suppose a FileWriter class that needs validation that it will not erase a file already present, if one is found. It would have two functions:

```<code>public bool FileExists(string filePath) //...
public bool WriteFile(string filePath, string text) //...
</code>```

The main concern is to not erase a file already present. A first interface is actually just interaction via a console:

```<code>public void Save()
{
    FileWriter fileWriter;
    //...
    if (fileWriter.FileExists(filePath))
    {
        Console.WriteLine("File already exists. Continue? Press 'y' for yes");
        if (Console.ReadKey().KeyChar != 'y')
            return;
    }
    fileWriter.WriteFile(filePath, text);
}
</code>```

And some time later comes a second interface, this one with a GUI, that needs the same user interaction:

```<code>public void SaveButton_click(object sender, EventArgs e)
{
    FileWriter fileWriter;
    //...
    if (fileWriter.FileExists(filePath))
    {
        if (DialogResult.Yes != MessageBox.Show("File already exists. Continue?", "", MessageBoxButtons.YesNo))
            return;
    }
    fileWriter.WriteFile(filePath, text);
}
</code>```

Save for the way the interaction is made, the logic is the same. What pattern can be used to not duplicate this logic? Is a callback function to perform the check the best approach?

Formatted as C#, but doesn't have to be C# specific.

答:
I don't know if it's a pattern wih a name, but this is a nice way to solve it:

```<code>interface IUserInputService
{
  bool AskQuestion( string q );
}

class FileWriterService
{
  public FileWriterService( IUserInputService scv )
  {
    this.svc = svc
  }

  public void WriteFileIfItDoesntExist( string path, string text )
  {
    FileWriter fileWriter;
    if( fileWriter.FileExists( path ) )
      if( !svc.AskQuestion( "File exists, continue?" ) )
        return;
    fileWriter.WriteFile( path, text );
  }
}
</code>```

then you provide implementations of the input service dependinh on whether you're on a console or want a dialog/popup/...

Body:
I don't know if it's a pattern wih a name, but this is a nice way to solve it:

interface IUserInputService
{
  bool AskQuestion( string q );
}

class FileWriterService
{
  public FileWriterService( IUserInputService scv )
  {
    this.svc = svc
  }

  public void WriteFileIfItDoesntExist( string path, string text )
  {
    FileWriter fileWriter;
    if( fileWriter.FileExists( path ) )
      if( !svc.AskQuestion( "File exists, continue?" ) )
        return;
    fileWriter.WriteFile( path, text );
  }
}

then you provide implementations of the input service dependinh on whether you're on a console or want a dialog/popup/...


答:
If you have a business logic class (in this case your FileWriter) that needs to bring up some UI (the dialog or console input in your case) one should separate this UI from the business logic. You didn't describe it in these terms, but I think your question goes into that direction.

In that case your FileWriter would only expose the one method WriteFile() and would check internally, whether the file exists. If it does, it would call a delegate (e.g. a callback passed into the WriteFile() method) to ask for permission to overwrite it. This way all your business logic (checking file existance, writing the file, etc.) is encapsulated in the FileWriter class and the code calling from the UI would provide the means to ask for confirmation.

If there are additional situations where  FileWriter might need to call back to the code invoking it, having individual delegates for each of these situations might be a bit messy. If the situations are all very similar, you might provide additional information about them in the event args to the delegate. Or the user could pass in an interface (say IConfirmationProvider) whose methods the FileWriter could call to ask for confirmation in each of the different situations. Really depends on the exact nature of the situations where permission is needed.

Title: Pattern for user interaction and confirmation

Body:
Suppose a FileWriter class that needs validation that it will not erase a file already present, if one is found. It would have two functions:

```<code>public bool FileExists(string filePath) //...
public bool WriteFile(string filePath, string text) //...
</code>```

The main concern is to not erase a file already present. A first interface is actually just interaction via a console:

```<code>public void Save()
{
    FileWriter fileWriter;
    //...
    if (fileWriter.FileExists(filePath))
    {
        Console.WriteLine("File already exists. Continue? Press 'y' for yes");
        if (Console.ReadKey().KeyChar != 'y')
            return;
    }
    fileWriter.WriteFile(filePath, text);
}
</code>```

And some time later comes a second interface, this one with a GUI, that needs the same user interaction:

```<code>public void SaveButton_click(object sender, EventArgs e)
{
    FileWriter fileWriter;
    //...
    if (fileWriter.FileExists(filePath))
    {
        if (DialogResult.Yes != MessageBox.Show("File already exists. Continue?", "", MessageBoxButtons.YesNo))
            return;
    }
    fileWriter.WriteFile(filePath, text);
}
</code>```

Save for the way the interaction is made, the logic is the same. What pattern can be used to not duplicate this logic? Is a callback function to perform the check the best approach?

Formatted as C#, but doesn't have to be C# specific.


答:
One particularly interesting way of promoting your open source project is StackOverflow's own Free Vote-Based Advertising for Open Source Projects1:

Here’s how it works:

Visit the special meta.stackoverflow.com question thread for this advertising period. It will always be tagged [open-source-advertising].

Construct a 220×220 image advertisement for the open source project that you would like to publicize to your fellow programmers.

Post an answer containing your image to the question. It must be in exactly the right format, as documented in the question itself.

Get at least (n) upvotes for your answer.

Your advertisement will now be featured in Stack Overflow’s remnant ad inventory, in the sidebar ad slot on most pages.

I think it will serve the an eye specifically towards finding other developers interested in contributing goal finely, as the most visited sites of the network are geared towards developers (SO and this one) or technical savvy people (SuperUser).

I'm also very fond of Ohloh:

Ohloh is a new kind of software directory, combining community-driven content with a unique source code crawler that monitors up-to-date development activity.

Lastly, if your project relies on other open source projects, you could reach out to their communities.

And of course my answer is meant in addition to everything in Chiron's answer.

1 Also: Free Vote-Based Advertising for Open Source Projects and Open Source Advertising - Sidebar - 1H 2012 on Meta StackOverflow.


答: When you are sure about the stability of your software go for a release though there can be pending features. Stability is more important than features. Get the feedback, incorporate with existing features and decide on what has to be delivered next and when!  </p>


答:
For automated documentation there is XML comments for C# (like javadoc). However this only makes the documentation as good as your comments. Also there are debuggers out there that try to visualise stuff, but I haven't found them to be that useful.

As for design document, I think it helps to have use cases or stories on how a user will use a system.
This leads very well in BDD (behaviour driven dev), which sounds like it will suit you more than trying to write up some long IEEE standardised spec/test plan.

However it did sound like you might have some fundamental issues.
(from the Joel Test:)
1. Do you use source control?
4. Do you have a bug database?
7. Do you have a spec?
10. Do you have testers?
A 'no' on any of those questions will make your life difficult.

Title: Design Document From Code

Body:
I am not much familiar with documenting/System designing stuff.

I have to maintain an application written in C# - working as windows service.

However there is no documentation for this system which makes it really pathetic to find where some problem (conceptually) occurred.

I would like to know the best way to design/document it (using current code) manually or preferably automatically so that I can identify the exact problems.

Like I feel as if sequence diagram won't much help probably.

Also, please guide me if I am taking it on wrong side?


答: Get on podcasts! Herding Code, Dot Net Rocks come to mind. Also, get talked about on good blogs as much as possible. </p>


答:
I find Doxygen very useful for extracting information from raw source code. Methods, arguments, types, variables, dependency trees, call and caller trees... All of that in hypertexted HTML for jumping between code elements.

Moreover, if during your maintenance activities you insert tagged comments, you can get that documentation more and more useful.

Title: Design Document From Code


问:
Is Python's C interface faster than JNI?
I was reading What makes JNI calls slow? and I was wondering if Python's C interface is any better than JNI.

I heard that if you want to make certain parts of your python programs faster, or if a certain part of the program was really hurting your program's performance, you write them in C, and make Python call them.

Does the C interface it incur the same costs JNI does? why or why not?

答:
Even though I don't know a direct answer to your question, I can't resist answering indirectly:

I heard that if you want to make certain parts of your python programs faster, or if a certain part of the program was really hurting your program's performance, you write them in C, and make Python call them.

As written in the topmost answer of the SO question you linked to, "slow" here means tens of nanoseconds. If your expensive part (written in C) takes even one microsecond to execute, then the proportional cost of the C/JNI interface is negligible. The cost only comes whenever you call the native part (and when the call returns), not while the native part is executing. If you keep the number of calls low, then the extra cost is low. That is, don't write tight Python loops that call C functions; do write the loop itself in C and call it from Python.

As another example that the JNI costs are usually negligible: many of JDK's core classes, e.g. most functions in Math, and ultimately all graphics and I/O functions map to JNI calls under the hood. Regardless, Java is usually considered to be way faster than CPython.


问:
Is there a measure of code rot?
I'm dealing, again, with a messy C++ application, tons of classes with confusing names, objects have pointers into each other and all over, longwinded Boost and STL data types, etc.  (Pause and consider your favorite terror of messy legacy code.  We probably have it.)  The phrase "code rot" oft comes to mind when I work on this project.

Is there a quantitative way to measure code rot?  I wouldn't expect anything highly meaningful or scientific, since no other measure of code productivity or quality is so fine.   I'm not looking for a mere opposite of measures of code quality, but specifically a measure of how many bad things  happened after a series of maintenance software "engineers" have had turns hacking at the code.

A general measure applying to any language, or many languages, would be great.  If there's no such thing, at least for C++, which is a better than average language for creating messes.

Maybe something involving a measure of topology of how objects connect during runtime, a count of chunks of commented out code, how mane files a typical variable's usage is scattered over, I don't know... but surely now, a decade into the 21st Century, someone has attempted to define some sort of rot measure.

It would be especially interesting to automate a series of svn checkouts, measure the "rottenosity" of each, and plot the decay over time.

答:
Which door represents your code?...

...Which door represents your team or your company? Why are we in that room? Is this just a normal code review or have we found a stream of horrible problems shortly after going live? Are we debugging in a panic, poring over code that we thought worked? Are customers leaving in droves and managers breathing down our necks? How can we make sure we wind up behind the right door when the going gets tough? (Robert "Uncle Bob" Martin, Clean Code: A Handbook of Agile Software Craftsmanship)

Any quality measure / metric is at risk of being useless unless backed by code reviews. In my experience I haven't yet seen a metric that was impossible to trick into 100%-perfect-digits garbage. On the other hand I can't recall a code review where I was able to trick reviewer (though have to admit I never tried it hard).

OwnerDisplayName: DarenW

Title: Is there a measure of code rot?


答: Business rules, data model, class diagrams,setup parameters for production/test/development, security details in test/dev/production, source control process (where is the last good version!), method documentation, business classes and issue logs (with resolution) are all good information that would help people manage an application. As you said, a sequence diagram is not enough.</p>

Title: Design Document From Code


答: Make your project useful, filling a gap in the people's needs. Find the users first - and some of them will become contributors later. The other way around is doomed to be fruitless.</p>


答: Hire a good offside java developer in India. You will be amazed how good talent you can hire so inexpensively. You can give the candidate a week's worth of work to see if he/she fits. However, don't hire services from a company. Hiring a developer directly will benefit you and developer both.</p>

Title: Hiring programmers for small companies?

Body:
I've been running a company for nearly 10 years, and all this time it's been just myself, another programmer (who's a great friend and cofounder), and a salesman (who's also a friend). Together, we've managed to do decent business and we've all managed to make a living, but we've been trying to expand for a long time now.

Unfortunately, there are a few problems:

The technology we use is not obsolete, but it's also not as popular
compared to other web development options like PHP

We work in a competitive market, competing against multi-million
dollar companies

We can't afford to pay new programmers or salesmen very well. We make
enough money for ourselves, but unless we got a significant number of
new customers we wouldn't be able to pay much.

Because of the fact we can't pay much, we use a slightly more rare
technology, and we compete against large companies, we find it
difficult to find new programmers or salesman.

We desperately need to expand, but when we try to get more customers, we can't support them with so few people (or their demands grow outside of our range of expertise) and when we try to hire new programmers and salesman, we usually don't get a high quality and they usually don't provide a major benefit for our company.

Does anyone have some suggestions or tips on how we could expand?


问:
What would be an appropriate algorithm to factorise numbers in the range of a few billion?
I'm learning Python at the moment and to give me reasons to apply what i'm learning I'm having a crack at some of the problems on Project Euler

I'm currently on number 3, which is to determine the highest prime factor of said number.

I've deduced I need to probably have two algorithms, one to determine primality, and the second which would involve finding factors of the number.

So i've been reading up on Wiki articles. Trying to determine what might be the best algorithm to use and how to go about it.

But it's been a while since i've done some hardcore maths based programming and i'm struggling to start somewhere.

I was looking at using Fermat's factorization method with inclusion of Trial by Division but I don't want to make something too complicated I'm not after to crack RSA I just want two algorithsm suitable for my problem and there in lies my question.

What algorithms would you use for testing for primality / factoring a number that are suitable to the problem at hand?

Edit

Thank you all for your answers and insights they have been most helpful I upvoted all that were useful either through advice or through there own Euler experiences. The one I marked as right was simply the most useful as It gave me a proper place to start from which was a push in the right direction. Thanks again =)

答:
I solved some ProjectEuler problems some time ago in Ruby using trial division with prime numbers.

I found that generating the prime numbers was far more critical than the actual factorization algorithm. As soon as I replaced my naïve prime number generation approach with a sieve my execution times came down to a reasonable amount.


答:
It's well worth writing some code that does factorising and prime-finding (basically the same thing) because you will probably re-use in lots of other Euler questions. You will be able to improve the code for later questions and perhaps look into non-exhaustive primality tests if you find its no longer efficient enough, so I suggest the simplest approach for now is to:

Write a simple loop which finds all the prime numbers (ie. for each number, test its divisibility by each previously found prime, and if they all fail, add it to the list of primes).

Try to divide the number you're trying to factorise by each prime up to the square root of the number.

Title: What would be an appropriate algorithm to factorise numbers in the range of a few billion?

Body:
I'm learning Python at the moment and to give me reasons to apply what i'm learning I'm having a crack at some of the problems on Project Euler

I'm currently on number 3, which is to determine the highest prime factor of said number.

I've deduced I need to probably have two algorithms, one to determine primality, and the second which would involve finding factors of the number.

So i've been reading up on Wiki articles. Trying to determine what might be the best algorithm to use and how to go about it.

But it's been a while since i've done some hardcore maths based programming and i'm struggling to start somewhere.

I was looking at using Fermat's factorization method with inclusion of Trial by Division but I don't want to make something too complicated I'm not after to crack RSA I just want two algorithsm suitable for my problem and there in lies my question.

What algorithms would you use for testing for primality / factoring a number that are suitable to the problem at hand?

Edit

Thank you all for your answers and insights they have been most helpful I upvoted all that were useful either through advice or through there own Euler experiences. The one I marked as right was simply the most useful as It gave me a proper place to start from which was a push in the right direction. Thanks again =)


答:
Keeping it very simple ...

Finding the factors of X: I would start (n) at 2 and work up to the integer (floor, not round) of the square-root of X. If dividing X by n yields Y and Y is an integer, both n and Y are factors. The lowest values of n will yield the highest values of Y.

Primality of Y: Again, loop (m) from 2 to the square root of Y and see if Y / m is an integer. If it is then Y is not prime. Go back to find another factor.

If m hits the root of Y, you have your prime number. Stop looking. Y is the answer.

If n hits the root of X, there aren't any prime factors.


问:
How important are design patterns in programming?
I'm a university student and I've just started learning about design patterns and im struggling to understand the purpose of them. I have tried researching them but all the resources I have found seem to talk about them in an academic, not professional, way.

What is their purpose and are they important to learn?

答: Design patterns are solutions to common encountered problems in software development. There is always more than one solution to some problems, and design patterns help you to decide which solution is the best by providing you a set of good solutions to these common problems.</p>


问:
Form screenshot for legal proof of clicking one of the checkboxes?
We got a request from one of our customers, and since I've never encountered such a request before, I don't even know where to start looking.

Our customer is a network of colleges, and we're building them a site. On that site, among other things, will be a form which potential applicants can fill out in order to get more info about the studies in one of the colleges. After a user fills out this form - including giving their email and/or phone number - the relevant college then contacts them with the relevant info.

Now, for legal reasons, the client is asking that this form also have a checkbox that the potential applicant checks to indicate that they agree to get promotional material from these colleges. That's of course no problem. But here comes the weird part of the request:

The details of each filled out form have to be be saved in a reliable method. Apparently, saving the form values in a database - a column indicating if the user agreed or didn't agree - isn't enough, because a DB could be changed after the users has sent the form. Our client claims that other college portals create a screenshot of the filled-out form, and save it somewhere in a dedicated folder, in a manner that is easily found, such as giving the file a name that includes the user's name, and the date and time.

My question is as follows: have you heard of using screenshots as a method of proving a user has actually filled out a form? Are there other methods that are are considered reliable?

答:
I have never heard of something like that, and it would be ridiculous, because a fake screenshot can be produced just as easily as a fake value in a database.

EDIT Besides, I mean, WTF? since you cannot get a screenshot of someone's screen over the web, you will obviously have to reconstruct the page on the server and take a screenshot of that, and then who's to say you did not doctor it?


答:
This being a legal question, a real answer will of course depend on national and possibly even local laws and exact circumstances. So obviously a real answer can only come from a lawyer.

However, as far as my (limited) legal knowledge goes, I see no reason to assume a screenshot would be considered evidence for anything, as it is obviously very easy to fake.

Your best course of action is probably to explain to your client that this is essentially a legal problem, and that the help of a lawyer is required. Then discuss with them whether they want you to discuss it with a lawyer, or whether they want to do it themselves.

To get a feasible solution, you might want to do the discussing yourself (if the client agrees). If you don't want that hassle (or fear they might not be willing to pay you for it), let them do it.

Title: Form screenshot for legal proof of clicking one of the checkboxes?

Body:
We got a request from one of our customers, and since I've never encountered such a request before, I don't even know where to start looking.

Our customer is a network of colleges, and we're building them a site. On that site, among other things, will be a form which potential applicants can fill out in order to get more info about the studies in one of the colleges. After a user fills out this form - including giving their email and/or phone number - the relevant college then contacts them with the relevant info.

Now, for legal reasons, the client is asking that this form also have a checkbox that the potential applicant checks to indicate that they agree to get promotional material from these colleges. That's of course no problem. But here comes the weird part of the request:

The details of each filled out form have to be be saved in a reliable method. Apparently, saving the form values in a database - a column indicating if the user agreed or didn't agree - isn't enough, because a DB could be changed after the users has sent the form. Our client claims that other college portals create a screenshot of the filled-out form, and save it somewhere in a dedicated folder, in a manner that is easily found, such as giving the file a name that includes the user's name, and the date and time.

My question is as follows: have you heard of using screenshots as a method of proving a user has actually filled out a form? Are there other methods that are are considered reliable?


答:
Actually this is an area of active research in Mathematics and Computer Science. The wikipedia article gives a good overview:

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

Pick any algorithm you like/find interesting, and have a go at it.

You'll probably have to make a tradeoff: Most of the "good" algorithms require a fair bit of Math background to really understand (though you could implement them without completely understanding them).

If you don't know where to start, I'd recommend the quadratic sieve:

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

It does not require insane Math knowledge, yet performs well.


答:
I would think the real question would be did the person whose name appears on the form really fill out the form?

In other words if someone goes to the website and enters the name "Bill Gates" and clicks the box "it's OK to send me email" how would a screenshot prove it was the real Bill Gates?

Have they considered doing what lots of sites do and that is send a verification email with a unique link that someone has to click on to confirm? That way at least you have a record that you have confirmation from someone with access to that email account.


答:
You can always nurse a project for ever and ever.

A very good rule is that you should never add things that are not in an approved use case.  This ensures that you don't end up with a lot of things that would be nice to have, but which nobody uses.  Approving ensures that others than you agree that this is needed in your project.


答:
I know that I am beginning this answer with a question but I do have a point:

Without calling to question the supposed absurdity of the request, if this is a typical HTTP browser based web application how would one programatically capture a screenshot and send it to the server?

I would hope this is impossible as it would represent a serious browser security and privacy concern.

Now imagine if someones credit card number was also on the screen at the time of screenshot capture.  Now you are inadvertently capture credit card information and your system should now be PCI compliant.  This is another avenue of concern altogether.

The only way to do it would probably be using a third-party browser plugin like, Flash, Silverlight, Java Applets, or an ActiveX control with elevated system privileges.  The component would need to be signed and the user would need to agree to the component having access to run code on their machine.

There are too many holes with this plan and I seriously doubt that other college's implement something similar.  I have certainly never heard of this in my professional career, at least not with a web application.

EDIT:

I just thought of another option that would probably more greatly reflect what I think your client is really asking for.

I had an application I did for a client where the client had to agree and sign an NDA document to gain access to the application.  I acheived this through a signable PDF document.  You could have a signature field in a PDF document that by either using a pen+pad USB component or through just clicking it to acknowledge will for legal purposes be just as good as if you were to have physically signed the document by hand.

It is called an electronic signature and they do hold up in court.

The PDF document after being signed becomes encrypted and a hash is stored along with it that verifies the document has NOT been tampered with after signing.  Modern PDF readers like Adobe can actually transmit a signed document to a server where you can store it in a document management system or database for safe keeping.

At any time administrator users can recall one of these documents and print them.

This may be more along the lines of what your customer actually needs, but had a poor time of explaining properly.


问:
Is there a reason to prefer lambda syntax even if there is only one parameter?
```<code>List.ForEach(Console.WriteLine);

List.ForEach(s => Console.WriteLine(s));
</code>```

To me, the difference is purely cosmetic, but are there any subtle reasons why one might be preferred over the other?

答: I'd prefer the lambda syntax in general. When you see that, then it tells you what the type is. When you see Console.WriteLine, you'd have to ask the IDE what type it is. Of course, in this trivial example, it's obvious, but in the general case, it might not be so much.


问:
Where should date formatting take place in an MVC pattern?
Suppose that you want to show a user list, on a web application having to handle custom date formats (depending on current selected interface language).

Several locations for applying the date format seem possible. Which one would you use, and why?

At model, for example doing a DATE_FORMAT(user.birthdate, '%d/%m/%Y') for date fields (supposing we have a MySQL DB).

At controller level, for example (supposing we use PHP):

```<code>$users = UserModel::getUsers();
// loops through results before display to format dates.
// in the $users structure, we have to know which fields are dates or not
$users = MagicFunctionFormattingDates($users);

$view = new View('someTemplate');
$view->assign('users', $users);
</code>```

At view level, for example (supposing we use a template language such as Smarty):

```<code>{foreach key=keyitem item=row from=$users}
  <tr>
  {foreach key=keyfield item=field from=$row.fields}
     {* Here $field should be an Object or associative array
        holding its 'type' (is it a date or something else) *}
     <td>{MagicFunctionForFormatting field=$field}</td>
  {/foreach}
  </tr>
{/endforeach}
</code>```

A similar and related question goes for sumbitting dates (e.g. on a user registration form). Where should the date conversion take place:

In the controller processing and validating the form, before calling the model?

In the model?

答:
It's really entirely up to you.

I would consider it a display detail. If you were to replace the front-end with a web service, you would want to "display" it in an entirely different way. And thus I'd put it in the view. Personally.


答:
My approach for those problems is usually this one: build the simplest possible algorithm to solve it, which is usually a brute force naive approach, and then test/figure mathematically whether or not it's too slow. Most of the time it's good enough. When it's not you have a clear starting point to work on and optimize things around until the algorithm is efficient enough.

Here's a simple algorithm to solve Problem 3 on Project Euler (in C, but translating it to the Python should be trivial):

```<code>#include <stdio.h>
#include <math.h>

int isPrime(int n){
    int i;

    if (n==2)
        return 1;

    if (n%2==0)
        return 0;
    for (i=3;i<sqrt(n);i+=2)
        if (n%i==0)
            return 0;
    return 1;
}

int main(){
    long long int n = 600851475143;
    int i = 3;

    while (i<50000){
        if (isPrime(i))
            if (n%i==0)
                printf("%d\n",i);
        i+=2;
    }
    return 0;
}
</code>```

Body:
My approach for those problems is usually this one: build the simplest possible algorithm to solve it, which is usually a brute force naive approach, and then test/figure mathematically whether or not it's too slow. Most of the time it's good enough. When it's not you have a clear starting point to work on and optimize things around until the algorithm is efficient enough.

Here's a simple algorithm to solve Problem 3 on Project Euler (in C, but translating it to the Python should be trivial):

#include <stdio.h>
#include <math.h>

int isPrime(int n){
    int i;

    if (n==2)
        return 1;

    if (n%2==0)
        return 0;
    for (i=3;i<sqrt(n);i+=2)
        if (n%i==0)
            return 0;
    return 1;
}

int main(){
    long long int n = 600851475143;
    int i = 3;

    while (i<50000){
        if (isPrime(i))
            if (n%i==0)
                printf("%d\n",i);
        i+=2;
    }
    return 0;
}


答:
I'd suggest two things:

The model is where your database I/O happens. In that case you want everything going in and out of the database to be a a predefined form. This is your "neutral" form, the defined interface to everything else which must always be consistent.

After getting 1 clear, you can do transforms somewhere else. Where else is up to your design.

HOWEVER... in thinking about this a bit more, suppose the date format changes. Suppose, further, that you allow date format to be presented according to user preferences.

In that case you would seem to have 2 choices:

Model: the interface is in the users preferred format. OR

Model: the interface is always the neutral format, in which case, VIEW should probably be where you transform to/from the way that the user gets to see it.

Going with option 2, this means that controller can also always work with the neutral format meaning that coding functions/operations in it might be easier and/or less prone to change or reworking.

However, this does all depend on what you are trying to achieve.

My final take on all this: keep to a neutral form as long as you possibly can and then convert to/from the user preferred form as late as you possibly can. (And this probably means View is where your transforms should take place).

Title: Where should date formatting take place in an MVC pattern?

Body:
Suppose that you want to show a user list, on a web application having to handle custom date formats (depending on current selected interface language).

Several locations for applying the date format seem possible. Which one would you use, and why?

At model, for example doing a DATE_FORMAT(user.birthdate, '%d/%m/%Y') for date fields (supposing we have a MySQL DB).

At controller level, for example (supposing we use PHP):

```<code>$users = UserModel::getUsers();
// loops through results before display to format dates.
// in the $users structure, we have to know which fields are dates or not
$users = MagicFunctionFormattingDates($users);

$view = new View('someTemplate');
$view->assign('users', $users);
</code>```

At view level, for example (supposing we use a template language such as Smarty):

```<code>{foreach key=keyitem item=row from=$users}
  <tr>
  {foreach key=keyfield item=field from=$row.fields}
     {* Here $field should be an Object or associative array
        holding its 'type' (is it a date or something else) *}
     <td>{MagicFunctionForFormatting field=$field}</td>
  {/foreach}
  </tr>
{/endforeach}
</code>```

A similar and related question goes for sumbitting dates (e.g. on a user registration form). Where should the date conversion take place:

In the controller processing and validating the form, before calling the model?

In the model?


答:
Another option would be to log the raw HTTP Post from the client. This would have their IP, where they came from, what browser, etc., without requiring a screenshot. You could then log this into a insert only table in raw form, or a simple flat log file...

Just trying to think up some other options because I tend to run into ridiculous requests like this much more often than I would like...


问:
Entity Framework and "ViewModel"
Earlier I asked a question about "Entity Framework and layer seperation" and found out that some people use a ViewModel to show their data in the UI.

For example if we got a "Person" table and an "Address" table and I want to show a combination of the two tables. I would then create a ViewModel, lets call it PersonAddress, and show it on the UI.

I have a few questions regarding this:

How do you save the "PersonAddress" object to the database since it does not exist in my EF context?

If I only wanted to show the "Person" object, would I still create an identical "ViewModel" object to the one EF creates for me (without the EF specific properties ofcourse)

Do people use the "EntityState" property and dosent it become useless if you only interact with the "ViewModel"?

答:
How do you best save the "PersonAddress" object to the database since it does not exist in my EF context?

You don't. You save a Person and the attached Address separately (in a transaction, if needed). Loading data and saving data can also be thought as different concerns (see CQRS).

If I only wanted to show the "Person" object, would I still create an identical "ViewModel" object to the one EF creates for me (without the EF specific properties of course)

Yes. Again, this is about separation of concerns.

Do people use the "EntityState" property and dosent it become useless if you only interact with the "ViewModel"?

Depends on what you are doing. A ViewModel models the UI, not your data.

Title: Entity Framework and "ViewModel"