Skip to content
This repository was archived by the owner on Aug 12, 2024. It is now read-only.
This repository was archived by the owner on Aug 12, 2024. It is now read-only.

This isn't a switch case... #7

Description

@LeFisheAuCoordLogger

What you have here is an autistic way of slowing down the program via an object oriented approach to a "switch case", which is really just a brute force/linear search as you keep adding cases until you find the matching value. This means that if we have a value that matches with the last "case", it will take longer for the program to reach it.

Switch cases are meant to be fast, they take an integer value, index a constant jump table (only initialized once in the program) and then jump to the corresponding instruction address. This indexing is done in a constant time complexity meaning every case takes the same time to be matched.
In addition, if the switch case isn't broken, it falls through to the next case.

In a higher level (Java) this would be:

switch(5){
case 0:
case 1:
    System.out.println("Case 0 or 1");
    break;
default:
    System.out.println("Default case");
case 5:
    System.out.println("Case 5");
}

The most similar approach in Lua (efficiency wise) is initializing a constant table with functions as values and handle fall-throughs recursively:

function doTableSwitch(value,cases)
	local case = cases[value];
	local function FallThrough(case)
		return cases[case](FallThrough);
	end
	return (case or cases.default)(FallThrough);
end

cases = {
	[0] = function(FallThrough)
		return FallThrough(1);
	end,
	[1] = function(FallThrough)
		print("Case 0 or 1");
	end,
	default = function(FallThrough)
		print("Default case");
		return FallThrough(5);
	end,
	[5] = function(FallThrough)
		print("Case 5");
	end,
}

doTableSwitch(5,cases) 

I hope this clears up everything, consider renaming your "Switch Case" to "Redundant Object Oriented If Else".

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions