Naming convention of mutable/immutable methods - language-agnostic

What is the naming convention when you have two generic-name methods performing the same operation, while one is immutable and the other is mutable?
EXAMPLE
Consider cellwise operation accepting 2 arrays of numbers: immutable version creates a new array to put the result in, while the mutable version stores the result in first array parameter.
Since the method name is something generic like apply as operation strategy (add, sub, mul, div) is specified by third argument, you can not use common words like add for mutability (a = a + 1) and plus for immutability (c = a + b).
CODE (TO BE SKIPPED)
Following details might be offtopic, but for illustration about what method I'm talking about:
#FunctionalInterface
public interface BinaryOperation { double apply(double a, double b); }
public final class BinaryOperations {
private BinaryOperations() {}
public static final BinaryOperation ADD = (a, b) -> a + b;
public static final BinaryOperation SUB = (a, b) -> a - b;
public static final BinaryOperation MUL = (a, b) -> a * b;
public static final BinaryOperation DIV = (a, b) -> a / b;
}
public final class DoubleArraysMath {
private DoubleArrayMath() {}
// ---> METHOD NAME OF INTEREST
public static void applyAsMutable(double[] a, double[] b, BinaryOperation o) {
apply(a, a, b, o);
}
// ---> METHOD NAME OF INTEREST
public static double[] applyAsImmutable(double[] a, double[] b, BinaryOperation o) {
double[] c = new double[a.length];
return apply(c, a, b, o);
return c;
}
private static void apply(double[] result, double[] a, double[] b, BinaryOperation o) {
for (int i = 0; i < a.length; i++) { result[i] = o.apply(a[i], b[i]); }
}
}
// just an example of usage
double[] r = DoubleArraysMath.applyAsImmutable(a, b, BinaryOperations.MUL);
DoubleArraysMath.applyAsMutable(a, b, BinaryOperations.ADD);
DoubleArraysMath.applyAsMutable(a, b, (ai, bi) -> ai*ai + bi); // some custom operation
SEPARATE CLASSES
Having mutable and immutable methods separated in DoubleArraysMutableMath and DoubleArraysImmutableMath classes avoids writting of "mutable/immutable" prefix/suffix at the begining/end of each method name. Following this pattern, you will end up with any utility class named as "mutable/immutable" (whether it is good or not I will leave as an open question).
SINGLE CLASS PROBLEM
In case we want to have these methods in single class (better maintenance), what is the proper naming "pattern"? Pattern I have used in my code sample "asMutable/asImmutable" or generally "mutable/immutable" might be incompatible with longer method names. Is there any other options?

Edit based on the comments
You should definitely implement mutable and immutable classes separately. Method names can be similar or different, it doesn't matter as interfaces will be different anyway.
Single class
Mutability strategy can be mentioned as an additional argument of the method, for example:
apply(a,b,Operation.ADD, ResultValue.NEW)
apply(a,b,Operation.ADD, ResultValue.FIRST_ARG)
apply(a,b,Operation.ADD, ResultValue.SECOND_ARG)
However, using multiple strategies in a single method will make the method confusing for the clients and error-prone.
If the signature of the method is
double [] apply(double[] arg1, double[] arg2, BinaryOperation)
then mutability or immutability can be part of the BinaryOperation itself:
public class FirstArgMutablePlusOperation {
double[] apply(double[] arg1, double[] arg2) {
//sample mutation
arg1[0] = arg1[0] + arg2[0];
// still return arg1 as a result
return arg1;
}
}
public class SecondArgMutablePlusOperation {
double[] apply(double[] arg1, double[] arg2) {
//sample mutation
arg2[0] = arg1[0] + arg2[0];
// still return arg2 as a result
return arg2;
}
}
public class ImmutablePlusOperation {
double[] apply(double[] arg1, double[] arg2) {
//sample mutation
double[] result = new double[arg1.length];
result[0] = arg1[0] + arg2[0];
return result;
}
}
Then a user can call apply method with correct strategy:
apply(arg1, arg2, new FirstArgMutablePlusOperation());
apply(arg1, arg2, new SecondArgMutablePlusOperation());
double[] result = apply(arg1, arg2, new ImmutablePlusOperation());
Immutable/mutable strategy can be a part of the BinaryOperation.
However, I rather avoid this solution as it will introduce if statements and a bulky implementation:
public enum ResultStrategy
{ RESULT, FIRST_ARG, SECOND_ARG };
public class PlusOperation extends BinaryOperation {
private final ResultStrategy strategy;
public PlusOperation(final ResultStrategy strategy) {
this.strategy = strategy
}
double[] apply(double[] arg1, double[] arg2) {
if(strategy == ResultStrategy.FIRST_ARG) {
//sample mutation
arg1[0] = arg1[0] + arg2[0];
// still return arg1 as a result
return arg1;
} else if(strategy == ResultStrategy.SECOND_ARG) {
//sample mutation
arg2[0] = arg1[0] + arg2[0];
// still return arg2 as a result
return arg2;
} else if(strategy == ResultStrategy.RESULT) {
double[] result = new double[arg1.length];
result[0] = arg1[0] + arg2[0];
return result;
}
}
}
Usage:
apply(arg1, arg2, new PlusOperation(ResultStrategy.FIRST_ARG));
apply(arg1, arg2, new PlusOperation(ResultStrategy.SECOND_ARG));
double[] result = apply(arg1, arg2, new PlusOperation(ResultStrategy.RESULT));
UPDATE
According to sample code provided in question
public enum ResultStrategy { FIRST_ARG, NEW_RESULT;} // SECOND_ARG = apply(b, a)
public class DoubleArraysMath {
...
public static double[] apply(ResultStrategy rs, double[] a, double[] b, BinaryOperation o) {
if (rs == ResultStrategy.FIRST_ARG) { return apply(a, a, b, o); }
return apply(new double[a.length], a, b, o);
}
}

Related

How do I initialize a final class property in a constructor?

In Java you are allowed to do this:
class A {
private final int x;
public A() {
x = 5;
}
}
In Dart, I tried:
class A {
final int x;
A() {
this.x = 5;
}
}
I get two compilation errors:
The final variable 'x' must be initialized.
and
'x' can't be used as a setter because its final.
Is there a way to set final properties in the constructor in Dart?
You cannot instantiate final fields in the constructor body. There is a special syntax for that:
class Point {
final num x;
final num y;
final num distanceFromOrigin;
// Old syntax
// Point(x, y) :
// x = x,
// y = y,
// distanceFromOrigin = sqrt(pow(x, 2) + pow(y, 2));
// New syntax
Point(this.x, this.y) :
distanceFromOrigin = sqrt(pow(x, 2) + pow(y, 2));
}
You can make it even shorter with this. syntax in the constructor (described in https://www.dartlang.org/guides/language/language-tour#constructors):
class Point {
final num x;
final num y;
final num distanceFromOrigin;
Point(this.x, this.y)
: distanceFromOrigin = sqrt(pow(x, 2) + pow(y, 2));
}
If you have some more complicated initialization you should use factory constructor, and the code become:
class Point {
final num x;
final num y;
final num distanceFromOrigin;
Point._(this.x, this.y, this.distanceFromOrigin);
factory Point(num x, num y) {
num distance = distanceFromOrigin = sqrt(pow(x, 2) + pow(y, 2));
return new Point._(x, y, distance);
}
}
Here is a simplified summary of the ways to initialize a final class variable.
class MyClass {
final int x; // <-- initialize this
}
Initializer value
class MyClass {
final int x = 'hello'.length;
}
You'd only use final if the initialization could only be done at runtime. Otherwise, static const is better:
class MyClass {
static const int x = 0;
}
Initializer formal
class MyClass {
MyClass(this.x);
final int x;
}
This is the most common approach.
Initializer list
class MyClass {
MyClass(int x)
: _x = x;
final int _x;
}
This is useful when you want to keep a field private.
Default parameter value
You can surround the parameter with square brackets ([]) for an unnamed parameter or curly braces ({}) for a named parameter and then give it a default value.
class MyClass {
MyClass({this.x = 0});
final int x;
}
This is useful if you want to make the parameter optional.
You could accomplish the same thing with an initializer list as well:
class MyClass {
MyClass({int? x})
: _x = x ?? 0;
final int _x;
}
Late initialization
class MyClass {
MyClass(String? a) {
x = a?.length ?? 0;
}
late final int x;
}
This is useful if you need to do more complex initialization than is allowed in the initializer list. For example, I've done this when initializing a gesture recognizer in Flutter.
Lazy initialization
Another advantage of using late is that it doesn't initialize a value until you access the value.
class MyClass {
late final int x = _doHeavyTask();
int _doHeavyTask() {
var sum = 0;
for (var i = 0; i < 100000000; i++) {
sum += 1;
}
return sum;
}
}
This is useful if you have a heavy calculation that you only want call if you absolutely need it.
This doesn't initialize x:
final myClass = MyClass();
But this does initialize x:
final myClass = MyClass();
final value = myClass.x;
I've had a similar problem: I was trying to initialise a final field from the constructor, while simultaneously calling a super constructor. You could think of the following example
class Point2d {
final int x;
final int y;
Point2d.fromCoordinates(Coordinates coordinates)
: this.x = coordinates.x,
this.y = coordinates.y;
}
class Point3d extends Point2d {
final int z;
Point3d.fromCoordinates(Coordinates coordinates)
:this.z = coordinates.z,
super.fromCoordinates(coordinates);
}
/// Demo class, to simulate constructing an object
/// from another object.
class Coordinates {
final int x;
final int y;
final int z;
}
Well apparently this works. You can initialise your final fields by using the above syntax (check Point3d's constructor) and it works just fine!
Run a small program like this to check:
void main() {
var coordinates = Coordinates(1, 2, 3);
var point3d = Point3d.fromCoordinates(coordinates);
print("x: ${point3d.x}, y: ${point3d.y}, z: ${point3d.z}");
}
It should prin x: 1, y: 2, z: 3
I've come to a dilemma here where I wanted to initialize a final List with no items, and a Stream to be defined inside the constructor (like in this case distanceFromOrigin).
I couldn't do that with any of the answers below, but I mixed them both and it worked.
Example:
class MyBloc {
final BehaviorSubject<List<String>> itemsStream;
final List<String> items = [];
MyBloc() : this.itemsStream = BehaviorSubject<List<String>>.seeded([]) {
items.addAll(List.generate(20, (index) => "Hola! I'm number $index"));
itemsStream.add(items);
}
}
class A{
final int x;
A(this.x){
}
}

How to attach a DataPoint with a Theory?

#DataPoints public static final Integer[] input1={1,2};
#Theory
#Test
public void test1(int input1){
}
#DataPoints public static final Integer[] input2={3,4};
#Theory
#Test
public void test2(int input2 ){
}
I want that test1 runs with data set input1 - {1,2} and test2 runs with input2 - {3,4}. But currently each test runs with both the data sets {1,2,3,4}. How to bind specific #DataPoints to specific #Theorys
With JUnit 4.12 (not sure when it was introduced) it is possible to name the DataPoints and assign them to parameters (i learned it from http://farenda.com/junit/junit-theories-with-datapoints/):
#RunWith(Theories.class)
public class TheoriesAndDataPointsTest {
#DataPoints("a values")
public static int[] aValues() {
return new int[]{1, 2};
}
#DataPoints("b values")
public static int[] bValues() {
return new int[]{3, 4};
}
#Theory
public void theoryForA(#FromDataPoints("a values") int a) {
System.out.printf("TheoryForA called with a = %d\n", a);
}
#Theory
public void theoryForB(#FromDataPoints("b values") int a) {
System.out.printf("TheoryForB called with b = %d\n", a);
}
}
Output:
TheoryForA called with a = 1
TheoryForA called with a = 2
TheoryForB called with b = 3
TheoryForB called with b = 4
DataPoints apply to the class. If you have a #Theory method which takes an int, and you have a DataPoint which is an array of ints, then it will be called with the int.
#RunWith(Theories.class)
public class TheoryTest {
#DataPoint public static int input1 = 45;
#DataPoint public static int input2 = 46;
#DataPoints public static String[] inputs = new String[] { "foobar", "barbar" };
#Theory public void testString1(String input) {
System.out.println("testString1 input=" + input);
}
#Theory public void testString2(String input) {
System.out.println("testString2 input=" + input);
}
#Theory public void test1(int input) {
System.out.println("test1 input=" + input);
}
#Theory public void test2(int input) {
System.out.println("test2 input=" + input);
}
}
This calls test1 with 45 & 46, and test2 with 45 & 46. It calls testString1 with "foobar" and "barbar" and testString2 with "foobar" and "barbar".
If you really want to use different data sets for different theories, you can wrap the data in a private class:
#RunWith(Theories.class)
public class TheoryTest {
public static class I1 { int i; public I1(int i) { this.i = i;} }
public static class I2 { int i; public I2(int i) { this.i = i;} }
#DataPoint public static I1 input1 = new I1(45);
#DataPoint public static I2 input2 = new I2(46);
#Theory
public void test1(I1 input) {
System.out.println("test1 input=" + input.i);
}
#Theory
public void test2(I2 input) {
System.out.println("test2 input=" + input.i);
}
}
This calls test1 with 45 and test2 with 46. This works, but in my opinion, it obscures the code, and it may be a better solution to just split the Test class into two classes.
In reference to Gábor Lipták's answer, named datapoints can be defined as a static fields (reference) which give us more concise code:
#RunWith(Theories.class)
public class TheoriesAndDataPointsTest {
#DataPoints("a values")
public static int[] aValues = {1, 2};
#DataPoints("b values")
public static int[] bValues = {3, 4};
#Theory
public void theoryForA(#FromDataPoints("a values") int a) {
System.out.printf("TheoryForA called with a = %d\n", a);
}
#Theory
public void theoryForB(#FromDataPoints("b values") int a) {
System.out.printf("TheoryForB called with b = %d\n", a);
}
}
Some of the references I have seen talking about using tests for specific values and theories for verifying behavior. As an example, if you have a class that has methods to add and subtract from an attribute, a test would verify correctness of the result (e.g., 1+3 returns 4) whereas a theory might verify that, for the datapoint values (x1, y1), (x2, y2), x+y-y always equals x, x-y+y always equals x, x*y/y always equals x, etc. This way, the results of theories are not coupled as tightly with the data. With theories, you also can filter out cases such as y == 0; they don't count as failure. Bottom line: you can use both. A good paper is: http://web.archive.org/web/20110608210825/http://shareandenjoy.saff.net/tdd-specifications.pdf

How to increase position offsets in a lucene index to correspond to <p> tags?

I am using Lucene 3.0.3. In preparation to using SpanQuery and PhraseQuery, I would like to mark paragraph boundaries in my index in a way that will discourage these queries from matching across paragraph boundaries. I understand that I need to increment position by some suitably large value in the PositionIncrementAttribute when processing text to mark paragraph boundaries. Let's assume that in the source document, my paragraph boundaries are marked by <p>...</p> pairs.
How do I set up my token stream to detect the tags? Also, I don't actually want to index the tags themselves. For the purposes of indexing, I would rather increment the position of the next legitimate token, rather than emitting a token that corresponds to the tag, since I don't want it to affect search.
The easiest way to add gaps (= PositionIncrement > 1) is to provide a custom TokenStream. You do not need to change your Analyzer for that. However, HTML parsing should be done upstream (i.e., you should segment and clean your input text accordingly before feeding it to Lucene).
Here is a full, working example (imports omitted):
public class GapTest {
public static void main(String[] args) throws Exception {
final Directory dir = new RAMDirectory();
final IndexWriterConfig iwConfig = new IndexWriterConfig(Version.LUCENE_4_10_1, new SimpleAnalyzer());
final IndexWriter iw = new IndexWriter(dir, iwConfig);
Document doc = new Document();
doc.add(new TextField("body", "A B C", Store.YES));
doc.add(new TextField("body", new PositionIncrementTokenStream(10)));
doc.add(new TextField("body", "D E F", Store.YES));
System.out.println(doc);
iw.addDocument(doc);
iw.close();
final IndexReader ir = DirectoryReader.open(dir);
IndexSearcher is = new IndexSearcher(ir);
QueryParser qp = new QueryParser("body", new SimpleAnalyzer());
for (String q : new String[] { "\"A B C\"", "\"A B C D\"",
"\"A B C D\"", "\"A B C D\"~10", "\"A B C D E F\"~10",
"\"A B C D F E\"~10", "\"A B C D F E\"~11" }) {
Query query = qp.parse(q);
TopDocs docs = is.search(query, 10);
System.out.println(docs.totalHits + "\t" + q);
}
ir.close();
}
/**
* A gaps-only TokenStream (uses {#link PositionIncrementAttribute}
*
* #author Christian Kohlschuetter
*/
private static final class PositionIncrementTokenStream extends TokenStream {
private boolean first = true;
private PositionIncrementAttribute attribute;
private final int positionIncrement;
public PositionIncrementTokenStream(final int positionIncrement) {
super();
this.positionIncrement = positionIncrement;
attribute = addAttribute(PositionIncrementAttribute.class);
}
#Override
public boolean incrementToken() throws IOException {
if (first) {
first = false;
attribute.setPositionIncrement(positionIncrement);
return true;
} else {
return false;
}
}
#Override
public void reset() throws IOException {
super.reset();
first = true;
}
}
}

How do I implement a fibonacci sequence in java using try/catch logic?

I know how to do it using simple recursion, but in order to complete this particular assignment I need to be able to accumulate on the stack and throw an exception that holds the answer in it.
So far I have:
public static int fibo(int index) {
int sum = 0;
try {
fibo_aux(index, 1, 1);
}
catch (IntegerException me) {
sum = me.getIntValue();
}
return sum;
}
fibo_aux is supposed to throw an IntegerException (which holds the value of the answer that is retireved via getIntValue) and accumulates the answer on the stack, but so far I can't figure it out. Can anyone help?
I don't know what your implementations for fibo_aux and IntegerException look like, but the following two implementations work with your existing code (I don't think there's anything wrong with the code you posted, so I assume something is awry in either fibo_aux or IntegerException). Maybe you'll find this helpful.
public static void fibo_aux(int index, int a, int b) throws IntegerException
{
if (--index > 0)
fibo_aux(index, b, a + b);
else
throw new IntegerException(a + b);
}
An implementation for IntegerException:
public class IntegerException extends Exception
{
private static final long serialVersionUID = -6795044518321782305L;
private Integer intValue;
public IntegerException(int i)
{
this.intValue = i;
}
public Integer getIntValue()
{
return intValue;
}
}
Here you go :
public class ExcFib {
/**
* #param args
*/
public static void main(String[] args) {
new ExcFib().fibo ( 10 );
}
class FiboException extends Throwable
{
public int n;
public FiboException(int n)
{
this.n = n;
}
private static final long serialVersionUID = 1L;
}
public void fibo(int idx) {
try {
fibo_aux(idx-1,1,1);
} catch (FiboException e) {
System.out.println ( "F(" + idx + ") = " + e.n );
}
}
private void fibo_aux(int i, int j, int k) throws FiboException {
if ( i < 1 )
{
throw new FiboException(k);
}
fibo_aux(i - 1, k, j + k );
}
}

What's your most reused class?

Every programmer ends up with a set of utility classes after a while. Some of them are true programming pearls and they are reused in several of your projects. For example, in java:
class Separator {
private String separator;
private boolean called;
public Separator(String aSeparator) {
separator = aSeparator;
called = false;
}
#Override
public String toString() {
if (!called) {
called = true;
return "";
} else {
return separator;
}
}
}
and:
public class JoinHelper {
public static <T> String join(T... elements) {
return joinArray(" ", elements);
}
public static <T> String join(String separator, T... elements) {
return joinArray(separator, elements);
}
private static <T> String joinArray(String sep, T[] elements) {
StringBuilder stringBuilder = new StringBuilder();
Separator separator = new Separator(sep);
for (T element : elements) {
stringBuilder.append(separator).append(element);
}
return stringBuilder.toString();
}
}
What is your most reused class?
System.Object - almost all my types extend it.
A utility class that has logging and email functionality. An extensions class that contains extension methods. A reporting class that basically harness the reporting services web service and makes it easy to stream reports as excel, pdf, etc.
Examples...
1.) Utility Class (static)
public static void LogError(Exception ex)
{
EventLog log = new EventLog();
if (ex != null)
{
log.Source = ConfigurationManager.AppSettings["EventLog"].ToString();
StringBuilder sErrorMessage = new StringBuilder();
if (HttpContext.Current.Request != null && HttpContext.Current.Request.Url != null)
{
sErrorMessage.Append(HttpContext.Current.Request.Url.ToString() + System.Environment.NewLine);
}
sErrorMessage.Append(ex.ToString());
log.WriteEntry(sErrorMessage.ToString(), EventLogEntryType.Error);
}
}
2.) Extensions Class
public static IEnumerable<TSource> WhereIf<TSource>(this IEnumerable<TSource> source, bool condition, Func<TSource, bool> predicate)
{
if (condition)
return source.Where(predicate);
else
return source;
}
public static short getLastDayOfMonth(short givenMonth, short givenYear)
{
short lastDay = 31;
switch (givenMonth)
{
case 4:
case 6:
case 9:
case 11:
lastDay = 30;
break;
case 2:
if ((int)givenYear % 4 == 0)
{
lastDay = 29;
}
else
{
lastDay = 28;
}
break;
}
return lastDay;
}
Most reused but boring:
public static void handleException(Exception e) throws RuntimeException {
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
}
throw new RuntimeException(e); //NOPMD
}
Less boring (also methods for building lists and sets):
/**
* Builds a Map that is based on the Bean List.
*
* #param items Bean List items
* #param keyField Bean Field that will be key of Map elements (not null)
* #return a Map that is based on the Bean List
*/
#SuppressWarnings("unchecked")
public static <T, K> Map<K, T> buildMapFromCollection(final Collection<T> items,
boolean linkedMap,
final String keyField,
final Class<K> keyType) {
if (items == null) {
return Collections.emptyMap();
}
if (keyField == null) {
throw new IllegalArgumentException("KeyField is null");
}
final Map<K, T> result;
if (linkedMap) {
result = new LinkedHashMap<K, T>();
} else {
result = new HashMap<K, T>();
}
BeanMapper mapper = null;
for (final T item : items) {
if (mapper == null) {
mapper = new BeanMapper(item.getClass());
}
final K key = (K) mapper.getFieldValue(item, keyField);
result.put(key, item);
}
return result;
}
Logger class: Which logs the flow of control in a log file.
Configuration Reader/Setter: which reads the configuration from ini/xml file and sets the environment of the application
Most reused? Hmmm...
boost::shared_ptr<> with boost::weak_ptr<>
probably most reused (also probably most bang-for-buck ratio)
Globals
Just a simple class with static DBConnString, and a few other app wide settings.
Have reused the simple file in about 2 dozen projects since working with .Net
A ConcurrentDictionary I wrote, which I now seem to use everywhere (I write lots of parallel programs)