Let's say we have the following block of code:
if (thing instanceof ObjectType) {
((ObjectType)thing).operation1();
((ObjectType)thing).operation2();
((ObjectType)thing).operation3();
}
All the typecasting makes the code look ugly, is there a way of declaring 'thing' as ObjectType inside that block of code? I know I could do
OjectType differentThing = (ObjectType)thing;
and work with 'differentThing' from then on, but that brings some confusion to the code. Is there a nicer way of doing this, possibly something like
if (thing instanceof ObjectType) {
(ObjectType)thing; //this would declare 'thing' to be an instance of ObjectType
thing.operation1();
thing.operation2();
thing.operation3();
}
I am pretty sure this question has been asked in the past, I couldn't find it though. Feel free to point me to the possible duplicate.
Declaring (Creating) Variablestype variableName = value; Where type is one of Java's types (such as int or String ), and variableName is the name of the variable (such as x or name). The equal sign is used to assign values to the variable.
Assigning Values to VariablesThe equal sign (=) is used to assign values to variables.
Python is a dynamically-typed language, which means that we don't have to specify data types when we create variables and functions. While this reduces the amount of code we need to write, the workload that we save is in turn added to the next developer that needs to understand and debug the existing function!
Specify a Variable Type Casting in python is therefore done using constructor functions: int() - constructs an integer number from an integer literal, a float literal (by rounding down to the previous whole number), or a string literal (providing the string represents a whole number)
No, once a variable is declared, the type of that variable is fixed. I believe that changing the type of a variable (potentially temporarily) would bring far more confusion than the:
ObjectType differentThing = (ObjectType)thing;
approach you believe to be confusing. This approach is widely used and idiomatic - where it's required at all, of course. (This is typically a bit of a code smell.)
Another option is to extract a method:
if (thing instanceof ObjectType) {
performOperations((ObjectType) thing);
}
...
private void performOperations(ObjectType thing) {
thing.operation1();
thing.operation2();
thing.operation3();
}
Once a variable is declared, it's type cannot change. Your differentThing
approach is the correct one:
if (thing instanceof ObjectType) {
OjectType differentThing = (ObjectType)thing;
differentThing.operation1();
differentThing.operation2();
differentThing.operation3();
}
I wouldn't call it confusing, either: as long as the scope of the differentThing
variable is limited to the body of the if
operator, it is clear to the readers what is going on.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With