[Kafka] Czy Kafka ma czysty kod?

0

Weźmy sobie konstruktory takiego KafkaConsumer. Inicjowanie różnych pól napisane jest ciągiem, wielkie traje (try) na kilkadziesiąt linijek. Czy to nie powinno być wydzielone chociaż do prywatnych metod?

public KafkaConsumer(Map<String, Object> configs) {
        this((Map)configs, (Deserializer)null, (Deserializer)null);
    }

    public KafkaConsumer(Map<String, Object> configs, Deserializer<K> keyDeserializer, Deserializer<V> valueDeserializer) {
        this(new ConsumerConfig(ConsumerConfig.addDeserializerToConfig(configs, keyDeserializer, valueDeserializer)), keyDeserializer, valueDeserializer);
    }

    public KafkaConsumer(Properties properties) {
        this((Properties)properties, (Deserializer)null, (Deserializer)null);
    }

    public KafkaConsumer(Properties properties, Deserializer<K> keyDeserializer, Deserializer<V> valueDeserializer) {
        this(new ConsumerConfig(ConsumerConfig.addDeserializerToConfig(properties, keyDeserializer, valueDeserializer)), keyDeserializer, valueDeserializer);
    }

    private KafkaConsumer(ConsumerConfig config, Deserializer<K> keyDeserializer, Deserializer<V> valueDeserializer) {
        this.closed = false;
        this.currentThread = new AtomicLong(-1L);
        this.refcount = new AtomicInteger(0);

        try {
            GroupRebalanceConfig groupRebalanceConfig = new GroupRebalanceConfig(config, ProtocolType.CONSUMER);
            this.groupId = Optional.ofNullable(groupRebalanceConfig.groupId);
            this.clientId = buildClientId(config.getString("client.id"), groupRebalanceConfig);
            LogContext logContext;
            if (groupRebalanceConfig.groupInstanceId.isPresent()) {
                logContext = new LogContext("[Consumer instanceId=" + (String)groupRebalanceConfig.groupInstanceId.get() + ", clientId=" + this.clientId + ", groupId=" + (String)this.groupId.orElse("null") + "] ");
            } else {
                logContext = new LogContext("[Consumer clientId=" + this.clientId + ", groupId=" + (String)this.groupId.orElse("null") + "] ");
            }

            this.log = logContext.logger(this.getClass());
            boolean enableAutoCommit = config.getBoolean("enable.auto.commit");
            if (!this.groupId.isPresent()) {
                if (!config.originals().containsKey("enable.auto.commit")) {
                    enableAutoCommit = false;
                } else if (enableAutoCommit) {
                    throw new InvalidConfigurationException("enable.auto.commit cannot be set to true when default group id (null) is used.");
                }
            } else if (((String)this.groupId.get()).isEmpty()) {
                this.log.warn("Support for using the empty group id by consumers is deprecated and will be removed in the next major release.");
            }

            this.log.debug("Initializing the Kafka consumer");
            this.requestTimeoutMs = (long)config.getInt("request.timeout.ms");
            this.defaultApiTimeoutMs = config.getInt("default.api.timeout.ms");
            this.time = Time.SYSTEM;
            this.metrics = buildMetrics(config, this.time, this.clientId);
            this.retryBackoffMs = config.getLong("retry.backoff.ms");
            Map<String, Object> userProvidedConfigs = config.originals();
            userProvidedConfigs.put("client.id", this.clientId);
            List<ConsumerInterceptor<K, V>> interceptorList = (new ConsumerConfig(userProvidedConfigs, false)).getConfiguredInstances("interceptor.classes", ConsumerInterceptor.class);
            this.interceptors = new ConsumerInterceptors(interceptorList);
            if (keyDeserializer == null) {
                this.keyDeserializer = (Deserializer)config.getConfiguredInstance("key.deserializer", Deserializer.class);
                this.keyDeserializer.configure(config.originals(), true);
            } else {
                config.ignore("key.deserializer");
                this.keyDeserializer = keyDeserializer;
            }

            if (valueDeserializer == null) {
                this.valueDeserializer = (Deserializer)config.getConfiguredInstance("value.deserializer", Deserializer.class);
                this.valueDeserializer.configure(config.originals(), false);
            } else {
                config.ignore("value.deserializer");
                this.valueDeserializer = valueDeserializer;
            }

            OffsetResetStrategy offsetResetStrategy = OffsetResetStrategy.valueOf(config.getString("auto.offset.reset").toUpperCase(Locale.ROOT));
            this.subscriptions = new SubscriptionState(logContext, offsetResetStrategy);
            ClusterResourceListeners clusterResourceListeners = this.configureClusterResourceListeners(keyDeserializer, valueDeserializer, this.metrics.reporters(), interceptorList);
            this.metadata = new ConsumerMetadata(this.retryBackoffMs, config.getLong("metadata.max.age.ms"), !config.getBoolean("exclude.internal.topics"), config.getBoolean("allow.auto.create.topics"), this.subscriptions, logContext, clusterResourceListeners);
            List<InetSocketAddress> addresses = ClientUtils.parseAndValidateAddresses(config.getList("bootstrap.servers"), config.getString("client.dns.lookup"));
            this.metadata.bootstrap(addresses);
            String metricGrpPrefix = "consumer";
            FetcherMetricsRegistry metricsRegistry = new FetcherMetricsRegistry(Collections.singleton("client-id"), metricGrpPrefix);
            ChannelBuilder channelBuilder = ClientUtils.createChannelBuilder(config, this.time, logContext);
            IsolationLevel isolationLevel = IsolationLevel.valueOf(config.getString("isolation.level").toUpperCase(Locale.ROOT));
            Sensor throttleTimeSensor = Fetcher.throttleTimeSensor(this.metrics, metricsRegistry);
            int heartbeatIntervalMs = config.getInt("heartbeat.interval.ms");
            ApiVersions apiVersions = new ApiVersions();
            NetworkClient netClient = new NetworkClient(new Selector(config.getLong("connections.max.idle.ms"), this.metrics, this.time, metricGrpPrefix, channelBuilder, logContext), this.metadata, this.clientId, 100, config.getLong("reconnect.backoff.ms"), config.getLong("reconnect.backoff.max.ms"), config.getInt("send.buffer.bytes"), config.getInt("receive.buffer.bytes"), config.getInt("request.timeout.ms"), ClientDnsLookup.forConfig(config.getString("client.dns.lookup")), this.time, true, apiVersions, throttleTimeSensor, logContext);
            this.client = new ConsumerNetworkClient(logContext, netClient, this.metadata, this.time, this.retryBackoffMs, config.getInt("request.timeout.ms"), heartbeatIntervalMs);
            this.assignors = PartitionAssignorAdapter.getAssignorInstances(config.getList("partition.assignment.strategy"), config.originals());
            this.coordinator = !this.groupId.isPresent() ? null : new ConsumerCoordinator(groupRebalanceConfig, logContext, this.client, this.assignors, this.metadata, this.subscriptions, this.metrics, metricGrpPrefix, this.time, enableAutoCommit, config.getInt("auto.commit.interval.ms"), this.interceptors);
            this.fetcher = new Fetcher(logContext, this.client, config.getInt("fetch.min.bytes"), config.getInt("fetch.max.bytes"), config.getInt("fetch.max.wait.ms"), config.getInt("max.partition.fetch.bytes"), config.getInt("max.poll.records"), config.getBoolean("check.crcs"), config.getString("client.rack"), this.keyDeserializer, this.valueDeserializer, this.metadata, this.subscriptions, this.metrics, metricsRegistry, this.time, this.retryBackoffMs, this.requestTimeoutMs, isolationLevel, apiVersions);
            this.kafkaConsumerMetrics = new KafkaConsumerMetrics(this.metrics, metricGrpPrefix);
            config.logUnused();
            AppInfoParser.registerAppInfo("kafka.consumer", this.clientId, this.metrics, this.time.milliseconds());
            this.log.debug("Kafka consumer initialized");
        } catch (Throwable var20) {
            if (this.log != null) {
                this.close(0L, true);
            }

            throw new KafkaException("Failed to construct kafka consumer", var20);
        }
    }

    KafkaConsumer(LogContext logContext, String clientId, ConsumerCoordinator coordinator, Deserializer<K> keyDeserializer, Deserializer<V> valueDeserializer, Fetcher<K, V> fetcher, ConsumerInterceptors<K, V> interceptors, Time time, ConsumerNetworkClient client, Metrics metrics, SubscriptionState subscriptions, ConsumerMetadata metadata, long retryBackoffMs, long requestTimeoutMs, int defaultApiTimeoutMs, List<ConsumerPartitionAssignor> assignors, String groupId) {
        this.closed = false;
        this.currentThread = new AtomicLong(-1L);
        this.refcount = new AtomicInteger(0);
        this.log = logContext.logger(this.getClass());
        this.clientId = clientId;
        this.coordinator = coordinator;
        this.keyDeserializer = keyDeserializer;
        this.valueDeserializer = valueDeserializer;
        this.fetcher = fetcher;
        this.interceptors = (ConsumerInterceptors)Objects.requireNonNull(interceptors);
        this.time = time;
        this.client = client;
        this.metrics = metrics;
        this.subscriptions = subscriptions;
        this.metadata = metadata;
        this.retryBackoffMs = retryBackoffMs;
        this.requestTimeoutMs = requestTimeoutMs;
        this.defaultApiTimeoutMs = defaultApiTimeoutMs;
        this.assignors = assignors;
        this.groupId = Optional.ofNullable(groupId);
        this.kafkaConsumerMetrics = new KafkaConsumerMetrics(metrics, "consumer");
    }
3

Popraw, zrób Pull Requesta i wrzuć na forum to zerkniemy. Przy open source ciężko zachować dobrą jakość niestety, jeszcze zależy od aktywności ownerów repo.

1

Niezły kupsztal.

Ktoś coś dodaje, to boi się ruszyć tej kupy zależności, to dodaje nowego ifa i lecimy.

2

Nic nie ma czystego kodu. Czysty kod produkują tylko mądrale z tego forum, ale nikt tego nie widział, bo tego kodu nie pokazują, tylko się mądrzą. Android ma straszliwy kod np, java też, .net tak samo. To czemu Kafka ma mieć czysty kod dla odmiany?

Zrób test: weź kawałek kodu z jakiegokolwiek projektu czy biblioteki używanej przez miliony programistów, wytnij go i daj tu do oceny. Zostaniesz zmieszany z błotem, że wszystko źle.

0

No, ale Kafkę napisał Linkedin, więc to nie był open source od początku.
To z czego polecalibyście się uczyć?
Zasubskrybowałem Kafkę i czytam te ich Jiry i commity, ale skoro kaszana jest to lepiej żebym nie brał przykładu. Może jakieś googlowe projekty będą lepsze?

O to mi się podoba:

static {
        DEFAULT_ISOLATION_LEVEL = IsolationLevel.READ_UNCOMMITTED.toString().toLowerCase(Locale.ROOT);
        CONFIG = (new ConfigDef()).define("bootstrap.servers", Type.LIST, Collections.emptyList(), new NonNullValidator(), Importance.HIGH, "A list of host/port pairs to use for establishing the initial connection to the Kafka cluster. The client will make use of all servers irrespective of which servers are specified here for bootstrapping&mdash;this list only impacts the initial hosts used to discover the full set of servers. This list should be in the form <code>host1:port1,host2:port2,...</code>. Since these servers are just used for the initial connection to discover the full cluster membership (which may change dynamically), this list need not contain the full set of servers (you may want more than one, though, in case a server is down).").define("client.dns.lookup", Type.STRING, ClientDnsLookup.DEFAULT.toString(), ValidString.in(new String[]{ClientDnsLookup.DEFAULT.toString(), ClientDnsLookup.USE_ALL_DNS_IPS.toString(), ClientDnsLookup.RESOLVE_CANONICAL_BOOTSTRAP_SERVERS_ONLY.toString()}), Importance.MEDIUM, "Controls how the client uses DNS lookups. If set to <code>use_all_dns_ips</code> then, when the lookup returns multiple IP addresses for a hostname, they will all be attempted to connect to before failing the connection. Applies to both bootstrap and advertised servers. If the value is <code>resolve_canonical_bootstrap_servers_only</code> each entry will be resolved and expanded into a list of canonical names.").define("group.id", Type.STRING, (Object)null, Importance.HIGH, "A unique string that identifies the consumer group this consumer belongs to. This property is required if the consumer uses either the group management functionality by using <code>subscribe(topic)</code> or the Kafka-based offset management strategy.").define("group.instance.id", Type.STRING, (Object)null, Importance.MEDIUM, "A unique identifier of the consumer instance provided by the end user. Only non-empty strings are permitted. If set, the consumer is treated as a static member, which means that only one instance with this ID is allowed in the consumer group at any time. This can be used in combination with a larger session timeout to avoid group rebalances caused by transient unavailability (e.g. process restarts). If not set, the consumer will join the group as a dynamic member, which is the traditional behavior.").define("session.timeout.ms", Type.INT, 10000, Importance.HIGH, "The timeout used to detect client failures when using Kafka's group management facility. The client sends periodic heartbeats to indicate its liveness to the broker. If no heartbeats are received by the broker before the expiration of this session timeout, then the broker will remove this client from the group and initiate a rebalance. Note that the value must be in the allowable range as configured in the broker configuration by <code>group.min.session.timeout.ms</code> and <code>group.max.session.timeout.ms</code>.").define("heartbeat.interval.ms", Type.INT, 3000, Importance.HIGH, "The expected time between heartbeats to the consumer coordinator when using Kafka's group management facilities. Heartbeats are used to ensure that the consumer's session stays active and to facilitate rebalancing when new consumers join or leave the group. The value must be set lower than <code>session.timeout.ms</code>, but typically should be set no higher than 1/3 of that value. It can be adjusted even lower to control the expected time for normal rebalances.").define("partition.assignment.strategy", Type.LIST, Collections.singletonList(RangeAssignor.class), new NonNullValidator(), Importance.MEDIUM, "A list of class names or class types, ordered by preference, of supported assignors responsible for the partition assignment strategy that the client will use to distribute partition ownership amongst consumer instances when group management is used. Implementing the <code>org.apache.kafka.clients.consumer.ConsumerPartitionAssignor</code> interface allows you to plug in a custom assignment strategy.").define("metadata.max.age.ms", Type.LONG, 300000, Range.atLeast(0), Importance.LOW, "The period of time in milliseconds after which we force a refresh of metadata even if we haven't seen any partition leadership changes to proactively discover any new brokers or partitions.").define("enable.auto.commit", Type.BOOLEAN, true, Importance.MEDIUM, "If true the consumer's offset will be periodically committed in the background.").define("auto.commit.interval.ms", Type.INT, 5000, Range.atLeast(0), Importance.LOW, "The frequency in milliseconds that the consumer offsets are auto-committed to Kafka if <code>enable.auto.commit</code> is set to <code>true</code>.").define("client.id", Type.STRING, "", Importance.LOW, "An id string to pass to the server when making requests. The purpose of this is to be able to track the source of requests beyond just ip/port by allowing a logical application name to be included in server-side request logging.").define("client.rack", Type.STRING, "", Importance.LOW, "A rack identifier for this client. This can be any string value which indicates where this client is physically located. It corresponds with the broker config 'broker.rack'").define("max.partition.fetch.bytes", Type.INT, 1048576, Range.atLeast(0), Importance.HIGH, "The maximum amount of data per-partition the server will return. Records are fetched in batches by the consumer. If the first record batch in the first non-empty partition of the fetch is larger than this limit, the batch will still be returned to ensure that the consumer can make progress. The maximum record batch size accepted by the broker is defined via <code>message.max.bytes</code> (broker config) or <code>max.message.bytes</code> (topic config). See fetch.max.bytes for limiting the consumer request size.").define("send.buffer.bytes", Type.INT, 131072, Range.atLeast(-1), Importance.MEDIUM, "The size of the TCP send buffer (SO_SNDBUF) to use when sending data. If the value is -1, the OS default will be used.").define("receive.buffer.bytes", Type.INT, 65536, Range.atLeast(-1), Importance.MEDIUM, "The size of the TCP receive buffer (SO_RCVBUF) to use when reading data. If the value is -1, the OS default will be used.").define("fetch.min.bytes", Type.INT, 1, Range.atLeast(0), Importance.HIGH, "The minimum amount of data the server should return for a fetch request. If insufficient data is available the request will wait for that much data to accumulate before answering the request. The default setting of 1 byte means that fetch requests are answered as soon as a single byte of data is available or the fetch request times out waiting for data to arrive. Setting this to something greater than 1 will cause the server to wait for larger amounts of data to accumulate which can improve server throughput a bit at the cost of some additional latency.").define("fetch.max.bytes", Type.INT, 52428800, Range.atLeast(0), Importance.MEDIUM, "The maximum amount of data the server should return for a fetch request. Records are fetched in batches by the consumer, and if the first record batch in the first non-empty partition of the fetch is larger than this value, the record batch will still be returned to ensure that the consumer can make progress. As such, this is not a absolute maximum. The maximum record batch size accepted by the broker is defined via <code>message.max.bytes</code> (broker config) or <code>max.message.bytes</code> (topic config). Note that the consumer performs multiple fetches in parallel.").define("fetch.max.wait.ms", Type.INT, 500, Range.atLeast(0), Importance.LOW, "The maximum amount of time the server will block before answering the fetch request if there isn't sufficient data to immediately satisfy the requirement given by fetch.min.bytes.").define("reconnect.backoff.ms", Type.LONG, 50L, Range.atLeast(0L), Importance.LOW, "The base amount of time to wait before attempting to reconnect to a given host. This avoids repeatedly connecting to a host in a tight loop. This backoff applies to all connection attempts by the client to a broker.").define("reconnect.backoff.max.ms", Type.LONG, 1000L, Range.atLeast(0L), Importance.LOW, "The maximum amount of time in milliseconds to wait when reconnecting to a broker that has repeatedly failed to connect. If provided, the backoff per host will increase exponentially for each consecutive connection failure, up to this maximum. After calculating the backoff increase, 20% random jitter is added to avoid connection storms.").define("retry.backoff.ms", Type.LONG, 100L, Range.atLeast(0L), Importance.LOW, "The amount of time to wait before attempting to retry a failed request to a given topic partition. This avoids repeatedly sending requests in a tight loop under some failure scenarios.").define("auto.offset.reset", Type.STRING, "latest", ValidString.in(new String[]{"latest", "earliest", "none"}), Importance.MEDIUM, "What to do when there is no initial offset in Kafka or if the current offset does not exist any more on the server (e.g. because that data has been deleted): <ul><li>earliest: automatically reset the offset to the earliest offset<li>latest: automatically reset the offset to the latest offset</li><li>none: throw exception to the consumer if no previous offset is found for the consumer's group</li><li>anything else: throw exception to the consumer.</li></ul>").define("check.crcs", Type.BOOLEAN, true, Importance.LOW, "Automatically check the CRC32 of the records consumed. This ensures no on-the-wire or on-disk corruption to the messages occurred. This check adds some overhead, so it may be disabled in cases seeking extreme performance.").define("metrics.sample.window.ms", Type.LONG, 30000, Range.atLeast(0), Importance.LOW, "The window of time a metrics sample is computed over.").define("metrics.num.samples", Type.INT, 2, Range.atLeast(1), Importance.LOW, "The number of samples maintained to compute metrics.").define("metrics.recording.level", Type.STRING, RecordingLevel.INFO.toString(), ValidString.in(new String[]{RecordingLevel.INFO.toString(), RecordingLevel.DEBUG.toString()}), Importance.LOW, "The highest recording level for metrics.").define("metric.reporters", Type.LIST, Collections.emptyList(), new NonNullValidator(), Importance.LOW, "A list of classes to use as metrics reporters. Implementing the <code>org.apache.kafka.common.metrics.MetricsReporter</code> interface allows plugging in classes that will be notified of new metric creation. The JmxReporter is always included to register JMX statistics.").define("key.deserializer", Type.CLASS, Importance.HIGH, "Deserializer class for key that implements the <code>org.apache.kafka.common.serialization.Deserializer</code> interface.").define("value.deserializer", Type.CLASS, Importance.HIGH, "Deserializer class for value that implements the <code>org.apache.kafka.common.serialization.Deserializer</code> interface.").define("request.timeout.ms", Type.INT, 30000, Range.atLeast(0), Importance.MEDIUM, "The configuration controls the maximum amount of time the client will wait for the response of a request. If the response is not received before the timeout elapses the client will resend the request if necessary or fail the request if retries are exhausted.").define("default.api.timeout.ms", Type.INT, 60000, Range.atLeast(0), Importance.MEDIUM, "Specifies the timeout (in milliseconds) for client APIs. This configuration is used as the default timeout for all client operations that do not specify a <code>timeout</code> parameter.").define("connections.max.idle.ms", Type.LONG, 540000, Importance.MEDIUM, "Close idle connections after the number of milliseconds specified by this config.").define("interceptor.classes", Type.LIST, Collections.emptyList(), new NonNullValidator(), Importance.LOW, "A list of classes to use as interceptors. Implementing the <code>org.apache.kafka.clients.consumer.ConsumerInterceptor</code> interface allows you to intercept (and possibly mutate) records received by the consumer. By default, there are no interceptors.").define("max.poll.records", Type.INT, 500, Range.atLeast(1), Importance.MEDIUM, "The maximum number of records returned in a single call to poll().").define("max.poll.interval.ms", Type.INT, 300000, Range.atLeast(1), Importance.MEDIUM, "The maximum delay between invocations of poll() when using consumer group management. This places an upper bound on the amount of time that the consumer can be idle before fetching more records. If poll() is not called before expiration of this timeout, then the consumer is considered failed and the group will rebalance in order to reassign the partitions to another member. For consumers using a non-null <code>group.instance.id</code> which reach this timeout, partitions will not be immediately reassigned. Instead, the consumer will stop sending heartbeats and partitions will be reassigned after expiration of <code>session.timeout.ms</code>. This mirrors the behavior of a static consumer which has shutdown.").define("exclude.internal.topics", Type.BOOLEAN, true, Importance.MEDIUM, "Whether internal topics matching a subscribed pattern should be excluded from the subscription. It is always possible to explicitly subscribe to an internal topic.").defineInternal("internal.leave.group.on.close", Type.BOOLEAN, true, Importance.LOW).define("isolation.level", Type.STRING, DEFAULT_ISOLATION_LEVEL, ValidString.in(new String[]{IsolationLevel.READ_COMMITTED.toString().toLowerCase(Locale.ROOT), IsolationLevel.READ_UNCOMMITTED.toString().toLowerCase(Locale.ROOT)}), Importance.MEDIUM, "Controls how to read messages written transactionally. If set to <code>read_committed</code>, consumer.poll() will only return transactional messages which have been committed. If set to <code>read_uncommitted</code>' (the default), consumer.poll() will return all messages, even transactional messages which have been aborted. Non-transactional messages will be returned unconditionally in either mode. <p>Messages will always be returned in offset order. Hence, in  <code>read_committed</code> mode, consumer.poll() will only return messages up to the last stable offset (LSO), which is the one less than the offset of the first open transaction. In particular any messages appearing after messages belonging to ongoing transactions will be withheld until the relevant transaction has been completed. As a result, <code>read_committed</code> consumers will not be able to read up to the high watermark when there are in flight transactions.</p><p> Further, when in <code>read_committed</code> the seekToEnd method will return the LSO").define("allow.auto.create.topics", Type.BOOLEAN, true, Importance.MEDIUM, "Allow automatic topic creation on the broker when subscribing to or assigning a topic. A topic being subscribed to will be automatically created only if the broker allows for it using `auto.create.topics.enable` broker configuration. This configuration must be set to `false` when using brokers older than 0.11.0").define("security.providers", Type.STRING, (Object)null, Importance.LOW, "A list of configurable creator classes each returning a provider implementing security algorithms. These classes should implement the <code>org.apache.kafka.common.security.auth.SecurityProviderCreator</code> interface.").define("security.protocol", Type.STRING, "PLAINTEXT", Importance.MEDIUM, CommonClientConfigs.SECURITY_PROTOCOL_DOC).withClientSslSupport().withClientSaslSupport();
    }
1

@Meini: nie przesadzaj. Oczywiście że są projekty w których jest czysty kod. Przy czym "czysty" to pojęcie względne i zawsze znajdzie się coś do poprawy lub co inna osoba zastąpiła by alternatywnym kodem. Ale tak ogólnie to jak najbardziej stosuje się czysty kod w różnych projektach. Chociażby w projekcie w którym ja pracuję na próżno byś szukał długich metod z wymieszaną odpowiedzialnością. Dla mnie np. metoda która ma więcej niż 20 linii na oko zapala wewnętrzna czerwoną lampkę i sprawdzam czy czasem za dużo się w niej nie dzieje- w większości przypadków tak właśnie jest i wydzielam część kodu do odrębnej metody (lub metod).

0

No tak, w projekcie w którym ty pracujesz, tylko nikt go nie widział. Ty umiesz czysty kod, ale nie pokażesz, a Google nie umie i np Androida napisał źle. O tym mówię przecież.

Patrząc na to z boku: tu gdzie pracują szeregowi programiści, piszą czysty kod dla swoich firm. A wielcy robią tylko kupę, bo inaczej nie umią czyli ci szeregowi są lepsi pewnie

1

Mam dzielić się prywatnym kodem firmy który nie należy do mnie? Dobre żarty... Jeśli chodzi o jakiś kod na GH to sprawa jest prosta- nie mam żadnego większego projektu napisanego prywatnie. Poza tym w kwestii gorszych praktyk w kodzie frameworków to również sprawa jest prosta- tam często celem nadrzędnym jest wydajność, i jest to dostarczane właśnie kosztem jakości kodu (i co za tym idzie również większą możliwością bugów). Ja piszę kod biznesowy. Jego wydajność jest zapewniona przede wszystkim dzięki frameworkom i odpowiedniej architekturze, a nie szczegółom implementacyjnym. Kod biznesowy ma być właśnie czytelny, czysty i spójny z domeną którą obsługuje- to jest właśnie to na co jest czas i środki, wydajność to sprawa drugorzędna. Problemy wydajnościowe naprawia się dopiero kiedy one się pojawią, a pojawiają się rzadko właśnie dzięki temu że korzysta się z gotowych rozwiązań.

0

Bo najlepiej jakby Kafka nie byla napisana w Javie ;)
stąd pomysły jak RedPanda od https://vectorized.io/ heh

a kod który musi miec wysoki performance czesto jest brzydki tak czy inaczej

jeszcze mi sie przypomnialo... GOTO tez jest brzydkie co nie? https://manybutfinite.com/post/goto-and-the-folly-of-dogma/

a dla wiekszego mindfucku:
"Why Every Element of SOLID is Wrong" https://speakerdeck.com/tastapod/why-every-element-of-solid-is-wrong
"It's probably time to stop recommending Clean Code" https://qntm.org/clean
IT depends, always.

Odnosnie GOTO jak ktos lubi takie ciekawostki:

Title of "GO TO Statement considered harmful" https://www.cs.utexas.edu/users/EWD/transcriptions/EWD02xx/EWD215.html was "A Case against the GO TO Statement", Dijkstra mentioned it in the last paragraph here http://www.cs.utexas.edu/users/EWD/transcriptions/EWD13xx/EWD1308.html
"Finally a short story for the record. In 1968, the Communications of the ACM published a text of mine under the title "The goto statement considered harmful", which in later years would be most frequently referenced, regrettably, however, often by authors who had seen no more of it than its title, which became a cornerstone of my fame by becoming a template: we would see all sorts of articles under the title "X considered harmful" for almost any X, including one titled "Dijkstra considered harmful". But what had happened? I had submitted a paper under the title "A case against the goto statement", which, in order to speed up its publication, the editor had changed into a "letter to the Editor", and in the process he had given it a new title of his own invention! The editor was Niklaus Wirth."

0
karsa napisał(a):

Bo najlepiej jakby Kafka nie byla napisana w Javie ;)

Pytanie z ciekawości - czemu?

W czym byś nie napisał Kafki to będą problemy. Java w tej kwestii ma jedną dużą zaletę - jest ich relatywnie mało, a jak wystąpią to zazwyczaj dość łatwo namierzyć czy stwierdzić co poszło nie tak.

1
karsa napisał(a):

a kod który musi miec wysoki performance czesto jest brzydki tak czy inaczej

Jeśli, aby osiągnąć dobrą wydajność musisz pisać brzydki kod
to znaczy, że kompilator/jezyk obsysa - praktycznie wszystkie współczesne (2020) kompilatory to niestety dramat na jakimś poziomie. Ale ciągle jest postęp, wiele rzeczy, które kiedyś trzeba było robić ręcznie (asm/c ) sdą obecnie ładnie załatwiane na wyższym poziomie (np. naprawdę wydajne użycie rejestrów).

Co do GOTO considered harmfull to imo już dawno minęliśmy ten punkt, że goto jest potrzebne ze względów wydajnościowych.

Krytyka SOLID - sensowna, mam od dawna bardzo podobne przemyślenia (tylko nie chce otwierać tego frontu :-)) - z wyjątkiem ostatniego punktu - Dependency Inversion w żadnym razie nie prowadzi to używania frameworków, to tylko wynaturzenie, które zdarzyło się w javie.

1 użytkowników online, w tym zalogowanych: 0, gości: 1