groovy list api creating new lists versus modifying current list - collections

Just could not fathom why the groovy list api would have classes of methods that
a) allow modification of current list
b) return a new list,
e.g.
aList-['Hello','World']
// modifying a list
aList.set(2,'Modifying') //will modify aList itself, i.e. aList=['Hello','World','Modifying'
//create a new list without modifying self
aList.plus(1,'Worlds') //aList is not modified, although this statements creates a new list: ['Hello','Worlds','Modifying']
My question is: why wouldn't the authors of Groovy stick to a standard, i.e. either have completely immutable collections so that all methods would either return new list instances without modifying the current collection instance, OR allow for methods such as 'plus' to modify the current collection. It seems a little un-intuitive to have two standards on this.

Groovy wraps around Java and allows you to call existing Java methods.
So set is a Java method that manipulates the underlying list. Therefore in Groovy, it just calls this method and you mutate the list.
minus, plus and left-shift are Groovy additions, so in the case of lists, they are written to not mutate the original lists.
When it comes to Maps however,left-shift DOES mutate the map, but I guess this is just something you have to remember.

Related

Updating an object in a store in Svelte, is it by value or by reference?

Check out this Svelte REPL. Notice how I access the global state – which is an object – by key and also iterate over its values in App.svelte. So I also create a derived list of these values in global.js.
In general, is this the "Sveltonic" way (regarding performance, syntax, ...)?
I am unsure what happens inside .update() (in SetThings.svelte). Will the full object or parts get copied into the old object? Or will the variable referencing the old object be reassigned to the new object?
Regarding part one of the question: It is unwise to use an outermost object. Instead, I now use a list and let the child objects have their indexes as keys. As shown in the Svelte docs, for example here.
Regarding part two of the question, it seems the object (or parts of it) is not copied. See update() → set() → safe_not_equal() (returns true in this case) → value = value

Why are property accessor methods different for Immutable Maps and Records?

I am using Immutable JS in conjunction with React + Redux. For the most part I really love how it reinforces the Redux paradigm, with the exception of its property accessor methods.
For Immutable Maps, one must access properties using the Immutable get method.
Ex. this.props.exampleMap.get('mapProperty');
However, for Immutable Records, there is no get method. Instead you just access properties with the dot method as with normal JS objects.
Ex. this.props.exampleRecord.recordProperty
My question is, why is there this discrepancy? This is making me a little OCD because my components are now filled with a mix of both methods and frankly it's a little ugly.
You actually can use .get(...) for immutable records. The way I think of is that records have additional nicer syntax by allowing you to access the properties directly.
If you take a look at the type definitions of a record, you'll see that record constructors create objects with types Immutable.Map<string, any>.
This nicer syntax is possible because you predefine the properties of the record upon creation.
Here is the immutable record creation example taken directly from their docs
const { Record } = require('immutable')
const ABRecord = Record({ a: 1, b: 2 })
const myRecord = new ABRecord({ b: 3 })
So remember, you give the Record function an object with default values and it returns a constructor you can use to create object with new.

Defining Symfony Services to maximize maintainability

I'm working on a big domain, for which maintainability is very important.
There are these general workers called ExcelHandlers that implement ExcelHandlerInterface (more on the interface in the ideas section) and basically get an UploadedFile as their input, upload them wherever they want and return the read data as an associative array. Now I have created this base class ExcelFileHandler which does all of these tasks for all excel files given two arguments:
1. The Directory to upload the file
2. the mapping of the excel columns to the indexes of the associative array.
Some ExcelHandlers might have to extend the ExcelFileHandler and do some more processing, in order to get the associative array of data.
The UploadedFile is always passed to the ExcelHandler from the controller.
Now here is the question. Given the generic structure of the ExcelFileHandler how should I define services for specific ExcelHandlers given that some only differ with the original one in the directory to upload the file and the mapping array.
My Ideas:
1. The first approach involves giving the directory and the mapping as the function arguments to ExcelHandleInterface::handle this will make the prototype something like handle(UploadedFile $file, array $mapping, $dir), $mapping and $dir are given to the function as arguments and passed to the handler by the controllers which has the parameters as constructor injections.
2.1 Defining the prototype of handle to be handle(UploadedFile $file), this would require the ExcelHandlers to have knowledge of $dir and $mapping. $dir will always be injected from the constructor.
2.1.1 Foreach individual ExcelHandler in the application, define a separate class e.g: UserExcelHandler, ProductExcelHandler, .... Which extend the ExcelFileHandler and leaves us again with two choices.
2.1.1.1 inject $mapping from outside. e.g:
// in the child class
public function __construct($dir, $mapping){
parent::__construct($dir, $mapping);
}
2.1.1.2 define $mapping in the constructor of the child class. e.g:
// in the child class
public function __construct($dir){
$mapping = array(0 => 'name', 1 => 'gender');
parent::__construct($dir, $mapping);
}
2.1.2 Not to create a class for each separate ExcelHandler and instead define the ExcelFileHandler as an abstract service and decorate with the right parameters to get the concrete ExcelHandler Service with the desired functionality, obviously ExcelHandlers with custom logic must be defined seperately, and to create a uniform code base, $mapping will always be injected from the Container in this case.
In your experience, what other paths can I take and which ones yield better results in the long term?
First of all, it seams as you've already put two separate things into one.
Uploading a file and reading it's contents are two separate concerns, which can change separately (like you said, $directory and $mapping can change case-by-case). Thus I would suggest to use separate services for uploading and reading the file.
See Single responsibility principle for more information.
Furthermore, due to very similar reasons, I would not recommend base classes at all - I'd prefer composition over inheritance.
Imagine that you have 2 methods in your base class: upload, which stores file to a local directory, and parse, which reads excel file and maps columns to some data structure.
If you need to store file in a remote storage (for example FTP), you need to override upload method. Let's call this service1.
If you need to parse file differently, for example combining data from 2 sheets, you need to override parse method. Let's call this service2.
If you need to override both of these methods, while still being able to get service1 and service2, you're stuck, as you'll need to copy-and-paste the code. There's no easy way to use already written functionality from (1) and (2).
In comparison, if you have interface with upload method and interface with parse method, you can inject those 2 separate services where you need them as you need them. You can mix any implementations of those already available. All of them are already tested and you do not need to write any code - just to configure the services.
One more thing to mention - there is absolutely no need to create (and name) classes by their usage. Name them by their behaviour. For example, if you have ExcelParser, which takes $mapping as an argument to a constructor, no need to call it UserExcelParser if the code itself has nothing to do with users. If you need to parse data from several sheets, just create SheetAwareExcelParser etc., not ProductExcelParser. This way you can reuse the code. Also correct naming lets understand the code more easily.
In practice, I've seen when function or class is named by it's usage, and then it's just used in another place with no renaming, refactoring etc. These cases are really not what you're looking for.
Service names (in another words concrete objects, not classes), can of course be named by their purpose. You just configure them with any required functionality (single vs separate sheets etc.)
To summarize, I would use 2.1.2 above all other of your given options. I would inject $dir and $mapping via DI in any case, as these do not change in runtime - these are configuration.

What are the uses of constructor reference in java 8

I was reading about Java 8 features, which lead me to this article and I was wondering about the actual uses of constructor reference, I mean why not just use new Obj ?
P.S, I tried googling, but I failed to find something meaningful, if someone has a code example, link or tut it will be great
First of all, you should understand that constructor references are just a special form of method references. The point about method references is that they do not invoke the referenced method but provide a way to define a function which will invoke the method when being evaluated.
The linked article’s examples might not look that useful but that’s the general problem of short self-contained example code. It’s just the same as with the “hello world” program. It’s not more useful than typing the text “hello world” directly into the console but it’s not meant to be anyway. It’s purpose is to demonstrate the programming language.
As assylias has shown, there are use cases involving already existing functional interfaces using the JFC API.
Regarding the usefulness of a custom functional interface that’ll be used together with a constructor reference, you have to think about the reason to use (functional) interface in general: abstraction.
Since the purpose of an interface is to abstract the underlying operation, the use cases are the places where you do not want to perform an unconditional new SomeType(…) operation.
So one example is the commonly known Factory pattern where you define an interface to construct an object and implementing the factory via constructor reference is only one option out of the infinite possibilities.
Another important point are all kinds of Generic methods where the possibility to construct instances of the type, that is not known due to type erasure, is needed. They can be implemented via a function which is passed as parameter and whether one of the existing functional interfaces fits or a custom one is needed simply depends on the required number and types of parameters.
It's useful when you need to provide a constructor as a supplier or a function. Examples:
List<String> filtered = stringList.stream()
.filter(s -> !s.isEmpty())
.collect(Collectors.toCollection(ArrayList::new)); //() -> new ArrayList<> ()
Map<String, BigDecimal> numbersMap = new HashMap<>();
numbersMap.computeIfAbsent("2", BigDecimal::new); // s -> new BigDecimal(s)
someStream.toArray(Object[]::new); // i -> new Object[i]
etc.

What is main advantage of Tuple?

Can anyone tell me what is the main advantage of using tuple? In what scenarios do I need to use these?
I assume that you're talking about the Tuple<> type and not anonymous tuple classes.
Like an anonymous type, Tuple<> allows you to avoid declaring a new class just to group a few objects. Unlike anonymous types, tuple types have known names and thus can be used as method return and parameter values, etc.
Personally, I try to avoid heavy use of Tuple<> because it can make for difficult to understand code, expecially when used with primitive types (e. g. if you see a Tuple it's not obvious what each field represents).
One place I have found tuples to be very useful is as dictionary keys. Because Tuples implement Equals() and GetHashCode() (not ==, though!), they are perfect for things like private dictionaries that cache information based on a compound key.
It's used mostly to avoid declaring a class / struct with a few properties only for the sake of passing a group of objects around, where only one object can be passed.
Lets say I have a list of urls to go through and if i get an error (4xx or 5xx) I want to build a list and then either later display it to the user or just look at it in my debugger.
I'd catch the web exception and have a Tuple<string, int> (url, http error code) instead of creating a struct for one or two functions to use. Heck it might even be a foreach loop with a breakpoint on if the list has more then 0 items. Thats when it is useful.

Resources