DDD vs Clean Code - function parameter number - java

I'm trying to get my coding a little more into DDD aproach. Suppose I have a method, like a static constructor:
public class Enrollment {
private final User user;
private final EnrollmentStatus status;
private final ClassesParams classesParams;
public static Enrollment of(User user, EnrollmentStatus status, ClassesParams classesParams) {
// implementation goes here
}
}
Robert Martin says in his Clean Code book, that the less parameters function has the better, and 3 should be used in some exceptional cases. And I think it's perfectly reasonable in the above case to have just 1 parameter, because all these arguments are actually parts of some input data to create new Enrollment:
public static Enrollment of(NewEnrollmentRequest request) { // NewEnrollmentRequest would contain user, status and classesParams
// implementation goes here
}
The problem now is that NewEnrollmentRequest would be in fact some form of DTO, which is not part of the domain. And I guess I'm not supposed to put NewEnrollmentRequest outside the domain, because domain shouldn't depend on outside layers.
So the question is, how can I keep it both clean and DDD-style? Is it fine to have the constructor with all the fields - but what if I have not 3 but 6-7 fields? Or maybe the request class is part of the domain in this case? I feel there is some sort of tradeoff here, but I can't find it, or I'm just tackling the problem wrongly.

So the question is, how can I keep it both clean and DDD-style?
Create your domain interfaces in a way that conforms to the clean style
Including value objects with fluent interfaces that make clear to the programmer the semantics of the information that is being passed to the domain model. (In other words, having representations of documents, like an enrollment form, in your domain model is normal).
expect that you'll need to have a parser that copies information from the representations of the presentation layer to the representations of the domain model. Sometimes you will be able to leverage general purpose code that copies information from one information to another (like web server libraries that translate application/x-www-form-urlencoded byte sequences into sequences of key value pairs, or takes an application/json byte sequence and initializes your value object), but you should recognize that as a happy accident that may not hold for the life of the project.
Don't sweat the argument count constraint too much - Robert Martin's 2009 essay doesn't support his conclusion very well.
Instead, pay attention to the communication of argument semantics, and the fact that the arguments (a) have different lifespans and (b) those lifespans tend to "clump" into groups that are candidates for re-use.

Related

Java getter/setter naming convention when also using records [duplicate]

Java 14 introduced records feature. Record creates getter with the same name as field, so one would write print(person.name()) for example. But old Java bean convention dictates that one should name this method as getName().
Using both styles in the same code base does not look very nice. Migrating everything to records is not possible, as they are too limited to replace all use-cases.
Is there any official or semi-official guidelines how to name getters and setters after Java 14 in new code?
Quote from JEP 359:
It is not a goal to declare "war on boilerplate"; in particular, it is not a goal to address the problems of mutable classes using the JavaBean naming conventions.
My understanding, based on the same document is that records are transparent holders for shallowly immutable data.
That being said:
Records are not the place to look for getters/setters syntactical sugar, as they are not meant to replace JavaBeans.
I strongly agree with you that JavaBeans are too verbose. Maybe an additional feature (called beans instead of records) could be implemented - very similar behavior with the records feature but that would permit mutability. In that case, records and beans would not be mutually exclusive.
As it has been mentioned, records are in preview mode. Let's see what the feedback from community would be.
All in all, IMHO they are a step forward... I wrote this example set where you can see a code reduction to ~15% LOC from standard JavaBeans.
Also, note that records behave like normal classes: they can be declared top level or nested, they can be generic, they can implement interfaces (from the same document). You can actually partly simulate JavaBeans (only getters would make sense, though) by extracting an interface containing the getters - however that would be a lot of work and not a really clean solution...
So, based on the logic above, to address your question, no - I didn't see any (semi)official guideline for getters and setters and I don't think that there is a motivation for it right now because, again, records are not a replacement for JavaBeans...
The record spec is now "final" as of Java 17 and this naming convention discrepancy has unfortunately not been addressed. I stumbled upon it when attempting to leverage Records as shallow holder classes to implement interfaces part of an existing domain model.
Whilst this isn't as neat a solution as I'd like, Records can have methods, so you could add "legacy" getters to your record, as in the following (contrived but simple) example.
public interface Nameable {
public String getName();
}
public record Person(String name) implements Nameable {
public String getName() {
return name; // or return name();
}
}
At least this allows client code to continue to use that tried and tested (over 20 years old) convention, which - let's face it - is used far more than in pure JavaBeans context.
You could say that the language designers have lived up to their remit of "not declaring war on boilerplate"
I stumbled up this when researching naming conventions for my project. Looking at the "recent" additions to the std lib (e.g. Path, FileSystem, HttpRequest, ...) the only more-or-less "pattern" I could detect was that .prop() implies direct, unmodified access to the field value, and thus existance of the field with that very type.
Whereas "getXXX" conveys that you cannot/should not assume the existence of a field. This property might be calculated, direct field access or read-only wrapped (e.g. List.copyOf) or converted.
So my conclusion is: if you want to communicate "structure" or enforce the precence of fields use .prop(). In all other cases stick to getXXX as it is more flexible (implementers can be entity classes, records or service classes.
Btw: I am aware that there are big offenders to this logic even in the jdk. e.g. BigDecimal that's why I focused on more recent additions.
In Java records, object fields must be private and final.
So there is just one kind of getter and one kind of setter possible.
In Java classes, object fields may be private or public.
In the latter type of field, one can get or set them simply by adding a period and the field name, e.g.
Employee emp = new Employee(); // Nullary constructor
emp.name = "John Schmidt"; // Setter
. . .
. . .
if (emp.name != "Buddy") // Getter
{
emp.bonus = 100.00;
}
Non-private fields are used a lot in Android apps to save memory and time extracting data. But there's no reason not to use them in Java where it's safe to do so.
Now, if you change away from the usual way in Java classes to something like that used in record types, e.g.
String name = emp.name(); // New getter convention for private field
you have a serious risk of confusion by code readers who might misinterpret this as a non-private object field.
And if you change the record getter to what is used in Java objects, i.e.
obj.getField()
then there is a risk of confusion by coder reviewers and possibly a compiler may treat it as a Java object, depending on execution decision criteria.
In short, it's a different type of object to the normal Java class or enum. Its accessors indicate this new type unambiguously.
That's how I see it anyhow.
Maybe someone on the Java development committee may be able to enlighten us further.

Passing many variables to a class (swing components) [duplicate]

I have just started to learn Java and is curious is it any good practice in Java for good object decomposition? Let me describe a problem. In big software project it's always a big classes like 'core' or 'ui' that tends to have a lot of methods and are intended as a mediators between smaller classes. For example, if user clicks a button on some window, this window's class sends a message to 'ui' class. This 'ui' class catches this message and acts accordingly by doing something with application user interface ( via calling method of one of it's member objects ) or by posting message to application 'core' if it's something like 'exit application' or 'start network connection'.
Such objects is very hard to break apart since they are a mere mediators between a lots of small application objects. But having a classes in application with hundreds and thousands of methods is not very handy, event if such methods are trivial task delegation from one object to another. C# solves such problem by allowing to break class implementation into multiple source files: you can divide god object any way you choose, and it will work.
Any practices by dividing such objects in Java?
One way to begin breaking such a large object apart is to first find a good subset of fields or properties managed by the large object that are related to each other and that don't interact with other fields or properties of the object. Then, create a new, smaller object using only those fields. That is, move all logic from the large class to the new smaller class. In the original large class, create a delegation method that simply passes the request along. This is a good first step that only involves changing the big object. It doesn't reduce the number of methods, but it can greatly reduce the amount of logic needed in the large class.
After a few rounds of doing this, you can begin to remove some of the delegation by pointing other objects directly at the newer, smaller objects, rather than going through the previously-huge object that was in the middle of everything.
See Wikipedia's Delegation pattern discussion for example.
As a simple example, if you have a personnel object to represent staff at a company, then you could create a payroll object to keep track of payroll-related values, a ratings object to keep track of employee ratings, an awards object to keep track of awards that the person has won, and so on.
To wit, if you started out with one big class containing the following methods, each containing business logic, among many other methods:
...
public boolean isManagement() { ... }
public boolean isExecutive() { ... }
public int getYearsOfService() { ... }
public Date getHireDate() { ... }
public int getDepartment() { ... }
public BigDecimal getBasePay() { ... }
public BigDecimal getStockShares() { ... }
public boolean hasStockSharePlan() { ... }
...
then this big object could, in its constructor, create a newly created object StaffType and a newly created object PayInformation and a newly created object StaffInformation, and initially these methods in the big object would look like:
// Newly added variables, initialized in the constructor (or as appropriate)
private final StaffType staffType;
private final StaffInformation staffInformation;
private final PayInformation payInformation;
...
public boolean isManagement() { return staffType.isManagement(); }
public boolean isExecutive() { return staffType.isExecutive(); }
public int getYearsOfService() { return staffInformation.getYearsOfService(); }
public Date getHireDate() { return staffInformation.getHireDate(); }
public int getDepartment() { return staffInformation.getDepartment(); }
public BigDecimal getBasePay() { return payInformation.getBasePay(); }
public BigDecimal getStockShares() { return payInformation.getStockShares(); }
public boolean hasStockSharePlan() { return payInformation.hasStockSharePlan(); }
...
where the full logic that used to be in the big object has been moved to these three new smaller objects. With this change, you can break the big object into smaller parts without having to touch anything that makes use of the big object. However, as you do this over time, you'll find that some clients of the big object may only need access to one of the divisible components. For these clients, instead of them using the big object and delegating to the specific object, they can make direct use of the small object. But even if this refactoring never occurs, you've improved things by separating the business logic of unrelated items into different classes.
The next logical step may be to change the BigClass into a java package. Next create new objects for each group of related functionality (noting in each class that the object is part of the new package).
The benefits of doing this are dependency reduction and performance.
No need to import the entire
package/BigClass just to get a few
methods.
Code changes to related
functionality don't require a
recompile/redeploy of the entire
package/BigClass.
Less memory used
for allocating/deallocating objects,
since you are using smaller classes.
I've seen some cases where this is solved by inheritance: let's say class Big takes care of 5 different things, and (for various reasons) they all have to be in the same class. So you pick an arbitrary inheritance order, and define:
BigPart1 // all methods dealing with topic #1
BigPart2 extends BigPart1 // all methods dealing with topic #2
...
Big extends BigPart4 // all methods dealing with the last topic.
If you can really layer things up, so that the breakage makes sense (Part2 actually uses stuff from Part1, but not vice versa, etc.) then maybe it makes some sense.
The place where I've seen this is in WebWorks, where a single class had tons of getter/setter methods -- the setters used for dependency injection (e.g., URL args passed to the object upon execution) and the getters for making values accessible to various page templates (I think it was JSPs).
So, the breakdown grouped stuff logically, e.g., assuming the class was called MyAction, there was MyActionBasicArgs (fields and setters for basic CGI arguments), extended by MyActionAdvancedArgs (advanced-option args), extended by MyActionExposedValues (getters), extended by MyActionDependencies (setters used by Spring dependency injection, non-CGI args), extended by MyAction (which contained the actual execute() method).
Because of the way dependency injection in WebWorks works (or at least, used to work, back then), it had to be one huge class, so breaking it down this way made things more maintainable. But first, please, please, see if you can simply avoid having a single huge class; think carefully about your design.
Yes, C# provides partial classes. I assume this is what you are referring to when you say:
C# solves such problem by allowing to break class implementation into multiple source
files: you can divide god object any way you choose, and it will work.
This does help make huge classes more manageable. However, I find partial classes best used when one needs to extend code created by a code generator. When a class is as large as you're talking about, it can almost always be divided into smaller classes by proper object oriented design. Using a partial class sidesteps the more correct object oriented design, which is sometimes OK as the end goal is stable, reliable, maintainable code, and not a textbook example of OO code. However, many times, putting the code of a large object into a large number of smaller partial class instances of the same class is not the ideal solution.
If you can possibly find subsets of the properties of the "god" object that do not interact with one another, then each one of those sets would logically make a good candidate for a new object type. However, if all properties of this "god" object depend on one another, then there is not much you can do to decompose the object.
I don't know why you would ever have such a large class.
I suppose if you were using a gui builder code generation and being lazy about it, you might end up in such a situation, but codegen usually ends up nasty unless you take control yourself.
Splitting a single class arbitrarily is a terrible solution to a terrible manufactured problem. (Code reuse, for one thing will become virtually impossible)
If you have to use a GUI builder, have it build smaller components, then use the small components to build up a bigger GUI. Each component should do exactly one job and do it well.
Try not to EVER edit generated code if you can avoid it. Putting business logic into a genned "frame" is just a horrid design pattern. Most code generators aren't very helpful with this, so try to just make a single, minimal edit to get at what you need from external classes (think MVC where the genned code is your View and the code you edit should be in your Model and Controller).
Sometimes you can just expose the getComponents method from the Frame object, get all the components out by iterating through the containers and then dynamically bind them to data and code (often binding to the name property works well), I've been able to safely use form editors this way, and all the binding code tends to be very easily abstracted and reused.
If you're not talking about generated code--Well in your "God" class, does it do exactly one small job and do it well? If not, pull out a "Job", put it in it's own class, and delegate to it.
Is your GOD class fully factored? When I've seen huge classes like this, I've usually seen a lot of copy/paste/edit lines. If there is enough of a similarity to copy and past and edit some section, then there is enough to factor these lines into a single chunk of code.
If your big class is a GUI class, consider decorators--reusable and moves stuff out of your main class. A double win.
I guess the answer to your question is that in Java we just use good OO to ensure that the problem doesn't arise in the first place (or we don't--Java's certainly not immune to the problems you are talking about any more than any other language)

Represent email, telephonenumber and id's as POJO's instead of Strings

I have a typical business web application where the domain contains entities like accounts and users. My backend is Java, so they're represented by POJO's. During an early iteration, every attribute of those POJO's were just strings. This made sense because the html input was a string, and the way the data is persisted in the DB is also similar to a string.
Recently, we've been working on validating this kind of input and I found it helps if I switch over to an object notation for this kind attributes. For example, a TelephoneNumber class consists of:
(int) country calling code
(string) rest of number
(static char) the character to prefix the country calling code (in our case this is a +)
(static pattern) regular expression to match if phonenumber is sensical
methods to compare and validate telephone numbers.
This class has advantages and disadvantages:
not good: Additional object creation and conversion between string/object
good: OOP and all logic regarding telephone numbers is bundled in one class (high cohesion),
good: whenever a telephone number is needed as an argument for a method or constructor, java's strict typing makes it very clear we're not just dealing with a random string.
Compare the possible confusing double strings:
public User(String name, String telephoneNumber)
vs the clean OOP way:
public User(String name, TelephoneNumber telephoneNumber)
I think in this case the advantages outweight the disadvantges. My concern is now for the following two attributes:
-id's (like b3e99627-9754-4276-a527-0e9fb49d15bb)
-e-mailadresses
This "objects" are really just a single string. It seems overkill to turn them into objects. Especially the user.getMail.getMailString() kind of methods really bother me because I know the mailString is the only attribute of mail. However, if I don't turn them into an object, I lose some of the advantages.
So my question is: How do you deal with this concepts in a web application? Are there best practices or other concerns to take into account?
If you use Strings for everything you are essentially giving up type safety, and you have to "type check" with validation in any class or method where the string is used. Inevitably this validation code gets duplicated and makes other classes bloated, confusing, and potentially inconsistent because the validation isn't the same in all places. You can never really be sure what the string holds, so debugging becomes more difficult, maintenance gets ugly, and ultimately it wastes lots of developer time. Given the power of modern processors, you shouldn't worry about the performance cost of using lots of objects because it's not worth sacrificing programmer productivity (in most cases).
One other thing that I have found is that string variables tend to be more easily abused by future programmers who need to make a "quick fix", so they'll set new values for convenience just where they need them, instead of extending a type and making it clear what's going on.
My recommendation is to use meaningful types everywhere possible.
Maximizing the benefit of typing leads to the idea of "tiny types", which you can read about here: http://darrenhobbs.com/2007/04/11/tiny-types/
Essentially it means you make classes to represent everything. In your example with the User class, that would mean you would also make a Name class to represent the name. Inside that class you might also have two more classes, FirstName and LastName. This adds clarity to your code, and maximizes the number of logical errors the compiler stops you from making. In most cases you would never use a first name where you want a last name and vice versa.
One of the biggest advantages of objects is the fact that they can have methods. For example, all your data object (phone number, address, email etc.) can implement the same interface IValidatable with validate method, which does the obvious. In this case, it would make sense to wrap email in an object as well, since we do want to validate emails. Regarding ID - assuming it's assigned internally by your app, you probably don't need to wrap it.

design issue about multiple parameters in a function

first of all I'm using java, even though it could be a question for any language
say I have a complicated system, now sometimes I end up building objects (setting all the parameters), then passing it over to a "target layer"(manager), which opens the object (getting the parameters).
if I were to pass all the parameters in one function, it would be considered poor design, because there's suppose to be a small amount of parameters per function
this seems like a waste, and in the past I also decided to set the parameters straight to the "target layer"
is there a design pattern that deals with this issue?
or something that books or experts in the subject recommend?
You might take a look on the Effective Java Book that will cover Design method signatures carefully
There will be three techniques for shortening long parameters :
break the method into multiple methods, each which require only a subset of the parameters
create helper classes to hold group of parameters (typically static member classes)
adapt the Builder
pattern from object construction to method invocation
Since you're asking the reference, I hope it can help solve your problem and don't forget to buy the book here
Since you were asking about book references, here is one from Clean Code, Chapter 3: Functions:
When a function seems to need more than two or three arguments, it is
likely that some of those arguments ought to be wrapped into a class
of their own. [...]
Reducing the number of arguments by creating objects out of them may
seem like cheating, but it’s not. When groups of variables are passed
together, [...] they are likely part
of a concept that deserves a name of its own.
So I guess it's ok to group a lot of method arguments into classes, as long as these classes represent some coherent concepts.
Personally if I do something like this, I like the wrapper class to be immutable and created by a dedicated builder. Which increases the number of additional classes twofold (wrapper and the builder), but enables the treatment of such a class as one atomic argument.
Extract the parameters into its own "Parameter-Object" (pattern name) and pass that object to the function.
If the Parameter-Object itself is complicated to construct, use the Builder-Pattern which simplifies the construction if the object can be constructed in different ways.
For Example:
function(param1, param2, param3, ...)
The parameters are then extracted into an Object:
class ParamObject {
param1;
param2;
param3;
}
with its corresponding setters and getters.
To construct the ParamObject use the BuilderPattern.
And finally, the invocation would look like this:
function(paramobject):
Inside the function the former arguments are then retreived from the object.
As siledh stated: Make sure to group arguments into classes that share a common concept, which means that it´s ok to create several classes out of the paramlist.
This sounds like a Data Transfer Object to me.
http://martinfowler.com/eaaCatalog/dataTransferObject.html

What is better: a single class with some attributes unfilled or multiple classes with attributes filled?

I have a class called Page in my program. It has 10 attributes, but at certain point, only 3 attributes are needed (RawPage) and in other point, all or almost all atributes are needed (ProcessedPage).
Is better I have only only one class with all attributes or split these class into two classes, one for every need?
EDIT: the processed atributes are new attributes in the Page, and not overwrites none.
I suspect someone will suggest using inheritance here, but I won't... it sounds like you logically create a "processed page" from a "raw page" (via processing) - so why not model it exactly like that?
class ProcessedPage
{
private final RawPage source;
// Other stuff - the results of the processing
}
class RawPage
{
// The data you need here
public ProcessedPage process(...)
}
When a class has information which is only sometimes valid / needed / relevant, it ends up being quite tricky to work with, especially as the system grows in size. With a more explicit model, you do potentially end up with some duplication, but your classes end up with a better defined purpose in life, rather than suffering from multiple personality disorder.
Note that I haven't made ProcessedPage a subclass of RawPage - because I don't imagine you'd normally want to treat a ProcessedPage as a RawPage, potentially reprocessing it. You may want to have a common interface that they both implement which doesn't include the process method, of course, but that's slightly different.
Answer is it depends. If the attributes are not related, can be categorized then it makes sense to split the current class into two.
However if the attributes have generalization - specialization relationship, then you can have one class as base and put rest of the attributes into a different classs which is the extension of the first class
Shash
Are they the exact same attributes? Sometimes you may have attributes in logical data scopes that have the same name but different contextual meaning. Is that the case for your scenario? If not then I would say go with one class, unless there is behavior associated with the RawPage that you want to encapsulate differently than that for your ProcessedPage.

Categories