Type pool or class of constants? - abap

What is the difference between Type-pool and creating a class for constants?
What is better?
My question is for a large group of constants and to be accessible to other groups.
Thank you
EDIT - Thank you for the answers and I will improve my question. I need something to store constants and I will use them on programs or other classes. Basically, I wanted to know if it is better to use a type-pool or a class with constants (only). I can have more than one class or type-pool.

The documentation mentions this:
Since it is possible to also define data types and constants in the public visibility section of global classes, type groups are obsolete and should no longer be created. Existing type groups can still be used.
A sensibly named interface with the constants you desire is the way to go. An additional benefit is that ABAP OO enforces some more rules.

Agree with #petul's answer, except for one detail: I'd recommend creating one enumeration-like class per logical group of constants, instead of collecting constants in interfaces.
Consider using the new enum language feature for specifying the constant values.
Interfaces can be accidentally "implemented", which doesn't make sense here. Classes can prevent this with final.
Making one class per logical group simplifies finding the constants with IDE features such as Ctrl+Shift+A search in the ABAP Development Tools. Constants that are randomly thrown together into interfaces are hard to find later on.
Classes allow adding enumeration-like helper methods like converters, existence checks, numbering all values.
Classes also allow adding unit tests, such as ensuring that the constant collection is still in sync with the fixed values of an underlying domain.

Related

Is defining all constants of a project in a single class acceptable?

There are some constants and enumerations in a project, and each one is used by some other classes.
As a design pattern, is it acceptable to create a class for constants and enumerations definition? Or is there a better way to define and use those constants?
It depends on the problem domain. Generally speaking it is rather standard practice to keep them in Java enumeration. The question is - how would you like to use those constants? I have such experience, that constants being hold in interfaces/enumerations are being duplicated and created over and over again due to lack of the knowledge of developers of past constants. In the result, there are many files as such Constants.java, BusinessLogic.java, AppConstants.java etc.. It causes big overwhelm over the purpose and then you don't know if the some constant, lets say APP_MODE should be used from Constants.java or AppConstants.java ?
One of the solutions is to keep those constants in one (or many?) properties files and inject thme using spring' #Value annotation.
You may group by using some prefixing, building groups separated by dot.
One of the advantages of the property files is that you keep one Java logic of using properties, but you still can provide property file (which may vary depending on application). A lot of flexibility, no redundancy.
Another solution is to create one Service to provide properties / constants from database. You can differentiate the values over diffrent environements, but that's another story.
If I were you I create a constant container class packege by package. Just span the logically coherent parts together. Otherwise you will increase the the coupling and dependency. And the most general constants (problem domain independent ones) take place in the utility package's constant container class.

When do I put logic in a class as opposed to passing the class into a utility class?

When I have a series of processes which are similar in nature but work on slightly different types of objects, do I unify the type of work in a single utility class, or do I put the functionality directly on each object that will need to utilized the functionality?
I'm not concerned about a specific case per-se, but I'm most curious about what factors go into this decision.
I think it depends on the class-ancestry of your objects, the real difference in logic between each object, and the future-possible-need to do this on some other kind of class.
It sounds to me like the utility class is a good way to go if the functionaliy you're applying to multiple classes is largely the same, and could be applied to future classes down the road.
if on the other hand the functionality is different enoguh that you'd end up with a big switch/case statement in your utility class to accomodate the differnet object types, you might want to implement it in the objects themselves.
You have two approaches to your problem: One is to use generic programming (horizontal polymorphism) or to attack it using a more traditional vertical hierarchy based implementation.
You decisions have to be based in the type of similarities that are shared among the various data types. In the case that we can define a complete and orthogonal contract that can be operated in any type then we can easily decide to use generics.
This for example is the case with List, Dictionary and all the class under the System.Collections.Generic name space that eventually replaced their corresponding non generic counterparts of the early versions of .NET.
In the other hand, again from the .NET world we can use as an example of a vertical hierarchy, the UserControl class than derives from ContainerControl and serves as the base for other controls specializing it behavior using its virtual methods...
In most of the cases though the design of your class hierarchy involves a lot of judgment calls that are not always to defined deterministically as they rely more on your experience and talent as a developer rather in a concrete model that can be applied across the board in every possible situation..

Is it bad form to have a a MiscUtilities class? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
Our company keeps a MiscUtilities class that consists solely of public static methods that do often unrelated tasks like converting dates from String to Calendar and writing ArrayLists to files. We refer to it in other classes and find it pretty convenient. However, I've seen that sort of Utilities class derided on TheDailyWTF. I'm just wondering if there's any actual downside to this sort of class, and what the alternatives are.
Rather than giving personal opinion, I will quote from an authoritative source in the Java community, and examples from 2 very reputable third party libraries.
A quote from Effective Java 2nd Edition, Item 4: Enforce noninstantiability with a private constructor:
Occasionally you'll want to write a class that is just a grouping of static methods and static fields. Such classes have acquired a bad reputation because some people abuse them to avoid thinking in terms of objects, but they do have valid uses. They can be used to group related methods on primitive values or arrays, in the manner of java.lang.Math or java.util.Arrays. They can also be used to group static methods, including factory methods, for objects that implements a particular interface, in the manner of java.util.Collections. Lastly, they can be used to group methods on a final class, instead of extending the class.
Java libraries has many examples of such utility classes.
Apache Commons Lang follows the TypeUtils naming convention
ArrayUtils, StringUtils, ObjectUtils, BooleanUtils, etc
Guava follows the Types naming convention
Objects, Strings, Throwables, Collections2, Iterators, Iterables, Lists, Maps, etc.
The package summary actually has a specific section on classes of static utility methods
Another entire package consists of nothing but utility classes for working with Java primitives, Ints, Floats, Booleans, etc.
Short summary
Prefer good OOP design, always
static utility classes have valid uses to group related methods on:
Primitives (since they're not objects)
Interfaces (since they can't have anything concrete of their own)
final classes (since they're not extensible)
Prefer good organization, always
Group utility methods for SomeType to SomeTypeUtils or SomeTypes
Avoid a single big utility class that contains various unrelated tasks on different types/concepts
Convenient, most likely.
Possible to grow into a scary, hard to maintain swiss-army-rocket-chainsaw-and-floor-polisher, also most likely.
I'd recommend separating the various tasks into separate classes, with some logical grouping besides "won't fit anywhere else".
The risk here is that the class becomes a tangled mess nobody fully comprehends and noone dares to touch - or replace. If you feel that is an acceptable risk and/or avoidable under your circumstances, nothing really prevents you from using it.
I've never been a fan of the MiscUtilities class. My biggest issue is that I never know what is in it. Anything filed under miscellaneous is not discoverable. Instead I prefer to use a common dll that I can import into my projects that contains well named, separated classes for different purposes. The difference is subtle, but I find that it makes my life a little easier.
For languages that support functions, this sort of class is undeniably bad form.
For languages that don't, this sort of class isn't, and is probably superior to extending other classes with random utility methods. The static utility methods, because they are in some other class, can only use the public interface of the objects they handle, which decreases the likelihood of certain kinds of bug. And this approach also avoids polluting public interfaces with a random grab bag of whatever people happened to find useful at the time.
There's a certain amount of personal style involved of course. I'm not a big believer in classes that provide everything under the sun (even C++'s std::string is a tad over-featured for my taste) and tend to prefer to have helper functionality as separate functions. Makes maintenance of the class easier, forces the public interface to be useful and efficient, and with duck-typing style mechanisms the external functions can be used across a wide range of types without having to duplicate source text or share base classes and so on. (The oft-derided algorithms in the C++ Standard Library are a good demonstration of this, imperfect and verbose as they are.)
That said, I've worked with many who complain about strings that don't know how to interpret themselves as filenames, or split themselves into words, or what have you, and so on. (I pick on strings because they seem to be the prime target for utility functions...) I happen to think there are unseen maintenance and reliability costs associated with having large classes like that, quite apart from the ugliness of having a nominally simple class that's actually a vast illogical mishmash of unrelated concerns whose grubby fingers end up poking themselves into every last corner -- because your self-tokenizing string needs some kind of container to put the tokens in, right?! -- but it's a balancing act, even if my wording suggests it's more clean-cut than that.
I'm not a big believer in the notion of "OO dogma", but perhaps the paranoid might see it at work here. There's no good reason that all functionality should be attached to a particular class, and many good reasons why it should not. But some languages still don't allow the creation of functions, which does nothing to remove the need for them and forces people to work around the restriction by creating classes that consist of nothing but static methods. This rather overloads the meaning of the class concept, to my mind, and not in any good way.
So that IS a good reason to rail against this practice, but it's pretty futile unless the language changes to accommodate what people need to do. And languages don't come without functions unless their designers have an axe to grind, or there are technical reasons for it, so I should think that change in either case is unlikely.
I suppose the executive summary is: no.
Well, bad utility classes are derided on TheDailyWTF :)
There's really nothing wrong with having a generic utilities class for miscellaneous static business functions. I mean, you could try to put it all into a more object oriented approach, but at what cost in time and effort to the business and for what trade-off of maintainability? If the latter outweighs the former, go for it.
One approach you may be able to take, depending on the language, etc., is to perhaps move some of the logic into extensions on existing objects. For example, extending the String class (thinking in C# here) with a method that tries to parse the string into a DateTime. An in-house library of extensions just enhances the language with your business' own little DSL(s).
The company I work for has a class like that in its repository. Personally I find it annoying because you have to be really intimate with the class in order to know what it's useful for. Consequently, I've found myself re-writing methods that this class already covers! Double annoying because I've now wasted my time.
I would prefer a more object oriented approach that would lead to expandability. Have a Utilities class for sure, but inside it put other classes that expand toward specific functionality. Like Utilities.XML, Utilities.DataFunctions, Utilities.WhateverYouWant. That way you can expand and eventually take your 20 function MiscUtilities class and turn it into a 500 function class library.
A Class Library like this could then be used by anyone, and added to by anyone (with privileges) in a logically organized way.
I think the wrong defect of such a class is that it break Separation of concerns principle. I usually create multiple "Helpers" class to contains widely used, public static methods, for example ArrayHelpers to writing ArrayLists to files, and DatesHelper to converting dates from String to Calendar.
Moreover, if the class does contain complicated methods, it's better to try to refactor them using more object-oriented tecnique.
You can always switch from your "Helpers" class to the use of various OO pattern, leaving your old static methods to function as a Facade.
Yuo'll find great benefits everytime you'll be able to do so.
I keep a separate misc class for each project, and copy/paste code from other projects as needed. Perhaps not the best approach, but I prefer to avoid cross-project dependencies.
Examples of things in my helper class:
hex2, hex4, and hex8 (accept integer parameters, except hex8 which has integer and uinteger variations; all versions ignore higher-order bits)
byt (convert 8 lsb's of argument into a byte)
getSI, getUI, getSL, getUL (each takes a byte array and an offset, and returns the little-endian signed word, unsigned word, signed 32-bit word, or unsigned 32-bit word at that offset
putSI, putUI, putSL, putUL (takes a byte array, offset, and a value to put there in little-endian format)
hexArr (converts a byte array or portion thereof into a hex string)
hexToArr (converts a hex string to a byte array)
Zap(of T as iDisposable) (takes a byref iDisposable; if not Nothing, disposes it and sets it to Nothing)
Many of those are only useful when fiddling with binary data, but none of them is really domain-specific. Maybe the first six could go in a BinaryHelpers module, but I'm not sure where Zap should go other than in a misc utilities class.
Utility classes aren't bad, in and of themselves. They can be (mis|ab|over)used at times, but they do have their place. If you have utility methods for types you own, consider moving the static methods to the appropriate types. Or creating extension methods.
Do try to avoid a monolithic utilities class - they may be static methods, but they will have poor cohesion. Break up a large set of unrelated functions into smaller groupings of related functionality, much like you would your "normal" classes. Name them *Helper or *Utils, or whatever your preference is. But be consistent, and group them together, perhaps in a folder within a project.
When utility classes are broken up as described, you can create methods for working with specific types - primitives or classes, such as arrays, strings, dates and times, and so on. Admittedly, these wouldn't belong anywhere else, so a utility class is the place to go.
Personally, I often find such a class handy - even if only in the short term. That said, I try not to share them between projects. I would not keep a global version, but write one specific to each project - otherwise you're incorporating dead-weight which may cause issues for security or architecture.
What I do for my personal projects is keep a misc library but rather than adding a reference in my projects, I paste the relevant bits of code in to the relevant places. It's technically duplicaintg it, but not within a single solution and thats the important thing. However I don't think this would work on a larger scale, too messy.
I generally don't have a problem with them, although, like all things, they can be abused:
They grow wildly large, so that most problems that use the class don't use 99% of the functions.
They grow wildly large, so that 90% of the functions aren't used by any program still in use.
Often they are a dumping ground for functions which are specific to one domain. They should be pared off to a similar class use just by program in that domain. Often, these function would be better off incorporated into proper classes.
I used to have, in every project, a module called MiscStuffAndJunk. It was a place to hold everything that didn't have a clear place to go, either because the functionality was a one-off, or because I didn't want to change my focus, so as to do a proper design for a function that was needed by but extraneous away from what I was currently concentrating on.
Still, it these modules are clearly in violation of OO design principles.
So nowadays, I name the module StuffIHaventRefactoredYet, and all is right with the world.
Depending on what your static utility functions actually do and return, it may be cause problems unit testing. I have come across a method in a class that calls a static function on a static class that return things I do not want in my unit test, rendering the whole method untestable...

Naming convention and structure for utility classes and methods

Do you have any input on how to organize and name utility classes?
Whenever I run in to some code-duplication, could be just a couple of code lines, I move them to a utility class.
After a while, I tend to get a lot of small static classes, usually with only one method, which I usualy put in a utility namespace that gets bloated with classes.
Examples:
ParseCommaSeparatedIntegersFromString( string )
CreateCommaSeparatedStringFromIntegers( int[] )
CleanHtmlTags( string )
GetListOfIdsFromCollectionOfX( CollectionX )
CompressByteData( byte[] )
Usually, naming conventions tell you to name your class as a Noun. I often end up with a lot of classes like HtmlHelper, CompressHelper but they aren't very informative. I've also tried being really specific like HtmlTagCleaner, which usualy ends up with one class per utility method.
Have you any ideas on how to name and group these helper methods?
I believe there is a continuum of complexity, therefore corresponding organizations. Examples follow, choose depending of the complexity of your project and your utilities, and adapt to other constraints :
One class (called Helper), with a few methods
One package (called helper), with a few classes (called XXXHelper), each class with a few methods.
Alternatively, the classes may be split in several non-helper packages if they fit.
One project (called helper), with a few packages (called XXX), each package with ...
Alternatively, the packages can be split in several non-helper packages if they fit.
Several helper projects (split by tier, by library in use or otherwise)...
At each grouping level (package, class) :
the common part of the meaning is the name of the grouping name
inner codes don't need that meaning anymore (so their name is shorter, more focused, and doesn't need abbreviations, it uses full names).
For projects, I usually repeat the common meaning in a superpackage name. Although not my prefered choice in theory, I don't see in my IDE (Eclipse) from which project a class is imported, so I need the information repeated. The project is actually only used as :
a shipping unit : some deliverables or products will have the jar, those that don't need it won't),
to express dependencies : for example, a business project have no dependency on web tier helpers ; having expressed that in projects dependencies, we made an improvement in apparent complexity, good for us ; or finding such a dependency, we know something is wrong, and start to investigate... ; also, by reducing the dependencies, we may accelerate compilation and building ....
to categorize the code, to find it faster : only when it's huge, I'm talking about thousands of classes in the project
Please note that all the above applies to dynamic methods as well, not only static ones.
It's actually our good practices for all our code.
Now that I tried to answer your question (although in a broad way), let me add another thought
(I know you didn't ask for that).
Static methods (except those using static class members) work without context, all data have to be passed as parameters. We all know that, in OO code, this is not the preferred way. In theory, we should look for the object most relevant to the method, and move that method on that object. Remember that code sharing doesn't have to be static, it only has to be public (or otherwise visible).
Examples of where to move a static method :
If there is only one parameter, to that parameter.
If there are several parameters, choose between moving the method on :
the parameter that is used most : the one with several fields or methods used, or used by conditionals (ideally, some conditionnals would be removed by subclasses overriding) ...
one existing object that has already good access to several of the parameters.
build a new class for that need
Although this method moving may seem for OO-purist, we find this actually helps us in the long run (and it proves invaluable when we want to subclass it, to alter an algorithm). Eclipse moves a method in less than a minute (with all verifications), and we gain so much more than a minute when we look for some code, or when we don't code again a method that was coded already.
Limitations : some classes can't be extended, usually because they are out of control (JDK, libraries ...). I believe this is the real helper justification, when you need to put a method on a class that you can't change.
Our good practice then is to name the helper with the name of the class to extend, with Helper suffix. (StringHelper, DateHelper). This close matching between the class where we would like the code to be and the Helper helps us find those method in a few seconds, even without knowledge if someone else in our project wrote that method or not.
Helper suffix is a good convention, since it is used in other languages (at least in Java, IIRC rails use it).
The intent of your helper should be transported by the method name, and use the class only as placeholder. For example ParseCommaSeparatedIntegersFromString is a bad name for a couple of reasons:
too long, really
it is redundant, in a statically typed language you can remove FromString suffix since it is deduced from signature
What do you think about:
CSVHelper.parse(String)
CSVHelper.create(int[])
HTMLHelper.clean(String)
...

Best practice for naming subclasses

I am often in a situation where I have a concept represented by an interface or class, and then I have a series of subclasses/subinterfaces which extend it.
For example:
A generic "DoiGraphNode"
A "DoiGraphNode" representing a resource
A "DoiGraphNode" representing a Java resource
A "DoiGraphNode" with an associated path, etc., etc.
I can think of three naming conventions, and would appreciate comments on how to choose.
Option 1: Always start with the name of the concept.
Thus: DoiGraphNode, DoiGraphNodeResource, DoiGraphNodeJavaResource, DoiGraphNodeWithPath, etc.
Pro: It is very clear what I am dealing with, it is easy to see all the options I have
Con: Not very natural? Everything looks the same?
Option 2: Put the special stuff in the beginning.
Thus: DoiGraphNode, ResourceDoiGraphNode, JavaResourceDoiGraphNode, PathBaseDoiGraphNode,
etc., etc.
Pro: It is very clear when I see it in the code
Con: Finding it could be difficult, especially if I don't remember the name, lack of visual consistency
Option 3: Put the special stuff and remove some of the redundant text
Thus: DoiGraphNode, ResourceNode, JavaResourceNode, GraphNodeWithPath
Pro: Not that much to write and read
Con: Looks like cr*p, very inconsistent, may conflict with other names
Name them for what they are.
If naming them is hard or ambiguous, it's often a sign that the Class is doing too much (Single Responsibility Principle).
To avoid naming conflicts, choose your namespaces appropriately.
Personnally, I'd use 3
Use whatever you like, it's a subjective thing. The important thing is to make clear what each class represents, and the names should be such that the inheritance relationships make sense. I don't really think it's all that important to encode the relationships in the names, though; that's what documentation is for (and if your names are appropriate for the objects, people should be able to make good guesses as to what inherits from what).
For what it's worth, I usually use option 3, and from my experience looking at other people's code option 2 is probably more prevalent than option 1.
You could find some guidance in a coding standards document, for example there is the IDesign document for C# here.
Personally, I prefer option 2. This is generally the way the .NET Framework names its objects. For instance look at attribute classes. They all end in Attribute (TestMethodAttribute). The same goes for EventHandlers: OnClickEventHandler is a recommended name for an event handler that handles the Click event.
I usually try to follow this in designing my own code and interfaces. Thus an IUnitWriter produces a StringUnitWriter and a DataTableUnitWriter. This way I always know what their base class is and it reads more naturally. Self-documenting code is the end-goal for all agile developers so it seems to work well for me!
I usually name similar to option 1, especially when the classes will be used polymophically.
My reasoning is that the most important bit of information is listed first.
(I.e. the fact that the subclass is basically what the ancestor is,
with (usually) extensions 'added').
I like this option also because when sorting lists of class names,
the related classes will be listed together.
I.e. I usually name the translation unit (file name) the same as
the class name so related class files will naturally be listed together.
Similarly this is useful with incremental search.
Although I tended to use option 2 earlier in my programming career, I avoid it now because as you say it is 'inconsistant' and do not seem very orthogonal.
I often use option 3 when the subclass provides substantial extension or specification, or if the names would be rather long.
For example, my file system name classes are derived from String
but they greatly extend the String class and have a significantly different
use/meaning:
Directory_entry_name derived from String adds extensive functionality.
File_name derived from Directory_entry_name has rather specialized functions.
Directory_name derived from Directory_entry_name also has rather specialized functions.
Also along with option 1, I usually use an unqualified name for an interface class.
For example I might have a class interence chain:
Text (an interface)
Text_abstract (abstract (base) generalization class)
Text_ASCII (concrete class specific for ASCII coding)
Text_unicode (concrete class specific for unicode coding)
I rather like that the interface and the abstract base class automatically appear first in the sorted list.
Option three more logically follows from the concept of inheritance. Since you're specializing the interface or class, the name should show that it's no longer using the base implementation (if one exists).
There are a multitude of tools to see what a class inherits from, so a concise name indicating the real function of the class will go farther than trying to pack too much type information into the name.