What's the best way to declare a constant in Kotlin? - java

When we using kotlin there are mainly two ways of declaring constant:
class Foo {
companion object {
private const val a = "A"
}
}
And:
class Foo {
private val a = "A"
}
which one is better?
I searched the companion way is equivalent to
public static final class Companion {
#NotNull
private static final String a = "A";
}
in Java.
In this question
If a constant is not static, Java will allocate a memory for that constant in every object of the class (i.e., one copy of the constant per object).
If a constant is static, there will be only one copy of the constant
for that class (i.e., one copy per class).
Yes that's true.
BUT
If I have 100 or more constants in one class all static, when they are released? There are always in memory.
They won't be released until the program killed/terminated, right?
So I think the second way
class Foo {
private val a = "A"
}
is the right way. As any instance will be released some point then the memory is released.
Not quite sure I missed something. Any comments? Thanks!

BUT If I have 100 or more contacts in one class all static, when they are released?
You're going to write the info of 100 contacts in a source file? That's.. generally not where such data is supposed to go, but okay. 100.
You know what? That's bush league. Let's make it 10,000 contacts, all written out in one gigantic kotlin or java file.
It's still peanuts, memory wise. What's the share of a penny compared to the GDP of the world? Something along those lines. Whenever you load a class file, that's in memory. And is never getting released. And it doesn't matter one iota.
All those constant values are part of the class def and are loaded at least once in that sense no matter what you do.
The correct way is obviously for static data (i.e. things that are inherent to the class and do not ever change) to be loaded once precisely, instead of 'x times, where x is the amount of instances'. It's semantically correct (by its nature, unchanging, class-global stuff is static, that's what static means), and increments the 'load' of the fact that this class has been touched by a few percentage points (you're just adding references; all those strings are loaded only once and are loaded whether you make this stuff static or not, it's part of the class definition. Where do you imagine those strings go if there are 0 instances? JVM is not going to reload that class file from disk every time you call new Foo()!) - whereas if it's once-per-instance you might be looking at millions of refs for no reason at all.

There are many ways to define constants in Kotlin. They differ in their scope and use of namespaces, memory usage, and ability to inherit and override.
There's no single ‘best’ approach; it depends on what your constants represent, and how you're using them.
Here are some (simplified) examples:
At the top (file) level:
const val a = "A"
The declaration is ‘loose’ in a file, not contained in any class. This is usually the simplest and most concise way — but it may not occur to folks who are used to Java, as it has no direct Java equivalent.
The constant is available anywhere in the file (as a bare a); and if not private, it can also be used anywhere else (either as a fully-qualified list.of.packages.a, or if that's imported, simply as a). It can't be inherited or overridden.
In a companion object:
class A {
companion object {
const val a = "A"
}
}
If you know Java, this is roughly equivalent to a static field (as the question demonstrates). As with a top-level declaration, there is exactly one instance of the property in memory.
The main difference is that it's now part of A, which affects its scope and accessibility: it's available anywhere within A and its companion object, and (unless you restrict it) it can also be used elsewhere (as list.of.packages.A.a, and A.a if A is in scope, and simple a if the whole thing is imported). (You can't inherit from a singleton such as a companion object, so it can't be inherited or overridden.)
In a class:
class A {
val a = "A"
}
This differs both in concept and in practice, because every instance of A has its own property. This means that each instance of A will take an extra 4 or 8 bytes (or whatever the platform needs to store a reference) — even though they all hold the same reference. (The String object itself is interned.)
If A or a are closed (as here), that's is unlikely to make good sense either in terms of the meaning of the code, or its memory usage. (If you only have a few instances, it won't make much difference — but what if you have hundreds of thousands of instances in memory?) However, if A and a are both open, then subclasses can override the value, which can be handy. (However, see below.)
Once again, the property is available anywhere within A, and (unless restricted) anywhere that can see A. (Note that the property can't be const in this case, which means the compiler can't inline uses of it.)
In a class, with an explicit getter:
class A {
val a get() = "A"
}
This is conceptually very similar to the previous case: every instance of A has its own property, which can be overridden in subclasses. And it's accessed in exactly the same way.
However, the implementation is more efficient. This version provides the getter function — and because that makes no reference to a backing field, the compiler doesn't create one. So you get all the benefits of a class property, but without the memory overhead.
As enum values:
enum class A {
A
}
This makes sense only if you have a number of these values which are all examples of some common category; but if you do, then this is usually a much better way to group them together and make them available as named constants.
As values in a structure such as an array or map:
val letterConstants = mapOf('a' to "A")
This approach makes good sense if you want to look values up programatically, but if you have a lot of values and want to avoid polluting namespaces, it can still make sense even if you only ever access it with constants.
It can also be loaded up (or extended) at runtime (e.g. from a file or database).
(I'm sure there are other approaches, too, that I haven't thought of.)
As I said, it's hard to recommend a particular implementation, because it'll depend upon the problem you're trying to solve: what the constants mean, what they're associated with, and how and where they'll be used.

The ability to override makes a different between the two. Take a look at the following example. speed might be a property that is constant across a class, but you might want a different constant value for different subclasses.
import kotlin.reflect.KClass
open class Animal{
companion object{
val speed : Int = 1
}
var x: Int = 0
fun move(){
x += speed
print("${this} moved to ${x}\n")
}
}
class Dog : Animal(){
companion object{
val speed : Int = 3
}
}
class Cat : Animal(){
companion object{
val speed : Int = 2
}
}
fun main()
{
val a = Animal()
a.move()
val c = Cat()
c.move()
val d = Dog()
d.move()
}
Output:
Animal#49c2faae moved to 1
Cat#17f052a3 moved to 1
Dog#685f4c2e moved to 1
This doesn't work because speed in move() always refer to Animal.speed. So in this case, you want speed be an instance member instead of static (or companion).
open class Animal{
open val speed : Int = 1
var x: Int = 0
fun move(){
x += speed
print("${this} moved to ${x}\n")
}
}
class Dog : Animal(){
override val speed : Int = 3
}
class Cat : Animal(){
override val speed : Int = 2
}
Output:
Animal#37f8bb67 moved to 1
Cat#1d56ce6a moved to 2
Dog#17f052a3 moved to 3
As a general practice, if a value is something that is absolutely independent to individual instances, make it static. In contrast, if a property sounds like a property belongs to the individual instance, not belongs to a type, even it is constant across every instances (for the time being), I would put it as an instance member as it is likely subject to change in future development. Though it is totally fine to make it static until you actually find the needs to change in the future. For the above example, you might even eventually change speed to var instead of val when you later find that every individual dog has different speed. Just do what suit your needs at the moment :)

Related

Enable Kotlin typealias type check with annotations

Kotlin has typealiases that are really handy where you want to have a good naming. However, there are some occasions where you want to have a typealias that is a little more that just an alias, you want it to enforce an actual compile time check, without the need of creating a new class.
This is what I would like to achieve:
typealias MyNum = Int
fun isMagical(num: MyNum) = num == 42
fun main() {
// Should fail/warn
isMagical(42)
// Should pass
isMagical(42 as MyNum)
// Should fail/warn
val x = 3
isMagical(x)
// Should pass
val y: MyNum = 3
isMagical(y)
}
I know that I could use an inline class to achieve that, but I need many of these types check and don't want to create a class for each of them.
Is it possible to that with an annotation? Like:
#Target(AnnotationTarget.TYPEALIAS)
annotation class StrongType
#StrongType
typealias MyNum = Int
and then have an annotation processor doing the check?
I would like to do something similar to Android #IntDef:
// Android way (performant but needs to manually annotates methods and list the options in the annotation)
#Retention(SOURCE)
#IntDef({NAVIGATION_MODE_STANDARD, NAVIGATION_MODE_LIST, NAVIGATION_MODE_TABS})
public #interface NavigationMode {}
public static final int NAVIGATION_MODE_STANDARD = 0;
public static final int NAVIGATION_MODE_LIST = 1;
public static final int NAVIGATION_MODE_TABS = 2;
// Enum way (not performant)
enum class NavMode constructor(val value: Int){
STANDARD(0),
LIST(1),
TABS(2)
}
// Inline class (performant but generating a lot of code)
inline class NavMode(val value: Int) {
companion object {
val STANDARD = NavMode(0)
val LIST = NavMode(1)
val TABS = NavMode(2)
}
}
// This is what I would like: performant, type check in methods without annotating them, clean code
#StrongType
typealias NavMode = Int
const val STANDARD: NavMode = 0
const val LIST: NavMode = 1
const val TABS: NavMode = 2
Please notice that this is not my real use case, I have lots of such enums to create while remaining performant (just like in android APIs).
What do you think it's the most viable way to achieve what I want?
Thanks
typealias MyNum = Int means that MyNum is another name for Int, that's pretty much it. Your "should warn" checks don't work because a MyNum is an Int and an Int is a MyNum - there's no difference between the two as far as the type system is concerned.
If you want the type system to consider them as separate things, then you actually need a separate type, and you'll run into issues if you just want a "special Int" because Int is a final class, you can't subclass it unfortunately. So you wouldn't just be able to treat MyInt as an Int.
Your examples with the IntDefs, enums etc are a bit different - there you definitely want a new type, with a limited set of possible, pre-defined values. Some languages would allow you to do this and still treat it as an Int - Kotlin doesn't though.
IntDefs are probably the closest to what you want, where you have to annotate everything because that's how it's being checked - it's outside of the type system. It's unwieldy but that's because it's bolted on.
Sealed classes can get you the kind of "clean" definition you want:
// or an interface
abstract class MyInt() {
abstract val value: Int
}
// put them inside the sealed class (in {}) if you want them named NavMode.LIST etc
sealed class NavMode(override val value: Int) : MyInt()
object STANDARD : NavMode(0)
object LIST : NavMode(1)
object TABS : NavMode(2)
but this is basically an enum without the enumeration (which you can take advantage of to ensure that each value is unique - there's no checking here, you could pass 0 for every value)
You said you have "efficiency constraints", but do you? Like, would having one instance of each enum in memory actually be a problem, or holding references to objects instead of primitives? IntDefs are (were? you don't hear much about it these days...) the recommended way to avoid those object allocations and references, but it's a tradeoff with way more complex code.
Enums are simple, and sometimes that's more important. I'd recommend doing some profiling and see how much of an impact using them would actually be, before you throw out what's probably the best solution. Just worth thinking about!
Annotation processors can't change the way compiler does his job. They can only generate new source code files (and give them to the compiler).
You can make annotation processor to generate inline class from annotated typealias (inline class MyNum(val v: Int)), but it's not enough. You also need to replace all Int to MyInt type casts with actual MyInt instances creation (42 as MyNum should become MyNum(42)) and all their usages with property access: (num == 42 should become num.v == 42).
And that's impossible, because:
Reflection API doesn't provide access to local variables of type (unless you explicitly marked them with some annotations too).
Annotation processors can’t modify existing files, they can only create new ones (by the way, typealias will be there too and will collide with generated inline class)
Probably it could be done with compiler plugin, but currently "Kotlin compiler plugins API is extremely experimental and is under heavy development"

Local Type Inference vs Instance

I've tried to scan JEP-286 about local type inference. I see that this works only for local variables - understood. So this does work indeed:
public class TestClass {
public static void main(String [] args){
var list = new ArrayList<>();
list.add("1");
System.out.println(list.get(0)); // 1
}
}
I do see that this on the other hand does not compile:
public class TestClass {
public var list = new ArrayList<>();
public static void main(String [] args){
}
}
It's obvious that it does not, since the JEP says so. Now my question:
It makes perfect sense for a public/protected member declared as var to fail, at least IMO. But why does it not compile even if it's private? I can only assume that you can still get a hold of that variable via reflection (and I can't get local fields like this)... And getting that variable would require a cast, well, a very confused cast probably.
The motivation for forbidding type inference for fields and method returns is that APIs should be stable; field access and method invocation are linked by descriptor at runtime, so things that cause subtle changes to inferred types could cause existing compiled clients to break in terrible ways if a change to the implementation caused the inferred type to change (modulo erasure.) So using this for implementation, but not for API, is a sensible guiding principle.
It is reasonable to ask "so, what about private fields and methods?" And indeed, we could well have chosen to do that. Like all design decisions, this is a tradeoff; it would enable inference to be used in more places, in exchange for more complexity in the user model. (I don't care as much about complexity in the spec or the compiler; that's our problem.) It is easier to reason about "inference for local variables yes, fields and methods no" than adding various epicyclic considerations like "but, fields and methods are OK if they are private". Drawing the line where we did also means that the compatibility consequences of changing a field or method from private to nonprivate doesn't have accidental interactions with inference.
So the short answer is, doing it this way makes the language simpler, without making the feature dramatically less useful.
Various reasons:
Visibility and type are orthogonal - one shouldn't impact the other. If private variables could be initialized with var, you'd had to change that when making them protected or public.
Because var uses the right-hand side to infer the type, such private fields always needed to be initialized right away. If moving initialization into a constructor, you'd have to make the type explicit.
With var the compiler can infer types that you can currently can't express in Java (e.g. intersection types like Comparable & Serializable). You might of course end up relying on those specific types and when you have to stop using var at some point for any reason, you might have to refactor quite a lot to keep your code working.
It’s not like it was entirely impossible to turn these variables into fields that can be inspected via Reflection. E.g., you can do
var l = new ArrayList<String>();
l.add("text");
System.out.println(l);
System.out.println(
new Object(){ { var x = l; } }.getClass().getDeclaredFields()[0].getGenericType()
);
In the current version, it just prints ArrayList, so the actual generic type has not been stored in the class file of the anonymous inner class and it’s unlikely that this will change, as supporting this introspection is not an the actual goal. It’s also just a special case that the type is denotable like ArrayList<String>. To illustrate a different case:
var acs = true? new StringBuilder(): CharBuffer.allocate(10);
acs.append("text");
acs.subSequence(1, 2);
System.out.println(
new Object(){ { var x = acs; } }.getClass().getDeclaredFields()[0].getGenericType()
);
The type of acs is an intersection type of Appendable and CharSequence, as demonstrated by invoking a method of either interface on it, but since it is not specified whether the compiler infers #1 extends Appendable&CharSequence or #1 extends CharSequence&Appendable, it is unspecified whether the code will print java.lang.Appendable or java.lang.CharSequence.
I don’t think that this is an issue for a synthetic field, but for an explicitly declared field, it might be.
However, I doubt that the expert group considered such impacts en detail. Instead, the decision not to support field declarations (and hence skip lengthy thinking about the implications) was made right from the start, as local variables always were the intended target for that feature. The number of local variables is much higher than the number of field declarations, so reducing the boilerplate for local variable declarations has the biggest impact.
Elaborating on Nicolai's answer (specifically his #2 reason), the proposed draft of JLS 10 states that both var e; and var g = null; are illegal for local variables, and for good reason; it's not clear from the right-hand side (or lack thereof) which type to infer for var.
Currently, non-final instance variables are automatically initialized depending on their type (primitives to 0 and false, and references to null, as I'm sure you already know). The inferred type of an instance variable would remain unclear unless it is initialized at declaration or within its respective class' constructor(s).
For that reason, I support allowing var to be used only when the variable is both private and final so we can ensure that it is initialized by the time that the class is created. Though, I cannot say how difficult this would be to implement.
It would be a reasonable decision to allow var for private fields (IMO). But omitting it makes the feature simpler.
Also it can be added in some future release after there is more experience with the local-only type inference, while removing a feature is much harder.

the static concept in java

I can't seem to understand the static key word (java) so I googled it up and viewed a thread in this website, though I'm sure the answer was conclusive and clear -it always is over here- I didn't seem to understand it for two reasons; I'm not a native English speaker and the language was a bit vague for me, and it lacked exemples of use in classes, instance of classes, interfaces (if possible), instance of interfaces and variables, lists and arrays ect.
I would really appreciate any help and please keep the English as simple as possible ;)
Thank you
Aditsan
Note from editor: Please note that the original poster is asking for examples, and is not a native English speaker as you provide answers. From the comments, it appears that OP doesn't understand the concept well enough to ask about the parts that don't make sense yet, so examples would be awesome! It may take extra details and multiple different explanations to find the combination of answers that works best.
I think it helps to understand what non-static means, i.e. field/methods/... that are declared without the keyword static.
Every field declared without the keyword static exists as part of an object. If you have two objects, each of these two objects has a field with possibly different contents:
class X {
int f;
}
X x1 = new X();
X x2 = new X();
x1.f = 5;
x2.f = 10;
// x1.f still is 5
However, static fields exist not per object, but per class. So in the following example, there is only one field g no matter how many (if any!) objects of class Y you have:
class Y {
static int g;
}
Y y1 = new Y();
Y y2 = new Y();
y1.g = 5;
y2.g = 10;
// y1.g is 10, because y1.g and y2.g mean the exact same thing
I personally think accesses to static fields should be made using the class (Y.g) instead of mentioning object instances (y1.g), so that the existence without any object instance is more explicit.
For methods the difference is that non-static methods are associated to an object instance, which can be accesses using this inside the method. When invoking a method declared with void m() you can access non-static (and static) fields of the object it is invoked on (so for x1.m() from the example above you can get to the field containing 5, for x2.m() you can access the field containing 10.
Static methods, however, can be invoked without having a (corresponding?) object around. If the declaration is static void n() inside class Y, you can call this method using Y.n() or y1.n() (if y1 is an instanceof Y, as above). Here, too, I prefer the first way of writing it down. Because in static methods you do not have a reference to the object instance (which is named this in non-static methods), you cannot access specific non-static fields from inside a static method - simply because there is no clear association to a specific object.
Regarding static and class definitions: This is rather advanced. You can declare a class inside another class. If the inner class is not static, every object instance of the inner class also has a reference to an instance of the outer class (which also means that you only can create an instance of the inner class if you have an instance of the outer class). This is not always what you want. By declaring the inner class static it just exists and can be used, more or less, like a class defined in its own file.
Basically, static implies/provides two things:
1) Only one instance of an "item" exists in the whole system (JVM)
2) Static "items" are also context/state free
To explain (1) above: Suppose you have a Meal Token issuer. No matter how many users/processes are there in the system, all tokens must be issued by a single "thing". You would develop that "thing" as static. You would then decide what that "thing" is. It could be a class that does a complex operation and implements a complex business rule. Then you would have a single static class issuing tokens in "a single uniform way" for the whole system. Some times, all that matters is that the token should be "static" but how it is issued could be non-static. Then you would simply implement a "Static" token counter.
To explain (2) : Going by what is said for (1) above, you can easily see why it is important that the static "things" operate in a context-free manner. That is, they do not know who calls them or for what purpose. When they are called, they do not borrow anything from the past, they need all inputs from the current caller, and they just do their job, and remember nothing for the future.

Why doesn't Python use C++/Java-like syntax to define instance variables?

This plagued me for hours, as I am from the C++ world. I finally found out what was going on, but I do not know why this is the default behaviour. I'd like to understand why the language is designed this way.
I wanted an instance variable mem. So I tried this:
class x(object):
mem = []
obj = x()
obj.mem.append(1)
print(obj.mem)
objTWO = x()
objTWO.mem.append(2)
print(objTWO.mem)
Which prints this:
[1]
[1, 2]
Whereas:
class x(object):
def __init__(self):
self.mem = []
obj = x()
obj.mem.append(1)
print(obj.mem)
objTWO = x()
objTWO.mem.append(2)
print(objTWO.mem)
prints
[1]
[2]
Why would the first be the default behaviour? What is the intuition here, since its the opposite of how many mainstream OO languages work (they introduce the static keyword for the top case, which makes you explicitly say you want a static variable)? To newcomers to Python, this is a surprise.
Also, it seems you are allowed to have an instance variable and a class variable with the same name:
class x(object):
mem = []
def __init__(self):
self.mem = []
I would have to run this to figure out what would be printed. I can't even guess!
The intuition is that in Python, everything is an object, including classes themselves. There's no such thing as a "static" keyword in Python; there are classes, which are objects, and those classes have attributes. Everything that appears in the class definition is a class attribute -- that includes both methods and other kinds of attributes.
The benefit of this design is simplicity and consistency. There's no distinction between public or private, or between static and non-static attributes. The distinction between class and instance attributes emerges naturally through the class constructor. When __init__ is called (indirectly via ClassName(params)), it receives a new instance of the class via the self parameter, and it then modifies that instance directly. Everything happens explicitly, through constructs that are already defined -- you don't have to understand any new syntax or new keywords to see what's happening when an instance is created.
Then all you have to understand is Python's model for attribute lookup. It works almost identically to PATH resolution in most shells. In bash, for example, when you execute a command (ls), the first entry in the path is searched, then the second and so on, and the first version of the command that's found is the one that's executed. But in this case, the path looks like this (at least in simple cases with single inheritance):
instance; class; superclass; superclass; ... and so on
This really isn't so different from name resolution in nested scopes in c or c++. You complain:
Even worse is that it seems you are allowed to have an instance variable and a class variable with the same name.
But is that really any more confusing than the fact that c allows you to define int i; in a block, create an inner block, and then define another int i; that masks the original?
I agree that it's counter-intuitive, but it's got a good use -- aliasing functions.
This is from a library I wrote a while back, edited down for length
...
class UndrawnTurtle():
"""Acts just like the turtle package, but without bringing up a window to show it."""
...
def forward(self, distance):
angle_radians = math.radians(self.angle)
self.x = self.x + math.cos(angle_radians) * distance
self.y = self.y + math.sin(angle_radians) * distance
self._visit()
...
# Now for some aliases. Everything that's implemented in this class
# should be aliased the same way as the actual api.
fd = forward
...

Java variable declaration

Ok, this might be basic, but I want good programmers' opinions on this.
What is a good way to handle variables in a small class file?
I like modularizing methods and keeping methods that do really specific things.
I end up passing variables between those methods. Is it a good practice to make variables used across many methods as member variables? Or is it better to pass the variables to methods?
For example:
class Test{
somefunction(int a, int b, int c, int d) {
doSomething(a, b, c);
doOneMoreThing(a, c, d);
}
void doSomething(int a, int b, int c) { }
void doOneMoreThing(int a, int c, int d) { }
}
In the above example, do you think the variables should be kept as member variables?
Please explain why one methodology is preferred over the other.
Do you need to keep the variables around between method calls, and reuse their value? If so, they should be class members. (At least in some class - not necessarily this one.)
Otherwise it is somewhat a matter of taste. One important factor is though that local variables don't add state to the object, which can be useful if it is used concurrently. Keeping all variables local may even allow you to make your class immutable, which usually makes it automatically thread-safe. But even in a single-threaded environment an immutable class is easier to understand and maintain.
OTOH passing lots of parameters around can be awkward. You may consider introducing a Parameter Object to alleviate this problem.
If I have some variables that I would end up passing to a bunch of private methods, I'll often move them into a private inner worker class.
Instead of
class Foo {
public doSomething(...) {
// some setup
doSomethingRecursively(a, b, c);
}
private void doSomethingRecursively(A a, B b, C c) {
if (baseCase) { ... }
doSomethingRecursively(a + 1, b, c);
}
}
I'll move the variables that never difference into properties on a worker.
class Foo {
public doSomething(...) {
// some setup
new AppropriatelyNamedHelper(b, c).doSomethingRecursively(a);
}
private static final class AppropriatelyNamedHelper {
final B b;
final C c;
AppropriatelyNamedHelper(B b, C c) {
this.b = b;
this.c = c;
}
void doSomethingRecursively(A a) {
if (baseCase) { ... }
doSomethingRecursively(a + 1);
}
}
}
This makes it clear to a reviewer what in each scope is invariant within that scope.
Member variables should exist to maintain some kind of state in a class. If your class maintains state then definitely define member variables for those things you need to track. If a class does not maintain state then there is no reason to make things members (I have had to debug legacy code where variables should not have been made members but were and it was causing errors when making multiple calls to the object because the state was unpredictable).
However, while you might like "modularizing" functionality, read up on coupling vs. cohesion. There is a balance to be struck between having too much functionality in a class but fewer dependencies and having very little but highly specific functionality and lots of dependencies.
Having useless member variables is usually regarded to as bad design.
But you can (and should) combine multiple variable sets into a new class if you use that variables in lots of methods.
If you don't care about the state of the object, then passing the variables to the method is fine. In that case, I would use a static modifier on the method, then you don't have to instansiate the class and you can call the method like so:
Test.doSomething(1, 2, 3);
Instance Variables: Their values are unique to each instance of a class. When an object is allocated in the heap, there is a slot in it for each instance variable value. Therefore an instance variable is created when an object is created and destroyed when the object is destroyed.
Class Variable: The Class variables are declared with a static keyword/modifier.There is only one copy of class variable no matter how many times the class is instantiated. They are stored in static memory.
Local variables: Only accessible within the method they are declared. When a method is entered, an area is pushed onto the call stack. This area contains slots for each local variable and parameter. When the method is called, the parameter slots are initialized to the parameter values. When the method exits, this area is popped off the stack and the memory becomes available for the next called method.
If you are going to reuse the variables, then you can declare them as class variables. If not, then they should be local variables defined in their respective methods.
First of all Somefunction(... } is a syntax error. Second, method names should start with lower case letters, and class names should start with upper case. Third, we have no idea what the best way is without knowing what these methods do, what they're used for, and where their parameters come from
Depends on how often you have to change your code (or you should think about how often you're going to change it when you design it). If the signature changes you have to change it in a lot of places. That means more code to test even when you refactor the signature. I would err on the side of creating member variables and encapsulating.

Categories