Бизнес-объекты - Контейнеры или функциональный? [закрытый]

У меня есть клавиатура MS Natural также, и это является потрясающим. Мне удалось обучить меня использовать сторону моей левой руки (ниже мизинца) для удара клавиши Ctrl.

11
задан Walter 14 May 2010 в 10:11
поделиться

7 ответов

Объекты - это состояние и поведение вместе. Если объект имеет разумное поведение (например, вычисление возраста Человека по дате его рождения или общий налог для Счета-фактуры), обязательно добавьте его. Бизнес-объекты, которые представляют собой не что иное, как DTO, называются «анемичной моделью предметной области». Я не думаю, что это требование дизайна.

Настойчивость - это особый вид поведения. То, что я называю «разумным», - это деловое поведение. Бизнес-объекту не обязательно знать, что он постоянный. Я бы сказал, что DAO может отделить постоянство от бизнес-поведения. Я не помещаю «экономить» в категорию «разумных».

10
ответ дан 3 December 2019 в 03:35
поделиться

Бизнес-объекты МОГУТ иметь бизнес-функции .

Постоянство - это не бизнес-функция , а техническая реализация.

Короче говоря:

  1. Сохранить / Обновить / Удалить / Найти и т. Д. - держаться подальше от бизнес-объектов на уровне сохраняемости.
  2. CalculateSalary, ApplyDiscount и т. Д. Являются бизнес-методами и могут быть:
    1. методы бизнес-объектов (так что BO - это автономное представление сущности) или;
    2. отдельные службы , реализующие определенные функции (так что BO действуют больше как DTO).

Что касается пункт 2.
Я должен упомянуть, что подход 2.1 имеет тенденцию делать BO слишком раздутыми и нарушать SRP . В то время как 2.2 вводит большую сложность обслуживания .

Я обычно балансирую между 2,1 и 2,2, так что я помещаю тривиальные вещи, связанные с данными, в Business Objects и создаю службы для немного более сложных сценариев (если имеется более 4 строк кода - сделай это сервисом).

Это меняет парадигму бизнес-объектов, превращая их в объекты передачи данных.

Но все это упрощает разработку, тестирование и сопровождение проекта.

9
ответ дан 3 December 2019 в 03:35
поделиться

Я думаю, что для бизнес-объектов имеет больше смысла знать, как «управлять» самими собой, чем возлагать эту нагрузку на другое место в системе. В вашем примере для меня наиболее логичным местом, где можно было бы разобраться с тем, как «сохранить» данные о клиентах, будет объект «Клиент».

Это может быть связано с тем, что я считаю базу данных «контейнером данных», поэтому я Я за то, чтобы «бизнес-объекты» были более высоким уровнем, который защищает контейнер данных от прямого доступа И применяет стандартные «бизнес-правила» о том, как эти данные доступны / управляются.

2
ответ дан 3 December 2019 в 03:35
поделиться

The answer is the same regardless of platform or language. The key to this question is whether an object should be able to be autonomous or whether it is better for any given behavior to be spread out among objects with more focused responsibility.

For each class the answer might be different. We end up with a spectrum along which we can place classes based upon the Density of Responsibility.

                          (Level of responsibility for behavior)
         Autonomy - - - - - - - - - - - - - - - - - - - Dependence  
      High
  C      -   <<GOD object>>                            <<Spaghetti code>>
  l      -
  a      -  
  s      -                                      
  s      -                 
         -                        
  s      -  
  i      -  
  z      -
  e      -  <<Template>>                                <<Framework>>
       low  

Let's say you favor letting the class perform all the behaviours itself, or as many as you can. Starting on the left side of this graph, when you make your class more autonomous, the size of the class will grow unless you continuously refactor it to make it more generic. This leads to a template. If no refactoring is done, the temdency is for the class to become more "god-like" because if there is some behavior it needs, it has a method for that. The number of fields and methods grow and soon become both unmanageable and unavoidable. Since the class already does so much, coders would rather add to the monstrosity than try to piece it apart and cut the Gordian knot.

The right side of the graph has classes that depend on other classes to a large degree. If the dependency level is high but the individual class is small, that is a sign of a framework; each class doesn't do much and requires lots of dependent classes to accomplish some function. On the other hand, a highly-dependent class that also has a large amount of code is a sign that the class is full of Spaghetti.

The key to this question is to determine where you feel more comfortable on the graph. In any event, individual classes will end up spread out on the graph unless some organizational principle is applied, which is how you can achieve the results of Template or Framework.

Having just written that, I would say that there is a correlation between class size and degree of organization. Robert C. Martin (or "Uncle Bob") covers similar ground with package dependencies in his very thorough paper on Design Principles and Design Patterns. JDepend is an implementation of the ideas behind the graph on page 26 and complements static analysis tools such as Checkstyle and PMD.

4
ответ дан 3 December 2019 в 03:35
поделиться

Business objects should be about encapsulating data and associated behaviors of the business entity modeled by that object. Think of it like this: one of the major tenets of object-oriented programming is encapsulating data and associated behaviors on that data.

Persistence is not a behavior of the modeled object. I find development progresses more smoothly if business objects are persistence ignornant. Developing new code and unit testing new code happen more quickly and more smoother if the business objects are not specifically tied to the underlying plumbing. This is because I can mock those aspects and forget about having to go through hoops to get to the database, etc. My unit tests will execute more quickly (a huge plus if you have thousands of automated tests that run with each build) and I will have less stress because I won't have tests failing because of database connection issues (great if you often work offline or remotely and can't always access your database and oh, by the way, those aspects (database connectivity etc.) should be tested elsewhere!).

The other line of reasoning says, no, if I have a customer object I just want to call Customer.Save and be done with it. Why do I need to know about how to save a customer if I'm consuming the object?

Knowing that Customer has a Save method is already knowing how to save a customer object. You haven't avoided the problem by embedding that logic in your business object. Instead, you've made your code base more tightly coupled and therefore harder to maintain and test. Push off the responsibility of persisting the object to someone else.

1
ответ дан 3 December 2019 в 03:35
поделиться

Бизнес-объекты, как они называются, очевидно, должны обладать собственной бизнес-логикой, динамикой бизнес-логики среди доменов, находящихся на сервисном уровне.

С другой стороны, может ли БО быть контейнером данных (DTO?) состава и методов, то есть БО чисто функционально? Это позволило бы избежать всех преобразований между BO и DTO.

0
ответ дан 3 December 2019 в 03:35
поделиться

В архитектуре MVC,

Можно ли сказать, что Model содержит бизнес-объекты.

-1
ответ дан 3 December 2019 в 03:35
поделиться
Другие вопросы по тегам:

Похожие вопросы: