Jacobian Jacobian - 1 year ago 41
Java Question

How to avoid argument-order dependencies in statically typed languages like Java or C#

I'm from Python, Ruby and PHP world and one of techniques that I try to follow is removing argument-order dependencies from my code. This is a short demonstration of this technique implemented in Ruby:

class Gear
attr_reader :chainring, :cog, :wheel
def initialize(args)
@chainring = args[:chainring]
@cog = args[:cog]
@wheel = args[:wheel]

:chainring => 52,
:cog => 11,
:wheel => Wheel.new(26, 1.5)).gear_inches

As you can see the client code does not need to know the order of arguments for initializing a Gear instance and I like that. But now I just wonder how the same thing is implemented in statically typed languages like Java and I also wonder whether people try to follow such techniques or not in this kind of languages. If someone can share their experience and show some demo-code (let it be in Java, C# etc.), that would be great.


If it is only for creating new object, you can use Object Initializer :

public class Gear
    public int Chainring { get; set; }
    public int Cog { get; set; }
    public int Wheel { get; set; }

// ...
var gear = new Gear
    // could be in any order, 
    Cog = 11,
    Chainring = 52,