Elettracompany.com

Компьютерный справочник
4 просмотров
Рейтинг статьи
1 звезда2 звезды3 звезды4 звезды5 звезд
Загрузка...

Java project structure

Структура проекта Java объясняется для новичков?

Я родом из .NET-фона и совершенно новичок в Java, и я пытаюсь разобраться в структуре проекта Java.

Моя типичная структура решений .NET содержит проекты, которые обозначают логически различные компоненты, обычно называемые с использованием формата:

Название проекта обычно равно корневому пространству имен для проекта. Я мог бы разбить пространство имен дальше, если это большой проект, но чаще всего я не вижу необходимости в пространстве имен.

Теперь в Java у вас есть приложения, состоящие из проектов, а затем у вас есть новый логический уровень — пакет. Что такое пакет? Что он должен содержать? Как вы проецируете пространство внутри этой структуры App.Project.Package ? Где JAR вписываются во все это? В принципе, может ли кто-то представить новичку вступление в структуру приложения Java?

Изменить: Некоторые действительно трещины ответы спасибо ребятам. Затем следуют следующие вопросы:

  • У файлов .JAR есть скомпилированный код? Или просто сжатые файлы исходного кода?
  • Есть ли веская причина, почему имена пакетов в нижнем регистре?
  • У пакетов есть «круговые зависимости»? Другими словами, может ли Package.A использовать Package.B и наоборот?
  • Может ли кто-нибудь просто показать типичный синтаксис объявления класса как находящегося в пакете и объявить, что вы хотите ссылаться на другой пакет в классе (может быть?)?

10 ответов

32 Решение Carl Smotricz [2009-12-23 19:39:00]

«Простые» проекты J2SE

Как объяснил cletus, структура исходного каталога напрямую эквивалентна структуре пакета и, по сути, встроена в Java. Все остальное немного менее четкое.

Многие простые проекты организованы вручную, поэтому люди могут выбрать структуру, в которой они чувствуют себя хорошо. Что часто делается (и это также отражается в структуре проектов в Eclipse, очень доминирующем инструменте Java) заключается в том, чтобы исходное дерево начиналось в каталоге с именем src . Ваши исходные файлы без пакетов будут располагаться непосредственно в src, и ваша иерархия пакетов, обычно начиная с каталога com , также будет содержаться в src . Если вы CD в каталог src перед запуском компилятора javac , ваши скомпилированные файлы .class будут попадать в одну и ту же структуру каталогов, причем каждый .class файл находится в том же каталоге и рядом с его .java .

Если у вас много исходных и классных файлов, вы хотите отделить их друг от друга, чтобы уменьшить беспорядок. Руководство и организация Eclipse часто размещают каталог bin или classes , параллельный src , поэтому файлы .class попадают в иерархию, которая отражает структуру src .

Если ваш проект имеет набор файлов .jar для доставки возможностей из сторонних библиотек, то третий каталог, обычно lib , помещается параллельно src и bin . Все в lib необходимо поместить в путь к классам для компиляции и выполнения.

Наконец, есть куча этого и того, что более или менее необязательно:

  • docs в doc
  • ресурсы в resources
  • данные в data Конфигурация
  • в conf .

Вы получаете идею. Компилятор не заботится об этих каталогах, это просто способы организовать (или запутать) себя.

Проекты J2EE

J2EE примерно эквивалентен ASP.NET, это массивная (стандартная) структура для организации веб-приложений. Хотя вы можете разработать свой код для проектов J2EE по своему усмотрению, существует стандартный стандарт для структуры, которую веб-контейнер ожидает от вашего приложения. И эта структура, как правило, также немного отражается на исходном макете. Вот страница, в которой подробно описываются структуры проектов для проектов Java (они не очень согласны с тем, что я написал выше) и для проектов J2EE в частности:

Проекты Maven

Maven — очень универсальный инструмент построения проекта. Лично мои потребности в построении прекрасно удовлетворяются ant , что примерно сравнивается с nmake . Maven, с другой стороны, является полным-lifecyle управления строительством с управлением зависимостью болтами. Libs и источник для большей части кода в мире Java свободно доступны в «сети», а maven, если его спросят красиво, будет сканировать его для вас и принести домой все, что вам нужно, без необходимости даже рассказать об этом. Он также управляет небольшим репозитаром.

Недостатком этого чрезвычайно трудолюбивого искателя является тот факт, что он очень фашист в отношении структуры проекта. Вы делаете это Maven способом или совсем нет. Заставляя свой стандарт спускаться с горла, Maven удается сделать проекты по всему миру более похожими по своей структуре, проще управлять и легче создавать автоматически с минимальным вводом.

Если вы когда-либо выбираете Maven, вы можете перестать беспокоиться о структуре проекта, потому что может быть только один. Это он: http://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html

13 dball917 [2009-12-23 17:33:00]

Пакет в Java очень похож на пространство имен в .Net. Имя пакета по существу создает путь к классам, которые живут внутри него. Этот путь можно рассматривать как пространство имен классов (в терминах .Net), потому что это уникальный идентификатор для определенного класса, который вы хотите использовать. Например, если у вас есть пакет с именем:

И внутри у вас была куча классов:

Чтобы конкретно ссылаться на те классы, которые вы использовали бы:

Единственное реальное различие между этим и .Net(что я знаю) заключается в том, что Java упорядочивает свои «пространства имен» структурно (каждый пакет представляет собой отдельную папку), тогда как .Net позволяет вам областям видимости с использованием ключевого слова namespace и игнорирует, где находится документ.

Файл JAR примерно аналогичен DLL в большинстве случаев. Это сжатый файл (вы можете открыть их с помощью 7zip), который содержит исходный код из других проектов, которые могут быть добавлены в зависимости от вашего приложения. Библиотеки обычно содержатся в JAR.

То, что нужно помнить о Java, — это очень структурное; ГДЕ файлы живут очень важно. Конечно, есть история, а затем то, что я написал, но я думаю, что это должно заставить вас начать.

7 cletus [2009-12-23 17:22:00]

Пакет очень похож на пространство имен .Net. Общее соглашение в Java заключается в использовании вашего обратного имени домена в качестве префикса пакета, поэтому, если ваша компания example.com, ваши пакеты, вероятно, будут:

Его можно разбить на несколько уровней, а не только на одно (имя проекта), но обычно этого достаточно.

Внутри структуры структуры проекта обычно делятся на логические области: контроллеры, модели, представления и т.д. Это зависит от типа проекта.

В Java есть две доминирующие системы построения: Ant и Maven.

Ant — это, в основном, язык сценариев, специфичный для домена, и довольно гибкий, но вы в конечном итоге пишете много деталей шаблонов (задачи сборки, развертывания, тестирования и т.д.). Это быстро и удобно.

Maven более современна и более совершенна и заслуживает внимания (imho). Maven отличается от Ant тем, что Maven заявляет, что этот проект является «проектом веб-приложения» (называемым архетипом). После того, как это объявлено, структура каталогов задается после указания вашей groupId (com.example) и artifactId (название проекта).

Таким образом вы получаете много вещей бесплатно. Настоящий бонус Maven заключается в том, что он управляет вашими зависимостями проекта для вас, поэтому с pom.xml(файл проекта Maven) и правильно настроенным Maven вы можете предоставить это кому-то другому (с исходным кодом), и они могут создавать, развертывать, тестировать и запускайте свой проект с автоматической загрузкой библиотек.

Ant получает что-то подобное с Ivy.

Вот некоторые заметки о пакетах Java, которые должны вас запустить:

Наилучшей практикой с именами пакетов Java является использование доменного имени организации в качестве начала пакета, но в обратном порядке, например. если ваша компания владеет доменом «bobswidgets.com», вы можете начать свой пакет с «com.bobswidgets».

Следующий уровень вниз часто будет уровнем приложения или библиотеки, поэтому, если это ваши библиотеки электронной коммерции, это может быть что-то вроде «com.bobswidgets.ecommerce».

Далее, чем это часто представляет собой архитектуру вашего приложения. Классы и интерфейсы, которые являются основными для проекта, находятся в «корне», например. com.bobswidgets.ecommerce.InvalidRequestException.

Использование пакетов для разделения функций далее является общим. обычно шаблон состоит в том, чтобы поместить интерфейсы и исключения в любой корень подразделения и реализацию в подпакеты, например.

Это позволяет легко вытащить классы и пакеты оплаты в свой собственный проект.

Некоторые другие примечания:

Java-пакеты тесно связаны с структурой каталогов. Таким образом, в рамках проекта класс с пакетом com.example.MyClass всегда будет в com/example/MyClass.java. Это связано с тем, что когда он упакован в Jar, файл класса определенно будет в com/example/MyClass.class.

Java-пакеты слабо связаны с проектами. Вполне вероятно, что проекты будут иметь свои собственные имена пакетов, например. com.bobswidgets.ecommerce для электронной коммерции, com.bobswidgets.intranet для проекта интрасети.

Файлы Jar будут содержать файлы классов, которые являются результатом компиляции вашего .java-кода в байт-коды. Это всего лишь zip файлы с расширением .jar. Корень файла Jar является корнем иерархии пространства имен, например. com.bobswidgets.ecommerce будет/com/bobswidgets/ecommerce/в файле Jar. Файлы Jar также могут использовать ресурсы контейнера, например. файлы свойств и т.д.

Пакет представляет собой группировку исходных файлов, которая позволяет им видеть индивидуальные методы и переменные между отдельными частями, чтобы эта группа классов могла обращаться к вещам друг с другом, которые не могут выполнять другие классы.

Ожидается, что все классы java имеют пакет, который используется для устранения их неоднозначности. Поэтому, если вы открываете файл jar в своем проекте, например spring, каждый пакет начинается с org.springframework. Погрузчики классов не знают о имени jarfile, они используют только пакет.

Существует обычная практика нарушения вещей по типу объекта или функции, не все согласны с этим. Как и Cletus, размещенные здесь, существует тенденция группировать веб-контроллеры, объекты домена, службы и объекты доступа к данным в свои собственные пакеты. Я думаю, что некоторые люди, работающие с управлением доменами, не считают, что это хорошо. Преимущество состоит в том, что обычно все в вашем пакете имеет одинаковые зависимости (контроллеры могут зависеть от сервисов и объектов домена, сервисов зависят от объектов домена и объектов доступа к данным и т.д.), Поэтому это может быть удобно.

Итак, в java у вас есть три разных типа access для функций-членов классов и переменных

общественности защищенный Пакет-частное и частные

Все классы в одном пакете могут видеть все остальные общедоступные, защищенные и связанные с упаковкой элементы.

Читать еще:  Java util concurrent locks

Пакеты не являются иерархическими в системе. Обычно они организованы иерархически, но, насколько это касается времени выполнения, com.example.widgets — совершенно другой пакет из com.example.widgets.cogs

Пакеты упорядочены в виде каталогов, что помогает упорядочивать вещи: ваша файловая структура всегда похожа на вашу структуру пакета.

Они планируют добавить модульную систему к Java в JDK7 (называемую Project Jigsaw), и существует существующая система модулей под названием OSGi. Эти модульные системы будут/могут дать вам гораздо больше гибкости и мощности, чем простая система пакетов.

Кроме того, имена пакетов обычно являются строчными.:)

Maven Project Structure Example

Posted by: Francisco Hernandez in Maven February 23rd, 2016 0 Views

In this example we are going to see maven project structure and how the projects are organized.

Maven is a build automation tool used mainly for java projects from apache.

We are going to see some examples of maven project structure.

For this example we use the following technologies:

  • MAC OSX
  • Eclipse Mars.1
  • Maven3
  • JDK 1.8.0_65 64bits

1. Introduction

Maven is an universal software project management, in order to get maven users familiar with maven projects, maven defines some conventions or directory layouts.

Through those directory layouts maven achieves an uniform way to organize projects and files inside of it. This a very good approach because you can work on several projects and you always will have the same project structure, so you will switch between projects and you don´t have to expend time in order to learn how the project is organized.

You can see a typical jar maven project structure here

You can see a typical war maven project structure here

2. Directory layout. Files

Maven defines some conventions in order to organize the normal files inside a project. In this directories you can put all application sources files.

The directories are the following

2.1 src/main/java

Inside this folder you can put all the application source files. Classes and packages for the main (real) artifact should be put in this folder.

All the content inside of this directory will be put in the classpath of the generated artifact. If the artifact is a jar file, all the classes and packages will be in the root folder of the generated jar , so it will be available by default on the runtime classpath.

If the artifact is a war , all the classes and packages will be put inside the WEB-INF/classes directory, so it will be available on the runtime classpath by default.

When the project is build or packaged all those classes and packages will be put in the target folder.

If you use eclipse as your IDE, this directory will be put inside the java build path automatically when you give the maven nature to the project.

2.2 src/test/java

Inside this folder you can put all the application test source files. Classes and packages for the test artifact should be put in this folder.

All the content inside of this directory will NOT be put in the classpath of the generated artifact.

When the project is build or packaged all those classes and packages will be put in the target folder.

When you run your test you muyst be awared that maven surefire plugin will run the classes from the target directory.

If you use eclipse as your IDE, this directory will be put inside the java build path automatically when you give the maven nature to the project.

2.3 src/it

Inside this folder you can put all the application integration test source files. Classes and packages for the integration test artifact should be put in this folder.

All the content inside of this directory will NOT be put in the classpath of the generated artifact.

When the project is build or packaged all those classes and packages will be put in the target folder.

When you run your integration test you must be awared that the implicated plugin will run the classes from the target directory.

If you use eclipse as your IDE, this directory will be put inside the java build path automatically when you give the maven nature to the project.

3. Directory layout. Resources

Maven defines some conventions in order to organize the normal files inside a project. In this diectories you can put all application sources files.

The directories are the following

  • src/main/resources
  • src/test/resources
  • src/main/filters
  • src/test/filters

3.1 src/main/resources

Inside this folder you can put all the application resource files. Resources for the main (real) artifact should be put in this folder.

All the content inside of this directory will be put in the classpath of the generated artifact. If the artifact is a jar file, all the resources will be in the root folder of the generated jar , so it will be available by default on the runtime classpath.

If the artifact is a war , all resources will be put inside the WEB-INF/classes directory, so it will be available on the runtime classpath by default.

When the project is build or packaged all those resources will be put in the target folder.

If you use eclipse as your IDE, this directory will be put inside the java build path automatically when you give the maven nature to the project.

3.2 src/test/resources

Inside this folder you can put all the application test resource files. Resources for the test artifact should be put in this folder.

All the content inside of this directory will NOT be put in the classpath of the generated artifact.

When the project is build or packaged all those test resources will be put in the target folder.

When you run your test you must be awared that maven surefire plugin will use resources from the target directory.

If you use eclipse as your IDE, this directory will be put inside the java build path automatically when you give the maven nature to the project.

3.3 src/main/filters

Inside this folder you can put all the application filters files. Filters for the artifact should be put in this folder.

3.4 src/test/filters

Inside this folder you can put all the application test filters files. Filters for the test artifact should be put in this folder.

4. Directory layout. Misc

Maven defines some conventions for several purposes, like

  • src/assembly
  • LICENSE.txt: This file represents the project license file.
  • NOTICE.txt: This file are notes, notices and attributions for the project, as third party libraries mentions, licenses, etc…
  • README.txt: Project readme file.

4.1 src/assembly

Inside this folder you can put all the maven assembly plugin file. This files will be used by the maven assembly plugin.

  • You can see an example of the maven assembly plugin here.

5. Directory layout. Webapp

Maven project structure defines a folder in order to store all resources and files needed by a web application.

Inside this folder you can put all the required files for a web application like jsp files, js files, html files, css files, template files, reports files, WEB-INF files (like web.xml), META-INF files, etc…

All the content inside of this directory will be put in the classpath of the generated war artifact, all resources will be put inside the WEB-INF directory, so it will be available on the runtime classpath by default.

When the project is build or packaged all those resources will be put in the target/WEB-INF folder.

6. Directory layout. Target

The target folder is the maven default output folder. When a project is build or packaged, all the content of the sources, resources and web files will be put inside of it, it will be used for construct the artifacts and for run tests.

You can delete all the target folder content with mvn clean command.

7. Directory layout. Pom file

The pom (Project Object Model) file is a maven special file that describe how the project have to be build and from when maven should download artifacts/dependencies, what are those dependecies and so many more things.

This file is placed on the root project folder.

8. Directory layout. Personal files

You can put more folders inside of the project structure, but in those cases you have to instruct maven on the build tag of the pom file in order to manage those folder.

9. Conclusions

As you have seem, maven defined a good and a clear project structure in order to familiar users across projects. This is a very important point if you planned to work in several projects, avoiding the need to learn how different project are structured.

Java project package structure guidelines

The package is a fundamental concept in Java and one of the first things you stumble upon when starting programming in the language. As a beginner you probably don’t pay much attention to the structure of packages, but as you become a more experienced and mature software developer, you start to think what can be done to improve their clarity.

There are a few major options to consider and picking the right one might not be an obvious choice. This article should give you an overview of commonly selected strategies for structuring Java packages.

So let’s get down to it.

Why do we use packages?

From the language perspective, packages in Java provide two important features, which are utilized by the compiler. The most apparent one is the namespace definition for classes. Several classes with an exactly the same name can be used in a single project as long as they belong to different packages which distinguish one class from another.

Читать еще:  Восстановить виндовс 7 без диска на компьютере

If you can’t imagine how the language would look like if there were no packages, just have a look at the modularization strategies in the JavaScript world. Before ES2015 there were no official standards and a naming collision wasn’t a rare case.

The second thing is that packages allow defining access modifiers for particular members of a project. Accessibility of a class, an interface, or one of their members like fields and methods can be limited or completely prohibited for members of different packages.

Both features are first of all used by the compile to enforce language rules. For clean coders and software craftsmen the primary property of a package is possibility to have a meaningful name which describes its purpose and the reason for existence. For compilers, it’s just a random string of chars while for us, it’s another way to express our intention.

What is a package?

In the official Java tutorial we can find the definition which begins like this:

A package is a namespace that organizes a set of related classes and interfaces. Conceptually you can think of packages as being similar to different folders on your computer. You might keep HTML pages in one folder, images in another, and scripts or applications in yet another. (…)

The first sentence emphasizes the organization purpose of packages. The definition doesn’t explain, though, what kind of a relationship classes and interfaces should have to consider them as a single group. The question is open to all software developers.

Recently, Kent Beck wrote a general piece of advice which also applies to the topic discussed in this post:

if you’re ever stuck wondering what to clean up, move similar elements closer together and move different elements further apart

Yet, just like the word “related” in the aforementioned package definition, the word “similar” can have completely different meaning to different people. In the remaining part of the article we will consider possible options in the context of package organization.

Package by layer

Probably the most commonly recognized similarity between project classes is their responsibility. The approach which uses this property for organization is known as package by layer or horizontal slice and in practice looks more or less like on the picture below.

If you didn’t have a chance to work on a project with such structure, you could come across it in some framework tutorials. For instance, Play framework recommended such approach up to version 2.2. The tutorial of Angular.js initially suggested keeping things together based on their responsibilities. The fact they changed their opinions about the subject and updated tutorials should probably excite you to think what was the reason. But before we judge the solution, let’s look at its strengths and weaknesses.

Considering layered architecture as the most widely used, it shouldn’t be surprising that developers aim to reflect the chosen architecture in the package structure. The long prevalence of the approach influences the decision to apply the structure in new projects because it’s easier for team’s newcomers to adopt in the environment which is familiar to them.

Finding a right place for a new class in such application is actually a no-brainer operation. The structure is created at the beginning of development and kept untouched during the entire project’s existence. The simplicity allows keeping the project in order even by less experienced developers as the structure is easily understandable.

Some people say having all model classes in one place makes them easier to reuse because they can simply be copied with the whole package to another project. But is it really the case? The shape of a particular domain model is usually valid only in a bounded context within a project. For instance, the product class will have different properties in a shopping application than in an application which manages orders from manufactures. And even if you would like to use the same classes, it would be reasonable to extract them to a separate jar marked as a dependency in each application. Duplication of code leads to bugs even if it exists in separate but related projects, hence we should avoid copy-pasting.

A major disadvantage of the package by layer approach is overuse of the public access modifier. Modern IDEs create classes and methods with the public modifier by default without forcing a developer to consider a better fitting option. In fact, in the layered package organization there is no other choice. Exposing a repository just to a single service class requires the repository to be public. As a side effect the repository is accessible to all other classes in the project, even from layers which shouldn’t directly communicate with it. Such approach encourages creating an unmaintainable spaghetti code and results in high coupling between packages.

While jumping between connected classes in IDEs is nowadays rather simple no matter where they are located, adding a new set of classes for a new feature required more attention. It is also harder to assess the complexity of a feature just by looking at code as classes are spread across multiple directories.

At the beginning, we said that the name of a package should provide additional details about its content. In the package by layer approach, all packages describe the architecture of the solution, but separately they don’t give any useful information. Actually, in many cases, they duplicate information present in class names of its members.

Package by feature

On the other side of the coin you can structure your classes around features or domain models. You might have heard of this approach as the vertical slice organization. If you work only with the horizontal slice, at the first glance it might look a little bit messy, but in the end it’s just a question of mindset. The following picture represents the same classes as in the previous paragraph, but with a different package layout.

You probably don’t keep all your left shoes in one place and all right in another just because they fit the same feet. You keep your shoes in pairs because that’s the way you use them. By the same token, you can look at the classes in your project. The core idea of the vertical slice is to place all classes which build a particular feature in a single package. By following this rule, in return you will receive some benefits, but also face some negative consequences.

When all feature classes are in a single package, the public access modifier is much more expressive as it allows describing what part of a feature should be accessible by other parts of the application. Within a package you should favor usage of the package-private modifier to improve modularization. It’s a good idea to modify default templates in your IDE to avoid creating public classes and methods. Making something public should be a conscious decision. Fewer connections between classes from different packages will lead to cleaner and a more maintainable code base.

In the horizontal slice, packages have the same set of names in each project while in the vertical slice approach packages have much more meaningful names, which describe their functional purpose. Just by looking at project structure, you can probably guess what users can do with the application. The approach also expresses hierarchical connections between features. Aggregate roots of the domain can be easily identified as they exist at the lowest level of the package tree. Package structure documents the application.

Grouping classes based on features results in smaller and easier to navigate packages. In horizontal approach each new feature increases the total number of classes in layer packages and makes them harder to browse. Finding interesting elements on the long list of classes becomes an inefficient activity. By contrast, a package focused on a feature grows only if that feature is extended. A new feature receives its own package in an appropriate node of the tree.

It’s also worth to mention the flexibility of the vertical slice packaging. With the growing popularity of the microservice architecture, having a monolith application which is already sliced by features is definitely much easier to convert into separate services than a project which organizes classes by layers. Adopting the package by feature approach prepares your application for scalable growth.

Along with the development of the project, the structure of packages requires more care. It’s important to understand that the package tree evolves over time as the application gets more complex. From time to time you will have to stop for a while and consider moving a package to a different node or to split it into smaller ones. The clarity of the structure doesn’t come for free. The team is responsible for keeping it a good shape with alignment to knowledge about the domain.

Understanding the domain is the key element of clean project structure. Choosing a right place for a new feature may be problematic, especially for team newcomers as it requires knowledge about the business behind your application. Some people may consider this as an advantage as the approach encourages sharing knowledge among team members. Introduction of a new developer to the project is slightly more time consuming, yet it might be seen as an investment.

Mixed approach

You may think that no extremity is good. Can’t we just take what is best from both approaches and create a new quality that is intermediate between two extremes? There are two possible combinations. Either the first level of packages is divided by a layer and features are their children or features build the top level and layers are they sub nodes.

Читать еще:  Javascript create table

The first option is something that you might have encountered as it is a common solution for packages which grow to large sizes. It increases clarity of the structure, but unfortunately all disadvantages of the package by layer approach apply just like before. The greatest problem is that the public modifier must still be used almost everywhere in order to connect your classes and interfaces.

With the other option we should ask a question whether the solution really makes much sense. The package by feature approach supports organization of layers, but it does it on the class level and not using packages. By introducing additional levels of packages we lose the ability to leverage default access modifier. We also don’t gain much simplicity in the structure. If a feature package grows to unmanageable size, it’s probably better to extract a sub feature.

Summary

Picking the package structure is one of the first choices you have to make when starting a new project. The decision has an impact on future maintainability of the whole solution.

Although in the theory you can change the approach at any point in time, usually the overall cost of such shift simply prevents it from happening. That is why it’s particularly important to spend a few minutes with your whole team at the beginning and compare possible options. Once you make a choice all you have to do is to make sure that every developer follows the same strategy. It might be harder for the package by feature approach, especially if done for the first time, but the list of benefits is definitely worth the effort.

If you have any experience with the vertical slice and would like to add your two cents to the topic, don’t hesitate to share your thoughts in the comments. Also please consider sharing the post with your colleagues. It would be great to read the outcome of your discussions and feelings about the approach.

Основы программирования на Java

Структура программы

Основным строительным блоком программа на языке Java являются инструкции (statement). Каждая инструкция выполняет некоторое действие, например, вызовы методов, объявление переменных и присвоение им значений. После завершения инструкции в Java ставится точка с запятой (;). Данный знак указывает компилятору на конец инструкции. Например:

Данная строка представляет вызов метода System.out.println , который выводит на консоль строку «Hello Java!». В данном случае вызов метода является инструкцией и поэтому завершается точкой с запятой.

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

В этом блоке кода две инструкции, которые выводят на консоль определенную строку.

Выполнение программы. Метод main

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

То есть основу нашей программы составляет класс Program. При определении класса вначале идет модификатор доступа public , который указывает, что данный класс будет доступен всем, то есть мы сможем его запустить из командной строки. Далее идет ключевое слово class , а затем название класса. После названия класса идет блок кода, в котором расположено содержимое класса.

Входной точкой в программу на языке Java является функция main , которая определена в классе Program. Именно с нее начинается выполнение программы. Он обязательно должен присутствовать в программе. При этом его заголовок может быть только таким:

При запуске приложения виртуальная машина Java ищет в главном классе программы метод main с подобным заголовком, и после его обнаружения запускает его.

Вначале заголовка метода идет модификатор public , который указывает, что метод будет доступен извне. Слово static указывает, что метод main — статический, а слово void — что он не возвращает никакого значения. Далее в скобках у нас идут параметры метода — String args[] — это массив args, который хранит значения типа String, то есть строки. При запуске программы через этот массив мы можем передать в программу различные данные.

После заголовка метода идет его блок, который содержит набор выполняемых инструкций.

Комментарии

Код программы может содержать комментарии. Комментарии позволяют понять смыл программы, что делают те или иные ее части. При компиляции комментарии игнорируются и не оказывают никакого влияние на работу приложения и на его размер.

В Java есть два типа комментариев: однострочный и многострочный. Однострочный комментарий размещается на одной строке после двойного слеша //. А многострочный комментарий заключается между символами /* текст комментария */ . Он может размещаться на нескольких строках. Например:

Многоуровневая архитектура в проекте на Java (Часть 1)

В настоящее время в разработке ПО достаточно часто применяется многоуровневая архитектура или многослойная архитектура (n-tier architecture), в рамках которой компоненты проекта разделяются на уровни (или слои). Классическое приложение с многоуровневой архитектурой, чаще всего, состоит из 3 или 4 уровней, хотя их может быть и больше, учитывая возможность разделения некоторых уровней на подуровни. Одним из примеров многоуровневой архитектуры является предметно-ориентированное проектирование (Domain-driven Design, DDD), где основное внимание сконцентрировано на предметном уровне.

В проектах с многоуровневой архитектурой можно выделить четыре уровня (или слоя):

  • Слой представления, с которым взаимодействует пользователь или клиентский сервис. Реализацией слоя представления может быть, например, графический пользовательский интерфейс или веб-страница.
  • Сервисный слой, реализующий взаимодействие между слоями представления и бизнес-логики. Примерами реализаций сервисного слоя являются контроллеры, веб-сервисы и слушатели очередей сообщений.
  • Слой бизнес-логики, в котором реализуется основная логика проекта. Компоненты, реализующие бизнес-логику, обрабатывают запросы, поступающие от компонентов сервисного слоя, а так же используют компоненты слоя доступа к данным для обращения к источникам данных.
  • Слой доступа к данным — набор компонентов для доступа к хранимым данным. В качестве источников данных могут выступать различного рода базы данных, SOAP и REST-сервисы, файлы на файловой системе и т.д.

Направление зависимостей между слоями идёт от слоя представления к слою доступа к данным. В идеальной ситуации каждый слой зависит только от следующего слоя: слой представления зависит от сервисного слоя (например, представление зависит от контроллера), сервисный слой зависит от слоя бизнес-логики (например, контроллер зависит от бизнес-сервиса), а слой бизнес-логики — от слоя доступа к данным (например, бизнес-сервис зависит от репозитория). При этом компоненты бизнес-слоя могут зависеть от других компонентов бизнес-слоя, тогда как в других слоях аналогичные зависимости нежелательны (например, зависимость одного репозитория от другого). Так же нежелательны зависимости в обратном направлении (бизнес-слой не должен зависеть от сервисного слоя) и зависимости между слоями, не являющимися соседними (сервисный слой не должен зависеть от слоя доступа к данным, например).

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

Допустим, у нас есть код, реализующий бизнес-логику приложения, который находится в контроллере. Что если нам требуется разработать SOAP-сервис, реализующий ту же функциональность? Мы можем скопировать существующий код в SOAP-сервис и внести в него изменения по мере необходимости. Будет ли ли такой подход работать? Да! Вызовет ли такой подход проблемы? Тоже да! В процессе жизненного цикла проекта требования к нему имеют свойство меняться, что ведёт к неизбежным изменениям и в коде. Но при таком подходе нам придётся изменить код и в контроллере, и в SOAP-сервисе, а также внести изменения в их тесты (вы же тестируете свой код?). Но граздо правильнее будет вынести общий код, реализующий бизнес-логику, в компонент слоя бизнес-логики. В этом случае в контроллере и SOAP-сервисе останется код, преобразующий запрос к общему виду, понятному компоненту бизнес-логики.

Очевидным фактом является то, что бизнес-логика — самая важная составляющая вашего проекта. И именно с проработки компонентов слоя бизнес-логики должна начинаться разработка проекта.

К слову сказать, очень хорошей практикой является применение UML, в данном конкретном случае — диаграммы классов. Из собственной практики помню случай, когда я решил для почти готового проекта составить диаграмму классов, результатом чего стал рефакторинг, уменьшивший количество кода примерно на 20%. Составление диаграммы классов на ранних этапах разработки позволяет уменьшить дублирование кода, сделать структуру классов и зависимости между ними более понятными.

В так полюбившейся мне книге Роберта Марина «Чистая архитектура» автор пропагандирует идею независимости (или минимизации зависимости) архитектуры приложения от внешних факторов: фреймворков, баз данных и прочих сторонних зависимостей. Это говорит не об отказе от использования этих зависимостей (вы же не будете разрабатывать собственный механизм трансляции HTTP-вызовов или хранения данных?), а о минимизации их влияния на архитектуру вашего проекта.

Разработка бизнес-логики

Давайте возьмём в качестве примера разработку блокнота, который пользователь может использовать для работы с заметками. Заметьте, я не указал, что это будет онлайн-сервис или настольное приложение. Для начала определимся с набором типов (классов и интерфейсов), которые нам понадобятся для нашего проекта. Класс-сущность, описывающий заметку — Note, компонент бизнес-логики, реализующий работу с заметками — NoteService, ещё нам потребуется компонент слоя доступа к данным — NoteRepository. Простая реализация NoteService — SimpleNoteService, использует NoteRepository для доступа к источнику данных. Диаграмма классов, описывающая текущую архитектуру, будет достаточно простая:

Теперь можно описать эти типы в коде, написать тесты для SimpleNoteService и реализовать этот класс.

0 0 голоса
Рейтинг статьи
Ссылка на основную публикацию
ВсеИнструменты 220 Вольт