Adding methods to POCO classes

2020-07-10 10:51发布

问题:

I have the following setup: MVC > Services > Repositories. Now I want to allow users to be able to add a Note to a Document. Only Users associated with the Document (either as owners or reviewers) can add Notes so in my NoteService I do the following to ensure the User has permission on the selected Document:

public Note GetNewNote(int documentID)
    {
        if (!userHasAccess(Thread.CurrentPrincipal.Identity.Name))
            throw new BusinessLogicException();

        // Other stuff here...
    }

My question is, where should I define the userHasAccess method? It makes no sense in the NoteService as it is checking on a Document. I could define it in the DocumentService but will then NoteService will need access to this which seems to be introducing more coupling.

To me it makes more sense to define it on the Document POCO itself and then call document.userHasAccess(...). Would this be good practice or should a domain POCO be limited to simple properties? I am concerned that this is really part of the validation and that by placing the method in the POCO I am seperating the validation between Service and POCO.

What I am trying to ensure is that my application is easy to maintain and test. Any suggestions on how I should tackle this would be most appreciated!

回答1:

Where should I define the userHasAccess method?

It makes sense to be consistent with the rest of the design, while I don't know the full design I can at least say that a method called UserHasAccess() on the POCO itself makes sense.

Should a domain POCO be limited to simple properties?

No, a domain POCO should contain logic (especially validation logic) related to the object. Otherwise, it ends up being an object with no behaviour - something you should definitely avoid.

However, don't get confused between a domain (business) object and a view object, which will typically contain little logic.

You are concerned that you are separating the validation between Service and POCO.

I'd put validation in the POCO, and cross-domain logic in the services.



回答2:

Any domain entity can contain validation methods as well.



回答3:

  1. If you are following Domain Model Pattern then you can add attributes with behaviors. Check this by Martin fowler
  2. If you are following Table Module pattern then add behaviors in BLL class and attributes in POCO check this as well by Martin fowler